-
-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathlineage.go
More file actions
1536 lines (1341 loc) · 55.4 KB
/
lineage.go
File metadata and controls
1536 lines (1341 loc) · 55.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2024 Blnk Finance Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package blnk
import (
"context"
"encoding/json"
"fmt"
"math/big"
"sort"
"strings"
"time"
redlock "github.com/blnkfinance/blnk/internal/lock"
"github.com/blnkfinance/blnk/internal/notification"
"github.com/blnkfinance/blnk/model"
"github.com/sirupsen/logrus"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
)
// LineageProviderKey is the metadata key used to identify the provider of funds in a transaction.
const LineageProviderKey = "BLNK_LINEAGE_PROVIDER"
// LineageFundAllocation is the metadata key used to store fund allocation details in a transaction.
const LineageFundAllocation = "BLNK_FUND_ALLOCATION"
// Allocation strategies for fund lineage debit processing.
const (
AllocationFIFO = "FIFO"
AllocationLIFO = "LIFO"
AllocationProp = "PROPORTIONAL"
)
// LineageSource represents a source of funds available for allocation during lineage debit processing.
//
// Fields:
// - BalanceID string: The ID of the shadow balance holding the funds.
// - Balance *big.Int: The available balance amount.
// - CreatedAt time.Time: The creation time of the lineage mapping, used for FIFO/LIFO ordering.
type LineageSource struct {
BalanceID string
Balance *big.Int
CreatedAt time.Time
}
// Allocation represents the amount allocated from a specific shadow balance during debit processing.
//
// Fields:
// - BalanceID string: The ID of the shadow balance from which funds are allocated.
// - Amount *big.Int: The amount allocated from this balance.
type Allocation struct {
BalanceID string
Amount *big.Int
}
// LineageOutboxPayload contains the transaction data needed for deferred lineage processing.
type LineageOutboxPayload struct {
Amount float64 `json:"amount"`
PreciseAmount string `json:"precise_amount"`
Currency string `json:"currency"`
Precision float64 `json:"precision"`
Reference string `json:"reference"`
SkipQueue bool `json:"skip_queue"`
Inflight bool `json:"inflight"`
}
// ProviderBreakdown represents the fund breakdown for a specific provider in a balance's lineage.
//
// Fields:
// - Provider string: The name/identifier of the fund provider.
// - Amount *big.Int: The total amount received from this provider.
// - Available *big.Int: The amount still available (not yet spent).
// - Spent *big.Int: The amount that has been debited.
// - BalanceID string: The ID of the shadow balance tracking this provider's funds.
type ProviderBreakdown struct {
Provider string `json:"provider"`
Amount *big.Int `json:"amount"`
Available *big.Int `json:"available"`
Spent *big.Int `json:"spent"`
BalanceID string `json:"shadow_balance_id"`
}
// BalanceLineage represents the complete fund lineage for a balance.
//
// Fields:
// - BalanceID string: The ID of the balance being queried.
// - TotalWithLineage *big.Int: The total funds tracked across all providers.
// - AggregateBalanceID string: The ID of the aggregate shadow balance.
// - Providers []ProviderBreakdown: The breakdown of funds by provider.
type BalanceLineage struct {
BalanceID string `json:"balance_id"`
TotalWithLineage *big.Int `json:"total_with_lineage"`
AggregateBalanceID string `json:"aggregate_balance_id"`
Providers []ProviderBreakdown `json:"providers"`
}
type destinationLineageInfo struct {
shadowBalance *model.Balance
aggregateBalance *model.Balance
}
// processLineage handles fund lineage tracking for a transaction.
// It processes both credit (incoming funds with provider tracking) and debit (fund allocation from shadow balances).
//
// Parameters:
// - ctx context.Context: The context for the operation.
// - txn *model.Transaction: The transaction being processed.
// - sourceBalance *model.Balance: The source balance for the transaction.
// - destinationBalance *model.Balance: The destination balance for the transaction.
func (l *Blnk) processLineage(ctx context.Context, txn *model.Transaction, sourceBalance, destinationBalance *model.Balance) {
ctx, span := tracer.Start(ctx, "ProcessLineage")
defer span.End()
provider := l.getLineageProvider(txn)
// Validate provider against source balance
// If source tracks lineage but doesn't have the provider, ignore it
validatedProvider, err := l.validateLineageProvider(ctx, provider, sourceBalance)
if err != nil {
span.RecordError(err)
logrus.Errorf("lineage provider validation failed: %v", err)
notification.NotifyError(err)
validatedProvider = ""
}
if provider != "" && validatedProvider == "" && sourceBalance != nil {
span.AddEvent("Provider validation failed", trace.WithAttributes(
attribute.String("requested_provider", provider),
attribute.String("source_balance_id", sourceBalance.BalanceID),
))
}
// Credit processing requires a validated provider to know the source of funds
if validatedProvider != "" && destinationBalance != nil && destinationBalance.TrackFundLineage {
if err := l.processLineageCredit(ctx, txn, destinationBalance, validatedProvider); err != nil {
span.RecordError(err)
logrus.Errorf("lineage credit processing failed: %v", err)
notification.NotifyError(err)
}
}
// Debit processing doesn't require a provider - it allocates from existing shadow balances
if sourceBalance != nil && sourceBalance.TrackFundLineage {
if err := l.processLineageDebit(ctx, txn, sourceBalance, destinationBalance); err != nil {
span.RecordError(err)
logrus.Errorf("lineage debit processing failed: %v", err)
notification.NotifyError(err)
}
}
span.AddEvent("Lineage processing completed")
}
// getLineageProvider extracts the fund provider from the transaction metadata.
//
// Parameters:
// - txn *model.Transaction: The transaction to extract the provider from.
//
// Returns:
// - string: The provider identifier, or empty string if not set.
func (l *Blnk) getLineageProvider(txn *model.Transaction) string {
if txn.MetaData == nil {
return ""
}
provider, ok := txn.MetaData[LineageProviderKey].(string)
if !ok {
return ""
}
return provider
}
// validateLineageProvider checks if the specified provider exists on the source balance.
// If the source tracks fund lineage but doesn't have the specified provider,
// returns empty string (provider should be ignored).
// If the source doesn't track lineage (e.g., @world), any provider is valid.
//
// Parameters:
// - ctx context.Context: The context for the operation.
// - provider string: The provider specified in transaction metadata.
// - sourceBalance *model.Balance: The source balance (may be nil or not track lineage).
//
// Returns:
// - string: The validated provider name (empty if invalid/should be ignored).
// - error: An error if validation fails (database errors only, not for invalid providers).
func (l *Blnk) validateLineageProvider(ctx context.Context, provider string, sourceBalance *model.Balance) (string, error) {
if provider == "" {
return "", nil
}
// Source is nil or doesn't track lineage - provider is valid
if sourceBalance == nil || !sourceBalance.TrackFundLineage {
return provider, nil
}
// Source tracks lineage - verify provider exists
mapping, err := l.datasource.GetLineageMappingByProvider(ctx, sourceBalance.BalanceID, provider)
if err != nil {
return "", fmt.Errorf("failed to validate provider on source: %w", err)
}
if mapping == nil {
logrus.Warnf("lineage provider validation: provider %q does not exist on source balance %s - ignoring provider",
provider, sourceBalance.BalanceID)
return "", nil
}
return provider, nil
}
// processLineageCredit processes a credit transaction for fund lineage tracking.
// It creates shadow balances and queues a shadow transaction to track the provider's funds.
//
// Parameters:
// - ctx context.Context: The context for the operation.
// - txn *model.Transaction: The credit transaction being processed.
// - destBalance *model.Balance: The destination balance receiving the funds.
// - provider string: The identifier of the fund provider.
//
// Returns:
// - error: An error if the credit processing fails.
func (l *Blnk) processLineageCredit(ctx context.Context, txn *model.Transaction, destBalance *model.Balance, provider string) error {
ctx, span := tracer.Start(ctx, "ProcessLineageCredit")
defer span.End()
identityID := destBalance.IdentityID
if identityID == "" {
return fmt.Errorf("destination balance %s has no identity_id for lineage tracking", destBalance.BalanceID)
}
// Get or create the shadow and aggregate balances first (before locking)
shadowBalance, aggregateBalance, err := l.getOrCreateLineageBalances(ctx, identityID, provider, txn.Currency)
if err != nil {
return err
}
// Use MultiLocker to lock both shadow and aggregate balances
locker, err := l.acquireLineageLocks(ctx, []string{shadowBalance.BalanceID, aggregateBalance.BalanceID})
if err != nil {
span.RecordError(err)
return err
}
defer l.releaseLock(ctx, locker)
if err := l.queueShadowCreditTransaction(ctx, txn, destBalance, provider, shadowBalance, aggregateBalance, identityID); err != nil {
return err
}
if err := l.upsertCreditLineageMapping(ctx, destBalance, provider, shadowBalance, aggregateBalance, identityID); err != nil {
logrus.Errorf("failed to create lineage mapping after shadow transaction: %v (txn: %s, provider: %s)", err, txn.TransactionID, provider)
span.RecordError(err)
// Don't return error - shadow transaction succeeded, mapping is for optimization
}
span.AddEvent("Lineage credit processed", trace.WithAttributes(
attribute.String("provider", provider),
attribute.String("shadow_balance", shadowBalance.BalanceID),
))
return nil
}
// getOrCreateLineageBalances retrieves or creates the shadow and aggregate balances for lineage tracking.
//
// Parameters:
// - ctx context.Context: The context for the operation.
// - identityID string: The identity ID associated with the balance.
// - provider string: The fund provider identifier.
// - currency string: The currency for the balances.
//
// Returns:
// - *model.Balance: The shadow balance for the provider.
// - *model.Balance: The aggregate balance for all providers.
// - error: An error if the balances could not be retrieved or created.
func (l *Blnk) getOrCreateLineageBalances(ctx context.Context, identityID, provider, currency string) (*model.Balance, *model.Balance, error) {
identity, err := l.datasource.GetIdentityByID(identityID)
if err != nil {
return nil, nil, fmt.Errorf("failed to get identity %s: %w", identityID, err)
}
identifier := l.getIdentityIdentifier(identity)
shadowBalanceIndicator := fmt.Sprintf("@%s_%s_lineage", provider, identifier)
aggregateBalanceIndicator := fmt.Sprintf("@%s_lineage", identifier)
shadowBalance, err := l.getOrCreateBalanceByIndicator(ctx, shadowBalanceIndicator, currency)
if err != nil {
return nil, nil, fmt.Errorf("failed to get/create shadow balance: %w", err)
}
aggregateBalance, err := l.getOrCreateBalanceByIndicator(ctx, aggregateBalanceIndicator, currency)
if err != nil {
return nil, nil, fmt.Errorf("failed to get/create aggregate balance: %w", err)
}
return shadowBalance, aggregateBalance, nil
}
// upsertCreditLineageMapping creates or updates the lineage mapping for a credit transaction.
//
// Parameters:
// - ctx context.Context: The context for the operation.
// - destBalance *model.Balance: The destination balance.
// - provider string: The fund provider identifier.
// - shadowBalance *model.Balance: The shadow balance for the provider.
// - aggregateBalance *model.Balance: The aggregate balance.
// - identityID string: The identity ID associated with the balance.
//
// Returns:
// - error: An error if the mapping could not be created.
func (l *Blnk) upsertCreditLineageMapping(ctx context.Context, destBalance *model.Balance, provider string, shadowBalance, aggregateBalance *model.Balance, identityID string) error {
mapping := model.LineageMapping{
BalanceID: destBalance.BalanceID,
Provider: provider,
ShadowBalanceID: shadowBalance.BalanceID,
AggregateBalanceID: aggregateBalance.BalanceID,
IdentityID: identityID,
}
if err := l.datasource.UpsertLineageMapping(ctx, mapping); err != nil {
return fmt.Errorf("failed to upsert lineage mapping: %w", err)
}
return nil
}
// queueShadowCreditTransaction queues a shadow transaction to track credited funds from a provider.
//
// Parameters:
// - ctx context.Context: The context for the operation.
// - txn *model.Transaction: The original credit transaction.
// - destBalance *model.Balance: The destination balance.
// - provider string: The fund provider identifier.
// - shadowBalance *model.Balance: The shadow balance for the provider.
// - aggregateBalance *model.Balance: The aggregate balance.
// - identityID string: The identity ID associated with the balance.
//
// Returns:
// - error: An error if the shadow transaction could not be queued.
func (l *Blnk) queueShadowCreditTransaction(ctx context.Context, txn *model.Transaction, destBalance *model.Balance, provider string, shadowBalance, aggregateBalance *model.Balance, identityID string) error {
shadowTxn := &model.Transaction{
Source: shadowBalance.BalanceID,
Destination: aggregateBalance.BalanceID,
Amount: txn.Amount,
PreciseAmount: new(big.Int).Set(txn.PreciseAmount),
Currency: destBalance.Currency,
Precision: txn.Precision,
Reference: fmt.Sprintf("%s_shadow_%s", txn.Reference, provider),
Description: fmt.Sprintf("Shadow credit from %s", provider),
MetaData: map[string]interface{}{
"_shadow_for": txn.TransactionID,
"_provider": provider,
"_identity_id": identityID,
"_lineage_type": "credit",
"_main_balance": destBalance.BalanceID,
},
AllowOverdraft: true,
SkipQueue: true,
Inflight: txn.Inflight,
}
_, err := l.QueueTransaction(ctx, shadowTxn)
if err != nil {
return fmt.Errorf("failed to queue shadow credit transaction: %w", err)
}
return nil
}
// processLineageDebit processes a debit transaction for fund lineage tracking.
// It allocates funds from shadow balances based on the configured allocation strategy.
// Uses MultiLocker to lock ALL involved shadow balances (source AND destination) atomically,
// preventing both race conditions and deadlocks from nested lock acquisition.
//
// Parameters:
// - ctx context.Context: The context for the operation.
// - txn *model.Transaction: The debit transaction being processed.
// - sourceBalance *model.Balance: The source balance being debited.
// - destinationBalance *model.Balance: The destination balance receiving the funds.
//
// Returns:
// - error: An error if the debit processing fails.
func (l *Blnk) processLineageDebit(ctx context.Context, txn *model.Transaction, sourceBalance, destinationBalance *model.Balance) error {
ctx, span := tracer.Start(ctx, "ProcessLineageDebit")
defer span.End()
// Get mappings first (before locking) to know which shadow balances we need
mappings, err := l.datasource.GetLineageMappings(ctx, sourceBalance.BalanceID)
if err != nil {
return fmt.Errorf("failed to get lineage mappings: %w", err)
}
if len(mappings) == 0 {
// Check if there are pending credit outbox entries for this balance
// If so, retry later after those credits are processed
hasPending, err := l.datasource.HasPendingCreditOutbox(ctx, sourceBalance.BalanceID)
if err != nil {
logrus.Warnf("failed to check pending credit outbox for balance %s: %v", sourceBalance.BalanceID, err)
return nil
}
if hasPending {
return fmt.Errorf("pending credit outbox entries exist for balance %s, retry later", sourceBalance.BalanceID)
}
return nil
}
// Collect all balance IDs for locking - source shadows + source aggregate
lockKeys := make([]string, 0, len(mappings)+1)
for _, m := range mappings {
lockKeys = append(lockKeys, m.ShadowBalanceID)
}
lockKeys = append(lockKeys, mappings[0].AggregateBalanceID)
// Pre-create destination lineage balances (if destination tracks lineage) BEFORE acquiring locks
var destLineageBalances map[string]*destinationLineageInfo
if destinationBalance != nil && destinationBalance.TrackFundLineage && destinationBalance.IdentityID != "" {
destLineageBalances, err = l.prepareDestinationLineageBalances(ctx, mappings, destinationBalance)
if err != nil {
logrus.Warnf("failed to prepare destination lineage balances: %v", err)
} else {
for _, info := range destLineageBalances {
lockKeys = append(lockKeys, info.shadowBalance.BalanceID)
lockKeys = append(lockKeys, info.aggregateBalance.BalanceID)
}
}
}
locker, err := l.acquireLineageLocks(ctx, lockKeys)
if err != nil {
span.RecordError(err)
return err
}
defer l.releaseLock(ctx, locker)
sources, err := l.getLineageSources(ctx, mappings)
if err != nil {
return fmt.Errorf("failed to get lineage sources: %w", err)
}
allocations := l.calculateAllocation(sources, txn.PreciseAmount, sourceBalance.AllocationStrategy)
sourceAggBalance, err := l.getSourceAggregateBalance(ctx, sourceBalance)
if err != nil {
return err
}
l.processAllocations(ctx, txn, allocations, mappings, sourceBalance, destinationBalance, sourceAggBalance, destLineageBalances)
l.updateFundAllocationMetadata(ctx, txn, allocations, mappings)
span.AddEvent("Lineage debit processed", trace.WithAttributes(attribute.Int("allocations", len(allocations))))
return nil
}
// prepareDestinationLineageBalances pre-creates destination shadow and aggregate balances for all providers.
// This is called BEFORE acquiring locks to avoid nested lock acquisition deadlocks.
//
// Parameters:
// - ctx context.Context: The context for the operation.
// - mappings []model.LineageMapping: The source lineage mappings (one per provider).
// - destinationBalance *model.Balance: The destination balance.
//
// Returns:
// - map[string]*destinationLineageInfo: Map of provider to destination lineage balances.
// - error: An error if any balance could not be created.
func (l *Blnk) prepareDestinationLineageBalances(ctx context.Context, mappings []model.LineageMapping, destinationBalance *model.Balance) (map[string]*destinationLineageInfo, error) {
result := make(map[string]*destinationLineageInfo, len(mappings))
for _, mapping := range mappings {
shadowBalance, aggBalance, err := l.getOrCreateDestinationLineageBalances(ctx, mapping.Provider, destinationBalance)
if err != nil {
return nil, fmt.Errorf("failed to prepare destination lineage for provider %s: %w", mapping.Provider, err)
}
result[mapping.Provider] = &destinationLineageInfo{
shadowBalance: shadowBalance,
aggregateBalance: aggBalance,
}
}
return result, nil
}
// acquireLineageLocks acquires distributed locks for multiple shadow balances using MultiLocker.
// MultiLocker handles sorting (prevents deadlock) and deduplication automatically.
// This is used for both credit and debit lineage processing to prevent race conditions.
//
// Parameters:
// - ctx context.Context: The context for the operation.
// - balanceIDs []string: The balance IDs to lock.
//
// Returns:
// - *redlock.MultiLocker: The acquired multi-lock.
// - error: An error if the locks could not be acquired.
func (l *Blnk) acquireLineageLocks(ctx context.Context, balanceIDs []string) (*redlock.MultiLocker, error) {
// Prefix all keys to avoid collision with main transaction locks
lockKeys := make([]string, 0, len(balanceIDs))
for _, id := range balanceIDs {
lockKeys = append(lockKeys, fmt.Sprintf("lineage:%s", id))
}
// MultiLocker handles deduplication and sorts keys lexicographically
locker := redlock.NewMultiLocker(l.redis, lockKeys, model.GenerateUUIDWithSuffix("loc"))
err := locker.Lock(ctx, l.Config().Transaction.LockDuration)
if err != nil {
return nil, fmt.Errorf("failed to acquire lineage locks: %w", err)
}
return locker, nil
}
// getSourceAggregateBalance retrieves or creates the aggregate balance for the source identity.
//
// Parameters:
// - ctx context.Context: The context for the operation.
// - sourceBalance *model.Balance: The source balance.
//
// Returns:
// - *model.Balance: The aggregate balance.
// - error: An error if the balance could not be retrieved or created.
func (l *Blnk) getSourceAggregateBalance(ctx context.Context, sourceBalance *model.Balance) (*model.Balance, error) {
sourceIdentity, err := l.datasource.GetIdentityByID(sourceBalance.IdentityID)
if err != nil {
return nil, fmt.Errorf("failed to get source identity: %w", err)
}
sourceIdentifier := l.getIdentityIdentifier(sourceIdentity)
sourceAggIndicator := fmt.Sprintf("@%s_lineage", sourceIdentifier)
sourceAggBalance, err := l.getOrCreateBalanceByIndicator(ctx, sourceAggIndicator, sourceBalance.Currency)
if err != nil {
return nil, fmt.Errorf("failed to get source aggregate balance: %w", err)
}
return sourceAggBalance, nil
}
// processAllocations processes fund allocations by queuing release and receive transactions.
//
// Parameters:
// - ctx context.Context: The context for the operation.
// - txn *model.Transaction: The original transaction.
// - allocations []Allocation: The calculated allocations.
// - mappings []model.LineageMapping: The lineage mappings.
// - sourceBalance *model.Balance: The source balance.
// - destinationBalance *model.Balance: The destination balance.
// - sourceAggBalance *model.Balance: The source aggregate balance.
// - destLineageBalances map[string]*destinationLineageInfo: Pre-created destination lineage balances (may be nil).
func (l *Blnk) processAllocations(ctx context.Context, txn *model.Transaction, allocations []Allocation, mappings []model.LineageMapping, sourceBalance, destinationBalance, sourceAggBalance *model.Balance, destLineageBalances map[string]*destinationLineageInfo) {
for i, alloc := range allocations {
if alloc.Amount.Cmp(big.NewInt(0)) == 0 {
continue
}
mapping := l.findMappingByShadowID(mappings, alloc.BalanceID)
if mapping == nil {
continue
}
if err := l.queueReleaseTransaction(ctx, txn, alloc, mapping, sourceBalance, sourceAggBalance, i); err != nil {
logrus.Errorf("failed to queue release transaction: %v", err)
continue
}
if err := l.processDestinationLineage(ctx, txn, alloc, mapping, sourceBalance, destinationBalance, destLineageBalances, i); err != nil {
logrus.Errorf("failed to process destination lineage: %v", err)
// Continue processing other allocations even if one fails
}
}
}
// queueReleaseTransaction queues a transaction to release funds from the aggregate balance back to a shadow balance.
//
// Parameters:
// - ctx context.Context: The context for the operation.
// - txn *model.Transaction: The original transaction.
// - alloc Allocation: The allocation details.
// - mapping *model.LineageMapping: The lineage mapping for the provider.
// - sourceBalance *model.Balance: The source balance.
// - sourceAggBalance *model.Balance: The source aggregate balance.
// - index int: The allocation index for reference uniqueness.
//
// Returns:
// - error: An error if the transaction could not be queued.
func (l *Blnk) queueReleaseTransaction(ctx context.Context, txn *model.Transaction, alloc Allocation, mapping *model.LineageMapping, sourceBalance, sourceAggBalance *model.Balance, index int) error {
releaseTxn := &model.Transaction{
Source: sourceAggBalance.BalanceID,
Destination: alloc.BalanceID,
PreciseAmount: new(big.Int).Set(alloc.Amount),
Currency: sourceBalance.Currency,
Precision: txn.Precision,
Reference: fmt.Sprintf("%s_release_%s_%d", txn.Reference, mapping.Provider, index),
Description: fmt.Sprintf("Release %s funds", mapping.Provider),
MetaData: map[string]interface{}{
"_shadow_for": txn.TransactionID,
"_provider": mapping.Provider,
"_lineage_type": "release",
"_main_balance": sourceBalance.BalanceID,
"_allocation": sourceBalance.AllocationStrategy,
},
SkipQueue: true,
Inflight: txn.Inflight,
}
_, err := l.QueueTransaction(ctx, releaseTxn)
return err
}
// processDestinationLineage processes lineage tracking for the destination balance when it also tracks fund lineage.
// Uses pre-created destination balances to avoid nested lock acquisition (locks are already held by caller).
//
// Parameters:
// - ctx context.Context: The context for the operation.
// - txn *model.Transaction: The original transaction.
// - alloc Allocation: The allocation details.
// - mapping *model.LineageMapping: The lineage mapping for the provider.
// - sourceBalance *model.Balance: The source balance.
// - destinationBalance *model.Balance: The destination balance.
// - destLineageBalances map[string]*destinationLineageInfo: Pre-created destination lineage balances (may be nil).
// - index int: The allocation index for reference uniqueness.
//
// Returns:
// - error: An error if destination lineage processing fails.
func (l *Blnk) processDestinationLineage(ctx context.Context, txn *model.Transaction, alloc Allocation, mapping *model.LineageMapping, sourceBalance, destinationBalance *model.Balance, destLineageBalances map[string]*destinationLineageInfo, index int) error {
if destinationBalance == nil || !destinationBalance.TrackFundLineage || destinationBalance.IdentityID == "" {
return nil
}
// Use pre-created destination balances (locks already held by caller)
if destLineageBalances == nil {
return nil
}
destInfo, ok := destLineageBalances[mapping.Provider]
if !ok || destInfo == nil {
return nil
}
destShadowBalance := destInfo.shadowBalance
destAggBalance := destInfo.aggregateBalance
if err := l.queueReceiveTransaction(ctx, txn, alloc, mapping, sourceBalance, destinationBalance, destShadowBalance, destAggBalance, index); err != nil {
return fmt.Errorf("failed to queue receive transaction: %w", err)
}
destMapping := model.LineageMapping{
BalanceID: destinationBalance.BalanceID,
Provider: mapping.Provider,
ShadowBalanceID: destShadowBalance.BalanceID,
AggregateBalanceID: destAggBalance.BalanceID,
IdentityID: destinationBalance.IdentityID,
}
if err := l.datasource.UpsertLineageMapping(ctx, destMapping); err != nil {
return fmt.Errorf("failed to upsert destination lineage mapping: %w", err)
}
return nil
}
// getOrCreateDestinationLineageBalances retrieves or creates shadow and aggregate balances for the destination.
//
// Parameters:
// - ctx context.Context: The context for the operation.
// - provider string: The fund provider identifier.
// - destinationBalance *model.Balance: The destination balance.
//
// Returns:
// - *model.Balance: The destination shadow balance.
// - *model.Balance: The destination aggregate balance.
// - error: An error if the balances could not be retrieved or created.
func (l *Blnk) getOrCreateDestinationLineageBalances(ctx context.Context, provider string, destinationBalance *model.Balance) (*model.Balance, *model.Balance, error) {
destIdentity, err := l.datasource.GetIdentityByID(destinationBalance.IdentityID)
if err != nil {
return nil, nil, fmt.Errorf("failed to get destination identity: %w", err)
}
destIdentifier := l.getIdentityIdentifier(destIdentity)
destShadowIndicator := fmt.Sprintf("@%s_%s_lineage", provider, destIdentifier)
destAggIndicator := fmt.Sprintf("@%s_lineage", destIdentifier)
destShadowBalance, err := l.getOrCreateBalanceByIndicator(ctx, destShadowIndicator, destinationBalance.Currency)
if err != nil {
return nil, nil, fmt.Errorf("failed to create destination shadow balance: %w", err)
}
destAggBalance, err := l.getOrCreateBalanceByIndicator(ctx, destAggIndicator, destinationBalance.Currency)
if err != nil {
return nil, nil, fmt.Errorf("failed to create destination aggregate balance: %w", err)
}
return destShadowBalance, destAggBalance, nil
}
// queueReceiveTransaction queues a transaction to receive funds into the destination's shadow balance.
//
// Parameters:
// - ctx context.Context: The context for the operation.
// - txn *model.Transaction: The original transaction.
// - alloc Allocation: The allocation details.
// - mapping *model.LineageMapping: The lineage mapping for the provider.
// - sourceBalance *model.Balance: The source balance.
// - destinationBalance *model.Balance: The destination balance.
// - destShadowBalance *model.Balance: The destination shadow balance.
// - destAggBalance *model.Balance: The destination aggregate balance.
// - allocAmount float64: The allocation amount as a float.
// - index int: The allocation index for reference uniqueness.
//
// Returns:
// - error: An error if the transaction could not be queued.
func (l *Blnk) queueReceiveTransaction(ctx context.Context, txn *model.Transaction, alloc Allocation, mapping *model.LineageMapping, sourceBalance, destinationBalance, destShadowBalance, destAggBalance *model.Balance, index int) error {
receiveTxn := &model.Transaction{
Source: destShadowBalance.BalanceID,
Destination: destAggBalance.BalanceID,
PreciseAmount: new(big.Int).Set(alloc.Amount),
Currency: destinationBalance.Currency,
Precision: txn.Precision,
Reference: fmt.Sprintf("%s_receive_%s_%d", txn.Reference, mapping.Provider, index),
Description: fmt.Sprintf("Receive %s funds", mapping.Provider),
MetaData: map[string]interface{}{
"_shadow_for": txn.TransactionID,
"_provider": mapping.Provider,
"_lineage_type": "receive",
"_main_balance": destinationBalance.BalanceID,
"_from_balance": sourceBalance.BalanceID,
},
AllowOverdraft: true,
SkipQueue: true,
Inflight: txn.Inflight,
}
_, err := l.QueueTransaction(ctx, receiveTxn)
return err
}
// updateFundAllocationMetadata updates the transaction metadata with fund allocation details.
//
// Parameters:
// - ctx context.Context: The context for the operation.
// - txn *model.Transaction: The transaction to update.
// - allocations []Allocation: The calculated allocations.
// - mappings []model.LineageMapping: The lineage mappings.
func (l *Blnk) updateFundAllocationMetadata(ctx context.Context, txn *model.Transaction, allocations []Allocation, mappings []model.LineageMapping) {
if len(allocations) == 0 {
return
}
fundAllocation := l.buildFundAllocationList(allocations, mappings, txn.Precision)
if len(fundAllocation) == 0 {
return
}
newMetadata := map[string]interface{}{
LineageFundAllocation: fundAllocation,
}
if err := l.datasource.UpdateTransactionMetadata(ctx, txn.TransactionID, newMetadata); err != nil {
logrus.Errorf("failed to update transaction with fund allocation: %v", err)
}
}
// buildFundAllocationList builds a list of fund allocations for metadata storage.
//
// Parameters:
// - allocations []Allocation: The calculated allocations.
// - mappings []model.LineageMapping: The lineage mappings.
// - precision float64: The precision multiplier.
//
// Returns:
// - []map[string]interface{}: The fund allocation list for metadata.
func (l *Blnk) buildFundAllocationList(allocations []Allocation, mappings []model.LineageMapping, precision float64) []map[string]interface{} {
fundAllocation := make([]map[string]interface{}, 0, len(allocations))
for _, alloc := range allocations {
mapping := l.findMappingByShadowID(mappings, alloc.BalanceID)
if mapping == nil {
continue
}
fundAllocation = append(fundAllocation, map[string]interface{}{
"provider": mapping.Provider,
"amount": alloc.Amount,
})
}
return fundAllocation
}
// getIdentityIdentifier generates a unique identifier string for an identity.
// It uses the identity's name (first/last or organization) combined with a portion of the ID.
//
// Parameters:
// - identity *model.Identity: The identity to generate an identifier for.
//
// Returns:
// - string: The generated identifier.
func (l *Blnk) getIdentityIdentifier(identity *model.Identity) string {
var namePart string
if identity.FirstName != "" && identity.LastName != "" {
namePart = strings.ToLower(fmt.Sprintf("%s_%s", identity.FirstName, identity.LastName))
} else if identity.OrganizationName != "" {
namePart = strings.ToLower(strings.ReplaceAll(identity.OrganizationName, " ", "_"))
} else {
// No name available, use full ID
return identity.IdentityID
}
// Use first 8 characters of ID for uniqueness
idPart := identity.IdentityID
if len(idPart) > 8 {
idPart = idPart[:8]
}
return fmt.Sprintf("%s_%s", namePart, idPart)
}
// getLineageSources retrieves the available fund sources from shadow balances for allocation.
// Uses a single batch query to fetch all shadow balances instead of N individual queries.
//
// Parameters:
// - ctx context.Context: The context for the operation.
// - mappings []model.LineageMapping: The lineage mappings to get sources from.
//
// Returns:
// - []LineageSource: The available fund sources.
// - error: An error if the sources could not be retrieved.
func (l *Blnk) getLineageSources(ctx context.Context, mappings []model.LineageMapping) ([]LineageSource, error) {
if len(mappings) == 0 {
return nil, nil
}
// Collect all shadow balance IDs for batch query
shadowBalanceIDs := make([]string, 0, len(mappings))
for _, mapping := range mappings {
shadowBalanceIDs = append(shadowBalanceIDs, mapping.ShadowBalanceID)
}
// Fetch all shadow balances in a single query
balances, err := l.datasource.GetBalancesByIDsLite(ctx, shadowBalanceIDs)
if err != nil {
return nil, fmt.Errorf("failed to fetch shadow balances: %w", err)
}
// Build sources from the fetched balances
var sources []LineageSource
for _, mapping := range mappings {
balance, exists := balances[mapping.ShadowBalanceID]
if !exists {
continue
}
if balance.DebitBalance != nil && balance.CreditBalance != nil && balance.DebitBalance.Cmp(big.NewInt(0)) > 0 {
available := new(big.Int).Sub(balance.DebitBalance, balance.CreditBalance)
if available.Cmp(big.NewInt(0)) > 0 {
sources = append(sources, LineageSource{
BalanceID: mapping.ShadowBalanceID,
Balance: available,
CreatedAt: mapping.CreatedAt,
})
}
}
}
return sources, nil
}
// calculateAllocation calculates fund allocations based on the specified strategy.
// Supported strategies are FIFO, LIFO, and PROPORTIONAL.
//
// Parameters:
// - sources []LineageSource: The available fund sources.
// - amount *big.Int: The amount to allocate.
// - strategy string: The allocation strategy (FIFO, LIFO, or PROPORTIONAL).
//
// Returns:
// - []Allocation: The calculated allocations.
func (l *Blnk) calculateAllocation(sources []LineageSource, amount *big.Int, strategy string) []Allocation {
if len(sources) == 0 {
return nil
}
switch strategy {
case AllocationLIFO:
sort.Slice(sources, func(i, j int) bool {
return sources[i].CreatedAt.After(sources[j].CreatedAt)
})
return l.sequentialAllocation(sources, amount)
case AllocationProp:
return l.proportionalAllocation(sources, amount)
default:
sort.Slice(sources, func(i, j int) bool {
return sources[i].CreatedAt.Before(sources[j].CreatedAt)
})
return l.sequentialAllocation(sources, amount)
}
}
// sequentialAllocation allocates funds sequentially from sources (used for FIFO/LIFO).
//
// Parameters:
// - sources []LineageSource: The available fund sources in order.
// - amount *big.Int: The amount to allocate.
//
// Returns:
// - []Allocation: The calculated allocations.
func (l *Blnk) sequentialAllocation(sources []LineageSource, amount *big.Int) []Allocation {
var allocations []Allocation
// Skip if amount is zero or negative
if amount.Cmp(big.NewInt(0)) <= 0 {
return nil
}
remaining := new(big.Int).Set(amount)
for _, source := range sources {
if remaining.Cmp(big.NewInt(0)) <= 0 {
break
}
alloc := new(big.Int)
if source.Balance.Cmp(remaining) >= 0 {
alloc.Set(remaining)
} else {
alloc.Set(source.Balance)
}
// Skip zero allocations
if alloc.Cmp(big.NewInt(0)) <= 0 {
continue
}
allocations = append(allocations, Allocation{
BalanceID: source.BalanceID,
Amount: alloc,
})
remaining.Sub(remaining, alloc)
}
// Log warning if we couldn't allocate the full amount
if remaining.Cmp(big.NewInt(0)) > 0 {
logrus.Warnf("sequential allocation: could not allocate full amount, %s remaining unallocated", remaining.String())
}
return allocations
}
// proportionalAllocation allocates funds proportionally across all sources.
//
// Parameters:
// - sources []LineageSource: The available fund sources.
// - amount *big.Int: The amount to allocate.
//
// Returns:
// - []Allocation: The calculated allocations.
func (l *Blnk) proportionalAllocation(sources []LineageSource, amount *big.Int) []Allocation {
var allocations []Allocation
// Skip if amount is zero or negative
if amount.Cmp(big.NewInt(0)) <= 0 {
return nil
}
total := big.NewInt(0)
for _, source := range sources {
total.Add(total, source.Balance)
}
if total.Cmp(big.NewInt(0)) == 0 {
return nil
}
// Cap amount at total available to prevent over-allocation
effectiveAmount := new(big.Int).Set(amount)
if effectiveAmount.Cmp(total) > 0 {
logrus.Warnf("proportional allocation: requested amount %s exceeds total available %s, capping at available", amount.String(), total.String())
effectiveAmount.Set(total)
}
remaining := new(big.Int).Set(effectiveAmount)
for i, source := range sources {
var alloc *big.Int
if i == len(sources)-1 {
// Last source gets the remainder to handle rounding
alloc = new(big.Int).Set(remaining)
} else {
// Calculate proportional share: (effectiveAmount * source.Balance) / total