@agentbadge/database 0.6.8 → 0.6.10

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.
@@ -26,7 +26,7 @@ export declare class EntitlementRepository implements EntitlementStore {
26
26
  limit?: number;
27
27
  }): Promise<EntitlementRow[]>;
28
28
  listExpiring(nowMs: number, limit?: number): Promise<EntitlementRow[]>;
29
- listActiveWithSource(limit?: number, afterId?: string): Promise<EntitlementRow[]>;
29
+ listActiveWithSource(limit?: number, afterKey?: string): Promise<EntitlementRow[]>;
30
30
  applyStatus(id: string, expectedFrom: string, to: string, payloadPatch?: Record<string, JsonValue | undefined>): Promise<EntitlementRow | null>;
31
31
  }
32
32
  export declare class ReputationFactRepository implements ReputationFactStore {
@@ -1,4 +1,6 @@
1
+ import { param } from "@prisma/orm-postgres/relational-core/expression";
1
2
  import { isUniqueViolation } from "./commerce-repository.js";
3
+ import { parseReversalCursor } from "./identity-store.js";
2
4
  const catchUnique = async (p) => {
3
5
  try {
4
6
  return await p;
@@ -38,6 +40,24 @@ const toEntitlementRow = (r) => ({
38
40
  createdAt: r.createdAt,
39
41
  updatedAt: r.updatedAt,
40
42
  });
43
+ const ENTITLEMENT_ROW_SPEC = {
44
+ id: "pg/text@1",
45
+ ownerId: "pg/text@1",
46
+ productCode: "pg/text@1",
47
+ sourcePaymentId: { codecId: "pg/text@1", nullable: true },
48
+ status: "pg/text@1",
49
+ validFromMs: "pg/int8@1",
50
+ validUntilMs: { codecId: "pg/int8@1", nullable: true },
51
+ idempotencyKey: "pg/text@1",
52
+ activeSlot: { codecId: "pg/text@1", nullable: true },
53
+ payload: "pg/json@1",
54
+ createdAt: "pg/timestamptz-string@1",
55
+ updatedAt: "pg/timestamptz-string@1",
56
+ };
57
+ const FACT_COUNT_ROW_SPEC = {
58
+ factType: "pg/text@1",
59
+ n: "pg/int8@1",
60
+ };
41
61
  const toFactRow = (r) => ({
42
62
  id: r.id,
43
63
  actorWallet: r.actorWallet,
@@ -163,23 +183,20 @@ export class EntitlementRepository {
163
183
  .filter((r) => r.validUntilMs != null && r.validUntilMs <= nowMs);
164
184
  return rows.slice(0, need);
165
185
  }
166
- async listActiveWithSource(limit, afterId) {
167
- const rows = await this.orm
168
- .where({ status: "ACTIVE" })
169
- .orderBy((t) => t.createdAt.asc())
170
- .all();
171
- let out = rows
172
- .map(toEntitlementRow)
173
- .filter((r) => r.sourcePaymentId != null);
174
- out = out.sort((a, b) => a.createdAt.localeCompare(b.createdAt) ||
175
- a.id.localeCompare(b.id));
176
- if (afterId !== undefined) {
177
- const idx = out.findIndex((r) => r.id === afterId);
178
- out = idx >= 0 ? out.slice(idx + 1) : out;
179
- }
180
- if (limit !== undefined)
181
- out = out.slice(0, limit);
182
- return out;
186
+ async listActiveWithSource(limit, afterKey) {
187
+ const lim = param(limit ?? 500, { codecId: "pg/int4@1" });
188
+ const cur = afterKey !== undefined ? parseReversalCursor(afterKey) : null;
189
+ const plan = cur !== null
190
+ ? this.db.raw
191
+ .sql `SELECT "id","ownerId","productCode","sourcePaymentId","status","validFromMs","validUntilMs","idempotencyKey","activeSlot","payload","createdAt","updatedAt" FROM "entitlement" WHERE "status" = 'ACTIVE' AND "sourcePaymentId" IS NOT NULL AND ("createdAt" > ${param(cur.cAt, { codecId: "pg/timestamptz-string@1" })} OR ("createdAt" = ${param(cur.cAt, { codecId: "pg/timestamptz-string@1" })} AND "id" > ${param(cur.cId, { codecId: "pg/text@1" })})) ORDER BY "createdAt" ASC, "id" ASC LIMIT ${lim}`
192
+ .returnsRow(ENTITLEMENT_ROW_SPEC)
193
+ .build()
194
+ : this.db.raw
195
+ .sql `SELECT "id","ownerId","productCode","sourcePaymentId","status","validFromMs","validUntilMs","idempotencyKey","activeSlot","payload","createdAt","updatedAt" FROM "entitlement" WHERE "status" = 'ACTIVE' AND "sourcePaymentId" IS NOT NULL ORDER BY "createdAt" ASC, "id" ASC LIMIT ${lim}`
196
+ .returnsRow(ENTITLEMENT_ROW_SPEC)
197
+ .build();
198
+ const rows = await this.db.runtime().query(plan);
199
+ return rows.map(toEntitlementRow);
183
200
  }
184
201
  async applyStatus(id, expectedFrom, to, payloadPatch) {
185
202
  const existing = await this.getById(id);
@@ -241,10 +258,14 @@ export class ReputationFactRepository {
241
258
  return (await q.all()).map(toFactRow);
242
259
  }
243
260
  async countsByActor(actorWallet) {
244
- const rows = await this.orm.where({ actorWallet }).all();
261
+ const plan = this.db.raw
262
+ .sql `SELECT "factType", COUNT(*) AS "n" FROM "reputationFact" WHERE "actorWallet" = ${param(actorWallet, { codecId: "pg/text@1" })} GROUP BY "factType"`
263
+ .returnsRow(FACT_COUNT_ROW_SPEC)
264
+ .build();
265
+ const rows = (await this.db.runtime().query(plan));
245
266
  const out = {};
246
267
  for (const r of rows)
247
- out[r.factType] = (out[r.factType] ?? 0) + 1;
268
+ out[r.factType] = Number(r.n);
248
269
  return out;
249
270
  }
250
271
  }
@@ -48,7 +48,7 @@ export interface EntitlementStore {
48
48
  limit?: number;
49
49
  }): Promise<EntitlementRow[]>;
50
50
  listExpiring(nowMs: number, limit?: number): Promise<EntitlementRow[]>;
51
- listActiveWithSource(limit?: number, afterId?: string): Promise<EntitlementRow[]>;
51
+ listActiveWithSource(limit?: number, afterKey?: string): Promise<EntitlementRow[]>;
52
52
  applyStatus(id: string, expectedFrom: string, to: string, payloadPatch?: Record<string, JsonValue | undefined>): Promise<EntitlementRow | null>;
53
53
  }
54
54
  export interface ReputationFactInsert {
@@ -79,6 +79,10 @@ export interface IdentityStores {
79
79
  facts: ReputationFactStore;
80
80
  atomic<R>(fn: (stores: IdentityStores) => Promise<R>): Promise<R>;
81
81
  }
82
+ export declare const parseReversalCursor: (afterKey: string) => {
83
+ cAt: string;
84
+ cId: string;
85
+ } | null;
82
86
  export declare class InMemoryActorStore implements ActorStore {
83
87
  private readonly rows;
84
88
  upsert(a: ActorUpsert): Promise<ActorRow>;
@@ -100,7 +104,7 @@ export declare class InMemoryEntitlementStore implements EntitlementStore {
100
104
  limit?: number;
101
105
  }): Promise<EntitlementRow[]>;
102
106
  listExpiring(nowMs: number, limit?: number): Promise<EntitlementRow[]>;
103
- listActiveWithSource(limit?: number, afterId?: string): Promise<EntitlementRow[]>;
107
+ listActiveWithSource(limit?: number, afterKey?: string): Promise<EntitlementRow[]>;
104
108
  applyStatus(id: string, expectedFrom: string, to: string, payloadPatch?: Record<string, JsonValue | undefined>): Promise<EntitlementRow | null>;
105
109
  }
106
110
  export declare class InMemoryReputationFactStore implements ReputationFactStore {
@@ -1,4 +1,14 @@
1
1
  const nowIso = () => new Date().toISOString();
2
+ export const parseReversalCursor = (afterKey) => {
3
+ const sep = afterKey.indexOf("|");
4
+ if (sep <= 0 || sep === afterKey.length - 1)
5
+ return null;
6
+ const cAt = afterKey.slice(0, sep);
7
+ const cId = afterKey.slice(sep + 1);
8
+ if (Number.isNaN(Date.parse(cAt)))
9
+ return null;
10
+ return { cAt, cId };
11
+ };
2
12
  const entActiveSlot = (e) => e.status === "ACTIVE" ? `${e.ownerId}|${e.productCode}` : null;
3
13
  export class InMemoryActorStore {
4
14
  rows = new Map();
@@ -85,13 +95,16 @@ export class InMemoryEntitlementStore {
85
95
  out = out.slice(0, limit);
86
96
  return out;
87
97
  }
88
- async listActiveWithSource(limit, afterId) {
98
+ async listActiveWithSource(limit, afterKey) {
89
99
  let out = [...this.rows.values()].filter((r) => r.status === "ACTIVE" && r.sourcePaymentId != null);
90
100
  out = out.sort((a, b) => a.createdAt.localeCompare(b.createdAt) ||
91
101
  a.id.localeCompare(b.id));
92
- if (afterId !== undefined) {
93
- const idx = out.findIndex((r) => r.id === afterId);
94
- out = idx >= 0 ? out.slice(idx + 1) : out;
102
+ if (afterKey !== undefined) {
103
+ const cur = parseReversalCursor(afterKey);
104
+ if (cur) {
105
+ out = out.filter((r) => r.createdAt > cur.cAt ||
106
+ (r.createdAt === cur.cAt && r.id > cur.cId));
107
+ }
95
108
  }
96
109
  if (limit !== undefined)
97
110
  out = out.slice(0, limit);
@@ -1,3 +1,4 @@
1
+ import { param } from "@prisma/orm-postgres/relational-core/expression";
1
2
  import { TERMINAL_ATTEMPT_STATUSES } from "./payment-store.js";
2
3
  const num = (v) => Number(v);
3
4
  const numOrNull = (v) => v === null || v === undefined ? null : Number(v);
@@ -38,6 +39,23 @@ const toAttemptRow = (r) => ({
38
39
  createdAt: r.createdAt,
39
40
  updatedAt: r.updatedAt,
40
41
  });
42
+ const ATTEMPT_ROW_SPEC = {
43
+ id: "pg/text@1",
44
+ paymentId: "pg/text@1",
45
+ provider: "pg/text@1",
46
+ network: { codecId: "pg/text@1", nullable: true },
47
+ token: { codecId: "pg/text@1", nullable: true },
48
+ amount: "pg/numeric@1",
49
+ currency: "pg/text@1",
50
+ status: "pg/text@1",
51
+ providerReference: { codecId: "pg/text@1", nullable: true },
52
+ transactionHash: { codecId: "pg/text@1", nullable: true },
53
+ expiresAtMs: { codecId: "pg/int8@1", nullable: true },
54
+ confirmedAtMs: { codecId: "pg/int8@1", nullable: true },
55
+ payload: "pg/json@1",
56
+ createdAt: "pg/timestamptz-string@1",
57
+ updatedAt: "pg/timestamptz-string@1",
58
+ };
41
59
  const toReceiptRow = (r) => ({
42
60
  id: r.id,
43
61
  paymentId: r.paymentId,
@@ -294,18 +312,15 @@ export class PaymentAttemptRepository {
294
312
  return out;
295
313
  }
296
314
  async listRecentTerminal(sinceMs) {
315
+ const sinceParam = param(sinceMs, { codecId: "pg/int8@1" });
297
316
  const out = [];
298
317
  for (const status of TERMINAL_ATTEMPT_STATUSES) {
299
- const rows = await this.orm
300
- .where({ status })
301
- .all();
302
- for (const r of rows) {
303
- const stamp = r.updatedAt
304
- ? new Date(r.updatedAt).getTime()
305
- : (numOrNull(r.confirmedAtMs) ?? 0);
306
- if (stamp >= sinceMs)
307
- out.push(toAttemptRow(r));
308
- }
318
+ const plan = this.db.raw
319
+ .sql `SELECT "id","paymentId","provider","network","token","amount","currency","status","providerReference","transactionHash","expiresAtMs","confirmedAtMs","payload","createdAt","updatedAt" FROM "paymentAttempt" WHERE "status" = ${param(status, { codecId: "pg/text@1" })} AND COALESCE(EXTRACT(EPOCH FROM "updatedAt") * 1000, "confirmedAtMs"::float8, 0) >= ${sinceParam}`
320
+ .returnsRow(ATTEMPT_ROW_SPEC)
321
+ .build();
322
+ const rows = await this.db.runtime().query(plan);
323
+ out.push(...rows.map(toAttemptRow));
309
324
  }
310
325
  return out;
311
326
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentbadge/database",
3
- "version": "0.6.8",
3
+ "version": "0.6.10",
4
4
  "description": "Shared database layer for AgentBadge — Prisma ORM 8 client, repositories, store abstraction",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",