@digilogiclabs/platform-core 1.27.1 → 1.28.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -14260,6 +14260,272 @@ var MemoryBeta = class {
14260
14260
  }
14261
14261
  };
14262
14262
 
14263
+ // src/interfaces/ICreditLedger.ts
14264
+ var InsufficientCreditsError = class extends Error {
14265
+ constructor(accountId, requested, available) {
14266
+ super(
14267
+ `Account ${accountId} has ${available} credits available; ${requested} requested`
14268
+ );
14269
+ this.accountId = accountId;
14270
+ this.requested = requested;
14271
+ this.available = available;
14272
+ this.name = "InsufficientCreditsError";
14273
+ }
14274
+ code = "INSUFFICIENT_CREDITS";
14275
+ };
14276
+ var CreditIdempotencyConflictError = class extends Error {
14277
+ constructor(idempotencyKey) {
14278
+ super(`Idempotency key ${idempotencyKey} was used for a different request`);
14279
+ this.idempotencyKey = idempotencyKey;
14280
+ this.name = "CreditIdempotencyConflictError";
14281
+ }
14282
+ code = "IDEMPOTENCY_CONFLICT";
14283
+ };
14284
+ var CreditReservationStateError = class extends Error {
14285
+ code = "RESERVATION_STATE";
14286
+ constructor(message) {
14287
+ super(message);
14288
+ this.name = "CreditReservationStateError";
14289
+ }
14290
+ };
14291
+ var DEFAULT_RESERVATION_SECONDS = 600;
14292
+ function assertWholeCredits(value, field) {
14293
+ if (!Number.isSafeInteger(value) || value <= 0) {
14294
+ throw new RangeError(`${field} must be a positive whole number of credits`);
14295
+ }
14296
+ }
14297
+ var RESERVED_KEY_PREFIXES = ["reserve:", "settle:", "release:"];
14298
+ function assertIdempotencyKey(key) {
14299
+ if (typeof key !== "string" || key.length === 0 || key.length > 200) {
14300
+ throw new RangeError("idempotencyKey must be 1-200 characters");
14301
+ }
14302
+ if (RESERVED_KEY_PREFIXES.some((prefix) => key.startsWith(prefix))) {
14303
+ throw new RangeError(
14304
+ `idempotencyKey cannot start with ${RESERVED_KEY_PREFIXES.join(", ")}`
14305
+ );
14306
+ }
14307
+ }
14308
+ function reservationSeconds(value) {
14309
+ const seconds = value ?? DEFAULT_RESERVATION_SECONDS;
14310
+ if (!Number.isSafeInteger(seconds) || seconds <= 0) {
14311
+ throw new RangeError("expiresInSeconds must be a positive whole number");
14312
+ }
14313
+ return seconds;
14314
+ }
14315
+ var MAX_LIST_ENTRIES = 500;
14316
+ function clampEntryLimit(limit) {
14317
+ return Math.min(Math.max(Math.trunc(limit ?? 50), 1), MAX_LIST_ENTRIES);
14318
+ }
14319
+ function generateCreditId(prefix) {
14320
+ const random = globalThis.crypto.randomUUID().replace(/-/g, "");
14321
+ return `${prefix}_${random}`;
14322
+ }
14323
+ var MemoryCreditLedger = class {
14324
+ accounts = /* @__PURE__ */ new Map();
14325
+ entries = [];
14326
+ entriesByKey = /* @__PURE__ */ new Map();
14327
+ reservations = /* @__PURE__ */ new Map();
14328
+ reservationsByKey = /* @__PURE__ */ new Map();
14329
+ async getBalance(accountId) {
14330
+ const account = this.accounts.get(accountId);
14331
+ return {
14332
+ accountId,
14333
+ available: account?.available ?? 0,
14334
+ reserved: account?.reserved ?? 0
14335
+ };
14336
+ }
14337
+ async grant(input) {
14338
+ assertWholeCredits(input.credits, "credits");
14339
+ assertIdempotencyKey(input.idempotencyKey);
14340
+ const existing = this.entriesByKey.get(input.idempotencyKey);
14341
+ if (existing) {
14342
+ if (existing.accountId !== input.accountId || existing.kind !== input.kind || existing.delta !== input.credits) {
14343
+ throw new CreditIdempotencyConflictError(input.idempotencyKey);
14344
+ }
14345
+ return { ...existing };
14346
+ }
14347
+ const account = this.account(input.accountId);
14348
+ account.available += input.credits;
14349
+ return this.record({
14350
+ accountId: input.accountId,
14351
+ kind: input.kind,
14352
+ delta: input.credits,
14353
+ consumed: 0,
14354
+ availableAfter: account.available,
14355
+ reservationId: null,
14356
+ reference: input.reference ?? null,
14357
+ idempotencyKey: input.idempotencyKey
14358
+ });
14359
+ }
14360
+ async reserve(input) {
14361
+ assertWholeCredits(input.credits, "credits");
14362
+ assertIdempotencyKey(input.idempotencyKey);
14363
+ const seconds = reservationSeconds(input.expiresInSeconds);
14364
+ const existing = this.reservationsByKey.get(input.idempotencyKey);
14365
+ if (existing) {
14366
+ if (existing.accountId !== input.accountId || existing.credits !== input.credits) {
14367
+ throw new CreditIdempotencyConflictError(input.idempotencyKey);
14368
+ }
14369
+ return { ...existing };
14370
+ }
14371
+ const account = this.accounts.get(input.accountId);
14372
+ const available = account?.available ?? 0;
14373
+ if (!account || available < input.credits) {
14374
+ throw new InsufficientCreditsError(
14375
+ input.accountId,
14376
+ input.credits,
14377
+ available
14378
+ );
14379
+ }
14380
+ account.available -= input.credits;
14381
+ account.reserved += input.credits;
14382
+ const now = /* @__PURE__ */ new Date();
14383
+ const reservation = {
14384
+ id: generateCreditId("cr"),
14385
+ accountId: input.accountId,
14386
+ credits: input.credits,
14387
+ status: "held",
14388
+ consumed: null,
14389
+ reference: input.reference ?? null,
14390
+ idempotencyKey: input.idempotencyKey,
14391
+ expiresAt: new Date(now.getTime() + seconds * 1e3),
14392
+ createdAt: now
14393
+ };
14394
+ this.reservations.set(reservation.id, reservation);
14395
+ this.reservationsByKey.set(reservation.idempotencyKey, reservation);
14396
+ this.record({
14397
+ accountId: input.accountId,
14398
+ kind: "reserve",
14399
+ delta: -input.credits,
14400
+ consumed: 0,
14401
+ availableAfter: account.available,
14402
+ reservationId: reservation.id,
14403
+ reference: reservation.reference,
14404
+ idempotencyKey: `reserve:${reservation.id}`
14405
+ });
14406
+ return { ...reservation };
14407
+ }
14408
+ async settle(reservationId, consumed) {
14409
+ if (!Number.isSafeInteger(consumed) || consumed < 0) {
14410
+ throw new RangeError("consumed must be a whole number of credits >= 0");
14411
+ }
14412
+ const reservation = this.reservations.get(reservationId);
14413
+ if (!reservation) {
14414
+ throw new CreditReservationStateError(
14415
+ `Reservation ${reservationId} not found`
14416
+ );
14417
+ }
14418
+ const key = `settle:${reservationId}`;
14419
+ if (reservation.status === "settled") {
14420
+ const entry = this.entriesByKey.get(key);
14421
+ if (!entry || entry.consumed !== consumed) {
14422
+ throw new CreditIdempotencyConflictError(key);
14423
+ }
14424
+ return { ...entry };
14425
+ }
14426
+ if (reservation.status === "released") {
14427
+ throw new CreditReservationStateError(
14428
+ `Reservation ${reservationId} was released`
14429
+ );
14430
+ }
14431
+ if (consumed > reservation.credits) {
14432
+ throw new CreditReservationStateError(
14433
+ `Cannot consume ${consumed}; reservation holds ${reservation.credits}`
14434
+ );
14435
+ }
14436
+ return this.close(reservation, "settled", consumed, key);
14437
+ }
14438
+ async release(reservationId) {
14439
+ const reservation = this.reservations.get(reservationId);
14440
+ if (!reservation) {
14441
+ throw new CreditReservationStateError(
14442
+ `Reservation ${reservationId} not found`
14443
+ );
14444
+ }
14445
+ if (reservation.status !== "held") return;
14446
+ this.close(reservation, "released", 0, `release:${reservationId}`);
14447
+ }
14448
+ async clawback(input) {
14449
+ assertWholeCredits(input.credits, "credits");
14450
+ assertIdempotencyKey(input.idempotencyKey);
14451
+ const existing = this.entriesByKey.get(input.idempotencyKey);
14452
+ if (existing) {
14453
+ if (existing.accountId !== input.accountId || existing.kind !== "clawback") {
14454
+ throw new CreditIdempotencyConflictError(input.idempotencyKey);
14455
+ }
14456
+ return { entry: { ...existing }, clawedBack: -existing.delta };
14457
+ }
14458
+ const account = this.account(input.accountId);
14459
+ const taken = Math.min(input.credits, account.available);
14460
+ account.available -= taken;
14461
+ const entry = this.record({
14462
+ accountId: input.accountId,
14463
+ kind: "clawback",
14464
+ delta: -taken,
14465
+ consumed: 0,
14466
+ availableAfter: account.available,
14467
+ reservationId: null,
14468
+ reference: input.reference ?? null,
14469
+ idempotencyKey: input.idempotencyKey
14470
+ });
14471
+ return { entry, clawedBack: taken };
14472
+ }
14473
+ async expireReservations(now = /* @__PURE__ */ new Date()) {
14474
+ let released = 0;
14475
+ for (const reservation of this.reservations.values()) {
14476
+ if (reservation.status === "held" && reservation.expiresAt <= now) {
14477
+ this.close(reservation, "released", 0, `release:${reservation.id}`);
14478
+ released++;
14479
+ }
14480
+ }
14481
+ return released;
14482
+ }
14483
+ async getReservation(reservationId) {
14484
+ const reservation = this.reservations.get(reservationId);
14485
+ return reservation ? { ...reservation } : null;
14486
+ }
14487
+ async listEntries(accountId, options = {}) {
14488
+ const limit = clampEntryLimit(options.limit);
14489
+ return this.entries.filter((entry) => entry.accountId === accountId).reverse().slice(0, limit).map((entry) => ({ ...entry }));
14490
+ }
14491
+ account(accountId) {
14492
+ let account = this.accounts.get(accountId);
14493
+ if (!account) {
14494
+ account = { available: 0, reserved: 0 };
14495
+ this.accounts.set(accountId, account);
14496
+ }
14497
+ return account;
14498
+ }
14499
+ close(reservation, status, consumed, key) {
14500
+ const account = this.account(reservation.accountId);
14501
+ const returned = reservation.credits - consumed;
14502
+ account.reserved -= reservation.credits;
14503
+ account.available += returned;
14504
+ reservation.status = status;
14505
+ reservation.consumed = status === "settled" ? consumed : null;
14506
+ return this.record({
14507
+ accountId: reservation.accountId,
14508
+ kind: status === "settled" ? "settle" : "release",
14509
+ delta: returned,
14510
+ consumed,
14511
+ availableAfter: account.available,
14512
+ reservationId: reservation.id,
14513
+ reference: reservation.reference,
14514
+ idempotencyKey: key
14515
+ });
14516
+ }
14517
+ record(entry) {
14518
+ const full = {
14519
+ ...entry,
14520
+ id: generateCreditId("ce"),
14521
+ createdAt: /* @__PURE__ */ new Date()
14522
+ };
14523
+ this.entries.push(full);
14524
+ this.entriesByKey.set(full.idempotencyKey, full);
14525
+ return { ...full };
14526
+ }
14527
+ };
14528
+
14263
14529
  // src/index.ts
