|
| 1 | +// Copyright (c) 2026 Lerian Studio. All rights reserved. |
| 2 | +// Use of this source code is governed by the Elastic License 2.0 |
| 3 | +// that can be found in the LICENSE file. |
| 4 | + |
| 5 | +package command |
| 6 | + |
| 7 | +import ( |
| 8 | + "context" |
| 9 | + |
| 10 | + libCommons "github.com/LerianStudio/lib-commons/v3/commons" |
| 11 | + libOpentelemetry "github.com/LerianStudio/lib-commons/v3/commons/opentelemetry" |
| 12 | + redisBalance "github.com/LerianStudio/midaz/v3/components/transaction/internal/adapters/redis/balance" |
| 13 | + "github.com/LerianStudio/midaz/v3/pkg/mmodel" |
| 14 | + "github.com/LerianStudio/midaz/v3/pkg/utils" |
| 15 | + "github.com/google/uuid" |
| 16 | +) |
| 17 | + |
| 18 | +// SyncBalancesBatchResult holds the result of a batch sync operation. |
| 19 | +type SyncBalancesBatchResult struct { |
| 20 | + // KeysProcessed is the number of Redis keys that were attempted |
| 21 | + KeysProcessed int |
| 22 | + // BalancesAggregated is the number of unique balances after deduplication |
| 23 | + BalancesAggregated int |
| 24 | + // BalancesSynced is the number of balances actually written to database |
| 25 | + BalancesSynced int64 |
| 26 | + // KeysRemoved is the number of keys removed from the schedule |
| 27 | + KeysRemoved int64 |
| 28 | +} |
| 29 | + |
| 30 | +// SyncBalancesBatch performs a batch sync of balances from Redis to PostgreSQL. |
| 31 | +// |
| 32 | +// Algorithm: |
| 33 | +// 1. Fetch balance values for all provided keys using MGET |
| 34 | +// 2. Aggregate by composite key, keeping only highest version per key |
| 35 | +// 3. Persist aggregated balances to database in single transaction |
| 36 | +// 4. Remove synced keys from the schedule |
| 37 | +// |
| 38 | +// This method is resilient to: |
| 39 | +// - Missing keys (already expired): skipped in aggregation |
| 40 | +// - Version conflicts: optimistic locking in DB update |
| 41 | +// - Partial failures: keys only removed after successful DB write |
| 42 | +func (uc *UseCase) SyncBalancesBatch(ctx context.Context, organizationID, ledgerID uuid.UUID, keys []string) (*SyncBalancesBatchResult, error) { |
| 43 | + logger, tracer, _, metricFactory := libCommons.NewTrackingFromContext(ctx) |
| 44 | + |
| 45 | + ctx, span := tracer.Start(ctx, "command.sync_balances_batch") |
| 46 | + defer span.End() |
| 47 | + |
| 48 | + result := &SyncBalancesBatchResult{ |
| 49 | + KeysProcessed: len(keys), |
| 50 | + } |
| 51 | + |
| 52 | + if len(keys) == 0 { |
| 53 | + return result, nil |
| 54 | + } |
| 55 | + |
| 56 | + balanceMap, err := uc.RedisRepo.GetBalancesByKeys(ctx, keys) |
| 57 | + if err != nil { |
| 58 | + libOpentelemetry.HandleSpanError(&span, "Failed to get balances by keys", err) |
| 59 | + logger.Errorf("Failed to get balances by keys: %v", err) |
| 60 | + |
| 61 | + return nil, err |
| 62 | + } |
| 63 | + |
| 64 | + aggregatedBalances := make([]*redisBalance.AggregatedBalance, 0, len(keys)) |
| 65 | + |
| 66 | + for _, key := range keys { |
| 67 | + balance := balanceMap[key] |
| 68 | + if balance == nil { |
| 69 | + logger.Debugf("Balance key %s has no data (expired), skipping", key) |
| 70 | + continue |
| 71 | + } |
| 72 | + |
| 73 | + compositeKey, parseErr := redisBalance.BalanceCompositeKeyFromRedisKey(key) |
| 74 | + if parseErr != nil { |
| 75 | + logger.Warnf("Failed to parse composite key from %s: %v", key, parseErr) |
| 76 | + continue |
| 77 | + } |
| 78 | + |
| 79 | + compositeKey.AssetCode = balance.AssetCode |
| 80 | + |
| 81 | + aggregatedBalances = append(aggregatedBalances, &redisBalance.AggregatedBalance{ |
| 82 | + RedisKey: key, |
| 83 | + Balance: balance, |
| 84 | + Key: compositeKey, |
| 85 | + }) |
| 86 | + } |
| 87 | + |
| 88 | + aggregator := redisBalance.NewInMemoryAggregator() |
| 89 | + deduplicated := aggregator.Aggregate(ctx, aggregatedBalances) |
| 90 | + result.BalancesAggregated = len(deduplicated) |
| 91 | + |
| 92 | + if len(deduplicated) == 0 { |
| 93 | + logger.Info("No balances to sync after aggregation") |
| 94 | + return result, nil |
| 95 | + } |
| 96 | + |
| 97 | + balancesToSync := make([]mmodel.BalanceRedis, 0, len(deduplicated)) |
| 98 | + keysToRemove := make([]string, 0, len(deduplicated)) |
| 99 | + |
| 100 | + for _, ab := range deduplicated { |
| 101 | + balancesToSync = append(balancesToSync, *ab.Balance) |
| 102 | + keysToRemove = append(keysToRemove, ab.RedisKey) |
| 103 | + } |
| 104 | + |
| 105 | + synced, err := uc.BalanceRepo.SyncBatch(ctx, organizationID, ledgerID, balancesToSync) |
| 106 | + if err != nil { |
| 107 | + libOpentelemetry.HandleSpanError(&span, "Failed to sync batch to database", err) |
| 108 | + logger.Errorf("Failed to sync batch to database: %v", err) |
| 109 | + |
| 110 | + return nil, err |
| 111 | + } |
| 112 | + |
| 113 | + result.BalancesSynced = synced |
| 114 | + |
| 115 | + removed, err := uc.RedisRepo.RemoveBalanceSyncKeysBatch(ctx, keysToRemove) |
| 116 | + if err != nil { |
| 117 | + logger.Warnf("Failed to remove synced keys from schedule: %v", err) |
| 118 | + |
| 119 | + metricFactory.Counter(utils.BalanceSyncCleanupFailures).WithLabels(map[string]string{ |
| 120 | + "organization_id": organizationID.String(), |
| 121 | + "ledger_id": ledgerID.String(), |
| 122 | + }).AddOne(ctx) |
| 123 | + } |
| 124 | + |
| 125 | + result.KeysRemoved = removed |
| 126 | + |
| 127 | + logger.Infof("SyncBalancesBatch: processed=%d, aggregated=%d, synced=%d, removed=%d", |
| 128 | + result.KeysProcessed, result.BalancesAggregated, result.BalancesSynced, result.KeysRemoved) |
| 129 | + |
| 130 | + return result, nil |
| 131 | +} |
0 commit comments