-
-
Notifications
You must be signed in to change notification settings - Fork 107
Expand file tree
/
Copy pathbalance.go
More file actions
662 lines (583 loc) · 22.7 KB
/
balance.go
File metadata and controls
662 lines (583 loc) · 22.7 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
/*
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"
"strings"
"time"
"github.com/blnkfinance/blnk/config"
"github.com/blnkfinance/blnk/internal/filter"
"github.com/blnkfinance/blnk/internal/metrics"
"github.com/blnkfinance/blnk/internal/notification"
"github.com/blnkfinance/blnk/model"
"github.com/sirupsen/logrus"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
)
// balanceTracer is an OpenTelemetry tracer for tracking balance-related transactions.
var (
balanceTracer = otel.Tracer("blnk.transactions")
)
// NewBalanceTracker creates a new BalanceTracker instance.
// It initializes the Balances and Frequencies maps.
//
// Returns:
// - *model.BalanceTracker: A pointer to the newly created BalanceTracker instance.
func NewBalanceTracker() *model.BalanceTracker {
return &model.BalanceTracker{
Balances: make(map[string]*model.Balance),
Frequencies: make(map[string]int),
}
}
// checkBalanceMonitors checks the balance monitors for a given updated balance.
// It starts a tracing span, fetches the monitors, and checks each monitor's condition.
// If a condition is met, it sends a webhook notification.
//
// Parameters:
// - ctx context.Context: The context for the operation.
// - updatedBalance *model.Balance: A pointer to the updated Balance model.
func (l *Blnk) checkBalanceMonitors(ctx context.Context, updatedBalance *model.Balance) {
_, span := balanceTracer.Start(ctx, "CheckBalanceMonitors")
defer span.End()
// Fetch monitors using cache (avoids DB query on every transaction)
monitors, err := l.getBalanceMonitorsCached(ctx, updatedBalance.BalanceID)
if err != nil {
span.RecordError(err)
notification.NotifyError(err)
return
}
// Check each monitor's condition
for _, monitor := range monitors {
if monitor.CheckCondition(updatedBalance) {
span.AddEvent(fmt.Sprintf("Condition met for balance: %s", monitor.MonitorID))
go func(monitor model.BalanceMonitor) {
err := l.SendWebhook(NewWebhook{
Event: "balance.monitor",
Payload: monitor,
})
if err != nil {
notification.NotifyError(err)
}
}(monitor)
}
}
}
// getBalanceMonitorsCached retrieves balance monitors with caching.
// It first checks the cache for monitors, and if not found, fetches from the database
// and caches the result with a 5-minute TTL.
//
// Parameters:
// - ctx context.Context: The context for the operation.
// - balanceID string: The ID of the balance to get monitors for.
//
// Returns:
// - []model.BalanceMonitor: A slice of monitors for the balance.
// - error: An error if the monitors could not be retrieved.
func (l *Blnk) getBalanceMonitorsCached(ctx context.Context, balanceID string) ([]model.BalanceMonitor, error) {
cacheKey := "monitors:" + balanceID
var monitors []model.BalanceMonitor
err := l.cache.Get(ctx, cacheKey, &monitors)
if err == nil && monitors != nil {
return monitors, nil
}
monitors, err = l.datasource.GetBalanceMonitors(balanceID)
if err != nil {
return nil, err
}
if monitors == nil {
monitors = []model.BalanceMonitor{}
}
_ = l.cache.Set(ctx, cacheKey, monitors, 5*time.Minute)
return monitors, nil
}
// getOrCreateBalanceByIndicator retrieves a balance by its indicator and currency.
// If the balance does not exist, it creates a new one.
// It starts a tracing span, fetches or creates the balance, and records relevant events.
// When EnableQueuedChecks is enabled in the transaction config, it will fetch the balance with queued data included.
//
// Parameters:
// - ctx context.Context: The context for the operation.
// - indicator string: The indicator for the balance.
// - currency string: The currency for the balance.
//
// Returns:
// - *model.Balance: A pointer to the Balance model.
// - error: An error if the balance could not be retrieved or created.
func (l *Blnk) getOrCreateBalanceByIndicator(ctx context.Context, indicator, currency string) (*model.Balance, error) {
ctx, span := balanceTracer.Start(ctx, "GetOrCreateBalanceByIndicator")
defer span.End()
// Get configuration to check if queued checks are enabled
cfg, err := config.Fetch()
if err != nil {
span.RecordError(err)
logrus.Errorf("failed to fetch config: %v", err)
return nil, err
}
balance, err := l.datasource.GetBalanceByIndicator(indicator, currency)
if err != nil {
span.AddEvent("Creating new balance")
balance = &model.Balance{
Indicator: indicator,
LedgerID: GeneralLedgerID,
Currency: currency,
}
_, err := l.CreateBalance(ctx, *balance)
if err != nil && !strings.Contains(err.Error(), "Balance already exist") {
span.RecordError(err)
return nil, err
}
balance, err = l.datasource.GetBalanceByIndicator(indicator, currency)
if err != nil {
span.RecordError(err)
return nil, err
}
span.AddEvent("New balance created", trace.WithAttributes(attribute.String("balance.id", balance.BalanceID)))
// If queued checks are enabled, fetch the balance with queued data
if cfg.Transaction.EnableQueuedChecks {
balance, err = l.datasource.GetBalanceByID(balance.BalanceID, []string{}, true)
if err != nil {
span.RecordError(err)
return nil, err
}
}
return balance, nil
}
// If queued checks are enabled, fetch the balance with queued data
if cfg.Transaction.EnableQueuedChecks {
balance, err = l.datasource.GetBalanceByID(balance.BalanceID, []string{}, true)
if err != nil {
span.RecordError(err)
return nil, err
}
}
span.AddEvent("Balance found", trace.WithAttributes(attribute.String("balance.id", balance.BalanceID)))
return balance, nil
}
// postBalanceActions performs some actions after a balance has been created.
// It starts a tracing span, sends the balance to the search index queue, and sends a webhook notification.
//
// Parameters:
// - ctx context.Context: The context for the operation.
// - balance *model.Balance: A pointer to the newly created Balance model.
func (l *Blnk) postBalanceActions(ctx context.Context, balance *model.Balance) {
_, span := balanceTracer.Start(ctx, "PostBalanceActions")
defer span.End()
go func() {
err := l.queue.queueIndexData(balance.BalanceID, "balances", balance)
if err != nil {
span.RecordError(err)
notification.NotifyError(err)
}
err = l.SendWebhook(NewWebhook{
Event: "balance.created",
Payload: balance,
})
if err != nil {
span.RecordError(err)
notification.NotifyError(err)
}
span.AddEvent("Post balance actions completed", trace.WithAttributes(attribute.String("balance.id", balance.BalanceID)))
}()
}
// CreateBalance creates a new balance.
// It starts a tracing span, creates the balance, and performs post-creation actions.
//
// Parameters:
// - ctx context.Context: The context for the operation.
// - balance model.Balance: The Balance model to be created.
//
// Returns:
// - model.Balance: The created Balance model.
// - error: An error if the balance could not be created.
func (l *Blnk) CreateBalance(ctx context.Context, balance model.Balance) (model.Balance, error) {
ctx, span := balanceTracer.Start(ctx, "CreateBalance")
defer span.End()
balance, err := l.datasource.CreateBalance(balance)
if err != nil {
span.RecordError(err)
return model.Balance{}, err
}
l.postBalanceActions(ctx, &balance)
metrics.BalanceCreatedTotal.Add(ctx, 1)
span.AddEvent("Balance created", trace.WithAttributes(attribute.String("balance.id", balance.BalanceID)))
return balance, nil
}
// GetBalanceByID retrieves a balance by its ID.
// It starts a tracing span, fetches the balance, and records relevant events.
//
// Parameters:
// - ctx context.Context: The context for the operation.
// - id string: The ID of the balance to retrieve.
// - include []string: A slice of strings specifying additional data to include.
//
// Returns:
// - *model.Balance: A pointer to the Balance model if found.
// - error: An error if the balance could not be retrieved.
func (l *Blnk) GetBalanceByID(ctx context.Context, id string, include []string, withQueued bool) (*model.Balance, error) {
_, span := balanceTracer.Start(ctx, "GetBalanceByID")
defer span.End()
balance, err := l.datasource.GetBalanceByID(id, include, withQueued)
if err != nil {
span.RecordError(err)
return nil, err
}
span.AddEvent("Balance retrieved", trace.WithAttributes(attribute.String("balance.id", id)))
return balance, nil
}
// GetAllBalances retrieves all balances.
// It starts a tracing span, fetches all balances, and records relevant events.
//
// Parameters:
// - ctx context.Context: The context for the operation.
//
// Returns:
// - []model.Balance: A slice of Balance models.
// - error: An error if the balances could not be retrieved.
func (l *Blnk) GetAllBalances(ctx context.Context, limit, offset int) ([]model.Balance, error) {
_, span := balanceTracer.Start(ctx, "GetAllBalances")
defer span.End()
balances, err := l.datasource.GetAllBalances(limit, offset)
if err != nil {
span.RecordError(err)
return nil, err
}
span.AddEvent("All balances retrieved", trace.WithAttributes(attribute.Int("balance.count", len(balances))))
return balances, nil
}
// GetAllBalancesWithFilter retrieves balances using advanced filters.
// It starts a tracing span, fetches balances matching the filter criteria, and records relevant events.
//
// Parameters:
// - ctx context.Context: The context for the operation.
// - filters *filter.QueryFilterSet: Filter conditions to apply.
// - limit int: Maximum number of balances to return.
// - offset int: Offset for pagination.
//
// Returns:
// - []model.Balance: A slice of Balance models matching the filter criteria.
// - error: An error if the balances could not be retrieved.
func (l *Blnk) GetAllBalancesWithFilter(ctx context.Context, filters *filter.QueryFilterSet, limit, offset int) ([]model.Balance, error) {
_, span := balanceTracer.Start(ctx, "GetAllBalancesWithFilter")
defer span.End()
balances, err := l.datasource.GetAllBalancesWithFilter(ctx, filters, limit, offset)
if err != nil {
span.RecordError(err)
return nil, err
}
span.AddEvent("Balances with filter retrieved", trace.WithAttributes(attribute.Int("balance.count", len(balances))))
return balances, nil
}
// GetAllBalancesWithFilterAndOptions retrieves balances with advanced filters, sorting, and optional count.
func (l *Blnk) GetAllBalancesWithFilterAndOptions(ctx context.Context, filters *filter.QueryFilterSet, opts *filter.QueryOptions, limit, offset int) ([]model.Balance, *int64, error) {
_, span := balanceTracer.Start(ctx, "GetAllBalancesWithFilterAndOptions")
defer span.End()
balances, count, err := l.datasource.GetAllBalancesWithFilterAndOptions(ctx, filters, opts, limit, offset)
if err != nil {
span.RecordError(err)
return nil, nil, err
}
span.AddEvent("Balances with filter and options retrieved", trace.WithAttributes(attribute.Int("balance.count", len(balances))))
return balances, count, nil
}
// CreateMonitor creates a new balance monitor.
// It starts a tracing span, applies precision to the monitor's condition value, and creates the monitor.
// It records relevant events and errors.
//
// Parameters:
// - ctx context.Context: The context for the operation.
// - monitor model.BalanceMonitor: The BalanceMonitor model to be created.
//
// Returns:
// - model.BalanceMonitor: The created BalanceMonitor model.
// - error: An error if the monitor could not be created.
func (l *Blnk) CreateMonitor(ctx context.Context, monitor model.BalanceMonitor) (model.BalanceMonitor, error) {
_, span := balanceTracer.Start(ctx, "CreateMonitor")
defer span.End()
amount := int64(monitor.Condition.Value * monitor.Condition.Precision) // apply precision to value
amountBigInt := model.Int64ToBigInt(amount)
monitor.Condition.PreciseValue = amountBigInt
monitor, err := l.datasource.CreateMonitor(monitor)
if err != nil {
span.RecordError(err)
return model.BalanceMonitor{}, err
}
_ = l.cache.Delete(ctx, "monitors:"+monitor.BalanceID)
span.AddEvent("Monitor created", trace.WithAttributes(attribute.String("monitor.id", monitor.MonitorID)))
return monitor, nil
}
// GetMonitorByID retrieves a balance monitor by its ID.
// It starts a tracing span, fetches the monitor, and records relevant events.
//
// Parameters:
// - ctx context.Context: The context for the operation.
// - id string: The ID of the monitor to retrieve.
//
// Returns:
// - *model.BalanceMonitor: A pointer to the BalanceMonitor model if found.
// - error: An error if the monitor could not be retrieved.
func (l *Blnk) GetMonitorByID(ctx context.Context, id string) (*model.BalanceMonitor, error) {
_, span := balanceTracer.Start(ctx, "GetMonitorByID")
defer span.End()
monitor, err := l.datasource.GetMonitorByID(id)
if err != nil {
span.RecordError(err)
return nil, err
}
span.AddEvent("Monitor retrieved", trace.WithAttributes(attribute.String("monitor.id", id)))
return monitor, nil
}
// GetAllMonitors retrieves all balance monitors.
// It starts a tracing span, fetches all monitors, and records relevant events.
//
// Parameters:
// - ctx context.Context: The context for the operation.
//
// Returns:
// - []model.BalanceMonitor: A slice of BalanceMonitor models.
// - error: An error if the monitors could not be retrieved.
func (l *Blnk) GetAllMonitors(ctx context.Context) ([]model.BalanceMonitor, error) {
_, span := balanceTracer.Start(ctx, "GetAllMonitors")
defer span.End()
monitors, err := l.datasource.GetAllMonitors()
if err != nil {
span.RecordError(err)
return nil, err
}
span.AddEvent("All monitors retrieved", trace.WithAttributes(attribute.Int("monitor.count", len(monitors))))
return monitors, nil
}
// GetBalanceMonitors retrieves all monitors for a given balance ID.
// It starts a tracing span, fetches the monitors, and records relevant events.
//
// Parameters:
// - ctx context.Context: The context for the operation.
// - balanceID string: The ID of the balance for which to retrieve monitors.
//
// Returns:
// - []model.BalanceMonitor: A slice of BalanceMonitor models.
// - error: An error if the monitors could not be retrieved.
func (l *Blnk) GetBalanceMonitors(ctx context.Context, balanceID string) ([]model.BalanceMonitor, error) {
_, span := balanceTracer.Start(ctx, "GetBalanceMonitors")
defer span.End()
monitors, err := l.datasource.GetBalanceMonitors(balanceID)
if err != nil {
span.RecordError(err)
return nil, err
}
span.AddEvent("Monitors retrieved for balance", trace.WithAttributes(attribute.String("balance.id", balanceID), attribute.Int("monitor.count", len(monitors))))
return monitors, nil
}
// UpdateMonitor updates an existing balance monitor.
// It starts a tracing span, updates the monitor, and records relevant events and errors.
//
// Parameters:
// - ctx context.Context: The context for the operation.
// - monitor *model.BalanceMonitor: A pointer to the BalanceMonitor model to be updated.
//
// Returns:
// - error: An error if the monitor could not be updated.
func (l *Blnk) UpdateMonitor(ctx context.Context, monitor *model.BalanceMonitor) error {
_, span := balanceTracer.Start(ctx, "UpdateMonitor")
defer span.End()
err := l.datasource.UpdateMonitor(monitor)
if err != nil {
span.RecordError(err)
return err
}
_ = l.cache.Delete(ctx, "monitors:"+monitor.BalanceID)
span.AddEvent("Monitor updated", trace.WithAttributes(attribute.String("monitor.id", monitor.MonitorID)))
return nil
}
// DeleteMonitor deletes a balance monitor by its ID.
// It starts a tracing span, deletes the monitor, and records relevant events and errors.
//
// Parameters:
// - ctx context.Context: The context for the operation.
// - id string: The ID of the monitor to delete.
//
// Returns:
// - error: An error if the monitor could not be deleted.
func (l *Blnk) DeleteMonitor(ctx context.Context, id string) error {
_, span := balanceTracer.Start(ctx, "DeleteMonitor")
defer span.End()
monitor, err := l.datasource.GetMonitorByID(id)
if err != nil {
span.RecordError(err)
return err
}
err = l.datasource.DeleteMonitor(id)
if err != nil {
span.RecordError(err)
return err
}
_ = l.cache.Delete(ctx, "monitors:"+monitor.BalanceID)
span.AddEvent("Monitor deleted", trace.WithAttributes(attribute.String("monitor.id", id)))
return nil
}
// TakeBalanceSnapshots creates daily snapshots of balances in batches.
// It accepts a batch size parameter to control the number of balances processed at once,
// helping to manage memory usage for large datasets.
//
// Parameters:
// - ctx context.Context: The context for managing the operation's lifecycle and cancellation
// - batchSize int: The number of balances to process in each batch
//
// Returns:
// - int: The total number of snapshots created
// - error: An error if the snapshot creation fails
func (l *Blnk) TakeBalanceSnapshots(ctx context.Context, batchSize int) {
go func() {
startTime := time.Now()
// Log the start of snapshot operation
logrus.WithFields(logrus.Fields{
"batch_size": batchSize,
"operation": "balance_snapshots",
"status": "started",
"timestamp": startTime.Format(time.RFC3339),
}).Info("Balance snapshot operation starting")
_, span := balanceTracer.Start(ctx, "TakeBalanceSnapshots")
defer span.End()
// Call the datasource method to create snapshots
total, err := l.datasource.TakeBalanceSnapshots(context.Background(), batchSize)
// Calculate duration
duration := time.Since(startTime)
if err != nil {
// Log error with details
logrus.WithFields(logrus.Fields{
"batch_size": batchSize,
"operation": "balance_snapshots",
"status": "failed",
"duration_ms": duration.Milliseconds(),
"error": err.Error(),
}).Error("Balance snapshot operation failed")
span.RecordError(err)
return
}
// Log successful completion with metrics
logrus.WithFields(logrus.Fields{
"batch_size": batchSize,
"operation": "balance_snapshots",
"status": "completed",
"total_snapshots": total,
"duration_ms": duration.Milliseconds(),
"snapshots_per_second": float64(total) / duration.Seconds(),
"timestamp": time.Now().Format(time.RFC3339),
}).Info("Balance snapshot operation completed successfully")
span.AddEvent("Balance snapshots created", trace.WithAttributes(
attribute.Int("total_snapshots", total),
attribute.Int("batch_size", batchSize),
attribute.Int64("duration_ms", duration.Milliseconds()),
attribute.Float64("snapshots_per_second", float64(total)/duration.Seconds()),
))
}()
}
// GetBalanceAtTime retrieves a balance's state at a specific point in time.
// It can either use balance snapshots for efficiency or calculate from all source transactions
// based on the fromSource parameter.
//
// Parameters:
// - ctx context.Context: The context for the operation.
// - balanceID string: The ID of the balance to retrieve.
// - targetTime time.Time: The point in time for which to retrieve the balance state.
// - fromSource bool: If true, calculates balance from all transactions instead of using snapshots.
//
// Returns:
// - *model.Balance: A pointer to the Balance model representing the state at the given time.
// - error: An error if the historical balance state could not be retrieved.
func (l *Blnk) GetBalanceAtTime(ctx context.Context, balanceID string, targetTime time.Time, fromSource bool) (*model.Balance, error) {
_, span := balanceTracer.Start(ctx, "GetBalanceAtTime")
defer span.End()
span.SetAttributes(
attribute.String("balance.id", balanceID),
attribute.String("target.time", targetTime.String()),
attribute.Bool("from.source", fromSource),
)
if fromSource {
span.AddEvent("Calculating balance from source transactions")
} else {
span.AddEvent("Using snapshots to calculate balance")
}
balance, err := l.datasource.GetBalanceAtTime(ctx, balanceID, targetTime, fromSource)
if err != nil {
span.RecordError(err)
return nil, fmt.Errorf("failed to get balance at time: %w", err)
}
if balance == nil {
span.AddEvent("No balance data found for the specified time")
return nil, fmt.Errorf("no balance data found for time: %v", targetTime)
}
calculationMethod := "snapshot-based"
if fromSource {
calculationMethod = "transaction-based"
}
span.AddEvent("Historical balance state retrieved", trace.WithAttributes(
attribute.String("balance.id", balance.BalanceID),
attribute.String("snapshot.time", targetTime.String()),
attribute.String("calculation.method", calculationMethod),
))
return balance, nil
}
// GetBalanceByIndicator retrieves a balance by its indicator and currency.
// It starts a tracing span, fetches the balance, and records relevant events.
//
// Parameters:
// - ctx context.Context: The context for the operation.
// - indicator string: The indicator of the balance to retrieve.
// - currency string: The currency of the balance to retrieve.
//
// Returns:
// - *model.Balance: A pointer to the Balance model if found.
// - error: An error if the balance could not be retrieved.
func (l *Blnk) GetBalanceByIndicator(ctx context.Context, indicator, currency string) (*model.Balance, error) {
_, span := balanceTracer.Start(ctx, "GetBalanceByIndicator")
defer span.End()
span.SetAttributes(
attribute.String("balance.indicator", indicator),
attribute.String("balance.currency", currency),
)
balance, err := l.datasource.GetBalanceByIndicator(indicator, currency)
if err != nil {
span.RecordError(err)
return nil, err
}
span.AddEvent("Balance retrieved by indicator", trace.WithAttributes(attribute.String("balance.id", balance.BalanceID)))
return balance, nil
}
// UpdateBalanceIdentity updates only the identity_id associated with a balance.
// It validates that both the balance and the identity exist before applying the change.
//
// Parameters:
// - balanceID string: The ID of the balance whose identity reference should be modified.
// - identityID string: The new identity ID to associate with the balance.
//
// Returns:
// - error: An error is returned if either the balance or identity records are not found or the update fails.
func (l *Blnk) UpdateBalanceIdentity(balanceID, identityID string) error {
// Ensure the referenced identity exists
_, err := l.datasource.GetIdentityByID(identityID)
if err != nil {
return fmt.Errorf("identity validation failed: %w", err)
}
// Ensure the balance exists (lite lookup)
_, err = l.datasource.GetBalanceByIDLite(balanceID)
if err != nil {
return fmt.Errorf("balance validation failed: %w", err)
}
// Apply the update
if err := l.datasource.UpdateBalanceIdentity(balanceID, identityID); err != nil {
return err
}
return nil
}