@remit/drizzle-service 0.0.28 → 0.0.30

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@remit/drizzle-service",
3
- "version": "0.0.28",
3
+ "version": "0.0.30",
4
4
  "description": "Drizzle ORM service parameterized by dialect (Postgres / SQLite)",
5
5
  "type": "module",
6
6
  "main": "src/index.ts",
package/src/index.ts CHANGED
@@ -10,6 +10,7 @@ export {
10
10
  export { DrizzleEnvelopeRepository } from "./repos/envelope.js";
11
11
  export { FilterRepo } from "./repos/filter.js";
12
12
  export { FilterAnchorRepo } from "./repos/filter-anchor.js";
13
+ export { DrizzleFilterAnchorTransaction } from "./repos/filter-anchor-transaction.js";
13
14
  export * from "./repos/i4-account.js";
14
15
  export * from "./repos/i4-account-config.js";
15
16
  export * from "./repos/i4-account-export-request.js";
@@ -0,0 +1,136 @@
1
+ import assert from "node:assert";
2
+ import { after, before, describe, test } from "node:test";
3
+ import { FilterScope } from "@remit/domain-enums";
4
+ import { NotFoundError } from "../error.js";
5
+ import { createTestDb, randomId, type TestDb } from "../test-db.js";
6
+ import { FilterRepo } from "./filter.js";
7
+ import { FilterAnchorRepo } from "./filter-anchor.js";
8
+ import { DrizzleFilterAnchorTransaction } from "./filter-anchor-transaction.js";
9
+
10
+ describe("DrizzleFilterAnchorTransaction", () => {
11
+ let db: TestDb;
12
+ let close: () => Promise<void>;
13
+ let transaction: DrizzleFilterAnchorTransaction;
14
+ let filterRepo: FilterRepo;
15
+ let filterAnchorRepo: FilterAnchorRepo;
16
+
17
+ before(async () => {
18
+ ({ db, close } = await createTestDb());
19
+ transaction = new DrizzleFilterAnchorTransaction(db as never);
20
+ filterRepo = new FilterRepo(db as never);
21
+ filterAnchorRepo = new FilterAnchorRepo(db as never);
22
+ });
23
+
24
+ after(async () => {
25
+ await close();
26
+ });
27
+
28
+ test("creates the Filter and its FilterAnchor together", async () => {
29
+ const accountConfigId = randomId();
30
+
31
+ const filter = await transaction.createWithAnchor(
32
+ {
33
+ accountConfigId,
34
+ name: "Booking confirmations",
35
+ scope: FilterScope.Standing,
36
+ hasAnchor: true,
37
+ },
38
+ {
39
+ accountConfigId,
40
+ anchorMessageId: randomId(),
41
+ anchorEmbedding: [0.1, 0.2, 0.3],
42
+ anchorEmbeddingId: "amazon.titan-embed-text-v2:0@1024",
43
+ anchorSourceText: "Your booking is confirmed",
44
+ },
45
+ );
46
+
47
+ assert.equal(filter.hasAnchor, true);
48
+ const anchor = await filterAnchorRepo.get(accountConfigId, filter.filterId);
49
+ assert.ok(anchor, "the FilterAnchor row must exist");
50
+ assert.equal(anchor?.anchorSourceText, "Your booking is confirmed");
51
+ });
52
+
53
+ test("creates a purely-literal Filter when anchor is null", async () => {
54
+ const accountConfigId = randomId();
55
+
56
+ const filter = await transaction.createWithAnchor(
57
+ {
58
+ accountConfigId,
59
+ name: "From billing",
60
+ scope: FilterScope.Standing,
61
+ hasAnchor: false,
62
+ },
63
+ null,
64
+ );
65
+
66
+ assert.equal(filter.hasAnchor, false);
67
+ const anchor = await filterAnchorRepo.get(accountConfigId, filter.filterId);
68
+ assert.equal(anchor, null);
69
+ });
70
+
71
+ test("rolls back the Filter row when the FilterAnchor write fails (#351)", async () => {
72
+ const accountConfigId = randomId();
73
+
74
+ await assert.rejects(() =>
75
+ transaction.createWithAnchor(
76
+ {
77
+ accountConfigId,
78
+ name: "Broken anchor",
79
+ scope: FilterScope.Standing,
80
+ hasAnchor: true,
81
+ },
82
+ {
83
+ accountConfigId,
84
+ anchorMessageId: randomId(),
85
+ anchorEmbedding: [0.1, 0.2, 0.3],
86
+ anchorEmbeddingId: "amazon.titan-embed-text-v2:0@1024",
87
+ // A NOT NULL column at the DB level — simulates a real write
88
+ // failure on the second half of the pair (network blip,
89
+ // transient error), the exact case #351 leaves broken today.
90
+ anchorSourceText: null as unknown as string,
91
+ },
92
+ ),
93
+ );
94
+
95
+ const filters = await filterRepo.listByAccountConfig(accountConfigId);
96
+ assert.equal(
97
+ filters.length,
98
+ 0,
99
+ "the Filter row must not survive when its anchor write fails",
100
+ );
101
+ });
102
+
103
+ test("the caller never sees a Filter row with hasAnchor: true and no anchor (#351)", async () => {
104
+ const accountConfigId = randomId();
105
+
106
+ await assert.rejects(() =>
107
+ transaction.createWithAnchor(
108
+ {
109
+ accountConfigId,
110
+ name: "Broken anchor 2",
111
+ scope: FilterScope.Standing,
112
+ hasAnchor: true,
113
+ },
114
+ {
115
+ accountConfigId,
116
+ anchorMessageId: randomId(),
117
+ anchorEmbedding: [0.1, 0.2, 0.3],
118
+ anchorEmbeddingId: "amazon.titan-embed-text-v2:0@1024",
119
+ anchorSourceText: null as unknown as string,
120
+ },
121
+ ),
122
+ );
123
+
124
+ const filters = await filterRepo.listByAccountConfig(accountConfigId);
125
+ const orphan = filters.find((f) => f.hasAnchor);
126
+ assert.equal(
127
+ orphan,
128
+ undefined,
129
+ "no Filter with hasAnchor: true may exist without a FilterAnchor row",
130
+ );
131
+ });
132
+
133
+ test("get on a never-created filter still throws NotFoundError (sanity)", async () => {
134
+ await assert.rejects(filterRepo.get(randomId(), randomId()), NotFoundError);
135
+ });
136
+ });
@@ -0,0 +1,45 @@
1
+ import type {
2
+ CreateFilterAnchorInput,
3
+ CreateFilterInput,
4
+ FilterItem,
5
+ IFilterAnchorTransaction,
6
+ } from "@remit/data-ports";
7
+ import type { Db } from "../db.js";
8
+ import { runInTransaction } from "../tx.js";
9
+ import { FilterRepo } from "./filter.js";
10
+ import { FilterAnchorRepo } from "./filter-anchor.js";
11
+
12
+ type DB = Db<Record<string, unknown>>;
13
+
14
+ /**
15
+ * Runs the `Filter` create and its optional `FilterAnchor` write in one
16
+ * transaction (#351): a failure on either side rolls back both, so a
17
+ * `Filter` row can never persist with `hasAnchor: true` and no matching
18
+ * `FilterAnchor` row, and a `FilterAnchor` write failure surfaces as a
19
+ * failed create request rather than a silently-broken filter.
20
+ */
21
+ export class DrizzleFilterAnchorTransaction
22
+ implements IFilterAnchorTransaction
23
+ {
24
+ constructor(private db: DB) {}
25
+
26
+ createWithAnchor(
27
+ filterInput: CreateFilterInput,
28
+ anchorInput: Omit<CreateFilterAnchorInput, "filterId"> | null,
29
+ ): Promise<FilterItem> {
30
+ return runInTransaction(this.db, async (tx) => {
31
+ const filterRepo = new FilterRepo(tx as never);
32
+ const filter = await filterRepo.create(filterInput);
33
+
34
+ if (anchorInput) {
35
+ const filterAnchorRepo = new FilterAnchorRepo(tx as never);
36
+ await filterAnchorRepo.put({
37
+ ...anchorInput,
38
+ filterId: filter.filterId,
39
+ });
40
+ }
41
+
42
+ return filter;
43
+ });
44
+ }
45
+ }
@@ -2,12 +2,14 @@ import type {
2
2
  CreateLabelInput,
3
3
  ILabelRepository,
4
4
  LabelItem,
5
+ ResultList,
5
6
  UpdateLabelInput,
6
7
  } from "@remit/data-ports";
7
- import { and, eq } from "drizzle-orm";
8
+ import { and, asc, eq, gt, or } from "drizzle-orm";
8
9
  import type { NodePgDatabase } from "drizzle-orm/node-postgres";
9
10
  import { NotFoundError } from "../error.js";
10
11
  import { randomId } from "../id.js";
12
+ import { decodeToken, resultList } from "../pagination.js";
11
13
  import { labelTable } from "../schema.js";
12
14
 
13
15
  type DB = NodePgDatabase<Record<string, unknown>>;
@@ -107,6 +109,58 @@ export class LabelRepo implements ILabelRepository {
107
109
  return rows.map(rowToLabel);
108
110
  }
109
111
 
112
+ /**
113
+ * A single signed page of an account config's labels (issue #26), mirroring
114
+ * `FilterRepo.listPageByAccountConfig`: a `(createdAt, labelId)` keyset
115
+ * cursor that round-trips through `continuationToken`.
116
+ */
117
+ async listPageByAccountConfig(
118
+ accountConfigId: string,
119
+ options?: { limit?: number; continuationToken?: string },
120
+ ): Promise<ResultList<LabelItem>> {
121
+ const limit = options?.limit ?? 100;
122
+ const cursor = options?.continuationToken
123
+ ? decodeToken(options.continuationToken)
124
+ : undefined;
125
+ const after = cursor
126
+ ? {
127
+ createdAt: cursor.createdAt as number,
128
+ labelId: cursor.labelId as string,
129
+ }
130
+ : undefined;
131
+
132
+ const rows = await this.db
133
+ .select()
134
+ .from(labelTable)
135
+ .where(
136
+ and(
137
+ eq(labelTable.accountConfigId, accountConfigId),
138
+ after
139
+ ? or(
140
+ gt(labelTable.createdAt, after.createdAt),
141
+ and(
142
+ eq(labelTable.createdAt, after.createdAt),
143
+ gt(labelTable.labelId, after.labelId),
144
+ ),
145
+ )
146
+ : undefined,
147
+ ),
148
+ )
149
+ .orderBy(asc(labelTable.createdAt), asc(labelTable.labelId))
150
+ .limit(limit + 1);
151
+
152
+ const hasMore = rows.length > limit;
153
+ const items = rows.slice(0, limit).map(rowToLabel);
154
+ const lastItem = items[items.length - 1];
155
+ return resultList(
156
+ items,
157
+ limit,
158
+ hasMore && lastItem
159
+ ? { createdAt: lastItem.createdAt, labelId: lastItem.labelId }
160
+ : undefined,
161
+ );
162
+ }
163
+
110
164
  async findByNormalizedName(
111
165
  accountConfigId: string,
112
166
  normalizedName: string,
@@ -107,4 +107,55 @@ describe("MessageLabelRepo", () => {
107
107
  const messageIds = rows.map((r) => r.messageId).sort();
108
108
  assert.deepEqual(messageIds, [messageIdA, messageIdB].sort());
109
109
  });
110
+
111
+ test("listByMessageIds batch-fetches across several messages in one call", async () => {
112
+ const accountConfigId = randomId();
113
+ const messageIdA = randomId();
114
+ const messageIdB = randomId();
115
+ const messageIdC = randomId();
116
+ const labelId = randomId();
117
+
118
+ await repo.apply({ accountConfigId, messageId: messageIdA, labelId });
119
+ await repo.apply({ accountConfigId, messageId: messageIdB, labelId });
120
+
121
+ const rows = await repo.listByMessageIds([
122
+ messageIdA,
123
+ messageIdB,
124
+ messageIdC,
125
+ ]);
126
+ const messageIds = rows.map((r) => r.messageId).sort();
127
+ assert.deepEqual(messageIds, [messageIdA, messageIdB].sort());
128
+ });
129
+
130
+ test("listByMessageIds returns nothing for an empty list", async () => {
131
+ const rows = await repo.listByMessageIds([]);
132
+ assert.deepEqual(rows, []);
133
+ });
134
+
135
+ test("removeAllByLabelId clears every MessageLabel row for the label, scoped to the account", async () => {
136
+ const accountConfigId = randomId();
137
+ const labelId = randomId();
138
+ const messageIdA = randomId();
139
+ const messageIdB = randomId();
140
+ const foreignAccountConfigId = randomId();
141
+ const foreignMessageId = randomId();
142
+
143
+ await repo.apply({ accountConfigId, messageId: messageIdA, labelId });
144
+ await repo.apply({ accountConfigId, messageId: messageIdB, labelId });
145
+ await repo.apply({
146
+ accountConfigId: foreignAccountConfigId,
147
+ messageId: foreignMessageId,
148
+ labelId,
149
+ });
150
+
151
+ await repo.removeAllByLabelId(accountConfigId, labelId);
152
+
153
+ assert.deepEqual(await repo.listByMessageId(messageIdA), []);
154
+ assert.deepEqual(await repo.listByMessageId(messageIdB), []);
155
+ const foreignRows = await repo.listByLabelId(
156
+ foreignAccountConfigId,
157
+ labelId,
158
+ );
159
+ assert.equal(foreignRows.length, 1);
160
+ });
110
161
  });
