forked from StellarGateLabs/StellarGate
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.rs
More file actions
2924 lines (2689 loc) · 108 KB
/
Copy pathdb.rs
File metadata and controls
2924 lines (2689 loc) · 108 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
use anyhow::Result;
use sqlx::{Acquire, Pool, Row, Sqlite};
pub type Db = Pool<Sqlite>;
/// Run `PRAGMA optimize` to update SQLite query planner statistics. Should be
/// called periodically (e.g., at startup after migration and during graceful
/// shutdown) to keep query plans aligned with actual table sizes and
/// distributions. Without this, every index added by the schema is used
/// according to whatever the planner guesses, not what ANALYZE has measured.
pub async fn optimize(pool: &Db) -> Result<()> {
sqlx::query("PRAGMA optimize").execute(pool).await?;
Ok(())
}
/// Normalize a raw SQLite timestamp to strict RFC 3339 UTC with a Z suffix.
///
/// Handles both legacy rows (`"2026-04-29 15:00:00"` / `"2026-04-29T15:00:00"`)
/// and already-correct rows (`"2026-04-29T15:00:00Z"`). Any value that doesn't
/// look like a 19-character datetime is returned unchanged so we never silently
/// corrupt unexpected data.
fn normalize_ts(raw: &str) -> String {
let s = raw.trim();
// Already has an explicit offset/Z — nothing to do.
if s.ends_with('Z') || s.contains('+') {
return s.to_string();
}
// Replace the space separator with T if present, then append Z.
if s.len() == 19 {
let with_t = s.replacen(' ', "T", 1);
return format!("{with_t}Z");
}
s.to_string()
}
/// `LIKE` pattern every stored timestamp must match: strict RFC 3339 UTC with
/// a `Z` suffix and no fractional seconds, e.g. `2026-04-29T15:00:00Z`. `_`
/// matches exactly one character, so this pins the length and the position of
/// every separator without needing per-digit character classes SQLite's
/// dialect of `LIKE` cannot express.
///
/// Backing every timestamp `CHECK` constraint below (issue #314): every write
/// path already produces exactly this format via `strftime('%Y-%m-%dT%H:%M:%SZ',
/// ...)`, so this makes that a guarantee SQLite enforces rather than a
/// convention a future write path could silently break — which is exactly how
/// `expires_at` ended up compared as a lexical string against rows in the
/// legacy `"YYYY-MM-DD HH:MM:SS"` form (no `T`, no `Z`), which sorts *before*
/// every compliant timestamp and so reads as permanently expired.
///
/// Applies only to newly created tables: `CREATE TABLE IF NOT EXISTS` does not
/// retroactively add a constraint to a table that already exists, so an
/// upgrade of a running deployment does not gain this guarantee for rows
/// already on disk — the startup normalisation below is what repairs those.
const TS_PATTERN: &str = "____-__-__T__:__:__Z";
pub async fn migrate(pool: &Db) -> Result<()> {
sqlx::query(&format!(
"CREATE TABLE IF NOT EXISTS payments (
id TEXT PRIMARY KEY,
merchant_id TEXT NOT NULL DEFAULT 'anonymous',
destination_address TEXT NOT NULL,
memo TEXT NOT NULL UNIQUE,
amount TEXT NOT NULL,
asset TEXT NOT NULL DEFAULT 'XLM',
asset_issuer TEXT,
status TEXT NOT NULL DEFAULT 'pending',
webhook_url TEXT,
tx_hash TEXT,
paid_amount TEXT,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now'))
CHECK (created_at LIKE '{TS_PATTERN}'),
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now'))
CHECK (updated_at LIKE '{TS_PATTERN}'),
expires_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now','+1 hour'))
CHECK (expires_at LIKE '{TS_PATTERN}')
)",
))
.execute(pool)
.await?;
/* Bring pre-existing payment tables up to schema. New databases already have
`expires_at` from the CREATE TABLE above; older ones need it added in
place. SQLite rejects a non-constant DEFAULT on ALTER ... ADD COLUMN, so we
add it nullable and backfill below. */
let has_expires_at: i64 = sqlx::query_scalar(
"SELECT COUNT(*) FROM pragma_table_info('payments') WHERE name = 'expires_at'",
)
.fetch_one(&mut *tx)
.await?;
if has_expires_at == 0 {
sqlx::query("ALTER TABLE payments ADD COLUMN expires_at TEXT")
.execute(&mut *tx)
.await?;
}
/* Backfill any row without an expiry (legacy rows, or rows inserted in the
brief window before the column existed). `created_at + 1h` mirrors the
default TTL; SQLite's date functions accept the stored RFC 3339 `Z` form. */
sqlx::query(
"UPDATE payments
SET expires_at = strftime('%Y-%m-%dT%H:%M:%SZ', created_at, '+1 hour')
WHERE expires_at IS NULL",
)
.execute(&mut *tx)
.await?;
/* Pin each intent to the issuer it was priced in. Rows written before this
column existed only stored the asset *code*; `backfill_asset_issuers` fills
them from the current allow-list after config loads (issue #222). */
let has_asset_issuer: i64 = sqlx::query_scalar(
"SELECT COUNT(*) FROM pragma_table_info('payments') WHERE name = 'asset_issuer'",
)
.fetch_one(pool)
.await?;
if has_asset_issuer == 0 {
sqlx::query("ALTER TABLE payments ADD COLUMN asset_issuer TEXT")
.execute(pool)
.await?;
}
sqlx::query("CREATE INDEX IF NOT EXISTS idx_payments_memo ON payments(memo)")
.execute(&mut *tx)
.await?;
sqlx::query("CREATE INDEX IF NOT EXISTS idx_payments_status ON payments(status)")
.execute(&mut *tx)
.await?;
sqlx::query(
"CREATE INDEX IF NOT EXISTS idx_payments_created_id ON payments(created_at DESC, id DESC)",
)
.execute(&mut *tx)
.await?;
sqlx::query(
"CREATE INDEX IF NOT EXISTS idx_payments_status_expires_at ON payments(status, expires_at)
WHERE status IN ('pending', 'underpaid')",
)
.execute(pool)
.await?;
sqlx::query(&format!(
"CREATE TABLE IF NOT EXISTS webhook_deliveries (
id TEXT PRIMARY KEY,
payment_id TEXT NOT NULL,
url TEXT NOT NULL,
payload TEXT NOT NULL,
event_type TEXT,
status TEXT NOT NULL DEFAULT 'pending',
attempts INTEGER NOT NULL DEFAULT 0,
manual_attempts INTEGER NOT NULL DEFAULT 0,
last_attempt TEXT CHECK (last_attempt IS NULL OR last_attempt LIKE '{TS_PATTERN}'),
acknowledged_at TEXT CHECK (acknowledged_at IS NULL OR acknowledged_at LIKE '{TS_PATTERN}'),
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now'))
CHECK (created_at LIKE '{TS_PATTERN}')
)",
))
.execute(pool)
.await?;
/* Bring pre-existing delivery tables up to schema. `event_type` records
which event the payload represents so a redelivery can echo the original
`X-StellarGate-Event` header instead of guessing. Rows written before this
column existed stay NULL; readers fall back to the `event` field inside the
stored payload. */
let has_event_type: i64 = sqlx::query_scalar(
"SELECT COUNT(*) FROM pragma_table_info('webhook_deliveries') WHERE name = 'event_type'",
)
.fetch_one(&mut *tx)
.await?;
if has_event_type == 0 {
sqlx::query("ALTER TABLE webhook_deliveries ADD COLUMN event_type TEXT")
.execute(&mut *tx)
.await?;
}
/* `acknowledged_at` records that somebody has seen a terminal failure and
acted on it — set by the bulk requeue/acknowledge endpoint. It exists so
retention can distinguish "this failure was dealt with" from "nobody has
looked at this yet", and refuse to delete the latter (issue #319). Rows
that predate the column are NULL, i.e. unacknowledged, which is the safe
reading: we do not know that anyone saw them. */
let has_acknowledged_at: i64 = sqlx::query_scalar(
"SELECT COUNT(*) FROM pragma_table_info('webhook_deliveries') WHERE name = 'acknowledged_at'",
)
.fetch_one(pool)
.await?;
if has_acknowledged_at == 0 {
sqlx::query("ALTER TABLE webhook_deliveries ADD COLUMN acknowledged_at TEXT")
.execute(pool)
.await?;
}
/* Manual redeliveries must not share the automatic redrive budget (issue
#235). `manual_attempts` is incremented by POST .../redeliver; the redrive
worker only looks at `attempts`. */
let has_manual_attempts: i64 = sqlx::query_scalar(
"SELECT COUNT(*) FROM pragma_table_info('webhook_deliveries') WHERE name = 'manual_attempts'",
)
.fetch_one(pool)
.await?;
if has_manual_attempts == 0 {
sqlx::query(
"ALTER TABLE webhook_deliveries ADD COLUMN manual_attempts INTEGER NOT NULL DEFAULT 0",
)
.execute(pool)
.await?;
}
/* Durable key/value state — used by the Horizon poller to persist its
paging cursor so it resumes exactly where it left off across restarts. */
sqlx::query(&format!(
"CREATE TABLE IF NOT EXISTS kv_state (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now'))
CHECK (updated_at LIKE '{TS_PATTERN}')
)",
))
.execute(pool)
.await?;
/* Merchants are provisioned via POST /merchants. The raw API key is never
stored; only its SHA-256 hex digest is persisted so a DB breach does not
expose live credentials. */
sqlx::query(&format!(
"CREATE TABLE IF NOT EXISTS merchants (
id TEXT PRIMARY KEY,
api_key_hash TEXT NOT NULL UNIQUE,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now'))
CHECK (created_at LIKE '{TS_PATTERN}')
)",
))
.execute(pool)
.await?;
/* Per-merchant rate-limit override (issue: rate limiter keyed on IP, not
identity). NULL means "use the configured default"; a merchant only gets
a row value once an operator sets one explicitly. */
let has_rate_limit_per_sec: i64 = sqlx::query_scalar(
"SELECT COUNT(*) FROM pragma_table_info('merchants') WHERE name = 'rate_limit_per_sec'",
)
.fetch_one(pool)
.await?;
if has_rate_limit_per_sec == 0 {
sqlx::query("ALTER TABLE merchants ADD COLUMN rate_limit_per_sec INTEGER")
.execute(pool)
.await?;
}
/* API keys, one row per credential rather than one per merchant, so a key
can be rotated (issue a second, revoke the first) and revoked individually
without disturbing the merchant record.
Only the SHA-256 digest is stored; `prefix` keeps the first few characters
of the raw key so an operator can tell two keys apart in a list without the
secret being recoverable. `revoked_at` is a tombstone rather than a delete
so an audit trail survives revocation. */
sqlx::query(&format!(
"CREATE TABLE IF NOT EXISTS api_keys (
id TEXT PRIMARY KEY,
merchant_id TEXT NOT NULL,
key_hash TEXT NOT NULL UNIQUE,
prefix TEXT NOT NULL,
label TEXT,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now'))
CHECK (created_at LIKE '{TS_PATTERN}'),
last_used_at TEXT CHECK (last_used_at IS NULL OR last_used_at LIKE '{TS_PATTERN}'),
revoked_at TEXT CHECK (revoked_at IS NULL OR revoked_at LIKE '{TS_PATTERN}')
)",
))
.execute(pool)
.await?;
/* Authentication looks a key up by hash on every request, so this index is
load-bearing rather than an optimisation. */
sqlx::query("CREATE INDEX IF NOT EXISTS idx_api_keys_hash ON api_keys(key_hash)")
.execute(pool)
.await?;
sqlx::query("CREATE INDEX IF NOT EXISTS idx_api_keys_merchant ON api_keys(merchant_id)")
.execute(pool)
.await?;
/* Carry pre-existing single-key merchants across. Their raw key is not
recoverable, but the hash is all authentication needs, so keys issued
before this table existed keep working. The prefix is unknown for those
rows — mark them rather than inventing one. */
sqlx::query(
"INSERT OR IGNORE INTO api_keys (id, merchant_id, key_hash, prefix, label, created_at)
SELECT lower(hex(randomblob(16))), id, api_key_hash, 'legacy', 'migrated', created_at
FROM merchants
WHERE api_key_hash IS NOT NULL AND api_key_hash <> ''",
)
.execute(pool)
.await?;
/* `webhook_deliveries` is queried by payment_id on every delivery listing
and by the redrive worker; without this it is a full scan (issue #112). */
sqlx::query(
"CREATE INDEX IF NOT EXISTS idx_webhook_deliveries_payment
ON webhook_deliveries(payment_id)",
)
.execute(&mut *tx)
.await?;
/* Idempotency keys for payment creation. A key is unique per merchant and
maps to the payment id minted for the first request that used it, so a
client retrying after a network blip gets the original payment back
instead of a duplicate intent. */
sqlx::query(&format!(
"CREATE TABLE IF NOT EXISTS idempotency_keys (
merchant_id TEXT NOT NULL,
idempotency_key TEXT NOT NULL,
payment_id TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now'))
CHECK (created_at LIKE '{TS_PATTERN}'),
PRIMARY KEY (merchant_id, idempotency_key)
)",
))
.execute(pool)
.await?;
/* Every on-chain transaction we credit to an intent, one row per
(payment_id, tx_hash). The cumulative received amount for an intent is the
SUM of `amount_stroops` over its rows, so re-seeing a transaction (on a
later poll cycle, over the stream, or from a concurrent reconciler) is an
idempotent no-op instead of a double-credit. `amount_stroops` is the
integer stroop value so SUM is exact. */
sqlx::query(&format!(
"CREATE TABLE IF NOT EXISTS processed_transactions (
payment_id TEXT NOT NULL,
tx_hash TEXT NOT NULL,
amount_stroops INTEGER NOT NULL,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now'))
CHECK (created_at LIKE '{TS_PATTERN}'),
PRIMARY KEY (payment_id, tx_hash)
)",
))
.execute(pool)
.await?;
/* Backfill from legacy rows that recorded only the most-recent `tx_hash`
and a cumulative `paid_amount`, so upgrading preserves the received-amount
ledger for intents that are still in flight. Idempotent via ON CONFLICT, so
it is safe to run on every startup. */
let legacy = sqlx::query(
"SELECT id, tx_hash, paid_amount FROM payments
WHERE tx_hash IS NOT NULL AND tx_hash <> '' AND paid_amount IS NOT NULL",
)
.fetch_all(&mut *tx)
.await?;
for row in &legacy {
let id: String = row.get("id");
let tx_hash: String = row.get("tx_hash");
let paid_amount: String = row.get("paid_amount");
if let Some(stroops) = crate::money::parse_stroops(&paid_amount) {
sqlx::query(
"INSERT INTO processed_transactions (payment_id, tx_hash, amount_stroops)
VALUES (?, ?, ?)
ON CONFLICT(payment_id, tx_hash) DO NOTHING",
)
.bind(&id)
.bind(&tx_hash)
.bind(stroops)
.execute(&mut *tx)
.await?;
}
mark_migration_applied(pool, BACKFILL_PROCESSED_TRANSACTIONS).await?;
info!(
migration = BACKFILL_PROCESSED_TRANSACTIONS,
candidates = legacy.len(),
backfilled,
"migration applied"
);
}
/* Normalise legacy rows that were written by the old datetime('now') default,
which produced "YYYY-MM-DD HH:MM:SS" (space, no Z). This is a one-time
repair for rows written before the RFC 3339 format was enforced, so — like
the backfill above — it is gated behind a `kv_state` flag instead of
scanning both tables on every boot forever (issue #266).
`expires_at` is included for the same reason as the others (issue #314):
left in the legacy space-separated form, it sorts *before* every compliant
"…T…Z" timestamp — 'T' (0x54) > ' ' (0x20) — so `expires_at > strftime(...)`
in list_pending/expire_overdue/find_pending_by_memo reads such a row as
already expired. It would never surface as a detectable payment again and
would be swept on the very next expiry cycle. */
const NORMALIZE_LEGACY_TIMESTAMPS: &str = "normalize_legacy_timestamps";
if migration_applied(pool, NORMALIZE_LEGACY_TIMESTAMPS).await? {
info!(
migration = NORMALIZE_LEGACY_TIMESTAMPS,
"migration skipped (already applied)"
);
} else {
let mut normalized = 0u64;
for tbl_col in [
("payments", "created_at"),
("payments", "updated_at"),
("payments", "expires_at"),
("webhook_deliveries", "created_at"),
] {
let sql = format!(
"UPDATE {} SET {col} = replace({col}, ' ', 'T') || 'Z' WHERE {col} NOT LIKE '%T%'",
tbl_col.0,
col = tbl_col.1
);
normalized += sqlx::query(&sql).execute(pool).await?.rows_affected();
}
mark_migration_applied(pool, NORMALIZE_LEGACY_TIMESTAMPS).await?;
info!(
migration = NORMALIZE_LEGACY_TIMESTAMPS,
normalized, "migration applied"
);
sqlx::query(&sql).execute(&mut *tx).await?;
}
tx.commit().await?;
Ok(())
}
/// Fill `asset_issuer` on rows that only stored a code, using the current
/// allow-list. Duplicate codes are rejected at boot, so each code maps to at
/// most one issuer. Native assets stay NULL.
pub async fn backfill_asset_issuers(
pool: &Db,
accepted: &[crate::config::AcceptedAsset],
) -> Result<()> {
for asset in accepted {
let Some(issuer) = asset.issuer.as_deref() else {
continue;
};
sqlx::query(
"UPDATE payments
SET asset_issuer = ?
WHERE upper(asset) = upper(?)
AND (asset_issuer IS NULL OR asset_issuer = '')",
)
.bind(issuer)
.bind(&asset.code)
.execute(pool)
.await?;
}
Ok(())
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct Payment {
pub id: String,
pub merchant_id: String,
pub destination_address: String,
pub memo: String,
pub amount: String,
pub asset: String,
pub status: String,
pub webhook_url: Option<String>,
pub tx_hash: Option<String>,
pub paid_amount: Option<String>,
pub created_at: String,
pub updated_at: String,
/// When this intent stops being `pending` and is swept to `expired`.
pub expires_at: String,
/// Issuer account for a credit asset; `None` for native XLM. Settlement
/// matches this issuer, not any allow-list entry that shares the code
/// (issue #222).
pub asset_issuer: Option<String>,
}
fn row_to_payment(row: &sqlx::sqlite::SqliteRow) -> Payment {
Payment {
id: row.get("id"),
merchant_id: row.get("merchant_id"),
destination_address: row.get("destination_address"),
memo: row.get("memo"),
amount: row.get("amount"),
asset: row.get("asset"),
status: row.get("status"),
webhook_url: row.get("webhook_url"),
tx_hash: row.get("tx_hash"),
paid_amount: row.get("paid_amount"),
created_at: normalize_ts(&row.get::<String, _>("created_at")),
updated_at: normalize_ts(&row.get::<String, _>("updated_at")),
expires_at: normalize_ts(&row.get::<String, _>("expires_at")),
asset_issuer: row.get("asset_issuer"),
}
}
/// Fields needed to insert a new payment intent.
pub struct NewPayment<'a> {
pub id: &'a str,
pub merchant_id: &'a str,
pub destination_address: &'a str,
pub memo: &'a str,
pub amount: &'a str,
pub asset: &'a str,
/// Issuer for `asset`; `None` for native XLM.
pub asset_issuer: Option<&'a str>,
pub webhook_url: Option<&'a str>,
/// Seconds from now until the intent expires. The expiry timestamp is
/// computed by SQLite at insert time as `now + ttl_secs`.
pub ttl_secs: i64,
}
pub async fn create_payment(pool: &Db, new: NewPayment<'_>) -> Result<Payment> {
/* Canonicalize the amount: parse to stroops, then convert back to the
canonical string representation. This ensures "10.00", "10.0", and "10"
all serialize identically, eliminating spurious string-based comparisons
across create/get/webhook responses. */
let stroops =
crate::money::parse_stroops(new.amount).ok_or_else(|| anyhow::anyhow!("Invalid amount"))?;
let canonical_amount = crate::money::stroops_to_string(stroops);
/* Compute the expiry as `now + ttl_secs` in SQLite so it shares the exact
clock and RFC 3339 format as created_at. */
let ttl_modifier = format!("{:+} seconds", new.ttl_secs);
sqlx::query(
"INSERT INTO payments (id, merchant_id, destination_address, memo, amount, asset, asset_issuer, webhook_url, expires_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, strftime('%Y-%m-%dT%H:%M:%SZ','now',?))",
)
.bind(new.id)
.bind(new.merchant_id)
.bind(new.destination_address)
.bind(new.memo)
.bind(&canonical_amount)
.bind(new.asset)
.bind(new.asset_issuer)
.bind(new.webhook_url)
.bind(&ttl_modifier)
.execute(pool)
.await?;
get_payment(pool, new.id)
.await?
.ok_or_else(|| anyhow::anyhow!("Payment not found after insert"))
}
/// Look up the payment id previously minted for `(merchant_id, key)`, if any.
pub async fn find_payment_id_by_idempotency_key(
pool: &Db,
merchant_id: &str,
key: &str,
) -> Result<Option<String>> {
let id: Option<String> = sqlx::query_scalar(
"SELECT payment_id FROM idempotency_keys WHERE merchant_id = ? AND idempotency_key = ?",
)
.bind(merchant_id)
.bind(key)
.fetch_optional(pool)
.await?;
Ok(id)
}
/// Record the payment id minted for `(merchant_id, key)`. If the key already
/// exists (e.g. a concurrent request won the race), the existing mapping is left
/// untouched and the winning payment id is returned; otherwise `payment_id` is
/// stored and returned.
pub async fn save_idempotency_key(
pool: &Db,
merchant_id: &str,
key: &str,
payment_id: &str,
) -> Result<String> {
sqlx::query(
"INSERT INTO idempotency_keys (merchant_id, idempotency_key, payment_id)
VALUES (?, ?, ?)
ON CONFLICT(merchant_id, idempotency_key) DO NOTHING",
)
.bind(merchant_id)
.bind(key)
.bind(payment_id)
.execute(pool)
.await?;
// A concurrent insert may have won the race; re-read to get the canonical
// payment_id. If the row is missing despite the insert (which cannot happen
// given SQLite's serialised writes), fall back to our own value so the
// caller still gets a usable id rather than an error.
let stored = find_payment_id_by_idempotency_key(pool, merchant_id, key)
.await?
.unwrap_or_else(|| payment_id.to_string());
Ok(stored)
}
pub async fn get_payment(pool: &Db, id: &str) -> Result<Option<Payment>> {
let row = sqlx::query(
"SELECT id, merchant_id, destination_address, memo, amount, asset, asset_issuer, status,
webhook_url, tx_hash, paid_amount, created_at, updated_at, expires_at
FROM payments WHERE id = ?",
)
.bind(id)
.fetch_optional(pool)
.await?;
Ok(row.as_ref().map(row_to_payment))
}
/// Offset variant of `list_payments_keyset`. Rows are ordered by
/// `(created_at DESC, id DESC)` — exactly the keyset ordering — so a
/// `next_cursor` minted from this page resumes in cursor mode without
/// skipping or repeating rows. `created_at` is whole-second, so ties are
/// common; leaving their order to SQLite lets offset pages repeat or skip
/// rows and would make the migration cursor diverge from the keyset scan.
/// Offset-paginated page of a merchant's payments. Does **not** compute a row
/// count — see [`count_payments`] (issue #320). SQLite has no cached row
/// count, so a `COUNT(*)` here would scan every matching row on every list
/// request (including the first page) purely to fill a `total` field most
/// callers never read; keeping it a separate, opt-in query means the default
/// list path never pays for it.
pub async fn list_payments(
pool: &Db,
merchant_id: &str,
status: Option<&str>,
limit: i64,
offset: i64,
) -> Result<Vec<Payment>> {
let rows = if let Some(s) = status {
sqlx::query(
"SELECT id, merchant_id, destination_address, memo, amount, asset, asset_issuer, status,
webhook_url, tx_hash, paid_amount, created_at, updated_at, expires_at
FROM payments WHERE merchant_id = ? AND status = ? ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?",
)
.bind(merchant_id)
.bind(s)
.bind(limit)
.bind(offset)
.fetch_all(pool)
.await?
} else {
sqlx::query(
"SELECT id, merchant_id, destination_address, memo, amount, asset, asset_issuer, status,
webhook_url, tx_hash, paid_amount, created_at, updated_at, expires_at
FROM payments WHERE merchant_id = ? ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?",
)
.bind(merchant_id)
.bind(limit)
.bind(offset)
.fetch_all(pool)
.await?
};
Ok(rows.iter().map(row_to_payment).collect())
}
/// Count a merchant's payments matching an optional status filter. Split out
/// from [`list_payments`] so the default `GET /payments` path never pays for
/// a full-table `COUNT(*)` — this only runs when a caller explicitly asks for
/// `total` via `?include_total=true` (issue #320).
pub async fn count_payments(pool: &Db, merchant_id: &str, status: Option<&str>) -> Result<i64> {
let total = if let Some(s) = status {
sqlx::query_scalar("SELECT COUNT(*) FROM payments WHERE merchant_id = ? AND status = ?")
.bind(merchant_id)
.bind(s)
.fetch_one(pool)
.await?
} else {
sqlx::query_scalar("SELECT COUNT(*) FROM payments WHERE merchant_id = ?")
.bind(merchant_id)
.fetch_one(pool)
.await?
};
Ok(total)
}
pub async fn list_payments_keyset(
pool: &Db,
merchant_id: &str,
status: Option<&str>,
limit: i64,
cursor: Option<(&str, &str)>,
) -> Result<Vec<Payment>> {
let rows = match (status, cursor) {
(None, None) => {
sqlx::query(
"SELECT id, merchant_id, destination_address, memo, amount, asset, asset_issuer, status,
webhook_url, tx_hash, paid_amount, created_at, updated_at, expires_at
FROM payments WHERE merchant_id = ? ORDER BY created_at DESC, id DESC LIMIT ?",
)
.bind(merchant_id)
.bind(limit)
.fetch_all(pool)
.await?
}
(None, Some((ts, cid))) => {
sqlx::query(
"SELECT id, merchant_id, destination_address, memo, amount, asset, asset_issuer, status,
webhook_url, tx_hash, paid_amount, created_at, updated_at, expires_at
FROM payments
WHERE merchant_id = ? AND (created_at < ? OR (created_at = ? AND id < ?))
ORDER BY created_at DESC, id DESC LIMIT ?",
)
.bind(merchant_id)
.bind(ts)
.bind(ts)
.bind(cid)
.bind(limit)
.fetch_all(pool)
.await?
}
(Some(s), None) => {
sqlx::query(
"SELECT id, merchant_id, destination_address, memo, amount, asset, asset_issuer, status,
webhook_url, tx_hash, paid_amount, created_at, updated_at, expires_at
FROM payments WHERE merchant_id = ? AND status = ? ORDER BY created_at DESC, id DESC LIMIT ?",
)
.bind(merchant_id)
.bind(s)
.bind(limit)
.fetch_all(pool)
.await?
}
(Some(s), Some((ts, cid))) => {
sqlx::query(
"SELECT id, merchant_id, destination_address, memo, amount, asset, asset_issuer, status,
webhook_url, tx_hash, paid_amount, created_at, updated_at, expires_at
FROM payments
WHERE merchant_id = ? AND status = ? AND (created_at < ? OR (created_at = ? AND id < ?))
ORDER BY created_at DESC, id DESC LIMIT ?",
)
.bind(merchant_id)
.bind(s)
.bind(ts)
.bind(ts)
.bind(cid)
.bind(limit)
.fetch_all(pool)
.await?
}
};
Ok(rows.iter().map(row_to_payment).collect())
}
/// All payments still awaiting confirmation or top-up, oldest first. Rows whose
/// TTL has elapsed are excluded even if the sweeper hasn't transitioned them
/// yet, so an overdue intent is never polled.
pub async fn list_pending(pool: &Db) -> Result<Vec<Payment>> {
let rows = sqlx::query(
"SELECT id, merchant_id, destination_address, memo, amount, asset, asset_issuer, status,
webhook_url, tx_hash, paid_amount, created_at, updated_at, expires_at
FROM payments
WHERE status IN ('pending', 'underpaid')
AND expires_at > strftime('%Y-%m-%dT%H:%M:%SZ','now')
ORDER BY created_at ASC",
)
.fetch_all(pool)
.await?;
Ok(rows.iter().map(row_to_payment).collect())
}
/// Transition up to `batch` watchable payments whose TTL has elapsed to
/// `expired`, returning the rows that were swept so the caller can fire
/// `payment.expired` webhooks.
///
/// The whole batch is transitioned in a single `UPDATE … RETURNING` — one
/// round-trip instead of one guarded `UPDATE` per intent (issue #323). The
/// `WHERE … status IN ('pending','underpaid')` guard remains what makes a
/// concurrent settlement win the race: the subquery and update run under one
/// write lock, so a payment that settles in between is never selected here
/// (if the settlement committed first) and a payment this statement sweeps is
/// rejected by the settlement's own guard (issue #155) — never double-reported.
/// `RETURNING` yields exactly the rows this statement actually transitioned.
///
/// `batch` bounds each statement, so a large backlog drains over several
/// sweeps instead of one long write lock.
pub async fn expire_overdue(pool: &Db, batch: i64) -> Result<Vec<Payment>> {
let rows = sqlx::query(
"UPDATE payments
SET status = 'expired',
updated_at = strftime('%Y-%m-%dT%H:%M:%SZ','now')
WHERE id IN (
SELECT id FROM payments
WHERE status IN ('pending', 'underpaid')
AND expires_at <= strftime('%Y-%m-%dT%H:%M:%SZ','now')
ORDER BY created_at ASC
LIMIT ?
)
RETURNING id, merchant_id, destination_address, memo, amount, asset,
asset_issuer, status, webhook_url, tx_hash, paid_amount,
created_at, updated_at, expires_at",
)
.bind(batch)
.fetch_all(pool)
.await?;
Ok(rows.iter().map(row_to_payment).collect())
}
pub async fn find_pending_by_memo(pool: &Db, memo: &str) -> Result<Option<Payment>> {
let row = sqlx::query(
"SELECT id, merchant_id, destination_address, memo, amount, asset, asset_issuer, status,
webhook_url, tx_hash, paid_amount, created_at, updated_at, expires_at
FROM payments
WHERE memo = ?
AND status IN ('pending', 'underpaid')
AND expires_at > strftime('%Y-%m-%dT%H:%M:%SZ','now')",
)
.bind(memo)
.fetch_optional(pool)
.await?;
Ok(row.as_ref().map(row_to_payment))
}
/// Transition a payment to a new status, returning `true` when the row was
/// actually updated.
///
/// The `WHERE … AND status IN ('pending', 'underpaid')` guard is the key to
/// single-settlement under concurrent reconciliation (issue #155): SQLite's
/// serialized write path ensures that exactly one of two racing UPDATE
/// statements will match a row still in a watchable state. The loser sees
/// `rows_affected() == 0` and knows it must skip the webhook.
pub async fn update_payment_status(
pool: &Db,
id: &str,
status: &str,
tx_hash: &str,
paid_amount: &str,
) -> Result<bool> {
let result = sqlx::query(
"UPDATE payments
SET status = ?, tx_hash = ?, paid_amount = ?,
updated_at = strftime('%Y-%m-%dT%H:%M:%SZ','now')
WHERE id = ?
AND status IN ('pending', 'underpaid')",
)
.bind(status)
.bind(tx_hash)
.bind(paid_amount)
.bind(id)
.execute(pool)
.await?;
Ok(result.rows_affected() == 1)
}
/// Record that transaction `tx_hash`, worth `amount_stroops`, has been credited
/// to intent `payment_id`. Returns `true` when this is the first time the
/// transaction was recorded for the intent, and `false` when it was already
/// present (a re-seen record on a later poll cycle, over the stream, or from a
/// concurrent reconciler).
///
/// The `(payment_id, tx_hash)` primary key plus `ON CONFLICT DO NOTHING` makes
/// this the atomic dedup point: SQLite serialises writers, so exactly one of
/// two racing inserts for the same transaction observes `rows_affected() == 1`.
pub async fn record_processed_tx(
pool: &Db,
payment_id: &str,
tx_hash: &str,
amount_stroops: i64,
) -> Result<bool> {
let result = sqlx::query(
"INSERT INTO processed_transactions (payment_id, tx_hash, amount_stroops)
VALUES (?, ?, ?)
ON CONFLICT(payment_id, tx_hash) DO NOTHING",
)
.bind(payment_id)
.bind(tx_hash)
.bind(amount_stroops)
.execute(pool)
.await?;
Ok(result.rows_affected() == 1)
}
/// Sum of every transaction recorded against `payment_id`, in stroops. This is
/// the authoritative received-amount ledger for an intent — independent of how
/// many transactions arrived, or the order they were seen in.
pub async fn sum_processed_stroops(pool: &Db, payment_id: &str) -> Result<i64> {
let total: i64 = sqlx::query_scalar(
"SELECT COALESCE(SUM(amount_stroops), 0) FROM processed_transactions WHERE payment_id = ?",
)
.bind(payment_id)
.fetch_one(pool)
.await?;
Ok(total)
}
/// Read a value from the durable key/value state table, if present.
pub async fn get_state(pool: &Db, key: &str) -> Result<Option<String>> {
let value: Option<String> = sqlx::query_scalar("SELECT value FROM kv_state WHERE key = ?")
.bind(key)
.fetch_optional(pool)
.await?;
Ok(value)
}
/// Insert or update a value in the durable key/value state table.
pub async fn set_state(pool: &Db, key: &str, value: &str) -> Result<()> {
sqlx::query(
"INSERT INTO kv_state (key, value, updated_at)
VALUES (?, ?, strftime('%Y-%m-%dT%H:%M:%SZ','now'))
ON CONFLICT(key) DO UPDATE SET
value = excluded.value,
updated_at = excluded.updated_at",
)
.bind(key)
.bind(value)
.execute(pool)
.await?;
Ok(())
}
/// Record an outbound webhook delivery. `event_type` is the event name the
/// payload carries (e.g. `payment.underpaid`); it is persisted so a later
/// redelivery can reproduce the original `X-StellarGate-Event` header.
pub async fn save_webhook_delivery(
pool: &Db,
id: &str,
payment_id: &str,
url: &str,
payload: &str,
event_type: &str,
) -> Result<()> {
sqlx::query(
"INSERT INTO webhook_deliveries (id, payment_id, url, payload, event_type) VALUES (?, ?, ?, ?, ?)",
)
.bind(id)
.bind(payment_id)
.bind(url)
.bind(payload)
.bind(event_type)
.execute(pool)
.await?;
Ok(())
}
pub async fn update_webhook_delivery(
pool: &Db,
id: &str,
status: &str,
attempts: i64,
) -> Result<()> {
let result = sqlx::query(
"UPDATE webhook_deliveries SET status = ?, attempts = ?, last_attempt = strftime('%Y-%m-%dT%H:%M:%SZ','now') WHERE id = ?",
)
.bind(status)
.bind(attempts)
.bind(id)
.execute(pool)
.await?;
if result.rows_affected() == 0 {
anyhow::bail!("webhook delivery {id} not found for status update");
}
Ok(())
}
/// Record a merchant-initiated redelivery outcome.
///
/// Updates `status` and increments `manual_attempts` only. Leaves `attempts`
/// and `last_attempt` untouched so the automatic redrive budget and backoff
/// schedule are unaffected (issue #235).
pub async fn record_manual_redelivery(pool: &Db, id: &str, status: &str) -> Result<()> {
let result = sqlx::query(
"UPDATE webhook_deliveries
SET status = ?,
manual_attempts = manual_attempts + 1
WHERE id = ?",
)
.bind(status)
.bind(id)
.execute(pool)
.await?;
if result.rows_affected() == 0 {
anyhow::bail!("webhook delivery {id} not found for manual redelivery");
}
Ok(())
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct WebhookDelivery {
pub id: String,
pub payment_id: String,
pub url: String,
pub payload: String,
/// The event this payload represents. `None` only for rows written before
/// the column existed — use [`WebhookDelivery::event`] to read it.
pub event_type: Option<String>,
pub status: String,
pub attempts: i64,
/// Merchant-initiated redeliveries. Ignored by the redrive worker's budget
/// (issue #235); exposed on listing so operators can tell the two apart.
pub manual_attempts: i64,
pub last_attempt: Option<String>,
/// When somebody acted on this delivery — requeued it, or explicitly
/// acknowledged it. `None` means nobody has looked at it yet, which is
/// what keeps a terminal failure exempt from retention (issue #319).
pub acknowledged_at: Option<String>,
pub created_at: String,
}
/// Event name used when a legacy row has no `event_type` and its payload can't
/// be parsed. Every payload this gateway has ever written carries an `event`
/// field, so this is a last resort rather than an expected path.
const FALLBACK_EVENT: &str = "payment.completed";
impl WebhookDelivery {
/// The event name to report for this delivery, falling back to the `event`
/// field of the stored payload for rows written before `event_type`
/// existed. Used to reproduce the original `X-StellarGate-Event` header on
/// redelivery so the header can never contradict the body.
pub fn event(&self) -> String {
if let Some(event) = &self.event_type {