@proofoftech/flowsafe 0.4.0 → 0.7.0
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/CHANGELOG.md +327 -0
- package/README.md +295 -251
- package/dist/agent-runner/approval-shapes.d.ts +36 -0
- package/dist/agent-runner/approval-shapes.d.ts.map +1 -0
- package/dist/agent-runner/approval-shapes.js +101 -0
- package/dist/agent-runner/approval-shapes.js.map +1 -0
- package/dist/agent-runner/durable-agent-runner.d.ts +158 -0
- package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -0
- package/dist/agent-runner/durable-agent-runner.js +295 -0
- package/dist/agent-runner/durable-agent-runner.js.map +1 -0
- package/dist/agent-runner/index.d.ts +3 -0
- package/dist/agent-runner/index.d.ts.map +1 -0
- package/dist/agent-runner/index.js +10 -0
- package/dist/agent-runner/index.js.map +1 -0
- package/dist/approval-api/contract.d.ts +2 -2
- package/dist/approval-api/d1-store.d.ts.map +1 -1
- package/dist/approval-api/d1-store.js +87 -19
- package/dist/approval-api/d1-store.js.map +1 -1
- package/dist/approval-api/grants.d.ts +1 -1
- package/dist/approval-api/grants.js +1 -1
- package/dist/approval-api/index.d.ts +1 -1
- package/dist/approval-api/index.d.ts.map +1 -1
- package/dist/approval-api/index.js.map +1 -1
- package/dist/approval-api/router.d.ts +2 -2
- package/dist/approval-api/router.d.ts.map +1 -1
- package/dist/approval-api/router.js +1 -0
- package/dist/approval-api/router.js.map +1 -1
- package/dist/approval-api/service.d.ts +10 -11
- package/dist/approval-api/service.d.ts.map +1 -1
- package/dist/approval-api/service.js +22 -9
- package/dist/approval-api/service.js.map +1 -1
- package/dist/approval-api/store.d.ts +27 -22
- package/dist/approval-api/store.d.ts.map +1 -1
- package/dist/approval-api/store.js +25 -9
- package/dist/approval-api/store.js.map +1 -1
- package/dist/approval-api/tenant-context.d.ts +6 -6
- package/dist/approval-api/tenant-context.d.ts.map +1 -1
- package/dist/approval-api/tenant-context.js +15 -0
- package/dist/approval-api/tenant-context.js.map +1 -1
- package/dist/approval-api/tenant-store.d.ts +1 -1
- package/dist/approval-api/tenant-store.d.ts.map +1 -1
- package/dist/approval-api/types.d.ts +13 -4
- package/dist/approval-api/types.d.ts.map +1 -1
- package/dist/approval-api/types.js +2 -1
- package/dist/approval-api/types.js.map +1 -1
- package/dist/approval-ui/App.d.ts +2 -2
- package/dist/approval-ui/FilterBar.d.ts +3 -3
- package/dist/approval-ui/FilterBar.js +3 -3
- package/dist/approval-ui/client.d.ts +1 -1
- package/dist/approval-ui/components.d.ts +1 -1
- package/dist/approval-ui/stream.d.ts +3 -3
- package/dist/approval-ui/stream.js +2 -2
- package/dist/approval-ui/use-approval-dashboard.d.ts +9 -12
- package/dist/approval-ui/use-approval-dashboard.d.ts.map +1 -1
- package/dist/approval-ui/use-approval-dashboard.js +6 -9
- package/dist/approval-ui/use-approval-dashboard.js.map +1 -1
- package/dist/approval-ui/use-web-socket-transport.d.ts +1 -1
- package/dist/approval-ui/use-web-socket-transport.js +1 -1
- package/dist/background-tasks/d1-storage.d.ts +66 -0
- package/dist/background-tasks/d1-storage.d.ts.map +1 -0
- package/dist/background-tasks/d1-storage.js +196 -0
- package/dist/background-tasks/d1-storage.js.map +1 -0
- package/dist/background-tasks/host.d.ts +82 -0
- package/dist/background-tasks/host.d.ts.map +1 -0
- package/dist/background-tasks/host.js +275 -0
- package/dist/background-tasks/host.js.map +1 -0
- package/dist/background-tasks/index.d.ts +7 -0
- package/dist/background-tasks/index.d.ts.map +1 -0
- package/dist/background-tasks/index.js +10 -0
- package/dist/background-tasks/index.js.map +1 -0
- package/dist/background-tasks/routes.d.ts +15 -0
- package/dist/background-tasks/routes.d.ts.map +1 -0
- package/dist/background-tasks/routes.js +144 -0
- package/dist/background-tasks/routes.js.map +1 -0
- package/dist/do-runner/breakwater-keys.d.ts +1 -1
- package/dist/do-runner/breakwater-keys.js +1 -1
- package/dist/do-runner/cf-types.d.ts +1 -1
- package/dist/do-runner/d1-storage.d.ts +347 -5
- package/dist/do-runner/d1-storage.d.ts.map +1 -1
- package/dist/do-runner/d1-storage.js +571 -17
- package/dist/do-runner/d1-storage.js.map +1 -1
- package/dist/do-runner/do-error-response.d.ts +29 -0
- package/dist/do-runner/do-error-response.d.ts.map +1 -0
- package/dist/do-runner/do-error-response.js +73 -0
- package/dist/do-runner/do-error-response.js.map +1 -0
- package/dist/do-runner/durable-object.d.ts +3 -3
- package/dist/do-runner/durable-object.d.ts.map +1 -1
- package/dist/do-runner/durable-object.js +7 -21
- package/dist/do-runner/durable-object.js.map +1 -1
- package/dist/do-runner/hub-do.d.ts +2 -2
- package/dist/do-runner/index.d.ts +9 -3
- package/dist/do-runner/index.d.ts.map +1 -1
- package/dist/do-runner/index.js +8 -2
- package/dist/do-runner/index.js.map +1 -1
- package/dist/do-runner/init.d.ts +20 -0
- package/dist/do-runner/init.d.ts.map +1 -1
- package/dist/do-runner/init.js +12 -1
- package/dist/do-runner/init.js.map +1 -1
- package/dist/do-runner/memory-id.d.ts +3 -3
- package/dist/do-runner/memory-id.js +3 -3
- package/dist/do-runner/path-safe-id.d.ts +6 -6
- package/dist/do-runner/path-safe-id.js +6 -6
- package/dist/do-runner/pubsub.d.ts +18 -0
- package/dist/do-runner/pubsub.d.ts.map +1 -0
- package/dist/do-runner/pubsub.js +42 -0
- package/dist/do-runner/pubsub.js.map +1 -0
- package/dist/do-runner/runtime.d.ts +24 -1
- package/dist/do-runner/runtime.d.ts.map +1 -1
- package/dist/do-runner/runtime.js +28 -2
- package/dist/do-runner/runtime.js.map +1 -1
- package/dist/do-runner/thread-do.d.ts +74 -0
- package/dist/do-runner/thread-do.d.ts.map +1 -0
- package/dist/do-runner/thread-do.js +156 -0
- package/dist/do-runner/thread-do.js.map +1 -0
- package/dist/do-runner/thread-header.d.ts +16 -0
- package/dist/do-runner/thread-header.d.ts.map +1 -0
- package/dist/do-runner/thread-header.js +24 -0
- package/dist/do-runner/thread-header.js.map +1 -0
- package/dist/goals/index.d.ts +2 -0
- package/dist/goals/index.d.ts.map +1 -0
- package/dist/goals/index.js +7 -0
- package/dist/goals/index.js.map +1 -0
- package/dist/goals/objective-routes.d.ts +87 -0
- package/dist/goals/objective-routes.d.ts.map +1 -0
- package/dist/goals/objective-routes.js +375 -0
- package/dist/goals/objective-routes.js.map +1 -0
- package/dist/host-kit/approval-bridge.d.ts +28 -8
- package/dist/host-kit/approval-bridge.d.ts.map +1 -1
- package/dist/host-kit/approval-bridge.js +37 -15
- package/dist/host-kit/approval-bridge.js.map +1 -1
- package/dist/host-kit/bearer-auth.d.ts +1 -1
- package/dist/host-kit/bearer-auth.js +1 -1
- package/dist/host-kit/env-vars.d.ts +20 -0
- package/dist/host-kit/env-vars.d.ts.map +1 -1
- package/dist/host-kit/env-vars.js +30 -0
- package/dist/host-kit/env-vars.js.map +1 -1
- package/dist/host-kit/flowsafe-worker.d.ts +113 -6
- package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
- package/dist/host-kit/flowsafe-worker.js +253 -63
- package/dist/host-kit/flowsafe-worker.js.map +1 -1
- package/dist/host-kit/host-approval-service.d.ts +13 -13
- package/dist/host-kit/host-approval-service.js +10 -10
- package/dist/host-kit/index.d.ts +3 -1
- package/dist/host-kit/index.d.ts.map +1 -1
- package/dist/host-kit/index.js +7 -0
- package/dist/host-kit/index.js.map +1 -1
- package/dist/host-kit/memory-boundary.d.ts +64 -0
- package/dist/host-kit/memory-boundary.d.ts.map +1 -0
- package/dist/host-kit/memory-boundary.js +109 -0
- package/dist/host-kit/memory-boundary.js.map +1 -0
- package/dist/host-kit/route-path.d.ts +17 -0
- package/dist/host-kit/route-path.d.ts.map +1 -0
- package/dist/host-kit/route-path.js +35 -0
- package/dist/host-kit/route-path.js.map +1 -0
- package/dist/host-kit/run-router.d.ts +10 -11
- package/dist/host-kit/run-router.d.ts.map +1 -1
- package/dist/host-kit/run-router.js.map +1 -1
- package/dist/host-kit/stream-router.d.ts +1 -1
- package/dist/host-kit/stream-router.d.ts.map +1 -1
- package/dist/host-kit/stream-ticket.d.ts +3 -3
- package/dist/host-kit/stream-ticket.d.ts.map +1 -1
- package/dist/host-kit/stream-ticket.js +1 -1
- package/dist/host-kit/tenant-registry.d.ts +1 -1
- package/dist/host-kit/tenant-registry.js +1 -1
- package/dist/host-kit/thread-topology.d.ts +44 -0
- package/dist/host-kit/thread-topology.d.ts.map +1 -0
- package/dist/host-kit/thread-topology.js +76 -0
- package/dist/host-kit/thread-topology.js.map +1 -0
- package/dist/host-kit/verifier.d.ts +1 -1
- package/dist/host-kit/verifier.js +1 -1
- package/dist/index.d.ts +4 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/dist/internal-error-response.d.ts +3 -0
- package/dist/internal-error-response.d.ts.map +1 -0
- package/dist/internal-error-response.js +20 -0
- package/dist/internal-error-response.js.map +1 -0
- package/dist/numeric-config.d.ts +4 -0
- package/dist/numeric-config.d.ts.map +1 -0
- package/dist/numeric-config.js +23 -0
- package/dist/numeric-config.js.map +1 -0
- package/dist/schedules/index.d.ts +5 -0
- package/dist/schedules/index.d.ts.map +1 -0
- package/dist/schedules/index.js +13 -0
- package/dist/schedules/index.js.map +1 -0
- package/dist/schedules/router.d.ts +66 -0
- package/dist/schedules/router.d.ts.map +1 -0
- package/dist/schedules/router.js +827 -0
- package/dist/schedules/router.js.map +1 -0
- package/dist/schedules/schedules-d1.d.ts +30 -0
- package/dist/schedules/schedules-d1.d.ts.map +1 -0
- package/dist/schedules/schedules-d1.js +374 -0
- package/dist/schedules/schedules-d1.js.map +1 -0
- package/dist/schedules/storage.d.ts +11 -0
- package/dist/schedules/storage.d.ts.map +1 -0
- package/dist/schedules/storage.js +34 -0
- package/dist/schedules/storage.js.map +1 -0
- package/dist/schedules/tick.d.ts +132 -0
- package/dist/schedules/tick.d.ts.map +1 -0
- package/dist/schedules/tick.js +598 -0
- package/dist/schedules/tick.js.map +1 -0
- package/dist/signal-providers/delivery.d.ts +24 -0
- package/dist/signal-providers/delivery.d.ts.map +1 -0
- package/dist/signal-providers/delivery.js +62 -0
- package/dist/signal-providers/delivery.js.map +1 -0
- package/dist/signal-providers/github-provider.d.ts +33 -0
- package/dist/signal-providers/github-provider.d.ts.map +1 -0
- package/dist/signal-providers/github-provider.js +116 -0
- package/dist/signal-providers/github-provider.js.map +1 -0
- package/dist/signal-providers/host-do.d.ts +81 -0
- package/dist/signal-providers/host-do.d.ts.map +1 -0
- package/dist/signal-providers/host-do.js +229 -0
- package/dist/signal-providers/host-do.js.map +1 -0
- package/dist/signal-providers/host-topology.d.ts +27 -0
- package/dist/signal-providers/host-topology.d.ts.map +1 -0
- package/dist/signal-providers/host-topology.js +36 -0
- package/dist/signal-providers/host-topology.js.map +1 -0
- package/dist/signal-providers/index.d.ts +8 -0
- package/dist/signal-providers/index.d.ts.map +1 -0
- package/dist/signal-providers/index.js +21 -0
- package/dist/signal-providers/index.js.map +1 -0
- package/dist/signal-providers/provider.d.ts +93 -0
- package/dist/signal-providers/provider.d.ts.map +1 -0
- package/dist/signal-providers/provider.js +89 -0
- package/dist/signal-providers/provider.js.map +1 -0
- package/dist/signal-providers/subscription-d1.d.ts +88 -0
- package/dist/signal-providers/subscription-d1.d.ts.map +1 -0
- package/dist/signal-providers/subscription-d1.js +259 -0
- package/dist/signal-providers/subscription-d1.js.map +1 -0
- package/dist/signal-providers/webhook-route.d.ts +96 -0
- package/dist/signal-providers/webhook-route.d.ts.map +1 -0
- package/dist/signal-providers/webhook-route.js +444 -0
- package/dist/signal-providers/webhook-route.js.map +1 -0
- package/dist/signals/client.d.ts +72 -0
- package/dist/signals/client.d.ts.map +1 -0
- package/dist/signals/client.js +87 -0
- package/dist/signals/client.js.map +1 -0
- package/dist/signals/d1-shared.d.ts +43 -0
- package/dist/signals/d1-shared.d.ts.map +1 -0
- package/dist/signals/d1-shared.js +46 -0
- package/dist/signals/d1-shared.js.map +1 -0
- package/dist/signals/index.d.ts +9 -0
- package/dist/signals/index.d.ts.map +1 -0
- package/dist/signals/index.js +15 -0
- package/dist/signals/index.js.map +1 -0
- package/dist/signals/notification-dispatch.d.ts +52 -0
- package/dist/signals/notification-dispatch.d.ts.map +1 -0
- package/dist/signals/notification-dispatch.js +198 -0
- package/dist/signals/notification-dispatch.js.map +1 -0
- package/dist/signals/notifications-d1.d.ts +27 -0
- package/dist/signals/notifications-d1.d.ts.map +1 -0
- package/dist/signals/notifications-d1.js +703 -0
- package/dist/signals/notifications-d1.js.map +1 -0
- package/dist/signals/router.d.ts +73 -0
- package/dist/signals/router.d.ts.map +1 -0
- package/dist/signals/router.js +240 -0
- package/dist/signals/router.js.map +1 -0
- package/dist/signals/storage.d.ts +11 -0
- package/dist/signals/storage.d.ts.map +1 -0
- package/dist/signals/storage.js +27 -0
- package/dist/signals/storage.js.map +1 -0
- package/dist/signals/thread-do-routes.d.ts +82 -0
- package/dist/signals/thread-do-routes.d.ts.map +1 -0
- package/dist/signals/thread-do-routes.js +660 -0
- package/dist/signals/thread-do-routes.js.map +1 -0
- package/dist/signals/thread-state-d1.d.ts +22 -0
- package/dist/signals/thread-state-d1.d.ts.map +1 -0
- package/dist/signals/thread-state-d1.js +83 -0
- package/dist/signals/thread-state-d1.js.map +1 -0
- package/package.json +11 -2
|
@@ -0,0 +1,703 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// Track C (M-004), CI-M-004-002 — the D1 NotificationsStorage domain over
|
|
3
|
+
// TABLE_NOTIFICATIONS ('mastra_notifications'), mirroring core's abstract
|
|
4
|
+
// NotificationsStorage + InMemoryNotificationsStorage reference (create / list /
|
|
5
|
+
// listDue / get({threadId,id}) / update + findCoalescable coalescing). Composed
|
|
6
|
+
// into createD1Storage's store so `agent.sendNotificationSignal` persists here
|
|
7
|
+
// (core resolves the domain via `mastra.getStorage().getStore('notifications')`).
|
|
8
|
+
//
|
|
9
|
+
// NAMING: mastra_notifications is the AGENT inbox — signals delivered TO the
|
|
10
|
+
// model on its next turn. Distinct from flowsafe's ApprovalNotificationSink,
|
|
11
|
+
// which notifies HUMANS about approvals. Different layers.
|
|
12
|
+
//
|
|
13
|
+
// TENANCY: the `thread_id` column holds the tenant-salted threadId
|
|
14
|
+
// (`${tenantId}_${uuid}`), so purgeTenant's `[tid_, tid\x60)` range is exact
|
|
15
|
+
// over it (registered in TENANT_RANGE_PURGE_TABLES) and the notification TTL
|
|
16
|
+
// reaps terminal rows (purgeExpiredNotifications). Timestamps are ISO-8601 TEXT
|
|
17
|
+
// — the encoding the retention purges and the schema guard ride on.
|
|
18
|
+
import { NotificationsStorage, } from '@mastra/core/notifications';
|
|
19
|
+
import { d1Changes, dateOrUndefined, isoOrNull, jsonOrNull, parseJsonOrUndefined, } from './d1-shared.js';
|
|
20
|
+
/** status → the timestamp column that status stamps (mirrors core statusTimestamp). */
|
|
21
|
+
function statusTimestampColumn(status) {
|
|
22
|
+
switch (status) {
|
|
23
|
+
case 'delivered':
|
|
24
|
+
return 'deliveredAt';
|
|
25
|
+
case 'seen':
|
|
26
|
+
return 'seenAt';
|
|
27
|
+
case 'dismissed':
|
|
28
|
+
return 'dismissedAt';
|
|
29
|
+
case 'archived':
|
|
30
|
+
return 'archivedAt';
|
|
31
|
+
case 'discarded':
|
|
32
|
+
return 'discardedAt';
|
|
33
|
+
default:
|
|
34
|
+
return undefined;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
const NOTIFICATION_COLUMNS = [
|
|
38
|
+
'id',
|
|
39
|
+
'thread_id',
|
|
40
|
+
'source',
|
|
41
|
+
'kind',
|
|
42
|
+
'priority',
|
|
43
|
+
'status',
|
|
44
|
+
'summary',
|
|
45
|
+
'payload',
|
|
46
|
+
'resourceId',
|
|
47
|
+
'agentId',
|
|
48
|
+
'sourceId',
|
|
49
|
+
'dedupeKey',
|
|
50
|
+
'coalesceKey',
|
|
51
|
+
'coalescedCount',
|
|
52
|
+
'attributes',
|
|
53
|
+
'createdAt',
|
|
54
|
+
'updatedAt',
|
|
55
|
+
'deliverAt',
|
|
56
|
+
'summaryAt',
|
|
57
|
+
'deliveryReason',
|
|
58
|
+
'deliveryAttempts',
|
|
59
|
+
'lastDeliveryAttemptAt',
|
|
60
|
+
'lastDeliveryError',
|
|
61
|
+
'deliveredSignalId',
|
|
62
|
+
'summarySignalId',
|
|
63
|
+
'deliveredAt',
|
|
64
|
+
'seenAt',
|
|
65
|
+
'dismissedAt',
|
|
66
|
+
'archivedAt',
|
|
67
|
+
'discardedAt',
|
|
68
|
+
'metadata',
|
|
69
|
+
];
|
|
70
|
+
const NOTIFICATION_UPDATE_COLUMNS = NOTIFICATION_COLUMNS.filter((column) => column !== 'id' && column !== 'thread_id');
|
|
71
|
+
function validLimit(limit) {
|
|
72
|
+
return limit !== undefined && Number.isSafeInteger(limit) && limit >= 0;
|
|
73
|
+
}
|
|
74
|
+
function isDuplicateColumn(error) {
|
|
75
|
+
return error instanceof Error && /duplicate column/i.test(error.message);
|
|
76
|
+
}
|
|
77
|
+
export class D1NotificationsStorage extends NotificationsStorage {
|
|
78
|
+
#db;
|
|
79
|
+
#table;
|
|
80
|
+
#sequenceTable;
|
|
81
|
+
#ordinalIndex;
|
|
82
|
+
#legacyReplaceTrigger;
|
|
83
|
+
#legacyInsertTrigger;
|
|
84
|
+
#ready;
|
|
85
|
+
constructor(db, tablePrefix = '') {
|
|
86
|
+
super();
|
|
87
|
+
this.#db = db;
|
|
88
|
+
this.#table = `${tablePrefix}mastra_notifications`;
|
|
89
|
+
this.#sequenceTable = `${tablePrefix}flowsafe_notification_sequence`;
|
|
90
|
+
this.#ordinalIndex = `idx_${this.#table}_insertion_ordinal`;
|
|
91
|
+
this.#legacyReplaceTrigger = `trg_${this.#table}_preserve_insertion_ordinal`;
|
|
92
|
+
this.#legacyInsertTrigger = `trg_${this.#table}_allocate_insertion_ordinal`;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Lazy, memoized schema creation — the same clear-on-failure promise memo the
|
|
96
|
+
* approval store uses: only SUCCESS memoizes, so a transient DDL failure
|
|
97
|
+
* retries on the next call rather than pinning the domain to a dead promise.
|
|
98
|
+
* `init()` (called by the composite store) and every operation await it.
|
|
99
|
+
*/
|
|
100
|
+
#ensureSchema() {
|
|
101
|
+
if (!this.#ready) {
|
|
102
|
+
this.#ready = this.#createSchema().catch((error) => {
|
|
103
|
+
this.#ready = undefined;
|
|
104
|
+
throw error;
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
return this.#ready;
|
|
108
|
+
}
|
|
109
|
+
async #createSchema() {
|
|
110
|
+
await this.#db
|
|
111
|
+
.prepare(`CREATE TABLE IF NOT EXISTS ${this.#table} (
|
|
112
|
+
id TEXT NOT NULL,
|
|
113
|
+
thread_id TEXT NOT NULL,
|
|
114
|
+
source TEXT NOT NULL,
|
|
115
|
+
kind TEXT NOT NULL,
|
|
116
|
+
priority TEXT NOT NULL,
|
|
117
|
+
status TEXT NOT NULL,
|
|
118
|
+
summary TEXT NOT NULL,
|
|
119
|
+
payload TEXT,
|
|
120
|
+
resourceId TEXT,
|
|
121
|
+
agentId TEXT,
|
|
122
|
+
sourceId TEXT,
|
|
123
|
+
dedupeKey TEXT,
|
|
124
|
+
coalesceKey TEXT,
|
|
125
|
+
coalescedCount INTEGER NOT NULL DEFAULT 1,
|
|
126
|
+
attributes TEXT,
|
|
127
|
+
createdAt TEXT NOT NULL,
|
|
128
|
+
updatedAt TEXT NOT NULL,
|
|
129
|
+
deliverAt TEXT,
|
|
130
|
+
summaryAt TEXT,
|
|
131
|
+
deliveryReason TEXT,
|
|
132
|
+
deliveryAttempts INTEGER NOT NULL DEFAULT 0,
|
|
133
|
+
lastDeliveryAttemptAt TEXT,
|
|
134
|
+
lastDeliveryError TEXT,
|
|
135
|
+
deliveredSignalId TEXT,
|
|
136
|
+
summarySignalId TEXT,
|
|
137
|
+
deliveredAt TEXT,
|
|
138
|
+
seenAt TEXT,
|
|
139
|
+
dismissedAt TEXT,
|
|
140
|
+
archivedAt TEXT,
|
|
141
|
+
discardedAt TEXT,
|
|
142
|
+
metadata TEXT,
|
|
143
|
+
insertionOrdinal INTEGER,
|
|
144
|
+
PRIMARY KEY (thread_id, id)
|
|
145
|
+
)`)
|
|
146
|
+
.run();
|
|
147
|
+
await this.#migrateOrdinalSchema(true);
|
|
148
|
+
}
|
|
149
|
+
async #migrateOrdinalSchema(retryDuplicateColumn) {
|
|
150
|
+
const batch = this.#db.batch?.bind(this.#db);
|
|
151
|
+
if (!batch) {
|
|
152
|
+
throw new Error('D1NotificationsStorage requires database.batch() for atomic schema migration');
|
|
153
|
+
}
|
|
154
|
+
const { results: columns } = await this.#db
|
|
155
|
+
.prepare(`PRAGMA table_info(${this.#table})`)
|
|
156
|
+
.all();
|
|
157
|
+
const needsColumn = !columns.some((column) => column.name === 'insertionOrdinal');
|
|
158
|
+
const statements = [
|
|
159
|
+
this.#db.prepare(`CREATE TABLE IF NOT EXISTS ${this.#sequenceTable} (
|
|
160
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
161
|
+
value INTEGER NOT NULL
|
|
162
|
+
)`),
|
|
163
|
+
...(needsColumn
|
|
164
|
+
? [
|
|
165
|
+
this.#db.prepare(`ALTER TABLE ${this.#table} ADD COLUMN insertionOrdinal INTEGER`),
|
|
166
|
+
]
|
|
167
|
+
: []),
|
|
168
|
+
this.#db.prepare(`INSERT INTO ${this.#sequenceTable} (id, value)
|
|
169
|
+
SELECT 1, COALESCE(MAX(insertionOrdinal), 0)
|
|
170
|
+
FROM ${this.#table}
|
|
171
|
+
WHERE true
|
|
172
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
173
|
+
value = MAX(value, excluded.value)`),
|
|
174
|
+
// Assign pre-trigger legacy rows ordinals after any values already
|
|
175
|
+
// written by a newer binary. rowid is their only insertion-order
|
|
176
|
+
// evidence.
|
|
177
|
+
this.#db.prepare(`WITH ranked AS (
|
|
178
|
+
SELECT
|
|
179
|
+
rowid AS targetRowid,
|
|
180
|
+
COALESCE(
|
|
181
|
+
(SELECT MAX(insertionOrdinal) FROM ${this.#table}),
|
|
182
|
+
0
|
|
183
|
+
) + ROW_NUMBER() OVER (ORDER BY rowid) AS ordinal
|
|
184
|
+
FROM ${this.#table}
|
|
185
|
+
WHERE insertionOrdinal IS NULL
|
|
186
|
+
)
|
|
187
|
+
UPDATE ${this.#table}
|
|
188
|
+
SET insertionOrdinal = (
|
|
189
|
+
SELECT ordinal
|
|
190
|
+
FROM ranked
|
|
191
|
+
WHERE ranked.targetRowid = ${this.#table}.rowid
|
|
192
|
+
)
|
|
193
|
+
WHERE insertionOrdinal IS NULL`),
|
|
194
|
+
this.#db.prepare(`INSERT INTO ${this.#sequenceTable} (id, value)
|
|
195
|
+
SELECT 1, COALESCE(MAX(insertionOrdinal), 0)
|
|
196
|
+
FROM ${this.#table}
|
|
197
|
+
WHERE true
|
|
198
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
199
|
+
value = MAX(value, excluded.value)`),
|
|
200
|
+
// Keep a rollback-era writer (which omits insertionOrdinal) in the same
|
|
201
|
+
// ordering protocol. An existing key is updated in place, matching
|
|
202
|
+
// Map.set; a new key atomically claims the next sequence value.
|
|
203
|
+
this.#db.prepare(`CREATE TRIGGER IF NOT EXISTS ${this.#legacyReplaceTrigger}
|
|
204
|
+
BEFORE INSERT ON ${this.#table}
|
|
205
|
+
WHEN NEW.insertionOrdinal IS NULL
|
|
206
|
+
AND EXISTS (
|
|
207
|
+
SELECT 1 FROM ${this.#table}
|
|
208
|
+
WHERE thread_id = NEW.thread_id AND id = NEW.id
|
|
209
|
+
)
|
|
210
|
+
BEGIN
|
|
211
|
+
UPDATE ${this.#table}
|
|
212
|
+
SET ${NOTIFICATION_UPDATE_COLUMNS.map((column) => `${column} = NEW.${column}`).join(', ')}
|
|
213
|
+
WHERE thread_id = NEW.thread_id AND id = NEW.id;
|
|
214
|
+
SELECT RAISE(IGNORE);
|
|
215
|
+
END`),
|
|
216
|
+
this.#db.prepare(`CREATE TRIGGER IF NOT EXISTS ${this.#legacyInsertTrigger}
|
|
217
|
+
AFTER INSERT ON ${this.#table}
|
|
218
|
+
WHEN NEW.insertionOrdinal IS NULL
|
|
219
|
+
BEGIN
|
|
220
|
+
UPDATE ${this.#sequenceTable}
|
|
221
|
+
SET value = value + 1
|
|
222
|
+
WHERE id = 1;
|
|
223
|
+
UPDATE ${this.#table}
|
|
224
|
+
SET insertionOrdinal = (
|
|
225
|
+
SELECT value FROM ${this.#sequenceTable} WHERE id = 1
|
|
226
|
+
)
|
|
227
|
+
WHERE rowid = NEW.rowid;
|
|
228
|
+
END`),
|
|
229
|
+
this.#db.prepare(`CREATE UNIQUE INDEX IF NOT EXISTS ${this.#ordinalIndex}
|
|
230
|
+
ON ${this.#table} (insertionOrdinal)
|
|
231
|
+
WHERE insertionOrdinal IS NOT NULL`),
|
|
232
|
+
this.#db.prepare(`CREATE INDEX IF NOT EXISTS idx_${this.#table}_thread
|
|
233
|
+
ON ${this.#table} (thread_id)`),
|
|
234
|
+
this.#db.prepare(`CREATE INDEX IF NOT EXISTS idx_${this.#table}_status
|
|
235
|
+
ON ${this.#table} (thread_id, status)`),
|
|
236
|
+
];
|
|
237
|
+
try {
|
|
238
|
+
await batch(statements);
|
|
239
|
+
}
|
|
240
|
+
catch (error) {
|
|
241
|
+
// Two fresh isolates can both observe the legacy shape. D1 serializes
|
|
242
|
+
// their batches; the loser re-reads the now-migrated schema rather than
|
|
243
|
+
// treating the expected duplicate-column race as corruption.
|
|
244
|
+
if (retryDuplicateColumn && needsColumn && isDuplicateColumn(error)) {
|
|
245
|
+
await this.#migrateOrdinalSchema(false);
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
throw error;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
async init() {
|
|
252
|
+
await this.#ensureSchema();
|
|
253
|
+
}
|
|
254
|
+
async createNotification(input) {
|
|
255
|
+
await this.#ensureSchema();
|
|
256
|
+
const now = input.createdAt ?? new Date();
|
|
257
|
+
const record = {
|
|
258
|
+
id: input.id ?? crypto.randomUUID(),
|
|
259
|
+
threadId: input.threadId,
|
|
260
|
+
source: input.source,
|
|
261
|
+
kind: input.kind,
|
|
262
|
+
priority: input.priority ?? 'medium',
|
|
263
|
+
status: 'pending',
|
|
264
|
+
summary: input.summary,
|
|
265
|
+
payload: input.payload,
|
|
266
|
+
resourceId: input.resourceId,
|
|
267
|
+
agentId: input.agentId,
|
|
268
|
+
sourceId: input.sourceId,
|
|
269
|
+
dedupeKey: input.dedupeKey,
|
|
270
|
+
coalesceKey: input.coalesceKey,
|
|
271
|
+
coalescedCount: 1,
|
|
272
|
+
attributes: input.attributes,
|
|
273
|
+
createdAt: now,
|
|
274
|
+
updatedAt: now,
|
|
275
|
+
deliverAt: input.deliverAt,
|
|
276
|
+
summaryAt: input.summaryAt,
|
|
277
|
+
deliveryReason: input.deliveryReason,
|
|
278
|
+
deliveryAttempts: 0,
|
|
279
|
+
metadata: input.metadata,
|
|
280
|
+
};
|
|
281
|
+
const insertionOrdinal = await this.#allocateInsertionOrdinal();
|
|
282
|
+
if (!input.dedupeKey && !input.coalesceKey) {
|
|
283
|
+
await this.#insert(record, insertionOrdinal);
|
|
284
|
+
return record;
|
|
285
|
+
}
|
|
286
|
+
for (let attempt = 0; attempt < 16; attempt += 1) {
|
|
287
|
+
if (await this.#insertUnlessCoalescable(record, input, insertionOrdinal)) {
|
|
288
|
+
return record;
|
|
289
|
+
}
|
|
290
|
+
const existing = await this.#findCoalescableRow(input);
|
|
291
|
+
if (!existing)
|
|
292
|
+
continue;
|
|
293
|
+
const existingRecord = rowToRecord(existing);
|
|
294
|
+
const mergedAttributes = input.attributes
|
|
295
|
+
? { ...existingRecord.attributes, ...input.attributes }
|
|
296
|
+
: existingRecord.attributes;
|
|
297
|
+
const mergedMetadata = input.metadata
|
|
298
|
+
? { ...existingRecord.metadata, ...input.metadata }
|
|
299
|
+
: existingRecord.metadata;
|
|
300
|
+
const updatedAt = new Date();
|
|
301
|
+
const sets = ['summary = ?', 'updatedAt = ?'];
|
|
302
|
+
const binds = [input.summary, updatedAt.toISOString()];
|
|
303
|
+
if (input.payload != null) {
|
|
304
|
+
sets.push('payload = ?');
|
|
305
|
+
binds.push(jsonOrNull(input.payload));
|
|
306
|
+
}
|
|
307
|
+
if (input.priority !== undefined) {
|
|
308
|
+
sets.push('priority = ?');
|
|
309
|
+
binds.push(input.priority);
|
|
310
|
+
}
|
|
311
|
+
if (input.attributes) {
|
|
312
|
+
sets.push('attributes = ?');
|
|
313
|
+
binds.push(jsonOrNull(mergedAttributes));
|
|
314
|
+
}
|
|
315
|
+
if (input.deliverAt !== undefined) {
|
|
316
|
+
sets.push('deliverAt = ?');
|
|
317
|
+
binds.push(isoOrNull(input.deliverAt));
|
|
318
|
+
}
|
|
319
|
+
if (input.summaryAt !== undefined) {
|
|
320
|
+
sets.push('summaryAt = ?');
|
|
321
|
+
binds.push(isoOrNull(input.summaryAt));
|
|
322
|
+
}
|
|
323
|
+
if (input.deliveryReason !== undefined) {
|
|
324
|
+
sets.push('deliveryReason = ?');
|
|
325
|
+
binds.push(input.deliveryReason);
|
|
326
|
+
}
|
|
327
|
+
if (input.metadata) {
|
|
328
|
+
sets.push('metadata = ?');
|
|
329
|
+
binds.push(jsonOrNull(mergedMetadata));
|
|
330
|
+
}
|
|
331
|
+
sets.push('coalescedCount = coalescedCount + 1');
|
|
332
|
+
const match = this.#coalescableMatch(input);
|
|
333
|
+
const guards = ['id = ?', 'coalescedCount = ?', `(${match.clause})`];
|
|
334
|
+
binds.push(existing.id, existing.coalescedCount, ...match.binds);
|
|
335
|
+
if (input.attributes) {
|
|
336
|
+
guards.push('attributes IS ?');
|
|
337
|
+
binds.push(existing.attributes);
|
|
338
|
+
}
|
|
339
|
+
if (input.metadata) {
|
|
340
|
+
guards.push('metadata IS ?');
|
|
341
|
+
binds.push(existing.metadata);
|
|
342
|
+
}
|
|
343
|
+
const updated = await this.#db
|
|
344
|
+
.prepare(`UPDATE ${this.#table}
|
|
345
|
+
SET ${sets.join(', ')}
|
|
346
|
+
WHERE ${guards.join(' AND ')}
|
|
347
|
+
RETURNING *`)
|
|
348
|
+
.bind(...binds)
|
|
349
|
+
.first();
|
|
350
|
+
if (updated)
|
|
351
|
+
return rowToRecord(updated);
|
|
352
|
+
}
|
|
353
|
+
throw new Error('Notification coalescing failed after 16 contention attempts');
|
|
354
|
+
}
|
|
355
|
+
async listNotifications(input) {
|
|
356
|
+
await this.#ensureSchema();
|
|
357
|
+
const clauses = ['thread_id = ?'];
|
|
358
|
+
const binds = [input.threadId];
|
|
359
|
+
this.#pushIn(clauses, binds, 'status', input.status);
|
|
360
|
+
this.#pushIn(clauses, binds, 'priority', input.priority);
|
|
361
|
+
if (input.source !== undefined) {
|
|
362
|
+
clauses.push('source = ?');
|
|
363
|
+
binds.push(input.source);
|
|
364
|
+
}
|
|
365
|
+
if (input.resourceId !== undefined) {
|
|
366
|
+
clauses.push('resourceId = ?');
|
|
367
|
+
binds.push(input.resourceId);
|
|
368
|
+
}
|
|
369
|
+
if (input.agentId !== undefined) {
|
|
370
|
+
clauses.push('agentId = ?');
|
|
371
|
+
binds.push(input.agentId);
|
|
372
|
+
}
|
|
373
|
+
const sqlLimit = input.search === undefined && validLimit(input.limit)
|
|
374
|
+
? input.limit
|
|
375
|
+
: undefined;
|
|
376
|
+
if (sqlLimit !== undefined)
|
|
377
|
+
binds.push(sqlLimit);
|
|
378
|
+
const { results } = await this.#db
|
|
379
|
+
.prepare(`SELECT * FROM ${this.#table} WHERE ${clauses.join(' AND ')}
|
|
380
|
+
ORDER BY updatedAt DESC${sqlLimit !== undefined ? ' LIMIT ?' : ''}`)
|
|
381
|
+
.bind(...binds)
|
|
382
|
+
.all();
|
|
383
|
+
let records = results.map(rowToRecord);
|
|
384
|
+
// `search` mirrors the InMemory case-insensitive scan over summary/kind/source
|
|
385
|
+
// (kept in JS so the SQL stays index-friendly and the semantics match exactly).
|
|
386
|
+
if (input.search !== undefined) {
|
|
387
|
+
const needle = input.search.toLowerCase();
|
|
388
|
+
records = records.filter((r) => r.summary.toLowerCase().includes(needle) ||
|
|
389
|
+
r.kind.toLowerCase().includes(needle) ||
|
|
390
|
+
r.source.toLowerCase().includes(needle));
|
|
391
|
+
}
|
|
392
|
+
return input.search !== undefined ||
|
|
393
|
+
(input.limit !== undefined && !validLimit(input.limit))
|
|
394
|
+
? records.slice(0, input.limit)
|
|
395
|
+
: records;
|
|
396
|
+
}
|
|
397
|
+
/**
|
|
398
|
+
* Due pending notifications across ALL threads/tenants, filtered only by the
|
|
399
|
+
* optional agentId/resourceId — GLOBALLY UNSCOPED by tenant, exactly like
|
|
400
|
+
* core's InMemory reference (a cron dispatcher's cross-thread sweep). It is a
|
|
401
|
+
* trusted-computing-base-only read (no client route reaches it), so this is
|
|
402
|
+
* not a leak here. The trusted dispatcher that drives delivery from this list
|
|
403
|
+
* must scope each dispatch by the row's tenant-salted
|
|
404
|
+
* `resourceId` (`${tenantId}_…`) / per-thread `threadId` before it acts, or a
|
|
405
|
+
* cross-tenant sweep would deliver one tenant's inbox into another's loop.
|
|
406
|
+
*/
|
|
407
|
+
async listDueNotifications(input) {
|
|
408
|
+
await this.#ensureSchema();
|
|
409
|
+
const now = input.now.toISOString();
|
|
410
|
+
const clauses = [
|
|
411
|
+
"status = 'pending'",
|
|
412
|
+
'((deliverAt IS NOT NULL AND deliverAt <= ?) OR (summaryAt IS NOT NULL AND summaryAt <= ?))',
|
|
413
|
+
];
|
|
414
|
+
const binds = [now, now];
|
|
415
|
+
if (input.agentId !== undefined) {
|
|
416
|
+
clauses.push('agentId = ?');
|
|
417
|
+
binds.push(input.agentId);
|
|
418
|
+
}
|
|
419
|
+
if (input.resourceId !== undefined) {
|
|
420
|
+
clauses.push('resourceId = ?');
|
|
421
|
+
binds.push(input.resourceId);
|
|
422
|
+
}
|
|
423
|
+
const sqlLimit = validLimit(input.limit) ? input.limit : undefined;
|
|
424
|
+
if (sqlLimit !== undefined)
|
|
425
|
+
binds.push(sqlLimit);
|
|
426
|
+
const { results } = await this.#db
|
|
427
|
+
.prepare(`SELECT * FROM ${this.#table}
|
|
428
|
+
WHERE ${clauses.join(' AND ')}
|
|
429
|
+
ORDER BY
|
|
430
|
+
CASE
|
|
431
|
+
WHEN deliverAt IS NULL THEN summaryAt
|
|
432
|
+
WHEN summaryAt IS NULL THEN deliverAt
|
|
433
|
+
WHEN deliverAt <= summaryAt THEN deliverAt
|
|
434
|
+
ELSE summaryAt
|
|
435
|
+
END ASC,
|
|
436
|
+
updatedAt ASC${sqlLimit !== undefined ? ' LIMIT ?' : ''}`)
|
|
437
|
+
.bind(...binds)
|
|
438
|
+
.all();
|
|
439
|
+
const records = results.map(rowToRecord);
|
|
440
|
+
return input.limit !== undefined && !validLimit(input.limit)
|
|
441
|
+
? records.slice(0, input.limit)
|
|
442
|
+
: records;
|
|
443
|
+
}
|
|
444
|
+
async getNotification(input) {
|
|
445
|
+
await this.#ensureSchema();
|
|
446
|
+
const row = await this.#db
|
|
447
|
+
.prepare(`SELECT * FROM ${this.#table} WHERE thread_id = ? AND id = ?`)
|
|
448
|
+
.bind(input.threadId, input.id)
|
|
449
|
+
.first();
|
|
450
|
+
return row ? rowToRecord(row) : null;
|
|
451
|
+
}
|
|
452
|
+
async updateNotification(input) {
|
|
453
|
+
await this.#ensureSchema();
|
|
454
|
+
const now = new Date();
|
|
455
|
+
const sets = ['updatedAt = ?'];
|
|
456
|
+
const binds = [now.toISOString()];
|
|
457
|
+
if (input.status !== undefined) {
|
|
458
|
+
sets.push('status = ?');
|
|
459
|
+
binds.push(input.status);
|
|
460
|
+
const column = statusTimestampColumn(input.status);
|
|
461
|
+
if (column) {
|
|
462
|
+
sets.push(`${column} = ?`);
|
|
463
|
+
binds.push(now.toISOString());
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
if (input.summary !== undefined) {
|
|
467
|
+
sets.push('summary = ?');
|
|
468
|
+
binds.push(input.summary);
|
|
469
|
+
}
|
|
470
|
+
if (input.payload !== undefined) {
|
|
471
|
+
sets.push('payload = ?');
|
|
472
|
+
binds.push(jsonOrNull(input.payload));
|
|
473
|
+
}
|
|
474
|
+
if (input.attributes !== undefined) {
|
|
475
|
+
sets.push('attributes = ?');
|
|
476
|
+
binds.push(jsonOrNull(input.attributes));
|
|
477
|
+
}
|
|
478
|
+
if (input.metadata !== undefined) {
|
|
479
|
+
sets.push('metadata = ?');
|
|
480
|
+
binds.push(jsonOrNull(input.metadata));
|
|
481
|
+
}
|
|
482
|
+
if (input.deliverAt !== undefined) {
|
|
483
|
+
sets.push('deliverAt = ?');
|
|
484
|
+
binds.push(isoOrNull(input.deliverAt ?? undefined));
|
|
485
|
+
}
|
|
486
|
+
if (input.summaryAt !== undefined) {
|
|
487
|
+
sets.push('summaryAt = ?');
|
|
488
|
+
binds.push(isoOrNull(input.summaryAt ?? undefined));
|
|
489
|
+
}
|
|
490
|
+
if (input.deliveryReason !== undefined) {
|
|
491
|
+
sets.push('deliveryReason = ?');
|
|
492
|
+
binds.push(input.deliveryReason);
|
|
493
|
+
}
|
|
494
|
+
if (input.deliveryAttempts !== undefined) {
|
|
495
|
+
sets.push('deliveryAttempts = ?');
|
|
496
|
+
binds.push(input.deliveryAttempts);
|
|
497
|
+
}
|
|
498
|
+
if (input.lastDeliveryAttemptAt !== undefined) {
|
|
499
|
+
sets.push('lastDeliveryAttemptAt = ?');
|
|
500
|
+
binds.push(isoOrNull(input.lastDeliveryAttemptAt));
|
|
501
|
+
}
|
|
502
|
+
if (input.lastDeliveryError !== undefined) {
|
|
503
|
+
sets.push('lastDeliveryError = ?');
|
|
504
|
+
binds.push(input.lastDeliveryError);
|
|
505
|
+
}
|
|
506
|
+
if (input.deliveredSignalId !== undefined) {
|
|
507
|
+
sets.push('deliveredSignalId = ?');
|
|
508
|
+
binds.push(input.deliveredSignalId);
|
|
509
|
+
}
|
|
510
|
+
if (input.summarySignalId !== undefined) {
|
|
511
|
+
sets.push('summarySignalId = ?');
|
|
512
|
+
binds.push(input.summarySignalId);
|
|
513
|
+
}
|
|
514
|
+
binds.push(input.threadId, input.id);
|
|
515
|
+
const updated = await this.#db
|
|
516
|
+
.prepare(`UPDATE ${this.#table}
|
|
517
|
+
SET ${sets.join(', ')}
|
|
518
|
+
WHERE thread_id = ? AND id = ?
|
|
519
|
+
RETURNING *`)
|
|
520
|
+
.bind(...binds)
|
|
521
|
+
.first();
|
|
522
|
+
if (!updated) {
|
|
523
|
+
throw new Error(`Notification ${input.id} was not found for thread ${input.threadId}`);
|
|
524
|
+
}
|
|
525
|
+
return rowToRecord(updated);
|
|
526
|
+
}
|
|
527
|
+
async dangerouslyClearAll() {
|
|
528
|
+
await this.#ensureSchema();
|
|
529
|
+
await this.#db.prepare(`DELETE FROM ${this.#table}`).run();
|
|
530
|
+
}
|
|
531
|
+
/** Build a `column IN (?, ?)` clause for a single value or an array filter. */
|
|
532
|
+
#pushIn(clauses, binds, column, filter) {
|
|
533
|
+
if (filter === undefined)
|
|
534
|
+
return;
|
|
535
|
+
const values = Array.isArray(filter) ? filter : [filter];
|
|
536
|
+
if (values.length === 0) {
|
|
537
|
+
clauses.push('0 = 1');
|
|
538
|
+
return;
|
|
539
|
+
}
|
|
540
|
+
clauses.push(`${column} IN (${values.map(() => '?').join(', ')})`);
|
|
541
|
+
binds.push(...values);
|
|
542
|
+
}
|
|
543
|
+
/**
|
|
544
|
+
* The first PENDING record on the same (threadId, source, kind, agentId,
|
|
545
|
+
* resourceId) whose dedupeKey OR coalesceKey matches — mirrors the reference's
|
|
546
|
+
* `.find`. The agentId/resourceId equality (including undefined-vs-undefined)
|
|
547
|
+
* is done in JS because SQL `= NULL` never matches; the candidate set is tiny
|
|
548
|
+
* (one thread's pending rows of one source/kind).
|
|
549
|
+
*
|
|
550
|
+
* Core's InMemory `.find` walks Map insertion order. insertionOrdinal
|
|
551
|
+
* preserves that order independently of caller-controlled createdAt; the
|
|
552
|
+
* nullable rowid fallback keeps legacy writers readable during rollback.
|
|
553
|
+
*/
|
|
554
|
+
async #findCoalescableRow(input) {
|
|
555
|
+
if (!input.dedupeKey && !input.coalesceKey)
|
|
556
|
+
return undefined;
|
|
557
|
+
const match = this.#coalescableMatch(input);
|
|
558
|
+
const row = await this.#db
|
|
559
|
+
.prepare(`SELECT * FROM ${this.#table}
|
|
560
|
+
WHERE ${match.clause}
|
|
561
|
+
ORDER BY
|
|
562
|
+
insertionOrdinal IS NULL ASC,
|
|
563
|
+
insertionOrdinal ASC,
|
|
564
|
+
rowid ASC
|
|
565
|
+
LIMIT 1`)
|
|
566
|
+
.bind(...match.binds)
|
|
567
|
+
.first();
|
|
568
|
+
return row ?? undefined;
|
|
569
|
+
}
|
|
570
|
+
#coalescableMatch(input) {
|
|
571
|
+
return {
|
|
572
|
+
clause: `thread_id = ?
|
|
573
|
+
AND source = ?
|
|
574
|
+
AND kind = ?
|
|
575
|
+
AND status = 'pending'
|
|
576
|
+
AND agentId IS ?
|
|
577
|
+
AND resourceId IS ?
|
|
578
|
+
AND (
|
|
579
|
+
(? IS NOT NULL AND dedupeKey = ?)
|
|
580
|
+
OR (? IS NOT NULL AND coalesceKey = ?)
|
|
581
|
+
)`,
|
|
582
|
+
binds: [
|
|
583
|
+
input.threadId,
|
|
584
|
+
input.source,
|
|
585
|
+
input.kind,
|
|
586
|
+
input.agentId ?? null,
|
|
587
|
+
input.resourceId ?? null,
|
|
588
|
+
input.dedupeKey ?? null,
|
|
589
|
+
input.dedupeKey ?? null,
|
|
590
|
+
input.coalesceKey ?? null,
|
|
591
|
+
input.coalesceKey ?? null,
|
|
592
|
+
],
|
|
593
|
+
};
|
|
594
|
+
}
|
|
595
|
+
async #insertUnlessCoalescable(record, input, insertionOrdinal) {
|
|
596
|
+
const match = this.#coalescableMatch(input);
|
|
597
|
+
const result = await this.#db
|
|
598
|
+
.prepare(`INSERT INTO ${this.#table} (${NOTIFICATION_COLUMNS.join(', ')}, insertionOrdinal)
|
|
599
|
+
SELECT ${NOTIFICATION_COLUMNS.map(() => '?').join(', ')}, ?
|
|
600
|
+
WHERE NOT EXISTS (
|
|
601
|
+
SELECT 1 FROM ${this.#table} WHERE ${match.clause}
|
|
602
|
+
)
|
|
603
|
+
ON CONFLICT(thread_id, id) DO UPDATE SET
|
|
604
|
+
${NOTIFICATION_UPDATE_COLUMNS.map((column) => `${column} = excluded.${column}`).join(', ')}`)
|
|
605
|
+
.bind(...recordValues(record), insertionOrdinal, ...match.binds)
|
|
606
|
+
.run();
|
|
607
|
+
return d1Changes(result) > 0;
|
|
608
|
+
}
|
|
609
|
+
/** Upsert the public record while preserving its original insertion ordinal. */
|
|
610
|
+
async #insert(record, insertionOrdinal) {
|
|
611
|
+
await this.#db
|
|
612
|
+
.prepare(`INSERT INTO ${this.#table} (${NOTIFICATION_COLUMNS.join(', ')}, insertionOrdinal)
|
|
613
|
+
VALUES (${NOTIFICATION_COLUMNS.map(() => '?').join(', ')}, ?)
|
|
614
|
+
ON CONFLICT(thread_id, id) DO UPDATE SET
|
|
615
|
+
${NOTIFICATION_UPDATE_COLUMNS.map((column) => `${column} = excluded.${column}`).join(', ')}`)
|
|
616
|
+
.bind(...recordValues(record), insertionOrdinal)
|
|
617
|
+
.run();
|
|
618
|
+
}
|
|
619
|
+
async #allocateInsertionOrdinal() {
|
|
620
|
+
const row = await this.#db
|
|
621
|
+
.prepare(`UPDATE ${this.#sequenceTable}
|
|
622
|
+
SET value = value + 1
|
|
623
|
+
WHERE id = 1
|
|
624
|
+
RETURNING value`)
|
|
625
|
+
.first();
|
|
626
|
+
if (!row || !Number.isSafeInteger(row.value) || row.value < 1) {
|
|
627
|
+
throw new Error('Notification insertion ordinal allocation failed');
|
|
628
|
+
}
|
|
629
|
+
return row.value;
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
function recordValues(record) {
|
|
633
|
+
return [
|
|
634
|
+
record.id,
|
|
635
|
+
record.threadId,
|
|
636
|
+
record.source,
|
|
637
|
+
record.kind,
|
|
638
|
+
record.priority,
|
|
639
|
+
record.status,
|
|
640
|
+
record.summary,
|
|
641
|
+
jsonOrNull(record.payload),
|
|
642
|
+
record.resourceId ?? null,
|
|
643
|
+
record.agentId ?? null,
|
|
644
|
+
record.sourceId ?? null,
|
|
645
|
+
record.dedupeKey ?? null,
|
|
646
|
+
record.coalesceKey ?? null,
|
|
647
|
+
record.coalescedCount ?? 1,
|
|
648
|
+
jsonOrNull(record.attributes),
|
|
649
|
+
record.createdAt.toISOString(),
|
|
650
|
+
record.updatedAt.toISOString(),
|
|
651
|
+
isoOrNull(record.deliverAt),
|
|
652
|
+
isoOrNull(record.summaryAt),
|
|
653
|
+
record.deliveryReason ?? null,
|
|
654
|
+
record.deliveryAttempts ?? 0,
|
|
655
|
+
isoOrNull(record.lastDeliveryAttemptAt),
|
|
656
|
+
record.lastDeliveryError ?? null,
|
|
657
|
+
record.deliveredSignalId ?? null,
|
|
658
|
+
record.summarySignalId ?? null,
|
|
659
|
+
isoOrNull(record.deliveredAt),
|
|
660
|
+
isoOrNull(record.seenAt),
|
|
661
|
+
isoOrNull(record.dismissedAt),
|
|
662
|
+
isoOrNull(record.archivedAt),
|
|
663
|
+
isoOrNull(record.discardedAt),
|
|
664
|
+
jsonOrNull(record.metadata),
|
|
665
|
+
];
|
|
666
|
+
}
|
|
667
|
+
/** Map a stored row back to the core NotificationRecord shape. */
|
|
668
|
+
function rowToRecord(row) {
|
|
669
|
+
return {
|
|
670
|
+
id: row.id,
|
|
671
|
+
threadId: row.thread_id,
|
|
672
|
+
source: row.source,
|
|
673
|
+
kind: row.kind,
|
|
674
|
+
priority: row.priority,
|
|
675
|
+
status: row.status,
|
|
676
|
+
summary: row.summary,
|
|
677
|
+
payload: parseJsonOrUndefined(row.payload),
|
|
678
|
+
resourceId: row.resourceId ?? undefined,
|
|
679
|
+
agentId: row.agentId ?? undefined,
|
|
680
|
+
sourceId: row.sourceId ?? undefined,
|
|
681
|
+
dedupeKey: row.dedupeKey ?? undefined,
|
|
682
|
+
coalesceKey: row.coalesceKey ?? undefined,
|
|
683
|
+
coalescedCount: row.coalescedCount ?? undefined,
|
|
684
|
+
attributes: parseJsonOrUndefined(row.attributes),
|
|
685
|
+
createdAt: new Date(row.createdAt),
|
|
686
|
+
updatedAt: new Date(row.updatedAt),
|
|
687
|
+
deliverAt: dateOrUndefined(row.deliverAt),
|
|
688
|
+
summaryAt: dateOrUndefined(row.summaryAt),
|
|
689
|
+
deliveryReason: row.deliveryReason ?? undefined,
|
|
690
|
+
deliveryAttempts: row.deliveryAttempts ?? undefined,
|
|
691
|
+
lastDeliveryAttemptAt: dateOrUndefined(row.lastDeliveryAttemptAt),
|
|
692
|
+
lastDeliveryError: row.lastDeliveryError ?? undefined,
|
|
693
|
+
deliveredSignalId: row.deliveredSignalId ?? undefined,
|
|
694
|
+
summarySignalId: row.summarySignalId ?? undefined,
|
|
695
|
+
deliveredAt: dateOrUndefined(row.deliveredAt),
|
|
696
|
+
seenAt: dateOrUndefined(row.seenAt),
|
|
697
|
+
dismissedAt: dateOrUndefined(row.dismissedAt),
|
|
698
|
+
archivedAt: dateOrUndefined(row.archivedAt),
|
|
699
|
+
discardedAt: dateOrUndefined(row.discardedAt),
|
|
700
|
+
metadata: parseJsonOrUndefined(row.metadata),
|
|
701
|
+
};
|
|
702
|
+
}
|
|
703
|
+
//# sourceMappingURL=notifications-d1.js.map
|