@@ -3,7 +3,7 @@ import type {
3
3
  IMessageLabelRepository,
4
4
  MessageLabelItem,
5
5
  } from "@remit/data-ports";
6
- import { and, desc, eq } from "drizzle-orm";
6
+ import { and, desc, eq, inArray } from "drizzle-orm";
7
7
  import type { NodePgDatabase } from "drizzle-orm/node-postgres";
8
8
  import { deterministicBase36Id } from "../id.js";
9
9
  import { messageLabelTable } from "../schema.js";
@@ -77,6 +77,15 @@ export class MessageLabelRepo implements IMessageLabelRepository {
77
77
  return rows.map(rowToMessageLabel);
78
78
  }
79
79
 
80
+ async listByMessageIds(messageIds: string[]): Promise<MessageLabelItem[]> {
81
+ if (messageIds.length === 0) return [];
82
+ const rows = await this.db
83
+ .select()
84
+ .from(messageLabelTable)
85
+ .where(inArray(messageLabelTable.messageId, messageIds));
86
+ return rows.map(rowToMessageLabel);
87
+ }
88
+
80
89
  async listByLabelId(
81
90
  accountConfigId: string,
82
91
  labelId: string,
@@ -93,4 +102,18 @@ export class MessageLabelRepo implements IMessageLabelRepository {
93
102
  .orderBy(desc(messageLabelTable.createdAt));
94
103
  return rows.map(rowToMessageLabel);
95
104
  }
105
+
106
+ async removeAllByLabelId(
107
+ accountConfigId: string,
108
+ labelId: string,
109
+ ): Promise<void> {
110
+ await this.db
111
+ .delete(messageLabelTable)
112
+ .where(
113
+ and(
114
+ eq(messageLabelTable.accountConfigId, accountConfigId),
115
+ eq(messageLabelTable.labelId, labelId),
116
+ ),
117
+ );
118
+ }
96
119
  }