14264
14530
  init_IAI();
14265
14531
  init_IRAG();
@@ -19260,11 +19526,24 @@ async function checkRateLimit(operation, identifier, rule, options = {}) {
19260
19526
  retryAfterSeconds: 0
19261
19527
  };
19262
19528
  } catch (error) {
19263
- options.logger?.error("Rate limit check failed, allowing request", {
19264
- error: error instanceof Error ? error.message : String(error),
19265
- operation,
19266
- identifier
19267
- });
19529
+ options.logger?.error(
19530
+ rule.failClosed ? "Rate limit check failed, denying request (fail-closed rule)" : "Rate limit check failed, allowing request",
19531
+ {
19532
+ error: error instanceof Error ? error.message : String(error),
19533
+ operation,
19534
+ identifier
19535
+ }
19536
+ );
19537
+ if (rule.failClosed) {
19538
+ return {
19539
+ allowed: false,
19540
+ remaining: 0,
19541
+ resetAt,
19542
+ current: 0,
19543
+ limit,
19544
+ retryAfterSeconds: 30
19545
+ };
19546
+ }
19268
19547
  return {
19269
19548
  allowed: true,
19270
19549
  remaining: limit,
@@ -32446,6 +32725,444 @@ var PostgresBeta = class {
32446
32725
  }
32447
32726
  };
32448
32727
 
32728
+ // src/adapters/postgres-credits/PostgresCreditLedger.ts
32729
+ var SCHEMA_NAME = /^[a-z_][a-z0-9_]{0,62}$/;
32730
+ var TABLE_PREFIX = /^[a-z_][a-z0-9_]{0,19}$/;
32731
+ var UNIQUE_VIOLATION = "23505";
32732
+ function isUniqueViolation(error) {
32733
+ return error?.code === UNIQUE_VIOLATION;
32734
+ }
32735
+ function toEntry(row) {
32736
+ return {
32737
+ id: row.id,
32738
+ accountId: row.account_id,
32739
+ kind: row.kind,
32740
+ delta: Number(row.delta),
32741
+ consumed: Number(row.consumed),
32742
+ availableAfter: Number(row.available_after),
32743
+ reservationId: row.reservation_id ?? null,
32744
+ reference: row.reference ?? null,
32745
+ idempotencyKey: row.idempotency_key,
32746
+ createdAt: new Date(row.created_at)
32747
+ };
32748
+ }
32749
+ function toReservation(row) {
32750
+ return {
32751
+ id: row.id,
32752
+ accountId: row.account_id,
32753
+ credits: Number(row.credits),
32754
+ status: row.status,
32755
+ consumed: row.consumed === null ? null : Number(row.consumed),
32756
+ reference: row.reference ?? null,
32757
+ idempotencyKey: row.idempotency_key,
32758
+ expiresAt: new Date(row.expires_at),
32759
+ createdAt: new Date(row.created_at)
32760
+ };
32761
+ }
32762
+ var PostgresCreditLedger = class {
32763
+ pool;
32764
+ prefix;
32765
+ accounts;
32766
+ entries;
32767
+ reservations;
32768
+ constructor(config) {
32769
+ const schema = config.schema ?? "public";
32770
+ const prefix = config.tablePrefix ?? "credit_";
32771
+ if (!SCHEMA_NAME.test(schema) || !TABLE_PREFIX.test(prefix)) {
32772
+ throw new RangeError(
32773
+ "schema (max 63) and tablePrefix (max 20) must be lowercase SQL identifiers"
32774
+ );
32775
+ }
32776
+ this.pool = config.pool;
32777
+ this.prefix = prefix;
32778
+ this.accounts = `"${schema}"."${prefix}accounts"`;
32779
+ this.entries = `"${schema}"."${prefix}entries"`;
32780
+ this.reservations = `"${schema}"."${prefix}reservations"`;
32781
+ }
32782
+ /**
32783
+ * DDL for the ledger. Exposed so apps that hand-apply migrations can ship
32784
+ * it as a reviewed file instead of calling initialize() at runtime.
32785
+ */
32786
+ schemaSql() {
32787
+ return `
32788
+ CREATE TABLE IF NOT EXISTS ${this.accounts} (
32789
+ account_id text PRIMARY KEY,
32790
+ available bigint NOT NULL DEFAULT 0 CHECK (available >= 0),
32791
+ reserved bigint NOT NULL DEFAULT 0 CHECK (reserved >= 0),
32792
+ updated_at timestamptz NOT NULL DEFAULT now()
32793
+ );
32794
+ CREATE TABLE IF NOT EXISTS ${this.reservations} (
32795
+ id text PRIMARY KEY,
32796
+ account_id text NOT NULL REFERENCES ${this.accounts}(account_id),
32797
+ credits bigint NOT NULL CHECK (credits > 0),
32798
+ status text NOT NULL CHECK (status IN ('held','settled','released')),
32799
+ consumed bigint CHECK (consumed IS NULL OR (consumed >= 0 AND consumed <= credits)),
32800
+ reference text,
32801
+ idempotency_key text NOT NULL UNIQUE,
32802
+ expires_at timestamptz NOT NULL,
32803
+ created_at timestamptz NOT NULL DEFAULT now(),
32804
+ updated_at timestamptz NOT NULL DEFAULT now()
32805
+ );
32806
+ CREATE INDEX IF NOT EXISTS "${this.prefix}reservations_held_expiry"
32807
+ ON ${this.reservations} (expires_at) WHERE status = 'held';
32808
+ CREATE TABLE IF NOT EXISTS ${this.entries} (
32809
+ id text PRIMARY KEY,
32810
+ account_id text NOT NULL REFERENCES ${this.accounts}(account_id),
32811
+ kind text NOT NULL CHECK (kind IN ('purchase','grant','reserve','settle','release','clawback')),
32812
+ delta bigint NOT NULL,
32813
+ consumed bigint NOT NULL DEFAULT 0 CHECK (consumed >= 0),
32814
+ available_after bigint NOT NULL CHECK (available_after >= 0),
32815
+ reservation_id text REFERENCES ${this.reservations}(id),
32816
+ reference text,
32817
+ idempotency_key text NOT NULL UNIQUE,
32818
+ created_at timestamptz NOT NULL DEFAULT now()
32819
+ );
32820
+ CREATE INDEX IF NOT EXISTS "${this.prefix}entries_account_created"
32821
+ ON ${this.entries} (account_id, created_at DESC);
32822
+ `;
32823
+ }
32824
+ async initialize() {
32825
+ await this.pool.query(this.schemaSql());
32826
+ }
32827
+ async getBalance(accountId) {
32828
+ const { rows } = await this.pool.query(
32829
+ `SELECT available, reserved FROM ${this.accounts} WHERE account_id = $1`,
32830
+ [accountId]
32831
+ );
32832
+ const row = rows[0];
32833
+ return {
32834
+ accountId,
32835
+ available: row ? Number(row.available) : 0,
32836
+ reserved: row ? Number(row.reserved) : 0
32837
+ };
32838
+ }
32839
+ async grant(input) {
32840
+ assertWholeCredits(input.credits, "credits");
32841
+ assertIdempotencyKey(input.idempotencyKey);
32842
+ const replay = (entry) => {
32843
+ if (entry.accountId !== input.accountId || entry.kind !== input.kind || entry.delta !== input.credits) {
32844
+ throw new CreditIdempotencyConflictError(input.idempotencyKey);
32845
+ }
32846
+ return entry;
32847
+ };
32848
+ return this.idempotent(input.idempotencyKey, replay, async (client) => {
32849
+ await client.query(
32850
+ `INSERT INTO ${this.accounts} (account_id) VALUES ($1) ON CONFLICT DO NOTHING`,
32851
+ [input.accountId]
32852
+ );
32853
+ const { rows } = await client.query(
32854
+ `UPDATE ${this.accounts} SET available = available + $2, updated_at = now()
32855
+ WHERE account_id = $1 RETURNING available`,
32856
+ [input.accountId, input.credits]
32857
+ );
32858
+ return this.insertEntry(client, {
32859
+ accountId: input.accountId,
32860
+ kind: input.kind,
32861
+ delta: input.credits,
32862
+ consumed: 0,
32863
+ availableAfter: Number(rows[0].available),
32864
+ reservationId: null,
32865
+ reference: input.reference ?? null,
32866
+ idempotencyKey: input.idempotencyKey
32867
+ });
32868
+ });
32869
+ }
32870
+ async reserve(input) {
32871
+ assertWholeCredits(input.credits, "credits");
32872
+ assertIdempotencyKey(input.idempotencyKey);
32873
+ const seconds = reservationSeconds(input.expiresInSeconds);
32874
+ const existing = await this.reservationByKey(
32875
+ this.pool,
32876
+ input.idempotencyKey
32877
+ );
32878
+ if (existing) return this.replayReservation(existing, input);
32879
+ const client = await this.pool.connect();
32880
+ try {
32881
+ await client.query("BEGIN");
32882
+ const { rows } = await client.query(
32883
+ `UPDATE ${this.accounts}
32884
+ SET available = available - $2, reserved = reserved + $2, updated_at = now()
32885
+ WHERE account_id = $1 AND available >= $2
32886
+ RETURNING available`,
32887
+ [input.accountId, input.credits]
32888
+ );
32889
+ if (rows.length === 0) {
32890
+ await client.query("ROLLBACK");
32891
+ const current = await client.query(
32892
+ `SELECT available FROM ${this.accounts} WHERE account_id = $1`,
32893
+ [input.accountId]
32894
+ );
32895
+ throw new InsufficientCreditsError(
32896
+ input.accountId,
32897
+ input.credits,
32898
+ current.rows[0] ? Number(current.rows[0].available) : 0
32899
+ );
32900
+ }
32901
+ const id = generateCreditId("cr");
32902
+ const inserted = await client.query(
32903
+ `INSERT INTO ${this.reservations}
32904
+ (id, account_id, credits, status, reference, idempotency_key, expires_at)
32905
+ VALUES ($1, $2, $3, 'held', $4, $5, now() + make_interval(secs => $6))
32906
+ RETURNING *`,
32907
+ [
32908
+ id,
32909
+ input.accountId,
32910
+ input.credits,
32911
+ input.reference ?? null,
32912
+ input.idempotencyKey,
32913
+ seconds
32914
+ ]
32915
+ );
32916
+ await this.insertEntry(client, {
32917
+ accountId: input.accountId,
32918
+ kind: "reserve",
32919
+ delta: -input.credits,
32920
+ consumed: 0,
32921
+ availableAfter: Number(rows[0].available),
32922
+ reservationId: id,
32923
+ reference: input.reference ?? null,
32924
+ idempotencyKey: `reserve:${id}`
32925
+ });
32926
+ await client.query("COMMIT");
32927
+ return toReservation(inserted.rows[0]);
32928
+ } catch (error) {
32929
+ await client.query("ROLLBACK").catch(() => void 0);
32930
+ if (isUniqueViolation(error)) {
32931
+ const winner = await this.reservationByKey(
32932
+ client,
32933
+ input.idempotencyKey
32934
+ );
32935
+ if (winner) return this.replayReservation(winner, input);
32936
+ }
32937
+ throw error;
32938
+ } finally {
32939
+ client.release();
32940
+ }
32941
+ }
32942
+ async settle(reservationId, consumed) {
32943
+ if (!Number.isSafeInteger(consumed) || consumed < 0) {
32944
+ throw new RangeError("consumed must be a whole number of credits >= 0");
32945
+ }
32946
+ return (await this.closeReservation(reservationId, "settled", consumed)).entry;
32947
+ }
32948
+ async release(reservationId) {
32949
+ await this.closeReservation(reservationId, "released", 0);
32950
+ }
32951
+ async clawback(input) {
32952
+ assertWholeCredits(input.credits, "credits");
32953
+ assertIdempotencyKey(input.idempotencyKey);
32954
+ const replay = (entry2) => {
32955
+ if (entry2.accountId !== input.accountId || entry2.kind !== "clawback") {
32956
+ throw new CreditIdempotencyConflictError(input.idempotencyKey);
32957
+ }
32958
+ return entry2;
32959
+ };
32960
+ const entry = await this.idempotent(
32961
+ input.idempotencyKey,
32962
+ replay,
32963
+ async (client) => {
32964
+ await client.query(
32965
+ `INSERT INTO ${this.accounts} (account_id) VALUES ($1) ON CONFLICT DO NOTHING`,
32966
+ [input.accountId]
32967
+ );
32968
+ const { rows } = await client.query(
32969
+ `SELECT available FROM ${this.accounts} WHERE account_id = $1 FOR UPDATE`,
32970
+ [input.accountId]
32971
+ );
32972
+ const taken = Math.min(input.credits, Number(rows[0].available));
32973
+ const updated = await client.query(
32974
+ `UPDATE ${this.accounts} SET available = available - $2, updated_at = now()
32975
+ WHERE account_id = $1 RETURNING available`,
32976
+ [input.accountId, taken]
32977
+ );
32978
+ return this.insertEntry(client, {
32979
+ accountId: input.accountId,
32980
+ kind: "clawback",
32981
+ delta: -taken,
32982
+ consumed: 0,
32983
+ availableAfter: Number(updated.rows[0].available),
32984
+ reservationId: null,
32985
+ reference: input.reference ?? null,
32986
+ idempotencyKey: input.idempotencyKey
32987
+ });
32988
+ }
32989
+ );
32990
+ return { entry, clawedBack: -entry.delta };
32991
+ }
32992
+ async expireReservations(now) {
32993
+ const { rows } = await this.pool.query(
32994
+ `SELECT id FROM ${this.reservations}
32995
+ WHERE status = 'held' AND expires_at <= COALESCE($1::timestamptz, now())
32996
+ ORDER BY expires_at LIMIT 500`,
32997
+ [now ? now.toISOString() : null]
32998
+ );
32999
+ let released = 0;
33000
+ for (const row of rows) {
33001
+ const { closedHere } = await this.closeReservation(
33002
+ row.id,
33003
+ "released",
33004
+ 0
33005
+ );
33006
+ if (closedHere) released++;
33007
+ }
33008
+ return released;
33009
+ }
33010
+ async getReservation(reservationId) {
33011
+ const { rows } = await this.pool.query(
33012
+ `SELECT * FROM ${this.reservations} WHERE id = $1`,
33013
+ [reservationId]
33014
+ );
33015
+ return rows[0] ? toReservation(rows[0]) : null;
33016
+ }
33017
+ async listEntries(accountId, options = {}) {
33018
+ const limit = clampEntryLimit(options.limit);
33019
+ const { rows } = await this.pool.query(
33020
+ `SELECT * FROM ${this.entries} WHERE account_id = $1
33021
+ ORDER BY created_at DESC, id DESC LIMIT $2`,
33022
+ [accountId, limit]
33023
+ );
33024
+ return rows.map(toEntry);
33025
+ }
33026
+ // ─────────────────────────────────────────────────────────────
33027
+ // Internals
33028
+ // ─────────────────────────────────────────────────────────────
33029
+ /**
33030
+ * Runs `write` in a transaction keyed by `idempotencyKey`. An existing
33031
+ * entry with that key is replayed instead; a concurrent duplicate that
33032
+ * loses the unique insert rolls back and replays the winner.
33033
+ */
33034
+ async idempotent(idempotencyKey, replay, write) {
33035
+ const prior = await this.entryByKey(this.pool, idempotencyKey);
33036
+ if (prior) return replay(prior);
33037
+ const client = await this.pool.connect();
33038
+ try {
33039
+ await client.query("BEGIN");
33040
+ const entry = await write(client);
33041
+ await client.query("COMMIT");
33042
+ return entry;
33043
+ } catch (error) {
33044
+ await client.query("ROLLBACK").catch(() => void 0);
33045
+ if (isUniqueViolation(error)) {
33046
+ const winner = await this.entryByKey(client, idempotencyKey);
33047
+ if (winner) return replay(winner);
33048
+ }
33049
+ throw error;
33050
+ } finally {
33051
+ client.release();
33052
+ }
33053
+ }
33054
+ async closeReservation(reservationId, status, consumed) {
33055
+ const key = `${status === "settled" ? "settle" : "release"}:${reservationId}`;
33056
+ const client = await this.pool.connect();
33057
+ try {
33058
+ await client.query("BEGIN");
33059
+ const { rows } = await client.query(
33060
+ `SELECT * FROM ${this.reservations} WHERE id = $1 FOR UPDATE`,
33061
+ [reservationId]
33062
+ );
33063
+ if (!rows[0]) {
33064
+ throw new CreditReservationStateError(
33065
+ `Reservation ${reservationId} not found`
33066
+ );
33067
+ }
33068
+ const reservation = toReservation(rows[0]);
33069
+ if (reservation.status !== "held") {
33070
+ await client.query("ROLLBACK");
33071
+ const settledEntry = await this.entryByKey(
33072
+ client,
33073
+ `settle:${reservationId}`
33074
+ );
33075
+ if (status === "released") {
33076
+ const entry2 = settledEntry ?? await this.entryByKey(client, `release:${reservationId}`);
33077
+ return { entry: entry2, closedHere: false };
33078
+ }
33079
+ if (reservation.status === "released") {
33080
+ throw new CreditReservationStateError(
33081
+ `Reservation ${reservationId} was released`
33082
+ );
33083
+ }
33084
+ if (!settledEntry || settledEntry.consumed !== consumed) {
33085
+ throw new CreditIdempotencyConflictError(key);
33086
+ }
33087
+ return { entry: settledEntry, closedHere: false };
33088
+ }
33089
+ if (consumed > reservation.credits) {
33090
+ throw new CreditReservationStateError(
33091
+ `Cannot consume ${consumed}; reservation holds ${reservation.credits}`
33092
+ );
33093
+ }
33094
+ const returned = reservation.credits - consumed;
33095
+ const account = await client.query(
33096
+ `UPDATE ${this.accounts}
33097
+ SET reserved = reserved - $2, available = available + $3, updated_at = now()
33098
+ WHERE account_id = $1 RETURNING available`,
33099
+ [reservation.accountId, reservation.credits, returned]
33100
+ );
33101
+ await client.query(
33102
+ `UPDATE ${this.reservations} SET status = $2, consumed = $3, updated_at = now() WHERE id = $1`,
33103
+ [reservationId, status, status === "settled" ? consumed : null]
33104
+ );
33105
+ const entry = await this.insertEntry(client, {
33106
+ accountId: reservation.accountId,
33107
+ kind: status === "settled" ? "settle" : "release",
33108
+ delta: returned,
33109
+ consumed,
33110
+ availableAfter: Number(account.rows[0].available),
33111
+ reservationId,
33112
+ reference: reservation.reference,
33113
+ idempotencyKey: key
33114
+ });
33115
+ await client.query("COMMIT");
33116
+ return { entry, closedHere: true };
33117
+ } catch (error) {
33118
+ await client.query("ROLLBACK").catch(() => void 0);
33119
+ throw error;
33120
+ } finally {
33121
+ client.release();
33122
+ }
33123
+ }
33124
+ async insertEntry(client, entry) {
33125
+ const { rows } = await client.query(
33126
+ `INSERT INTO ${this.entries}
33127
+ (id, account_id, kind, delta, consumed, available_after, reservation_id, reference, idempotency_key)
33128
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
33129
+ RETURNING *`,
33130
+ [
33131
+ generateCreditId("ce"),
33132
+ entry.accountId,
33133
+ entry.kind,
33134
+ entry.delta,
33135
+ entry.consumed,
33136
+ entry.availableAfter,
33137
+ entry.reservationId,
33138
+ entry.reference,
33139
+ entry.idempotencyKey
33140
+ ]
33141
+ );
33142
+ return toEntry(rows[0]);
33143
+ }
33144
+ async entryByKey(db, idempotencyKey) {
33145
+ const { rows } = await db.query(
33146
+ `SELECT * FROM ${this.entries} WHERE idempotency_key = $1`,
33147
+ [idempotencyKey]
33148
+ );
33149
+ return rows[0] ? toEntry(rows[0]) : null;
33150
+ }
33151
+ async reservationByKey(db, idempotencyKey) {
33152
+ const { rows } = await db.query(
33153
+ `SELECT * FROM ${this.reservations} WHERE idempotency_key = $1`,
33154
+ [idempotencyKey]
33155
+ );
33156
+ return rows[0] ? toReservation(rows[0]) : null;
33157
+ }
33158
+ replayReservation(existing, input) {
33159
+ if (existing.accountId !== input.accountId || existing.credits !== input.credits) {
33160
+ throw new CreditIdempotencyConflictError(input.idempotencyKey);
33161
+ }
33162
+ return existing;
33163
+ }
33164
+ };
33165
+
32449
33166
  // src/app-logger.ts
32450
33167
  var LEVEL_PRIORITY2 = {
32451
33168
  debug: 0,
@@ -32579,9 +33296,12 @@ function createRedisClient(options) {
32579
33296
  const client = new Redis(url, {
32580
33297
  keyPrefix,
32581
33298
  maxRetriesPerRequest: maxRetries,
33299
+ // Never give up reconnecting. Returning null here ends the connection
33300
+ // for good, and a long-lived singleton (rate limiting, caching) would
33301
+ // then stay broken until the process restarts. maxRetriesPerRequest
33302
+ // still makes individual commands fail fast while disconnected.
32582
33303
  retryStrategy(times) {
32583
- if (times > maxRetries) return null;
32584
- return Math.min(times * 200, 2e3);
33304
+ return Math.min(times * 200, 5e3);
32585
33305
  },
32586
33306
  lazyConnect
32587
33307
  });
@@ -33471,11 +34191,14 @@ export {
33471
34191
  CommonRateLimits,
33472
34192
  ConsoleEmail,
33473
34193
  ConsoleLogger,
34194
+ CreditIdempotencyConflictError,
34195
+ CreditReservationStateError,
33474
34196
  CronPresets,
33475
34197
  CryptoConfigSchema,
33476
34198
  DEFAULT_AGENT_LOOP_OPTIONS,
33477
34199
  DEFAULT_BULKHEAD_OPTIONS,
33478
34200
  DEFAULT_CIRCUIT_BREAKER_OPTIONS,
34201
+ DEFAULT_RESERVATION_SECONDS,
33479
34202
  DEFAULT_RETRY_OPTIONS,
33480
34203
  DatabaseAIUsage,
33481
34204
  DatabaseAuditLog,
@@ -33497,10 +34220,12 @@ export {
33497
34220
  GoogleAIAdapter,
33498
34221
  HTML_TAG_PATTERN,
33499
34222
  HttpWebhook,
34223
+ InsufficientCreditsError,
33500
34224
  KEYCLOAK_DEFAULT_ROLES,
33501
34225
  LogLevelSchema,
33502
34226
  LoggingConfigSchema,
33503
34227
  LoginSchema,
34228
+ MAX_LIST_ENTRIES,
33504
34229
  MemoryAI,
33505
34230
  MemoryAIUsage,
33506
34231
  MemoryAuditLog,
@@ -33510,6 +34235,7 @@ export {
33510
34235
  MemoryBilling,
33511
34236
  MemoryCache,
33512
34237
  MemoryCompliance,
34238
+ MemoryCreditLedger,
33513
34239
  MemoryCrypto,
33514
34240
  MemoryDatabase,
33515
34241
  MemoryDevPortal,
@@ -33549,6 +34275,7 @@ export {
33549
34275
  PineconeRAG,
33550
34276
  PlatformConfigSchema,
33551
34277
  PostgresBeta,
34278
+ PostgresCreditLedger,
33552
34279
  PostgresDatabase,
33553
34280
  PostgresTenant,
33554
34281
  QueueConfigSchema,
@@ -33590,6 +34317,8 @@ export {
33590
34317
  WeaviateRAG,
33591
34318
  WebhookEventTypes,
33592
34319
  WrapperPresets,
34320
+ assertIdempotencyKey,
34321
+ assertWholeCredits,
33593
34322
  buildAllowlist,
33594
34323
  buildAuthCookies,
33595
34324
  buildErrorBody,
@@ -33603,6 +34332,7 @@ export {
33603
34332
  calculateRetryDelay,
33604
34333
  checkEnvVars,
33605
34334
  checkRateLimit,
34335
+ clampEntryLimit,
33606
34336
  classifyError,
33607
34337
  clearStoredBetaCode,
33608
34338
  closeSharedRedis,
@@ -33689,6 +34419,7 @@ export {
33689
34419
  generateBetaCode,
33690
34420
  generateBetaId,
33691
34421
  generateChecksum,
34422
+ generateCreditId,
33692
34423
  generateDeliveryId,
33693
34424
  generateErrorId,
33694
34425
  generateEventId,
@@ -33741,6 +34472,7 @@ export {
33741
34472
  parseKeycloakRoles,
33742
34473
  raceTimeout,
33743
34474
  refreshKeycloakToken,
34475
+ reservationSeconds,
33744
34476
  resetRateLimitForKey,
33745
34477
  resolveIdentifier,
33746
34478
  resolveRateLimitIdentifier,