caelum0x c3236f0bca feat(card-issuance,gateway,cli): add CloseCard — issued cards could never be shut off
CARD_STATUS_SUSPENDED/CLOSED have existed in common.proto since the
original build, and the Airwallex client package even defined
CardStatusSuspended/CardStatusClosed constants, but nothing in this
repo ever transitioned a stored card into either state: card-issuance's
airwallex.Client interface only exposed IssueCard/GetCard/
SetCardControls (limit/controls only, never status), so a leaked
credential, an offboarded cardholder's card, or any card that should
stop spending forever had no real operator path to close — only
"adjust-limit" to a smaller (but still nonzero-possible, still active)
limit.

Adds card_issuance.proto/gateway.proto's CloseCard RPC, a real
airwallex.Client.CloseCard on both Mock and Live (POST
/api/v1/issuing/cards/{id}/close), cardsvc.Service.CloseCard (releases
the card's full remaining ledger HOLD back to the tenant's available
balance, idempotent on an already-closed card), the gateway fan-out,
and `ration card close --card <id>`. AdjustCardLimit now rejects a
closed card instead of silently reopening a zombie hold.

tenantauth/ratelimit needed zero changes: both resolve card_id via
reflection, so CloseCardRequest's card_id field is automatically
tenant-scoped and rate-limited the same way GetCard/AdjustCardLimit
already are.

Verified live against the real bare-metal 7-service stack
(scripts/run-demo.sh): issued a real card (Held 1,000.00 USD), closed
it (status CLOSED, Held back to 0.00, Available back to 7,500.00),
re-closed it (idempotent — Available unchanged, no double-release),
confirmed adjust-limit on the closed card is rejected, and confirmed
closing an unknown card_id surfaces the same NotFound-wrapped error
GetCard/AdjustCardLimit already do. verify-chain: intact (5 records).
`go build`/`go vet` clean across every Go module (gateway,
card-issuance, cli, tui, auth, tenant-registry, webhook-ingestion,
agent, audit-log, sdk/go/ration), full `make build` (Rust+Go+SDK)
clean, 0 regressions.
2026-10-29 11:35:23 +03:00

353 lines
14 KiB
Go

