@drfed/models 0.2.0-dev.639 → 0.2.0-dev.651
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/README.md +32 -188
- package/dist/activity-delivery.d.mts +1 -1
- package/dist/activity-delivery.d.mts.map +1 -1
- package/dist/activity-delivery.mjs +34 -9
- package/dist/activity-delivery.mjs.map +1 -1
- package/dist/{db-DtcLuISw.d.mts → db-BBw4F4HU.d.mts} +478 -6
- package/dist/{db-DtcLuISw.d.mts.map → db-BBw4F4HU.d.mts.map} +1 -1
- package/dist/db.d.mts +1 -1
- package/dist/index.d.mts +3 -2
- package/dist/index.mjs +2 -1
- package/dist/instance.d.mts +1 -1
- package/dist/key.d.mts +1 -1
- package/dist/login.d.mts +1 -1
- package/dist/migrations-manifest.json +12 -0
- package/dist/relations.d.mts +1 -1
- package/dist/relations.mjs +65 -0
- package/dist/relations.mjs.map +1 -1
- package/dist/resource-revision-BuG5kUlA.d.mts +103 -0
- package/dist/resource-revision-BuG5kUlA.d.mts.map +1 -0
- package/dist/resource-revision-DWg6et77.mjs +313 -0
- package/dist/resource-revision-DWg6et77.mjs.map +1 -0
- package/dist/resource-revision.d.mts +2 -0
- package/dist/resource-revision.mjs +3 -0
- package/dist/resource.d.mts +1 -1
- package/dist/schema.d.mts +2 -2
- package/dist/schema.mjs +104 -5
- package/dist/schema.mjs.map +1 -1
- package/drizzle/20261026181201_resource_revision_storage/migration.sql +72 -0
- package/drizzle/20261026181201_resource_revision_storage/snapshot.json +4501 -0
- package/drizzle/20261026181206_guard_resource_revisions/migration.sql +175 -0
- package/drizzle/20261026181206_guard_resource_revisions/snapshot.json +4501 -0
- package/drizzle/20261026192411_capture_legacy_resource_revisions/migration.sql +249 -0
- package/drizzle/20261026192411_capture_legacy_resource_revisions/snapshot.json +4501 -0
- package/package.json +12 -7
package/README.md
CHANGED
|
@@ -17,200 +17,44 @@ Schema
|
|
|
17
17
|
| `instance_members` | `instanceId` → `instances`, `accountId` → `accounts` |
|
|
18
18
|
|
|
19
19
|
|
|
20
|
-
|
|
21
|
-
|
|
20
|
+
Resource revisions
|
|
21
|
+
------------------
|
|
22
22
|
|
|
23
|
-
|
|
23
|
+
`@drfed/models/resource-revision` provides trusted append and history reads for
|
|
24
|
+
full ActivityStreams JSON, with compare-and-swap heads and terminal deletion
|
|
25
|
+
markers. Existing local and inbound Create writers capture their documents in
|
|
26
|
+
the same transaction. Retained JSON can contain blind recipients; model reads
|
|
27
|
+
do not authorize access or prepare wire documents.
|
|
24
28
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
~~~~
|
|
29
|
+
See the [resource revision internals] for API examples, projections, legacy
|
|
30
|
+
upgrades and the boundaries of editor, federation and dispatch integration.
|
|
28
31
|
|
|
29
|
-
|
|
32
|
+
[resource revision internals]: https://drfed.org/internals/resource-revisions
|
|
30
33
|
|
|
31
|
-
~~~~ sh
|
|
32
|
-
mise run manifest:migrations --append
|
|
33
|
-
~~~~
|
|
34
34
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
Named rows from Drizzle's legacy upgrade retain generation milliseconds and
|
|
56
|
-
have SQL `NULL` in `applied_at`; these also match by generation second, name,
|
|
57
|
-
and hash. Other named rows require the exact manifest timestamp.
|
|
58
|
-
Database query failures propagate instead of being treated as a fresh database.
|
|
59
|
-
Connections subject to row-level security on migration history are rejected,
|
|
60
|
-
since filtered rows cannot prove that the history is complete.
|
|
61
|
-
|
|
62
|
-
`@drfed/models/migration-session` exposes `preparePostgresDatabase()` for
|
|
63
|
-
PostgreSQL. It verifies bundled SQL, connects a fresh owned [`pg.Client`], takes
|
|
64
|
-
a session advisory lock, inspects history before any metadata DDL, applies
|
|
65
|
-
verified pending SQL or legacy upgrades, and checks exact history afterward.
|
|
66
|
-
The optional client factory must return an unconnected, exclusive client;
|
|
67
|
-
the runner owns `connect()` and `end()` and never reconnects after failure.
|
|
68
|
-
The runner hashes the exact SQL bytes again after acquiring the lock and gives
|
|
69
|
-
Drizzle a private temporary snapshot, so a concurrent installation change cannot
|
|
70
|
-
supply unverified SQL between validation and application.
|
|
71
|
-
|
|
72
|
-
`lockTimeoutMs` bounds connection and lock acquisition; SQL application is
|
|
73
|
-
not limited by that deadline. `signal` aborts waiting or closes an active
|
|
74
|
-
connection. PostgreSQL can retain an interrupted statement and its lock until
|
|
75
|
-
it observes the disconnect, so another runner continues to wait rather than
|
|
76
|
-
stealing the lock. Migration errors have fixed codes and omit raw DB errors
|
|
77
|
-
and credentials; the `drfed.models.migration` debug category records the
|
|
78
|
-
backend PID after locking. Use a direct database connection or a proxy that
|
|
79
|
-
preserves sessions; transaction pooling is unsupported.
|
|
80
|
-
|
|
81
|
-
`@drfed/models/pglite-preparation` exposes `preparePgliteDatabase({ store })`
|
|
82
|
-
for a store returned by `openPersistentPglite()`. It verifies SQL and history,
|
|
83
|
-
refuses incompatible or untracked schemas before metadata DDL, applies exact
|
|
84
|
-
verified snapshots, then requires ready history. Verified legacy milliseconds
|
|
85
|
-
are preserved during metadata upgrade. Preparers sharing one client are
|
|
86
|
-
serialized, so a later request inspects the first request's committed history.
|
|
87
|
-
|
|
88
|
-
The caller owns the store throughout preparation and must refrain from other
|
|
89
|
-
queries until it settles. Preparation never closes the database or releases
|
|
90
|
-
its native lock, even after failure. `signal` is checked at safe boundaries;
|
|
91
|
-
active WASM SQL settles before an aborted operation completes. Drain preparation
|
|
92
|
-
before `store.close()`.
|
|
93
|
-
|
|
94
|
-
The existing `migrate()` remains a low-level API whose caller must ensure
|
|
95
|
-
exclusive access. The CLI uses the safe preparation APIs described above.
|
|
96
|
-
|
|
97
|
-
For contributor tests, point `DRFED_TEST_POSTGRES_URL` at an isolated
|
|
98
|
-
PostgreSQL cluster with `CREATEDB` and `CREATEROLE` permissions, then run:
|
|
99
|
-
|
|
100
|
-
~~~~ sh
|
|
101
|
-
mise run test:postgres
|
|
102
|
-
~~~~
|
|
35
|
+
Database lifecycle
|
|
36
|
+
------------------
|
|
37
|
+
|
|
38
|
+
See [database lifecycle internals] for migration
|
|
39
|
+
manifests, history inspection, safe PostgreSQL and PGlite preparation, native
|
|
40
|
+
file locks, and contributor verification commands. The caller owns borrowed
|
|
41
|
+
clients and stores; preparation does not replace runtime cleanup.
|
|
42
|
+
|
|
43
|
+
[database lifecycle internals]: https://drfed.org/internals/database-lifecycle
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
Activity deliveries
|
|
47
|
+
-------------------
|
|
48
|
+
|
|
49
|
+
`@drfed/models/activity-delivery` stores delivery observations separately from
|
|
50
|
+
ActivityPub resources. See [activity delivery internals] for
|
|
51
|
+
recording, attempt history, snapshot receipts and observed signing keys.
|
|
52
|
+
|
|
53
|
+
[activity delivery internals]: https://drfed.org/internals/activity-deliveries
|
|
54
|
+
|
|
103
55
|
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
The *drizzle/* directory is included in the published npm package so that
|
|
108
|
-
installed users can run migrations without access to the repository source.
|
|
109
|
-
|
|
110
|
-
[`pg.Client`]: https://node-postgres.com/apis/client
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
Persistent PGlite ownership
|
|
114
|
-
---------------------------
|
|
115
|
-
|
|
116
|
-
`@drfed/models/pglite-store` exposes `openPersistentPglite(dataPath)`. It
|
|
117
|
-
creates the directory, resolves its real absolute path, acquires an exclusive
|
|
118
|
-
native file lock, then constructs PGlite. Register the returned `close()`
|
|
119
|
-
immediately and await `ready` before querying. This promise maps asynchronous
|
|
120
|
-
initialization failures to the fixed `PgliteStoreError` code `open-failed`;
|
|
121
|
-
`close()` remains available even after an initialization failure. The shared
|
|
122
|
-
close promise shuts PGlite down before releasing its lock. If database close
|
|
123
|
-
fails, the lock stays held until that owner process exits.
|
|
124
|
-
|
|
125
|
-
[fs-native-extensions] supplies prebuilt Node addons for macOS, Windows and
|
|
126
|
-
Linux on x64/ARM64. Its file-description locks prevent another owner in the
|
|
127
|
-
same or a different process; suspension does not make a lock stale, and process
|
|
128
|
-
exit releases it. Loading an unavailable addon fails closed; there is no
|
|
129
|
-
compiler, heartbeat or PID-based fallback. Use a local filesystem. Network
|
|
130
|
-
filesystems and shared directories across container/PID namespaces are
|
|
131
|
-
unsupported.
|
|
132
|
-
|
|
133
|
-
The stable *.drfed.lock* file stays in the data directory after shutdown. Never
|
|
134
|
-
remove or replace it while an owner may be alive: two different inodes would
|
|
135
|
-
allow separate owners. A leftover file is harmless once the OS has released
|
|
136
|
-
its lock. After a failed close, stop that owner before reopening. Other code
|
|
137
|
-
that directly constructs PGlite bypasses this ownership API; coordinate all
|
|
138
|
-
access through it. The CLI uses this store for persistent PGlite databases.
|
|
139
|
-
|
|
140
|
-
The ordinary test task covers duplicate owners, a simultaneous process race,
|
|
141
|
-
symlink aliases, close ordering and failed-close ownership. POSIX-only tests
|
|
142
|
-
also suspend and forcibly terminate an owned child process before reopening.
|
|
143
|
-
|
|
144
|
-
[fs-native-extensions]: https://github.com/holepunchto/fs-native-extensions
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
Activity delivery storage
|
|
148
|
-
-------------------------
|
|
149
|
-
|
|
150
|
-
`activity_deliveries` stores delivery observations separately from ActivityPub
|
|
151
|
-
`activities`. `@drfed/models/activity-delivery` exposes `recordInbound`,
|
|
152
|
-
`receiveInbound`, `recordOutbound`, and `settleOutbound`. `receiveInbound`
|
|
153
|
-
marks an `acknowledged` inbound delivery `received` once a queued inbox
|
|
154
|
-
listener ran. An inbound delivery keeps the received
|
|
155
|
-
octets in `body` and the request headers in `headers`; `payload` is the body
|
|
156
|
-
parsed as JSON, and is SQL `NULL` when it does not parse or holds U+0000 or an
|
|
157
|
-
unpaired surrogate, which jsonb cannot store. `error` and `response_body`
|
|
158
|
-
are stored with U+FFFD for each U+0000, which text cannot store, so that a
|
|
159
|
-
remote response never keeps a delivery from being written. `created` is when
|
|
160
|
-
a request arrived or a delivery started, and `completed` when DrFed answered
|
|
161
|
-
the request or the delivery last changed status.
|
|
162
|
-
|
|
163
|
-
`settleOutbound` settles the most recent pending (`queued` or `failed`)
|
|
164
|
-
delivery to an inbox and never changes a `sent`, `permanently_failed`, or
|
|
165
|
-
`abandoned` one. Each attempt that ends is kept in
|
|
166
|
-
`activity_delivery_attempts`, so a retry never rewrites the outcome of an
|
|
167
|
-
earlier attempt.
|
|
168
|
-
|
|
169
|
-
`activity_id` links a delivery to the stored activity it carried.
|
|
170
|
-
`linkInboundActivity` links an inbound delivery only when it was verified and
|
|
171
|
-
answered with 2xx, by the activity IRI it recorded; `recordOutbound` takes the
|
|
172
|
-
`activityId` of the activity it sends. `recordInbound` does not take one, and
|
|
173
|
-
a CHECK constraint refuses a linked inbound delivery that is not verified,
|
|
174
|
-
`received` or `acknowledged`. A delivery outlives its activity.
|
|
175
|
-
`carried_snapshot` marks an inbound delivery whose payload is the stored
|
|
176
|
-
activity's document, and `carried_object_snapshot` one that carried the object
|
|
177
|
-
stored with that activity as well: the object was taken from the activity, or
|
|
178
|
-
`objects.fetched` says it was fetched and the delivery's `fetched_object`, what
|
|
179
|
-
its inbox listener fetched, is the stored document. Neither record function
|
|
180
|
-
takes a mark; `linkInboundActivity` decides both anew on every link, and
|
|
181
|
-
`recordFetchedObject` again for a delivery linked before its listener ran, so
|
|
182
|
-
that a mark left from a deleted activity never carries over to another stored
|
|
183
|
-
under the same IRI.
|
|
184
|
-
|
|
185
|
-
`activity_delivery_actors` relates a delivery to each local actor it concerns,
|
|
186
|
-
as the owner of the inbox, as an addressed recipient, or as the sender, with
|
|
187
|
-
one row per delivery and actor. An addressed actor keeps every way it was
|
|
188
|
-
addressed: `addressed_directly` when the activity named the actor itself, and
|
|
189
|
-
a row in `activity_delivery_actor_collections` for each addressed collection
|
|
190
|
-
it was a member of. Each row copies the delivery's `created`, by which an
|
|
191
|
-
actor's deliveries are ordered. Both record functions insert these rows in
|
|
192
|
-
the same transaction as the delivery. They record nothing and throw when the
|
|
193
|
-
inbox owner, the sender, or an addressed actor is not a local actor of the
|
|
194
|
-
delivery's instance, since neither foreign key can tell.
|
|
195
|
-
|
|
196
|
-
`@drfed/models/key` exposes public-JWK validation, RFC 7638/RFC 8037 SHA-256
|
|
197
|
-
thumbprints, and `observeKeyVersion`. `keys` identifies each exact key IRI;
|
|
198
|
-
`key_versions` retains immutable public material per fingerprint. Returning to
|
|
199
|
-
an earlier key reuses its version. Observation timestamps do not describe
|
|
200
|
-
remote rotation times or continuous use. Deliveries retain referenced versions
|
|
201
|
-
with `ON DELETE RESTRICT`, independently of Fedify cache expiry.
|
|
202
|
-
|
|
203
|
-
The `drfed-server` facade now uses these safe preparation APIs for automatic
|
|
204
|
-
migration and `inspectMigrationState()` for `--no-migrate`. Its persistent
|
|
205
|
-
PGlite owner remains held through preparation, serving and database cleanup.
|
|
206
|
-
The older `migrate()` function remains a low-level compatibility API; it does
|
|
207
|
-
not provide this facade ownership and history validation contract.
|
|
208
|
-
|
|
209
|
-
`preparePostgresDatabase` also accepts explicit node-postgres connection
|
|
210
|
-
settings as `credentials.connection`, without a `connectionString`. The facade
|
|
211
|
-
uses this form so that decoded host names, database names, credentials and TLS
|
|
212
|
-
policy are the same during migration and runtime. Both connections explicitly
|
|
213
|
-
verify the configured host identity for TLS, including IP addresses.
|
|
56
|
+
Database upgrades
|
|
57
|
+
-----------------
|
|
214
58
|
|
|
215
59
|
Installed users can run `drfed-migrate` from `@drfed/drfed` to prepare the
|
|
216
60
|
database; `drfed-migrate --check` only inspects history and exits 0 for ready
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { M as NewActivityDelivery, N as NewActivityDeliveryActor, o as ActivityDelivery, r as Transaction, t as Database } from "./db-
|
|
1
|
+
import { M as NewActivityDelivery, N as NewActivityDeliveryActor, o as ActivityDelivery, r as Transaction, t as Database } from "./db-BBw4F4HU.mjs";
|
|
2
2
|
import { t as Uuid } from "./uuid-CKMzlIND.mjs";
|
|
3
3
|
//#region src/activity-delivery.d.ts
|
|
4
4
|
/** The marks of what a delivery carried are the model's to decide. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"activity-delivery.d.mts","names":[],"sources":["../src/activity-delivery.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"activity-delivery.d.mts","names":[],"sources":["../src/activity-delivery.ts"],"mappings":";;;;KAwCK,gBAAgB,KACnB;UAIe;WACN,SAAS;WACT;;;;;;;;;KAUC,uBAAuB,KACjC;;;;WAMS,KAAK;WACL;WACA,oBAAoB,YAAY;WAChC,MAAM;WACN,qBAAqB;;WAErB,SAAS,SAAS;;WAElB,WAAW,SAAS;;;KAInB,wBAAwB,KAClC;WAUS;;KAGN,WAAW,KAAK;;WAEV;;;;;;;iBAQK,iBAAiB;WACtB,UAAU;WACV,qBAAqB;IAC5B;;;;;;;;iBAgJkB,cACpB,IAAI,YACF,WAAW,MAAM,OAAkB,SAAS,uBAC7C,QAAQ;;;;;;iBAuBW,eAAe,IAAI,UAAU,IAAI,OAAO;;;;;;;;;;;;iBAsJxC,oBACpB,IAAI,WAAW,aACf,YAAY,OACX;;;;;;;iBA+BmB,oBACpB,IAAI,UACJ,YAAY,MACZ,oBACC;;;;;;;;iBAyBmB,eACpB,IAAI,UACJ,OAAO,wBACN,QAAQ;;UAoBM;WACN;WACA;WACA;WACA;WACA;WACA;;WAEA;;WAEA,KAAK;;;;;;;;iBASM,eACpB,IAAI,UACJ,OAAO,qBACN"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { activities, activityDeliveries, activityDeliveryActorCollections, activityDeliveryActors, activityDeliveryAttempts, actors, objects, resources } from "./schema.mjs";
|
|
1
|
+
import { activities, activityDeliveries, activityDeliveryActorCollections, activityDeliveryActors, activityDeliveryAttempts, actors, objects, resourceRevisions, resources, revisionReceipts } from "./schema.mjs";
|
|
2
2
|
import { uuidV7 } from "./uuid.mjs";
|
|
3
3
|
import { storableText } from "./text.mjs";
|
|
4
4
|
import { and, desc, eq, inArray, isNotNull, isNull, sql } from "drizzle-orm";
|
|
@@ -133,20 +133,45 @@ async function receiveInbound(db, id) {
|
|
|
133
133
|
* and carries nothing. An unlinked delivery is left as is.
|
|
134
134
|
*/
|
|
135
135
|
async function decideCarried(tx, deliveryId) {
|
|
136
|
-
const [
|
|
136
|
+
const [delivery] = await tx.select({
|
|
137
|
+
activityId: activityDeliveries.activityId,
|
|
137
138
|
payload: activityDeliveries.payload,
|
|
138
|
-
fetchedObject: activityDeliveries.fetchedObject
|
|
139
|
-
|
|
140
|
-
|
|
139
|
+
fetchedObject: activityDeliveries.fetchedObject
|
|
140
|
+
}).from(activityDeliveries).where(and(eq(activityDeliveries.id, deliveryId), eq(activityDeliveries.direction, "inbound"))).for("update");
|
|
141
|
+
if (delivery === void 0) return;
|
|
142
|
+
const [activity] = delivery.activityId === null ? [] : await tx.select({
|
|
143
|
+
id: activities.id,
|
|
144
|
+
document: activities.document
|
|
145
|
+
}).from(activities).where(eq(activities.id, delivery.activityId));
|
|
146
|
+
const [object] = activity === void 0 ? [] : await tx.select({
|
|
147
|
+
id: objects.id,
|
|
148
|
+
document: objects.document,
|
|
141
149
|
fetched: objects.fetched
|
|
142
|
-
}).from(
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
const
|
|
150
|
+
}).from(objects).where(eq(objects.activityId, activity.id)).for("key share");
|
|
151
|
+
await tx.delete(revisionReceipts).where(eq(revisionReceipts.deliveryId, deliveryId));
|
|
152
|
+
if (activity === void 0) return;
|
|
153
|
+
const carriedSnapshot = delivery.payload != null && isDeepStrictEqual(delivery.payload, activity.document);
|
|
154
|
+
const carriedObjectSnapshot = carriedSnapshot && object !== void 0 && (!object.fetched || delivery.fetchedObject != null && isDeepStrictEqual(delivery.fetchedObject, object.document));
|
|
146
155
|
await tx.update(activityDeliveries).set({
|
|
147
156
|
carriedSnapshot,
|
|
148
157
|
carriedObjectSnapshot
|
|
149
158
|
}).where(eq(activityDeliveries.id, deliveryId));
|
|
159
|
+
if (!carriedSnapshot) return;
|
|
160
|
+
const revisions = await tx.select().from(resourceRevisions).where(and(inArray(resourceRevisions.resourceId, object === void 0 ? [activity.id] : [activity.id, object.id]), eq(resourceRevisions.sequence, 1), eq(resourceRevisions.kind, "snapshot")));
|
|
161
|
+
const activityRevision = revisions.find((revision) => revision.resourceId === activity.id);
|
|
162
|
+
if (activityRevision === void 0 || !isDeepStrictEqual(activityRevision.document, activity.document)) return;
|
|
163
|
+
const receipts = [{
|
|
164
|
+
deliveryId,
|
|
165
|
+
revisionId: activityRevision.id,
|
|
166
|
+
role: "activity"
|
|
167
|
+
}];
|
|
168
|
+
const objectRevision = object === void 0 ? void 0 : revisions.find((revision) => revision.resourceId === object.id);
|
|
169
|
+
if (carriedObjectSnapshot && object !== void 0 && objectRevision !== void 0 && isDeepStrictEqual(objectRevision.document, object.document)) receipts.push({
|
|
170
|
+
deliveryId,
|
|
171
|
+
revisionId: objectRevision.id,
|
|
172
|
+
role: "object"
|
|
173
|
+
});
|
|
174
|
+
await tx.insert(revisionReceipts).values(receipts);
|
|
150
175
|
}
|
|
151
176
|
/**
|
|
152
177
|
* Link an inbound delivery to the stored activity its activity IRI names.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"activity-delivery.mjs","names":[],"sources":["../src/activity-delivery.ts"],"sourcesContent":["// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n\nimport { isDeepStrictEqual } from \"node:util\";\n\nimport { and, desc, eq, inArray, isNotNull, isNull, sql } from \"drizzle-orm\";\n\nimport type { Database, Transaction } from \"./db.ts\";\nimport {\n type ActivityDelivery,\n type NewActivityDelivery,\n type NewActivityDeliveryActor,\n activities,\n activityDeliveries,\n activityDeliveryActorCollections,\n activityDeliveryActors,\n activityDeliveryAttempts,\n actors,\n objects,\n resources,\n} from \"./schema.ts\";\nimport { storableText } from \"./text.ts\";\nimport { type Uuid, uuidV7 } from \"./uuid.ts\";\n\n/** The marks of what a delivery carried are the model's to decide. */\ntype DeliveryEntry = Omit<\n NewActivityDelivery,\n \"id\" | \"direction\" | \"status\" | \"carriedSnapshot\" | \"carriedObjectSnapshot\"\n>;\n\nexport interface AddressedActor {\n readonly actorId: Uuid;\n readonly viaCollectionIri?: string | null;\n}\n\n/**\n * `payload` is `undefined` for an unparsable body and `null` for JSON `null`;\n * it is stored as SQL `NULL` when jsonb cannot hold it, and `body` keeps it.\n * `fetchedObject` is stored as SQL `NULL` when jsonb cannot hold it too.\n * An inbound delivery is linked to its activity only by\n * `linkInboundActivity()`.\n */\nexport type InboundDeliveryEntry = Omit<\n DeliveryEntry,\n \"body\" | \"verificationResult\" | \"recipientIris\" | \"activityId\"\n> & {\n /**\n * Chosen in advance when something must name the delivery before it exists.\n */\n readonly id?: Uuid;\n readonly status: \"received\" | \"acknowledged\" | \"unverified\" | \"rejected\";\n readonly verificationResult: NonNullable<DeliveryEntry[\"verificationResult\"]>;\n readonly body: Uint8Array;\n readonly addressed?: readonly AddressedActor[];\n /** When the request arrived, before verification and handling. */\n readonly created: Temporal.Instant;\n /** When DrFed answered the request. */\n readonly completed: Temporal.Instant;\n};\n\n/** `payload` is the document before signing, without `bto` and `bcc`. */\nexport type OutboundDeliveryEntry = Omit<\n DeliveryEntry,\n | \"verificationKeyId\"\n | \"verificationMechanism\"\n | \"verificationResult\"\n | \"body\"\n | \"headers\"\n | \"requestUrl\"\n | \"completed\"\n | \"fetchedObject\"\n> & {\n readonly activityIri: string;\n};\n\ntype ActorRow = Omit<NewActivityDeliveryActor, \"deliveryId\" | \"created\"> & {\n /** The addressed collections that reached the actor, sorted. */\n readonly collectionIris?: readonly string[];\n};\n\n/**\n * Merge the inbox owner and addressed actors into one row per actor, keeping\n * every way each was addressed, whatever order they come in.\n * @returns The actor rows of an inbound delivery.\n */\nexport function inboundActorRows(entry: {\n readonly actorId?: Uuid | null | undefined;\n readonly addressed?: readonly AddressedActor[] | undefined;\n}): ActorRow[] {\n const rows = new Map<Uuid, ActorRow>();\n if (entry.actorId != null) {\n rows.set(entry.actorId, { actorId: entry.actorId, inboxOwner: true });\n }\n for (const { actorId, viaCollectionIri } of entry.addressed ?? []) {\n const row = rows.get(actorId);\n const collectionIris = row?.collectionIris ?? [];\n rows.set(actorId, {\n ...row,\n actorId,\n addressed: true,\n addressedDirectly:\n row?.addressedDirectly === true || viaCollectionIri == null,\n collectionIris:\n viaCollectionIri == null\n ? collectionIris\n : [...new Set([...collectionIris, viaCollectionIri])].toSorted(),\n });\n }\n return [...rows.values()];\n}\n\n/**\n * PostgreSQL's jsonb holds neither U+0000 nor an unpaired surrogate, in keys\n * or in values.\n * @returns Whether the JSON value can be stored as jsonb.\n */\nfunction storableJson(value: unknown): boolean {\n if (typeof value === \"string\") return storableText(value);\n return (\n typeof value !== \"object\" ||\n value == null ||\n Object.entries(value).every(\n ([key, item]) => storableJson(key) && storableJson(item),\n )\n );\n}\n\n/**\n * Keep a payload jsonb cannot hold out of the delivery, rather than the\n * delivery.\n * @returns The value to store, SQL `NULL` for such a payload.\n */\nconst jsonb = (payload: unknown) =>\n payload === null\n ? sql`'null'::jsonb`\n : storableJson(payload)\n ? payload\n : null;\n\n/**\n * A fetched object is a JSON object, so nothing fetched is SQL `NULL`.\n * @returns The value to store.\n */\nconst storedObject = (document: unknown) =>\n document == null ? null : jsonb(document);\n\n/**\n * PostgreSQL's text holds no U+0000, which a remote response or an error\n * quoting one may carry; keep the rest of it rather than lose the delivery.\n * @returns The text with each U+0000 replaced by U+FFFD.\n */\nconst text = (value: string | null | undefined): string | null =>\n value?.replaceAll(\"\\0\", \"\\ufffd\") ?? null;\n\n/**\n * Refuse to relate a delivery to anything but local actors of its instance,\n * which neither foreign key can tell.\n * @throws {Error} When an actor is remote, or of another instance.\n */\nasync function checkLocalActors(\n tx: Transaction,\n instanceId: Uuid,\n actorIds: readonly (Uuid | null | undefined)[],\n): Promise<void> {\n const ids = [...new Set(actorIds.filter((id) => id != null))];\n if (ids.length === 0) return;\n const local = await tx.$count(\n actors,\n and(\n inArray(actors.id, ids),\n eq(actors.instanceId, instanceId),\n isNotNull(actors.localId),\n ),\n );\n if (local !== ids.length) {\n throw new Error(\n \"An activity delivery relates only to local actors of its instance.\",\n );\n }\n}\n\nasync function insertDelivery(\n db: Database,\n delivery: NewActivityDelivery,\n links: readonly ActorRow[],\n): Promise<ActivityDelivery> {\n return await db.transaction(async (tx) => {\n await checkLocalActors(tx, delivery.instanceId, [\n delivery.actorId,\n ...links.map(({ actorId }) => actorId),\n ]);\n const [row] = await tx\n .insert(activityDeliveries)\n .values({\n ...delivery,\n error: text(delivery.error),\n responseBody: text(delivery.responseBody),\n })\n .returning();\n if (row == null) {\n throw new Error(\"Missing activity delivery after insertion.\");\n }\n if (links.length > 0) {\n await tx.insert(activityDeliveryActors).values(\n links.map(({ collectionIris: _, ...link }) => ({\n ...link,\n deliveryId: row.id,\n created: row.created,\n })),\n );\n }\n const collections = links.flatMap(({ actorId, collectionIris = [] }) =>\n collectionIris.map((collectionIri) => ({\n deliveryId: row.id,\n actorId,\n collectionIri,\n })),\n );\n if (collections.length > 0) {\n await tx.insert(activityDeliveryActorCollections).values(collections);\n }\n return row;\n });\n}\n\n/**\n * Persist one inbound observation with its actor rows in one transaction.\n * The inbox owner and every addressed actor must be local actors of\n * `instanceId`; otherwise nothing is recorded.\n * @returns The inserted inbound delivery.\n * @throws {Error} When an actor is not a local actor of the instance.\n */\nexport async function recordInbound(\n db: Database,\n { addressed, body, id = uuidV7(), ...entry }: InboundDeliveryEntry,\n): Promise<ActivityDelivery> {\n return await insertDelivery(\n db,\n {\n ...entry,\n body: Buffer.from(body),\n payload: jsonb(entry.payload),\n fetchedObject: storedObject(entry.fetchedObject),\n id,\n direction: \"inbound\",\n // Whatever a caller outside TypeScript passes.\n carriedSnapshot: false,\n carriedObjectSnapshot: false,\n },\n inboundActorRows({ actorId: entry.actorId, addressed }),\n );\n}\n\n/**\n * Record that an inbox listener ran for an inbound delivery answered before it\n * did, as a queued one is.\n * @returns Whether an acknowledged inbound delivery was found.\n */\nexport async function receiveInbound(db: Database, id: Uuid): Promise<boolean> {\n const rows = await db\n .update(activityDeliveries)\n .set({ status: \"received\" })\n .where(\n and(\n eq(activityDeliveries.id, id),\n eq(activityDeliveries.direction, \"inbound\"),\n eq(activityDeliveries.status, \"acknowledged\"),\n ),\n )\n .returning({ id: activityDeliveries.id });\n return rows.length > 0;\n}\n\n/**\n * Decide what a linked inbound delivery carried, anew every time, so that a\n * mark left from an activity deleted since never carries over to another\n * stored under the same IRI:\n *\n * - The stored activity, when its payload is the stored document, since the\n * same IRI may arrive again with other contents.\n * - The object stored with that activity, when the delivery carried the\n * activity and the object was taken from it, or when its inbox listener\n * fetched the object as stored. Matching the activity proves nothing of\n * an object fetched apart from it, which may differ from fetch to fetch.\n *\n * A payload or a fetched object jsonb could not hold is stored as SQL `NULL`\n * and carries nothing. An unlinked delivery is left as is.\n */\nasync function decideCarried(tx: Transaction, deliveryId: Uuid): Promise<void> {\n const [row] = await tx\n .select({\n payload: activityDeliveries.payload,\n fetchedObject: activityDeliveries.fetchedObject,\n activity: activities.document,\n object: objects.document,\n fetched: objects.fetched,\n })\n .from(activityDeliveries)\n .innerJoin(activities, eq(activities.id, activityDeliveries.activityId))\n .leftJoin(objects, eq(objects.activityId, activityDeliveries.activityId))\n .where(\n and(\n eq(activityDeliveries.id, deliveryId),\n eq(activityDeliveries.direction, \"inbound\"),\n ),\n );\n if (row == null) return;\n const carriedSnapshot =\n row.payload != null && isDeepStrictEqual(row.payload, row.activity);\n const carriedObjectSnapshot =\n carriedSnapshot &&\n row.fetched != null &&\n (!row.fetched ||\n (row.fetchedObject != null &&\n isDeepStrictEqual(row.fetchedObject, row.object)));\n await tx\n .update(activityDeliveries)\n .set({ carriedSnapshot, carriedObjectSnapshot })\n .where(eq(activityDeliveries.id, deliveryId));\n}\n\n/**\n * Link an inbound delivery to the stored activity its activity IRI names.\n * Only a delivery Fedify verified and answered with 2xx is linked: Fedify\n * authenticates an activity before accepting it, so its actor has the origin\n * of the activity's ID, whether an inbox listener ran or it was a duplicate.\n * A delivery that is already linked is left as is.\n *\n * The link names the activity whatever the delivery carried; what it carried\n * is decided as the link is made, as `recordFetchedObject()` decides it again.\n * @returns Whether the delivery was linked.\n */\nexport async function linkInboundActivity(\n db: Database | Transaction,\n deliveryId: Uuid,\n): Promise<boolean> {\n return await db.transaction(async (tx) => {\n const [row] = await tx\n .update(activityDeliveries)\n .set({ activityId: resources.id })\n .from(resources)\n .innerJoin(activities, eq(activities.id, resources.id))\n .where(\n and(\n eq(activityDeliveries.id, deliveryId),\n eq(activityDeliveries.direction, \"inbound\"),\n inArray(activityDeliveries.status, [\"received\", \"acknowledged\"]),\n eq(activityDeliveries.verificationResult, \"verified\"),\n isNull(activityDeliveries.activityId),\n eq(resources.iri, activityDeliveries.activityIri),\n eq(resources.kind, \"activity\"),\n ),\n )\n .returning({ id: activityDeliveries.id });\n if (row == null) return false;\n await decideCarried(tx, deliveryId);\n return true;\n });\n}\n\n/**\n * Record the object an inbound delivery's inbox listener fetched from its IRI,\n * and decide again what the delivery carried if it is linked already, as a\n * duplicate queued for a worker is before its listener runs.\n * @returns Whether the inbound delivery was found.\n */\nexport async function recordFetchedObject(\n db: Database,\n deliveryId: Uuid,\n document: unknown,\n): Promise<boolean> {\n return await db.transaction(async (tx) => {\n const rows = await tx\n .update(activityDeliveries)\n .set({ fetchedObject: storedObject(document) })\n .where(\n and(\n eq(activityDeliveries.id, deliveryId),\n eq(activityDeliveries.direction, \"inbound\"),\n ),\n )\n .returning({ id: activityDeliveries.id });\n if (rows.length < 1) return false;\n await decideCarried(tx, deliveryId);\n return true;\n });\n}\n\n/**\n * Start a delivery observation. The payload is the document before signing.\n * The sender must be a local actor of `instanceId`; otherwise nothing is\n * recorded.\n * @returns The inserted queued outbound delivery.\n * @throws {Error} When the sender is not a local actor of the instance.\n */\nexport async function recordOutbound(\n db: Database,\n entry: OutboundDeliveryEntry,\n): Promise<ActivityDelivery> {\n return await insertDelivery(\n db,\n {\n ...entry,\n // The application clock, as inbound deliveries use, so both directions sort together.\n created: entry.created ?? Temporal.Now.instant(),\n payload: jsonb(entry.payload),\n id: uuidV7(),\n direction: \"outbound\",\n status: \"queued\",\n fetchedObject: null,\n carriedSnapshot: false,\n carriedObjectSnapshot: false,\n },\n entry.actorId == null ? [] : [{ actorId: entry.actorId, sender: true }],\n );\n}\n\n/** What a settled delivery shows; null fields for a successful attempt. */\nexport interface OutboundSettlement {\n readonly activityIri: string;\n readonly inboxUrl: string;\n readonly status: \"sent\" | \"failed\" | \"permanently_failed\" | \"abandoned\";\n readonly statusCode?: number | null;\n readonly error?: string | null;\n readonly responseBody?: string | null;\n /** Whether an attempt ended with this result, rather than none being made. */\n readonly attempted: boolean;\n /** Restrict a synchronous delivery to the row started by that invocation. */\n readonly id?: Uuid;\n}\n\n/**\n * Settle the most recent pending (`queued` or `failed`) delivery to an inbox,\n * keeping each ended attempt. `sent`, `permanently_failed` and `abandoned`\n * deliveries are never changed again.\n * @returns Whether a pending delivery was found.\n */\nexport async function settleOutbound(\n db: Database,\n entry: OutboundSettlement,\n): Promise<boolean> {\n const summary = {\n statusCode: entry.statusCode ?? null,\n error: text(entry.error),\n responseBody: text(entry.responseBody),\n };\n return await db.transaction(async (tx) => {\n const [delivery] = await tx\n .select({ id: activityDeliveries.id })\n .from(activityDeliveries)\n .where(\n and(\n eq(activityDeliveries.direction, \"outbound\"),\n eq(activityDeliveries.activityIri, entry.activityIri),\n eq(activityDeliveries.inboxUrl, entry.inboxUrl),\n inArray(activityDeliveries.status, [\"queued\", \"failed\"]),\n entry.id == null ? undefined : eq(activityDeliveries.id, entry.id),\n ),\n )\n .orderBy(desc(activityDeliveries.created), desc(activityDeliveries.id))\n .limit(1)\n .for(\"update\");\n if (delivery == null) return false;\n const completed = Temporal.Now.instant();\n if (entry.attempted) {\n await tx.insert(activityDeliveryAttempts).values({\n ...summary,\n id: uuidV7(),\n deliveryId: delivery.id,\n succeeded: entry.status === \"sent\",\n created: completed,\n });\n }\n await tx\n .update(activityDeliveries)\n .set({ ...summary, status: entry.status, completed })\n .where(eq(activityDeliveries.id, delivery.id));\n return true;\n });\n}\n"],"mappings":";;;;;;;;;;;AAkGA,SAAgB,iBAAiB,OAGlB;CACb,MAAM,uBAAO,IAAI,IAAoB;CACrC,IAAI,MAAM,WAAW,MACnB,KAAK,IAAI,MAAM,SAAS;EAAE,SAAS,MAAM;EAAS,YAAY;CAAK,CAAC;CAEtE,KAAK,MAAM,EAAE,SAAS,sBAAsB,MAAM,aAAa,CAAC,GAAG;EACjE,MAAM,MAAM,KAAK,IAAI,OAAO;EAC5B,MAAM,iBAAiB,KAAK,kBAAkB,CAAC;EAC/C,KAAK,IAAI,SAAS;GAChB,GAAG;GACH;GACA,WAAW;GACX,mBACE,KAAK,sBAAsB,QAAQ,oBAAoB;GACzD,gBACE,oBAAoB,OAChB,iBACA,CAAC,mBAAG,IAAI,IAAI,CAAC,GAAG,gBAAgB,gBAAgB,CAAC,CAAC,CAAC,CAAC,SAAS;EACrE,CAAC;CACH;CACA,OAAO,CAAC,GAAG,KAAK,OAAO,CAAC;AAC1B;;;;;;AAOA,SAAS,aAAa,OAAyB;CAC7C,IAAI,OAAO,UAAU,UAAU,OAAO,aAAa,KAAK;CACxD,OACE,OAAO,UAAU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B,OAAO,GAAG,KAAK,mBAAmB,EAAE,CAAC,CAAC,CACtE,MAAM,CAAC,CAAC,CACR,IAAI,QAAQ;EACf,IAAI,YAAY,MAAM,OAAO;EAC7B,MAAM,YAAY,SAAS,IAAI,QAAQ;EACvC,IAAI,MAAM,WACR,MAAM,GAAG,OAAO,wBAAwB,CAAC,CAAC,OAAO;GAC/C,GAAG;GACH,IAAI,OAAO;GACX,YAAY,SAAS;GACrB,WAAW,MAAM,WAAW;GAC5B,SAAS;EACX,CAAC;EAEH,MAAM,GACH,OAAO,kBAAkB,CAAC,CAC1B,IAAI;GAAE,GAAG;GAAS,QAAQ,MAAM;GAAQ;EAAU,CAAC,CAAC,CACpD,MAAM,GAAG,mBAAmB,IAAI,SAAS,EAAE,CAAC;EAC/C,OAAO;CACT,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"activity-delivery.mjs","names":[],"sources":["../src/activity-delivery.ts"],"sourcesContent":["// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n\nimport { isDeepStrictEqual } from \"node:util\";\n\nimport { and, desc, eq, inArray, isNotNull, isNull, sql } from \"drizzle-orm\";\n\nimport type { Database, Transaction } from \"./db.ts\";\nimport {\n type ActivityDelivery,\n type NewActivityDelivery,\n type NewActivityDeliveryActor,\n activities,\n activityDeliveries,\n activityDeliveryActorCollections,\n activityDeliveryActors,\n activityDeliveryAttempts,\n actors,\n objects,\n resourceRevisions,\n resources,\n revisionReceipts,\n} from \"./schema.ts\";\nimport { storableText } from \"./text.ts\";\nimport { type Uuid, uuidV7 } from \"./uuid.ts\";\n\n/** The marks of what a delivery carried are the model's to decide. */\ntype DeliveryEntry = Omit<\n NewActivityDelivery,\n \"id\" | \"direction\" | \"status\" | \"carriedSnapshot\" | \"carriedObjectSnapshot\"\n>;\n\nexport interface AddressedActor {\n readonly actorId: Uuid;\n readonly viaCollectionIri?: string | null;\n}\n\n/**\n * `payload` is `undefined` for an unparsable body and `null` for JSON `null`;\n * it is stored as SQL `NULL` when jsonb cannot hold it, and `body` keeps it.\n * `fetchedObject` is stored as SQL `NULL` when jsonb cannot hold it too.\n * An inbound delivery is linked to its activity only by\n * `linkInboundActivity()`.\n */\nexport type InboundDeliveryEntry = Omit<\n DeliveryEntry,\n \"body\" | \"verificationResult\" | \"recipientIris\" | \"activityId\"\n> & {\n /**\n * Chosen in advance when something must name the delivery before it exists.\n */\n readonly id?: Uuid;\n readonly status: \"received\" | \"acknowledged\" | \"unverified\" | \"rejected\";\n readonly verificationResult: NonNullable<DeliveryEntry[\"verificationResult\"]>;\n readonly body: Uint8Array;\n readonly addressed?: readonly AddressedActor[];\n /** When the request arrived, before verification and handling. */\n readonly created: Temporal.Instant;\n /** When DrFed answered the request. */\n readonly completed: Temporal.Instant;\n};\n\n/** `payload` is the document before signing, without `bto` and `bcc`. */\nexport type OutboundDeliveryEntry = Omit<\n DeliveryEntry,\n | \"verificationKeyId\"\n | \"verificationMechanism\"\n | \"verificationResult\"\n | \"body\"\n | \"headers\"\n | \"requestUrl\"\n | \"completed\"\n | \"fetchedObject\"\n> & {\n readonly activityIri: string;\n};\n\ntype ActorRow = Omit<NewActivityDeliveryActor, \"deliveryId\" | \"created\"> & {\n /** The addressed collections that reached the actor, sorted. */\n readonly collectionIris?: readonly string[];\n};\n\n/**\n * Merge the inbox owner and addressed actors into one row per actor, keeping\n * every way each was addressed, whatever order they come in.\n * @returns The actor rows of an inbound delivery.\n */\nexport function inboundActorRows(entry: {\n readonly actorId?: Uuid | null | undefined;\n readonly addressed?: readonly AddressedActor[] | undefined;\n}): ActorRow[] {\n const rows = new Map<Uuid, ActorRow>();\n if (entry.actorId != null) {\n rows.set(entry.actorId, { actorId: entry.actorId, inboxOwner: true });\n }\n for (const { actorId, viaCollectionIri } of entry.addressed ?? []) {\n const row = rows.get(actorId);\n const collectionIris = row?.collectionIris ?? [];\n rows.set(actorId, {\n ...row,\n actorId,\n addressed: true,\n addressedDirectly:\n row?.addressedDirectly === true || viaCollectionIri == null,\n collectionIris:\n viaCollectionIri == null\n ? collectionIris\n : [...new Set([...collectionIris, viaCollectionIri])].toSorted(),\n });\n }\n return [...rows.values()];\n}\n\n/**\n * PostgreSQL's jsonb holds neither U+0000 nor an unpaired surrogate, in keys\n * or in values.\n * @returns Whether the JSON value can be stored as jsonb.\n */\nfunction storableJson(value: unknown): boolean {\n if (typeof value === \"string\") return storableText(value);\n return (\n typeof value !== \"object\" ||\n value == null ||\n Object.entries(value).every(\n ([key, item]) => storableJson(key) && storableJson(item),\n )\n );\n}\n\n/**\n * Keep a payload jsonb cannot hold out of the delivery, rather than the\n * delivery.\n * @returns The value to store, SQL `NULL` for such a payload.\n */\nconst jsonb = (payload: unknown) =>\n payload === null\n ? sql`'null'::jsonb`\n : storableJson(payload)\n ? payload\n : null;\n\n/**\n * A fetched object is a JSON object, so nothing fetched is SQL `NULL`.\n * @returns The value to store.\n */\nconst storedObject = (document: unknown) =>\n document == null ? null : jsonb(document);\n\n/**\n * PostgreSQL's text holds no U+0000, which a remote response or an error\n * quoting one may carry; keep the rest of it rather than lose the delivery.\n * @returns The text with each U+0000 replaced by U+FFFD.\n */\nconst text = (value: string | null | undefined): string | null =>\n value?.replaceAll(\"\\0\", \"\\ufffd\") ?? null;\n\n/**\n * Refuse to relate a delivery to anything but local actors of its instance,\n * which neither foreign key can tell.\n * @throws {Error} When an actor is remote, or of another instance.\n */\nasync function checkLocalActors(\n tx: Transaction,\n instanceId: Uuid,\n actorIds: readonly (Uuid | null | undefined)[],\n): Promise<void> {\n const ids = [...new Set(actorIds.filter((id) => id != null))];\n if (ids.length === 0) return;\n const local = await tx.$count(\n actors,\n and(\n inArray(actors.id, ids),\n eq(actors.instanceId, instanceId),\n isNotNull(actors.localId),\n ),\n );\n if (local !== ids.length) {\n throw new Error(\n \"An activity delivery relates only to local actors of its instance.\",\n );\n }\n}\n\nasync function insertDelivery(\n db: Database,\n delivery: NewActivityDelivery,\n links: readonly ActorRow[],\n): Promise<ActivityDelivery> {\n return await db.transaction(async (tx) => {\n await checkLocalActors(tx, delivery.instanceId, [\n delivery.actorId,\n ...links.map(({ actorId }) => actorId),\n ]);\n const [row] = await tx\n .insert(activityDeliveries)\n .values({\n ...delivery,\n error: text(delivery.error),\n responseBody: text(delivery.responseBody),\n })\n .returning();\n if (row == null) {\n throw new Error(\"Missing activity delivery after insertion.\");\n }\n if (links.length > 0) {\n await tx.insert(activityDeliveryActors).values(\n links.map(({ collectionIris: _, ...link }) => ({\n ...link,\n deliveryId: row.id,\n created: row.created,\n })),\n );\n }\n const collections = links.flatMap(({ actorId, collectionIris = [] }) =>\n collectionIris.map((collectionIri) => ({\n deliveryId: row.id,\n actorId,\n collectionIri,\n })),\n );\n if (collections.length > 0) {\n await tx.insert(activityDeliveryActorCollections).values(collections);\n }\n return row;\n });\n}\n\n/**\n * Persist one inbound observation with its actor rows in one transaction.\n * The inbox owner and every addressed actor must be local actors of\n * `instanceId`; otherwise nothing is recorded.\n * @returns The inserted inbound delivery.\n * @throws {Error} When an actor is not a local actor of the instance.\n */\nexport async function recordInbound(\n db: Database,\n { addressed, body, id = uuidV7(), ...entry }: InboundDeliveryEntry,\n): Promise<ActivityDelivery> {\n return await insertDelivery(\n db,\n {\n ...entry,\n body: Buffer.from(body),\n payload: jsonb(entry.payload),\n fetchedObject: storedObject(entry.fetchedObject),\n id,\n direction: \"inbound\",\n // Whatever a caller outside TypeScript passes.\n carriedSnapshot: false,\n carriedObjectSnapshot: false,\n },\n inboundActorRows({ actorId: entry.actorId, addressed }),\n );\n}\n\n/**\n * Record that an inbox listener ran for an inbound delivery answered before it\n * did, as a queued one is.\n * @returns Whether an acknowledged inbound delivery was found.\n */\nexport async function receiveInbound(db: Database, id: Uuid): Promise<boolean> {\n const rows = await db\n .update(activityDeliveries)\n .set({ status: \"received\" })\n .where(\n and(\n eq(activityDeliveries.id, id),\n eq(activityDeliveries.direction, \"inbound\"),\n eq(activityDeliveries.status, \"acknowledged\"),\n ),\n )\n .returning({ id: activityDeliveries.id });\n return rows.length > 0;\n}\n\n/**\n * Decide what a linked inbound delivery carried, anew every time, so that a\n * mark left from an activity deleted since never carries over to another\n * stored under the same IRI:\n *\n * - The stored activity, when its payload is the stored document, since the\n * same IRI may arrive again with other contents.\n * - The object stored with that activity, when the delivery carried the\n * activity and the object was taken from it, or when its inbox listener\n * fetched the object as stored. Matching the activity proves nothing of\n * an object fetched apart from it, which may differ from fetch to fetch.\n *\n * A payload or a fetched object jsonb could not hold is stored as SQL `NULL`\n * and carries nothing. An unlinked delivery is left as is.\n */\nasync function decideCarried(tx: Transaction, deliveryId: Uuid): Promise<void> {\n // Both current callers already update this delivery; retain that lock order\n // explicitly so every recomputation serializes evidence and receipt changes.\n const [delivery] = await tx\n .select({\n activityId: activityDeliveries.activityId,\n payload: activityDeliveries.payload,\n fetchedObject: activityDeliveries.fetchedObject,\n })\n .from(activityDeliveries)\n .where(\n and(\n eq(activityDeliveries.id, deliveryId),\n eq(activityDeliveries.direction, \"inbound\"),\n ),\n )\n .for(\"update\");\n if (delivery === undefined) return;\n const [activity] =\n delivery.activityId === null\n ? []\n : await tx\n .select({\n id: activities.id,\n document: activities.document,\n })\n .from(activities)\n .where(eq(activities.id, delivery.activityId));\n // Lock separately, never the nullable side of an outer join. Deletion waits\n // for this transaction, then its AFTER DELETE cleanup sees our receipts.\n // This must precede receipt writes to avoid reversing the delete lock order.\n const [object] =\n activity === undefined\n ? []\n : await tx\n .select({\n id: objects.id,\n document: objects.document,\n fetched: objects.fetched,\n })\n .from(objects)\n .where(eq(objects.activityId, activity.id))\n .for(\"key share\");\n await tx\n .delete(revisionReceipts)\n .where(eq(revisionReceipts.deliveryId, deliveryId));\n if (activity === undefined) return;\n const carriedSnapshot =\n delivery.payload != null &&\n isDeepStrictEqual(delivery.payload, activity.document);\n const carriedObjectSnapshot =\n carriedSnapshot &&\n object !== undefined &&\n (!object.fetched ||\n (delivery.fetchedObject != null &&\n isDeepStrictEqual(delivery.fetchedObject, object.document)));\n await tx\n .update(activityDeliveries)\n .set({ carriedSnapshot, carriedObjectSnapshot })\n .where(eq(activityDeliveries.id, deliveryId));\n if (!carriedSnapshot) return;\n const revisions = await tx\n .select()\n .from(resourceRevisions)\n .where(\n and(\n inArray(\n resourceRevisions.resourceId,\n object === undefined ? [activity.id] : [activity.id, object.id],\n ),\n eq(resourceRevisions.sequence, 1),\n eq(resourceRevisions.kind, \"snapshot\"),\n ),\n );\n const activityRevision = revisions.find(\n (revision) => revision.resourceId === activity.id,\n );\n if (\n activityRevision === undefined ||\n !isDeepStrictEqual(activityRevision.document, activity.document)\n ) {\n return;\n }\n const receipts: (typeof revisionReceipts.$inferInsert)[] = [\n {\n deliveryId,\n revisionId: activityRevision.id,\n role: \"activity\",\n },\n ];\n const objectRevision =\n object === undefined\n ? undefined\n : revisions.find((revision) => revision.resourceId === object.id);\n if (\n carriedObjectSnapshot &&\n object !== undefined &&\n objectRevision !== undefined &&\n isDeepStrictEqual(objectRevision.document, object.document)\n ) {\n receipts.push({\n deliveryId,\n revisionId: objectRevision.id,\n role: \"object\",\n });\n }\n await tx.insert(revisionReceipts).values(receipts);\n}\n\n/**\n * Link an inbound delivery to the stored activity its activity IRI names.\n * Only a delivery Fedify verified and answered with 2xx is linked: Fedify\n * authenticates an activity before accepting it, so its actor has the origin\n * of the activity's ID, whether an inbox listener ran or it was a duplicate.\n * A delivery that is already linked is left as is.\n *\n * The link names the activity whatever the delivery carried; what it carried\n * is decided as the link is made, as `recordFetchedObject()` decides it again.\n * @returns Whether the delivery was linked.\n */\nexport async function linkInboundActivity(\n db: Database | Transaction,\n deliveryId: Uuid,\n): Promise<boolean> {\n return await db.transaction(async (tx) => {\n const [row] = await tx\n .update(activityDeliveries)\n .set({ activityId: resources.id })\n .from(resources)\n .innerJoin(activities, eq(activities.id, resources.id))\n .where(\n and(\n eq(activityDeliveries.id, deliveryId),\n eq(activityDeliveries.direction, \"inbound\"),\n inArray(activityDeliveries.status, [\"received\", \"acknowledged\"]),\n eq(activityDeliveries.verificationResult, \"verified\"),\n isNull(activityDeliveries.activityId),\n eq(resources.iri, activityDeliveries.activityIri),\n eq(resources.kind, \"activity\"),\n ),\n )\n .returning({ id: activityDeliveries.id });\n if (row == null) return false;\n await decideCarried(tx, deliveryId);\n return true;\n });\n}\n\n/**\n * Record the object an inbound delivery's inbox listener fetched from its IRI,\n * and decide again what the delivery carried if it is linked already, as a\n * duplicate queued for a worker is before its listener runs.\n * @returns Whether the inbound delivery was found.\n */\nexport async function recordFetchedObject(\n db: Database,\n deliveryId: Uuid,\n document: unknown,\n): Promise<boolean> {\n return await db.transaction(async (tx) => {\n const rows = await tx\n .update(activityDeliveries)\n .set({ fetchedObject: storedObject(document) })\n .where(\n and(\n eq(activityDeliveries.id, deliveryId),\n eq(activityDeliveries.direction, \"inbound\"),\n ),\n )\n .returning({ id: activityDeliveries.id });\n if (rows.length < 1) return false;\n await decideCarried(tx, deliveryId);\n return true;\n });\n}\n\n/**\n * Start a delivery observation. The payload is the document before signing.\n * The sender must be a local actor of `instanceId`; otherwise nothing is\n * recorded.\n * @returns The inserted queued outbound delivery.\n * @throws {Error} When the sender is not a local actor of the instance.\n */\nexport async function recordOutbound(\n db: Database,\n entry: OutboundDeliveryEntry,\n): Promise<ActivityDelivery> {\n return await insertDelivery(\n db,\n {\n ...entry,\n // The application clock, as inbound deliveries use, so both directions sort together.\n created: entry.created ?? Temporal.Now.instant(),\n payload: jsonb(entry.payload),\n id: uuidV7(),\n direction: \"outbound\",\n status: \"queued\",\n fetchedObject: null,\n carriedSnapshot: false,\n carriedObjectSnapshot: false,\n },\n entry.actorId == null ? [] : [{ actorId: entry.actorId, sender: true }],\n );\n}\n\n/** What a settled delivery shows; null fields for a successful attempt. */\nexport interface OutboundSettlement {\n readonly activityIri: string;\n readonly inboxUrl: string;\n readonly status: \"sent\" | \"failed\" | \"permanently_failed\" | \"abandoned\";\n readonly statusCode?: number | null;\n readonly error?: string | null;\n readonly responseBody?: string | null;\n /** Whether an attempt ended with this result, rather than none being made. */\n readonly attempted: boolean;\n /** Restrict a synchronous delivery to the row started by that invocation. */\n readonly id?: Uuid;\n}\n\n/**\n * Settle the most recent pending (`queued` or `failed`) delivery to an inbox,\n * keeping each ended attempt. `sent`, `permanently_failed` and `abandoned`\n * deliveries are never changed again.\n * @returns Whether a pending delivery was found.\n */\nexport async function settleOutbound(\n db: Database,\n entry: OutboundSettlement,\n): Promise<boolean> {\n const summary = {\n statusCode: entry.statusCode ?? null,\n error: text(entry.error),\n responseBody: text(entry.responseBody),\n };\n return await db.transaction(async (tx) => {\n const [delivery] = await tx\n .select({ id: activityDeliveries.id })\n .from(activityDeliveries)\n .where(\n and(\n eq(activityDeliveries.direction, \"outbound\"),\n eq(activityDeliveries.activityIri, entry.activityIri),\n eq(activityDeliveries.inboxUrl, entry.inboxUrl),\n inArray(activityDeliveries.status, [\"queued\", \"failed\"]),\n entry.id == null ? undefined : eq(activityDeliveries.id, entry.id),\n ),\n )\n .orderBy(desc(activityDeliveries.created), desc(activityDeliveries.id))\n .limit(1)\n .for(\"update\");\n if (delivery == null) return false;\n const completed = Temporal.Now.instant();\n if (entry.attempted) {\n await tx.insert(activityDeliveryAttempts).values({\n ...summary,\n id: uuidV7(),\n deliveryId: delivery.id,\n succeeded: entry.status === \"sent\",\n created: completed,\n });\n }\n await tx\n .update(activityDeliveries)\n .set({ ...summary, status: entry.status, completed })\n .where(eq(activityDeliveries.id, delivery.id));\n return true;\n });\n}\n"],"mappings":";;;;;;;;;;;AAoGA,SAAgB,iBAA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