@agentbadge/database 0.6.9 → 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.
@@ -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,
@@ -164,24 +184,19 @@ export class EntitlementRepository {
164
184
  return rows.slice(0, need);
165
185
  }
166
186
  async listActiveWithSource(limit, afterKey) {
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 (afterKey !== undefined) {
177
- const sep = afterKey.indexOf("|");
178
- const cAt = afterKey.slice(0, sep);
179
- const cId = afterKey.slice(sep + 1);
180
- out = out.filter((r) => r.createdAt > cAt || (r.createdAt === cAt && r.id > cId));
181
- }
182
- if (limit !== undefined)
183
- out = out.slice(0, limit);
184
- return out;
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);
185
200
  }
186
201
  async applyStatus(id, expectedFrom, to, payloadPatch) {
187
202
  const existing = await this.getById(id);
@@ -243,10 +258,14 @@ export class ReputationFactRepository {
243
258
  return (await q.all()).map(toFactRow);
244
259
  }
245
260
  async countsByActor(actorWallet) {
246
- 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));
247
266
  const out = {};
248
267
  for (const r of rows)
249
- out[r.factType] = (out[r.factType] ?? 0) + 1;
268
+ out[r.factType] = Number(r.n);
250
269
  return out;
251
270
  }
252
271
  }
@@ -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>;
@@ -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();
@@ -90,10 +100,11 @@ export class InMemoryEntitlementStore {
90
100
  out = out.sort((a, b) => a.createdAt.localeCompare(b.createdAt) ||
91
101
  a.id.localeCompare(b.id));
92
102
  if (afterKey !== undefined) {
93
- const sep = afterKey.indexOf("|");
94
- const cAt = afterKey.slice(0, sep);
95
- const cId = afterKey.slice(sep + 1);
96
- out = out.filter((r) => r.createdAt > cAt || (r.createdAt === cAt && r.id > cId));
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
+ }
97
108
  }
98
109
  if (limit !== undefined)
99
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.9",
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",