// Package grpcserver implements gateway.proto's Gateway service as a
// thin BFF (docs/SCALE-EXPANSION.md section 1, docs/adr/0004): every
// card and rationing-math RPC is a direct fan-out to services/card-issuance
// over internal/cardissuanceclient, translated at this one edge between
// cardissuance.* wire types and gateway.* wire types (which are
// structurally identical by design — gateway.proto's Card/IssueCardRequest/
// etc. messages are unchanged from before the split, so this translation
// is a mechanical field-by-field copy, not new business logic). Deposit
// simulation still talks to ledger-core directly (it always proxied
// straight through here, with no gateway-side business logic beyond
// defaulting expected_at_unix). StreamActivity serves this process's own
// activity bus, which cmd/gateway/main.go also feeds from
// services/webhook-ingestion's StreamEvents via internal/webhookeventsclient.
package grpcserver
import (
"context"
"fmt"
"sort"
"time"
cardissuancepb "github.com/caelum0x/ration/pkg/pb/cardissuance"
commonpb "github.com/caelum0x/ration/pkg/pb/common"
gatewaypb "github.com/caelum0x/ration/pkg/pb/gateway"
ledgerpb "github.com/caelum0x/ration/pkg/pb/ledger"
"github.com/caelum0x/ration/services/gateway/internal/activity"
"github.com/caelum0x/ration/services/gateway/internal/idgen"
)
// CardIssuanceClient is the subset of cardissuanceclient.Client the
// gateway needs — a narrow interface so tests can supply a fake without
// standing up a real gRPC server.
type CardIssuanceClient interface {
IssueCard(ctx context.Context, req *cardissuancepb.IssueCardRequest) (*cardissuancepb.Card, error)
AdjustCardLimit(ctx context.Context, req *cardissuancepb.AdjustCardLimitRequest) (*cardissuancepb.Card, error)
GetCard(ctx context.Context, cardID string) (*cardissuancepb.Card, error)
CloseCard(ctx context.Context, cardID string) (*cardissuancepb.Card, error)
ListCards(ctx context.Context, tenantID string) ([]*cardissuancepb.Card, error)
RationBridgeFunding(ctx context.Context, req *cardissuancepb.RationBridgeFundingRequest) (*cardissuancepb.RationBridgeFundingResponse, error)
}
// LedgerClient is the subset of ledgerclient.Client SimulateDeposit and
// GetDashboardSnapshot need.
type LedgerClient interface {
RecordDeposit(ctx context.Context, req *ledgerpb.RecordDepositRequest) (*ledgerpb.Deposit, error)
GetTenant(ctx context.Context, tenantID string) (*ledgerpb.Tenant, error)
// The remaining four back GetDashboardSnapshot only — see that
// method's doc comment.
ListTenants(ctx context.Context, req *ledgerpb.ListTenantsRequest) (*ledgerpb.ListTenantsResponse, error)
GetBalance(ctx context.Context, tenantID string) (*ledgerpb.Balance, error)
CheckReserveFloor(ctx context.Context, tenantID string, proposedDebitMinorUnits int64) (*ledgerpb.CheckReserveFloorResponse, error)
ListAgentDecisions(ctx context.Context, tenantID string, limit int32) ([]*ledgerpb.AgentDecision, error)
}
// Server implements gatewaypb.GatewayServer.
type Server struct {
gatewaypb.UnimplementedGatewayServer
cards CardIssuanceClient
ledger LedgerClient
bus *activity.Bus
newID func(prefix string) string
}
// New constructs a Server wiring the given card-issuance client, ledger
// client and activity bus.
func New(cards CardIssuanceClient, ledger LedgerClient, bus *activity.Bus) *Server {
return &Server{
cards: cards,
ledger: ledger,
bus: bus,
newID: idgen.New,
}
}
func (s *Server) publish(tenantID, kind, summary string) {
if s.bus == nil {
return
}
s.bus.Publish(activity.NewEvent(tenantID, kind, summary))
}
// toGatewayCard copies a cardissuance.Card into gateway.proto's identical
// Card message — the two protos define the same fields by design (see
// this package's doc comment), so this is a straight field copy, not a
// translation of meaning.
func toGatewayCard(c *cardissuancepb.Card) *gatewaypb.Card {
if c == nil {
return nil
}
return &gatewaypb.Card{
Id: c.GetId(),
TenantId: c.GetTenantId(),
AirwallexCardId: c.GetAirwallexCardId(),
CardholderName: c.GetCardholderName(),
Status: c.GetStatus(),
LimitMinorUnits: c.GetLimitMinorUnits(),
LimitInterval: c.GetLimitInterval(),
Currency: c.GetCurrency(),
CreatedAtUnix: c.GetCreatedAtUnix(),
}
}
// IssueCard implements gatewaypb.GatewayServer.
func (s *Server) IssueCard(ctx context.Context, req *gatewaypb.IssueCardRequest) (*gatewaypb.Card, error) {
c, err := s.cards.IssueCard(ctx, &cardissuancepb.IssueCardRequest{
TenantId: req.GetTenantId(),
CardholderName: req.GetCardholderName(),
LimitMinorUnits: req.GetLimitMinorUnits(),
LimitInterval: req.GetLimitInterval(),
Currency: req.GetCurrency(),
})
if err != nil {
return nil, err
}
s.publish(req.GetTenantId(), "card", fmt.Sprintf("issued card %s for %s, limit %d %s", c.GetId(), req.GetCardholderName(), c.GetLimitMinorUnits(), c.GetCurrency()))
return toGatewayCard(c), nil
}
// AdjustCardLimit implements gatewaypb.GatewayServer.
func (s *Server) AdjustCardLimit(ctx context.Context, req *gatewaypb.AdjustCardLimitRequest) (*gatewaypb.Card, error) {
c, err := s.cards.AdjustCardLimit(ctx, &cardissuancepb.AdjustCardLimitRequest{
CardId: req.GetCardId(),
NewLimitMinorUnits: req.GetNewLimitMinorUnits(),
Reason: req.GetReason(),
})
if err != nil {
return nil, err
}
s.publish(c.GetTenantId(), "card", fmt.Sprintf("adjusted card %s limit to %d %s (%s)", c.GetId(), c.GetLimitMinorUnits(), c.GetCurrency(), req.GetReason()))
return toGatewayCard(c), nil
}
// GetCard implements gatewaypb.GatewayServer.
func (s *Server) GetCard(ctx context.Context, req *gatewaypb.GetCardRequest) (*gatewaypb.Card, error) {
c, err := s.cards.GetCard(ctx, req.GetCardId())
if err != nil {
return nil, err
}
return toGatewayCard(c), nil
}
// CloseCard implements gatewaypb.GatewayServer.
func (s *Server) CloseCard(ctx context.Context, req *gatewaypb.CloseCardRequest) (*gatewaypb.Card, error) {
c, err := s.cards.CloseCard(ctx, req.GetCardId())
if err != nil {
return nil, err
}
s.publish(c.GetTenantId(), "card", fmt.Sprintf("closed card %s", c.GetId()))
return toGatewayCard(c), nil
}
// ListCards implements gatewaypb.GatewayServer.
func (s *Server) ListCards(ctx context.Context, req *gatewaypb.ListCardsRequest) (*gatewaypb.ListCardsResponse, error) {
cards, err := s.cards.ListCards(ctx, req.GetTenantId())
if err != nil {
return nil, err
}
out := make([]*gatewaypb.Card, 0, len(cards))
for _, c := range cards {
out = append(out, toGatewayCard(c))
}
return &gatewaypb.ListCardsResponse{Cards: out}, nil
}
// RationBridgeFunding implements gatewaypb.GatewayServer.
func (s *Server) RationBridgeFunding(ctx context.Context, req *gatewaypb.RationBridgeFundingRequest) (*gatewaypb.RationBridgeFundingResponse, error) {
result, err := s.cards.RationBridgeFunding(ctx, &cardissuancepb.RationBridgeFundingRequest{
TenantId: req.GetTenantId(),
RequestedMinorUnits: req.GetRequestedMinorUnits(),
Reason: req.GetReason(),
})
if err != nil {
return nil, err
}
s.publish(req.GetTenantId(), "agent_decision", result.GetExplanation())
return &gatewaypb.RationBridgeFundingResponse{
GrantedMinorUnits: result.GetGrantedMinorUnits(),
FullyGranted: result.GetFullyGranted(),
Explanation: result.GetExplanation(),
}, nil
}
// SimulateDeposit implements gatewaypb.GatewayServer. It is a demo/judging
// hook (see services/cli's `ration simulate-deposit`): it records an
// expected deposit with ledger-core, optionally backdated so
// ListLateDeposits immediately reports it as late. This is the one RPC
// gateway.proto exposes that the section 1 split didn't move anywhere
// else — it always talked to ledger-core directly, no card-issuance or
// webhook-ingestion involvement, and still does.
func (s *Server) SimulateDeposit(ctx context.Context, req *gatewaypb.SimulateDepositRequest) (*gatewaypb.SimulateDepositResponse, error) {
if req.GetTenantId() == "" {
return nil, fmt.Errorf("grpcserver: tenant_id is required")
}
if req.GetAmountMinorUnits() <= 0 {
return nil, fmt.Errorf("grpcserver: amount_minor_units must be > 0")
}
expectedAt := req.GetExpectedAtUnix()
if req.GetMarkLate() {
// Force the deposit to already be overdue: one hour in the past
// relative to "now", regardless of what expected_at_unix the
// caller passed, so ListLateDeposits picks it up immediately.
expectedAt = time.Now().Add(-1 * time.Hour).Unix()
} else if expectedAt == 0 {
expectedAt = time.Now().Add(24 * time.Hour).Unix()
}
tenant, err := s.ledger.GetTenant(ctx, req.GetTenantId())
if err != nil {
return nil, fmt.Errorf("grpcserver: get tenant %s: %w", req.GetTenantId(), err)
}
deposit, err := s.ledger.RecordDeposit(ctx, &ledgerpb.RecordDepositRequest{
TenantId: req.GetTenantId(),
ExpectedAmount: &commonpb.Money{
MinorUnits: req.GetAmountMinorUnits(),
Currency: tenant.GetCurrency(),
},
ExpectedAtUnix: expectedAt,
ExternalRef: s.newID("sim-deposit"),
})
if err != nil {
return nil, fmt.Errorf("grpcserver: record simulated deposit for %s: %w", req.GetTenantId(), err)
}
s.publish(req.GetTenantId(), "deposit", fmt.Sprintf("simulated deposit %s of %d minor units, expected_at=%d, late=%v", deposit.GetId(), req.GetAmountMinorUnits(), expectedAt, req.GetMarkLate()))
return &gatewaypb.SimulateDepositResponse{DepositId: deposit.GetId()}, nil
}
// defaultDashboardDecisionsPerTenant/defaultDashboardMaxDecisions are
// GetDashboardSnapshotRequest's server-side defaults when the caller
// leaves either field at 0 — the same demo-scale assumption
// services/tui's own decisionsPerTenant constant documents.
const (
defaultDashboardDecisionsPerTenant = 20
defaultDashboardMaxDecisions = 50
)
// GetDashboardSnapshot implements gatewaypb.GatewayServer. It is the
// one aggregate read the judge-facing web dashboard
// (services/gateway/internal/httpapi's "/v1/dashboard" routes) polls —
// see gateway.proto's doc comment on the RPC for why this aggregates
// rather than exposing N+1 separate RPCs to a browser: every tenant's
// balance/reserve-floor headroom (ledger-core's CheckReserveFloor, the
// exact number every bridge-funding decision is gated on — never
// recomputed here from available/reserve-floor separately, so this can
// never silently drift from the authoritative definition) plus the
// most recent agent decisions across every tenant, merged and sorted
// newest-first.
func (s *Server) GetDashboardSnapshot(ctx context.Context, req *gatewaypb.GetDashboardSnapshotRequest) (*gatewaypb.GetDashboardSnapshotResponse, error) {
decisionsPerTenant := req.GetDecisionsPerTenant()
if decisionsPerTenant <= 0 {
decisionsPerTenant = defaultDashboardDecisionsPerTenant
}
maxDecisions := int(req.GetMaxDecisions())
if maxDecisions <= 0 {
maxDecisions = defaultDashboardMaxDecisions
}
tenantsResp, err := s.ledger.ListTenants(ctx, &ledgerpb.ListTenantsRequest{PageSize: 1000})
if err != nil {
return nil, fmt.Errorf("grpcserver: list tenants for dashboard snapshot: %w", err)
}
snapshots := make([]*gatewaypb.TenantSnapshot, 0, len(tenantsResp.GetTenants()))
var allDecisions []*gatewaypb.AgentDecisionSummary
for _, t := range tenantsResp.GetTenants() {
balance, err := s.ledger.GetBalance(ctx, t.GetId())
if err != nil {
// One tenant's balance lookup failing must not blank out
// the whole dashboard for every other tenant — log via the
// returned error's absence (no logger threaded into this
// package today; skip this tenant's snapshot row, keep
// going) rather than failing the entire RPC.
continue
}
reserveResp, err := s.ledger.CheckReserveFloor(ctx, t.GetId(), 0)
if err != nil {
continue
}
snapshots = append(snapshots, &gatewaypb.TenantSnapshot{
TenantId: t.GetId(),
TenantName: t.GetName(),
Currency: t.GetCurrency(),
ReserveFloorMinorUnits: t.GetReserveFloorMinorUnits(),
AvailableMinorUnits: balance.GetAvailableMinorUnits(),
HeldMinorUnits: balance.GetHeldMinorUnits(),
HeadroomMinorUnits: reserveResp.GetHeadroomMinorUnits(),
})
decisions, err := s.ledger.ListAgentDecisions(ctx, t.GetId(), decisionsPerTenant)
if err != nil {
continue
}
for _, d := range decisions {
allDecisions = append(allDecisions, &gatewaypb.AgentDecisionSummary{
TenantId: d.GetTenantId(),
TenantName: t.GetName(),
Trigger: d.GetTrigger(),
Action: d.GetAction(),
Rationale: d.GetRationale(),
PolicySnapshotJson: d.GetPolicySnapshotJson(),
CreatedAtUnix: d.GetCreatedAtUnix(),
})
}
}
sort.SliceStable(allDecisions, func(i, j int) bool {
return allDecisions[i].GetCreatedAtUnix() > allDecisions[j].GetCreatedAtUnix()
})
if len(allDecisions) > maxDecisions {
allDecisions = allDecisions[:maxDecisions]
}
return &gatewaypb.GetDashboardSnapshotResponse{
Tenants: snapshots,
RecentDecisions: allDecisions,
}, nil
}
// StreamActivity implements gatewaypb.GatewayServer.
func (s *Server) StreamActivity(req *gatewaypb.StreamActivityRequest, stream gatewaypb.Gateway_StreamActivityServer) error {
ch, unsubscribe := s.bus.Subscribe(req.GetTenantId())
defer unsubscribe()
ctx := stream.Context()
for {
select {
case <-ctx.Done():
return ctx.Err()
case e, ok := <-ch:
if !ok {
return nil
}
if err := stream.Send(&gatewaypb.ActivityEvent{
Id: e.ID,
TenantId: e.TenantID,
Kind: e.Kind,
Summary: e.Summary,
AtUnix: e.AtUnix,
}); err != nil {
return err
}
}
}
}