Repository navigation
Expand file tree
/
Copy pathlineage_debit.go
More file actions
439 lines (385 loc) · 17.3 KB
/
Copy pathlineage_debit.go
File metadata and controls
439 lines (385 loc) · 17.3 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
/*
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"
"fmt"
"math/big"
redlock "github.com/blnkfinance/blnk/internal/lock"
"github.com/blnkfinance/blnk/model"
"github.com/sirupsen/logrus"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
)
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)
}
remaining, err := l.remainingDebitAmount(ctx, txn, mappings)
if err != nil {
return err
}
if remaining.Sign() <= 0 {
span.AddEvent("Lineage debit already fully processed; nothing to allocate")
return nil
}
allocations := l.calculateAllocation(sources, remaining, sourceBalance.AllocationStrategy)
sourceAggBalance, err := l.getSourceAggregateBalance(ctx, sourceBalance)
if err != nil {
return err
}
if err := l.processAllocations(ctx, txn, allocations, mappings, sourceBalance, destinationBalance, sourceAggBalance, destLineageBalances); err != nil {
return err
}
l.updateFundAllocationMetadata(ctx, txn, allocations, mappings)
span.AddEvent("Lineage debit processed", trace.WithAttributes(attribute.Int("allocations", len(allocations))))
return nil
}
// releaseReference and receiveReference build a provider's shadow transaction
// references, keyed on the parent reference and provider so they are stable
// across retries.
func releaseReference(parentRef, provider string) string {
return fmt.Sprintf("%s_release_%s", parentRef, provider)
}
func receiveReference(parentRef, provider string) string {
return fmt.Sprintf("%s_receive_%s", parentRef, provider)
}
// remainingDebitAmount returns the original debit amount minus any releases
// already persisted for this transaction's providers.
func (l *Blnk) remainingDebitAmount(ctx context.Context, txn *model.Transaction, mappings []model.LineageMapping) (*big.Int, error) {
released := big.NewInt(0)
for _, m := range mappings {
ref := releaseReference(txn.Reference, m.Provider)
exists, err := l.datasource.TransactionExistsByRef(ctx, ref)
if err != nil {
return nil, fmt.Errorf("failed to check release idempotency: %w", err)
}
if !exists {
continue
}
prior, err := l.datasource.GetTransactionByRef(ctx, ref)
if err != nil {
return nil, fmt.Errorf("failed to load prior release %s: %w", ref, err)
}
released.Add(released, prior.PreciseAmount)
}
return new(big.Int).Sub(txn.PreciseAmount, released), 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) error {
for _, alloc := range allocations {
if alloc.Amount.Cmp(big.NewInt(0)) == 0 {
continue
}
mapping := l.findMappingByShadowID(mappings, alloc.BalanceID)
if mapping == nil {
continue
}
exists, err := l.datasource.TransactionExistsByRef(ctx, releaseReference(txn.Reference, mapping.Provider))
if err != nil {
return fmt.Errorf("failed to check release idempotency: %w", err)
}
if exists {
continue
}
if err := l.queueReleaseTransaction(ctx, txn, alloc, mapping, sourceBalance, sourceAggBalance); err != nil {
return fmt.Errorf("failed to queue release transaction: %w", err)
}
if err := l.processDestinationLineage(ctx, txn, alloc, mapping, sourceBalance, destinationBalance, destLineageBalances); err != nil {
return fmt.Errorf("failed to process destination lineage: %w", err)
}
}
return nil
}
// 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) error {
releaseTxn := &model.Transaction{
Source: sourceAggBalance.BalanceID,
Destination: alloc.BalanceID,
PreciseAmount: new(big.Int).Set(alloc.Amount),
Currency: sourceBalance.Currency,
Precision: txn.Precision,
Reference: releaseReference(txn.Reference, mapping.Provider),
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) 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); 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) error {
receiveTxn := &model.Transaction{
Source: destShadowBalance.BalanceID,
Destination: destAggBalance.BalanceID,
PreciseAmount: new(big.Int).Set(alloc.Amount),
Currency: destinationBalance.Currency,
Precision: txn.Precision,
Reference: receiveReference(txn.Reference, mapping.Provider),
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.