foldkit-remote-server 0.22.0 → 0.24.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.
@@ -1,22 +1,42 @@
1
1
  import { Cause, Clock, Context, Data, Duration, Effect, Match, Option, Queue, Schema, Stream } from "effect";
2
- import { Derivation, Entity, Held, Operators, Query, QueryEvaluateError, SchemaShape, Write, assertSupported, assertSupported as assertSupported$1, evaluate, evaluate as evaluate$1, supported } from "foldkit-entity";
2
+ import { Derivation, Entity, Expr, Held, Operators, Query, QueryEvaluateError, SchemaShape, Write, assertSupported, assertSupported as assertSupported$1, evaluate, evaluate as evaluate$1, supported, supported as supported$1 } from "foldkit-entity";
3
3
  import { DEFAULT_MAX_BODY_BYTES, DEFAULT_MAX_IDS_PER_ENTITY, Diagnostics, EdgeCache, MutationRequest, QueryRequest, RELATION_ALIAS, REMOTE_PROTOCOL_VERSION, ReadBatch, Refusal, Remote, RemoteForbidden, RemoteJsonRequest, RemoteLiveError, RemoteLiveRefused, RemoteMutationError, RemotePrincipalChanged, RemoteProtocolError, RemoteQueryError, RemoteReadError, RemoteUnauthenticated, Requirement, aliasedField, connectionIdentity, entityKey, queryIdentity, refParts, refsIn, relationShape, stableStringify } from "foldkit-remote";
4
4
  import { HttpServerRequest, HttpServerResponse } from "effect/http";
5
5
  // src/diagnostics.ts
6
6
  /**
7
- * What a Remote server answers past without telling the caller why: a defect
8
- * it answered "Internal error", a committed mutation whose answer's read or
9
- * live publish failed, and a client's time it would not take. Each is
7
+ * What a Remote server answers past without telling the caller why: a failure
8
+ * on its side it answered "Internal error", a committed mutation whose answer's
9
+ * read or live publish failed, and a client's time it would not take. Each is
10
10
  * reported through `Diagnostics.report`, so a host's log (a Worker's
11
11
  * `wrangler tail`) shows it by default.
12
12
  */
13
13
  const source = "foldkit-remote-server";
14
- const serverDefect = (cause) => ({
15
- _tag: "ServerDefect",
16
- source,
17
- level: "error",
18
- message: `a request failed on this side, and its caller was answered "Internal error"\n${Cause.pretty(cause)}`,
19
- cause
14
+ /** What a caller reads of a failure on this side, whatever broke. */
15
+ const INTERNAL_ERROR = "Internal error";
16
+ /**
17
+ * 64 random bits as hex, short enough to quote. `getRandomValues` exists
18
+ * where `randomUUID` does not: a server run in a page over plain HTTP.
19
+ */
20
+ const mintIncident = () => Array.from(globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(8)), (byte) => byte.toString(16).padStart(2, "0")).join("");
21
+ /**
22
+ * Reports `cause` as a `ServerDefect` and answers what its caller is told
23
+ * instead: the one place a failure on this side becomes words for a caller.
24
+ */
25
+ const internalFailure = (during, cause) => Effect.suspend(() => {
26
+ const incident = mintIncident();
27
+ const defect = {
28
+ _tag: "ServerDefect",
29
+ source,
30
+ level: "error",
31
+ message: `incident ${incident}: ${during} failed on this side. No caller is told more of it than this id.\n${Cause.pretty(cause)}`,
32
+ cause,
33
+ incident,
34
+ during
35
+ };
36
+ return Effect.as(Diagnostics.report(defect), {
37
+ message: INTERNAL_ERROR,
38
+ incident
39
+ });
20
40
  });
21
41
  const answerUnread = (mutation, reason) => ({
22
42
  _tag: "AnswerUnread",
@@ -49,14 +69,239 @@ const cachedReadDiffers = (request) => ({
49
69
  request
50
70
  });
51
71
  // src/refusal.ts
52
- /** A caller who could not be told, as a 401 body: the twin of `answer`'s 403. */
72
+ /**
73
+ * A caller who could not be told, as a 401 body: the twin of `answer`'s 403.
74
+ * It says the refusal's `reason`, the words written for the caller, or
75
+ * "Unauthenticated"; a refusal's `message` may be anyone's, and is not sent.
76
+ */
53
77
  const unauthenticatedAnswer = (refusal) => ({
54
78
  status: 401,
55
79
  body: {
56
- error: refusal.message,
80
+ error: refusal.reason ?? "Unauthenticated",
57
81
  unauthenticated: refusal.reason === void 0 ? {} : { reason: refusal.reason }
58
82
  }
59
83
  });
84
+ // src/memoryWriter.ts
85
+ /**
86
+ * `RemoteServer.memoryWriter`: a declared write landed over a memory backend's
87
+ * rows, deciding what `foldkit-remote-drizzle`'s writer decides in its
88
+ * statement, so a first run, a test or a Domain aggregate lands the same
89
+ * writes with no database.
90
+ */
91
+ /**
92
+ * What a writer may run: a writer is given no viewer and no time, and one row,
93
+ * so neither context term, and nothing that reaches another row.
94
+ */
95
+ const writeOperations = supported.filter((operation) => operation !== "viewer" && operation !== "now");
96
+ /** Two values as a store holds them, which are JSON: equal when they encode the same. */
97
+ const sameStored = (left, right) => JSON.stringify(left) === JSON.stringify(right);
98
+ /** `keys` of `row` it holds as its own: never `Object`'s of the same name. */
99
+ const picked = (row, keys) => Object.fromEntries(keys.filter((key) => Object.hasOwn(row, key)).map((key) => [key, row[key]]));
100
+ /** Each link as the store holds it: its ref key, or null for none. */
101
+ const linkRefs = (links) => Object.fromEntries(Object.entries(links).map(([key, link]) => [key, Option.getOrNull(Option.map(link, (ref) => entityKey(ref.entity, ref.id)))]));
102
+ /** Each link as an invariant reads it: the id it points at, or null for none. */
103
+ const linkIds = (links) => Object.fromEntries(Object.entries(links).map(([key, link]) => [key, Option.getOrNull(Option.map(link, (ref) => ref.id))]));
104
+ /**
105
+ * A writer of `entity`'s rows in `store` (a memory backend's), for
106
+ * `RemoteServer.write`: an update lands while the row is at the revision it
107
+ * `expect`s, holds its `when`, and the row it would leave keeps every
108
+ * invariant, and moves the revision on by one; an insert lands while its id is
109
+ * free and its row keeps the state invariants; a delete while the row is at
110
+ * its revision and holds its `when`. Each refusal is the writer's own error,
111
+ * which `RemoteServer.write` answers as the mutation's `Conflict`, `Unmet`,
112
+ * `Invalid` or `Taken`. It holds no ledger, judges no rule that reads another
113
+ * row, and removes, restricts or clears nothing a delete would take with it,
114
+ * so `RemoteServer.write` and `GuardServer.writer` refuse, by name, a write or
115
+ * a rule that needs one of those. A write's postcondition (`ensures`) is
116
+ * judged beside the invariants, and refused the same way.
117
+ *
118
+ * ```ts
119
+ * RemoteServer.memory({
120
+ * domain,
121
+ * rows,
122
+ * mutations: store => [RemoteServer.write(ReserveStock, RemoteServer.memoryWriter(store, Product))],
123
+ * })
124
+ * ```
125
+ */
126
+ const memoryWriter = (store, entity, options = {}) => {
127
+ const operators = options.operators ?? Operators.kernel;
128
+ const invariants = Entity.invariants(entity);
129
+ const unrun = Expr.unsupported(invariants.map((held) => held.predicate), {
130
+ operations: [...writeOperations, "next"],
131
+ operators
132
+ });
133
+ if (unrun.length > 0) throw new Error(`[foldkit-remote-server] RemoteServer.memoryWriter: ${entity.name}'s invariants need ${unrun.join(", ")}, which this writer does not run`);
134
+ const relations = entity.relations;
135
+ const links = Object.entries(relations).filter(([, member]) => member._tag === "Relation" && member.cardinality === "one").map(([key]) => key);
136
+ const judged = (row) => {
137
+ const read = { ...row };
138
+ for (const key of links) {
139
+ const ref = Object.hasOwn(row, key) ? row[key] : void 0;
140
+ if (typeof ref === "string") read[key] = refParts(ref).id;
141
+ }
142
+ return read;
143
+ };
144
+ const clocked = new Set(Object.entries(entity.sets).filter(([, set]) => set.value._tag === "Now").map(([field]) => field));
145
+ const stored = (id) => Option.fromUndefinedOr(store.rows(entity.name).find((row) => String(row["id"]) === id));
146
+ /**
147
+ * The first invariant the change breaks, the write's postcondition after the
148
+ * Entity's, as the writer refuses it; none when it keeps them.
149
+ */
150
+ const broken = (change, id, ensures) => Match.value(Entity.judgeAgainst(ensures === void 0 ? invariants : [...invariants, ensures], change, operators)).pipe(Match.tagsExhaustive({
151
+ Valid: () => Effect.succeed(Option.none()),
152
+ Invalid: ({ failures }) => Effect.succeed(Option.map(Option.fromUndefinedOr(failures[0]), (held) => new RemoteInvalid({
153
+ message: held.message,
154
+ rule: Option.some(held.id),
155
+ path: held.path
156
+ }))),
157
+ Undecided: ({ fields }) => Effect.fail(new RemoteServerError({ message: `${entity.name} ${id}: an invariant reads ${fields.join(", ")}, which the row does not hold` }))
158
+ }));
159
+ /** Whether the row holds the write's `when`, judged over it as it is. */
160
+ const holds = (row, when) => Option.match(when, {
161
+ onNone: () => Effect.succeed(true),
162
+ onSome: ({ body, input }) => Effect.try({
163
+ try: () => evaluate(body, input, [judged(row)], { operators }).length > 0,
164
+ catch: (cause) => new RemoteServerError({
165
+ message: `${entity.name}'s write precondition could not be judged`,
166
+ cause
167
+ })
168
+ })
169
+ });
170
+ /** Whether `row` holds what a write set; a field set from its clock is stamped anew by a retry. */
171
+ const holdsWritten = (row, written) => Object.entries(written).every(([key, value]) => clocked.has(key) || sameStored(row[key], value));
172
+ const unmet = (id) => new RemoteUnmet({ message: `${entity.name} ${id} does not hold what the write asks of it` });
173
+ return {
174
+ entity: entity.name,
175
+ preconditions: true,
176
+ increments: true,
177
+ assignments: true,
178
+ invariants: true,
179
+ postconditions: true,
180
+ pins: true,
181
+ operators,
182
+ refuses: (write) => [
183
+ ...Option.match(write.when, {
184
+ onNone: () => [],
185
+ onSome: (body) => {
186
+ const missing = Query.unsupported(body, writeOperations, operators);
187
+ return missing.length === 0 ? [] : [`its precondition needs ${missing.join(", ")}, which a memory writer does not run`];
188
+ }
189
+ }),
190
+ ...write.assignments.flatMap(({ field, expr }) => {
191
+ const missing = Expr.unsupported([expr], {
192
+ operations: writeOperations,
193
+ operators
194
+ });
195
+ return missing.length === 0 ? [] : [`its assignment to "${field.key}" needs ${missing.join(", ")}`];
196
+ }),
197
+ ...Option.match(write.ensures, {
198
+ onNone: () => [],
199
+ onSome: (held) => {
200
+ const missing = Expr.unsupported([held.predicate], {
201
+ operations: [...writeOperations, "next"],
202
+ operators
203
+ });
204
+ return missing.length === 0 ? [] : [`its ${held.id} needs ${missing.join(", ")}`];
205
+ }
206
+ })
207
+ ],
208
+ read: ({ id, fields }) => Effect.succeed(Option.map(stored(id), (row) => picked(row, ["id", ...fields]))),
209
+ update: ({ id, values, increments, assignments, links, expect, when, ensures }) => Effect.gen(function* () {
210
+ const found = stored(id);
211
+ if (Option.isNone(found)) return Option.none();
212
+ const row = found.value;
213
+ const written = {
214
+ ...values,
215
+ ...linkRefs(links)
216
+ };
217
+ const answer = (from) => Option.some(picked(from, [
218
+ ...Object.keys(values),
219
+ ...Object.keys(increments),
220
+ ...Object.keys(assignments),
221
+ ...Object.keys(links),
222
+ ...Option.match(expect, {
223
+ onNone: () => [],
224
+ onSome: ({ field }) => [field]
225
+ })
226
+ ]));
227
+ const incrementing = Object.keys(increments).length + Object.keys(assignments).length > 0;
228
+ if (Option.isSome(expect) && !sameStored(row[expect.value.field], expect.value.revision)) {
229
+ const { field, revision } = expect.value;
230
+ return !incrementing && typeof revision === "number" && row[field] === revision + 1 && holdsWritten(row, written) ? answer(row) : Option.none();
231
+ }
232
+ const retried = Object.keys(written).length > 0 && !incrementing && holdsWritten(row, written);
233
+ if (!(yield* holds(row, when))) {
234
+ if (retried) return answer(row);
235
+ return yield* unmet(id);
236
+ }
237
+ const before = judged(row);
238
+ const applied = Write.apply(before, {
239
+ values: {
240
+ ...values,
241
+ ...linkIds(links)
242
+ },
243
+ increments,
244
+ assignments
245
+ }, { operators });
246
+ if (applied.unknown.length > 0) return yield* new RemoteServerError({ message: `${entity.name} ${id}: the write could not work out ${applied.unknown.join(", ")}` });
247
+ const after = applied.row;
248
+ const breaks = yield* broken({
249
+ before,
250
+ after
251
+ }, id, ensures);
252
+ if (Option.isSome(breaks)) {
253
+ if (!retried) return yield* breaks.value;
254
+ const asRow = yield* broken({ after }, id, ensures);
255
+ if (Option.isSome(asRow)) return yield* asRow.value;
256
+ return answer(row);
257
+ }
258
+ const moved = [...Object.keys(increments), ...Object.keys(assignments)];
259
+ const next = {
260
+ ...written,
261
+ ...picked(after, moved),
262
+ ...Option.match(expect, {
263
+ onNone: () => ({}),
264
+ onSome: ({ field }) => {
265
+ const revision = row[field];
266
+ return { [field]: typeof revision === "number" ? revision + 1 : revision };
267
+ }
268
+ })
269
+ };
270
+ store.write(entity.name, id, next);
271
+ return answer({
272
+ ...row,
273
+ ...next
274
+ });
275
+ }),
276
+ insert: ({ id, values, links, ensures }) => Effect.gen(function* () {
277
+ const breaks = yield* broken({ after: {
278
+ ...values,
279
+ ...linkIds(links),
280
+ id
281
+ } }, id, ensures);
282
+ if (Option.isSome(breaks)) return yield* breaks.value;
283
+ if (Option.isSome(stored(id))) return yield* new RemoteTaken({ message: `${entity.name} ${id} is already taken` });
284
+ const row = {
285
+ ...values,
286
+ ...linkRefs(links)
287
+ };
288
+ store.write(entity.name, id, row);
289
+ return row;
290
+ }),
291
+ delete: ({ id, expect, when }) => Effect.gen(function* () {
292
+ const found = stored(id);
293
+ if (Option.isNone(found)) return DeleteOutcome.Absent();
294
+ const row = found.value;
295
+ if (Option.isSome(expect) && !sameStored(row[expect.value.field], expect.value.revision)) return DeleteOutcome.Moved();
296
+ if (!(yield* holds(row, when))) return yield* unmet(id);
297
+ store.remove(entity.name, id);
298
+ return DeleteOutcome.Deleted({
299
+ cascaded: [],
300
+ cleared: []
301
+ });
302
+ })
303
+ };
304
+ };
60
305
  // src/body.ts
61
306
  /**
62
307
  * A request body read up to a limit, refused past it before anything decodes
@@ -186,7 +431,47 @@ const bodyLimit = (maxBytes = DEFAULT_MAX_BODY_BYTES) => (endpoint) => Effect.ge
186
431
  * turning them into Effect RPC handlers. It does not own HTTP, serialization, or
187
432
  * auth protocol; `principal` is resolved outside, and passed in or provided.
188
433
  */
189
- var RemoteServerError = class extends Schema.TaggedError()("RemoteServerError", { message: Schema.String }) {};
434
+ /**
435
+ * A Source's failure. Its `message` and `cause` stay on this side: the server
436
+ * reports them as a `ServerDefect` and answers "Internal error" with the id it
437
+ * reported them under, so a driver's words, a thrown error's or a rule's
438
+ * internals reach no caller. Only `RemoteServer.tell` makes one whose message
439
+ * the caller reads.
440
+ */
441
+ var RemoteServerError = class extends Schema.TaggedError()("RemoteServerError", {
442
+ message: Schema.String,
443
+ /** What was caught, for the report; never sent. */
444
+ cause: Schema.optional(Schema.Unknown),
445
+ /** Set by `RemoteServer.tell` alone: `message` was written for the caller, who reads it as it is. */
446
+ told: Schema.optional(Schema.Literal(true))
447
+ }) {};
448
+ /** A failure as `answer`'s body: its message, and the id it was reported under when it has one. */
449
+ const failureBody = (failure) => ({
450
+ error: failure.message,
451
+ ...failure.incident === void 0 ? {} : { incident: failure.incident }
452
+ });
453
+ /** A failure for a report of what it left unanswered: its message, and the incident that holds its cause. */
454
+ const reasonOf = (failure) => failure.incident === void 0 ? failure.message : `${failure.message}, incident ${failure.incident}`;
455
+ /** See `RemoteServer.tell`. */
456
+ const tell = (message) => new RemoteServerError({
457
+ message,
458
+ told: true
459
+ });
460
+ /**
461
+ * How a handler fails for its caller, as `fail` builds its error: a Source's
462
+ * failure in the Source's own words only where it wrote them for the caller
463
+ * (`tell`), and anything else, a defect included, reported and answered with
464
+ * nothing of it.
465
+ */
466
+ const failingAs = (during, fail) => {
467
+ const internal = (cause) => Effect.flatMap(internalFailure(during, cause), (said) => Effect.fail(fail(said)));
468
+ return {
469
+ source: (error) => error.told === true ? Effect.fail(fail({ message: error.message })) : internal(Cause.fail(error)),
470
+ internal
471
+ };
472
+ };
473
+ /** The names of `asked` the server serves, for a report: a name it does not serve is the caller's text. */
474
+ const servedOf = (served, asked) => [...new Set(asked)].filter((name) => served.has(name)).join(", ");
190
475
  /**
191
476
  * A writer's word that the row does not hold what the write's `when` asks of
192
477
  * it, where the write would commit: `RemoteServer.write` answers it as the
@@ -246,7 +531,8 @@ const readAs = (source, context) => {
246
531
  for (const field of allowed) if (Object.hasOwn(record.values, field)) values[field] = record.values[field];
247
532
  return {
248
533
  id: record.id,
249
- values
534
+ values,
535
+ ...record.revision === void 0 ? {} : { revision: record.revision }
250
536
  };
251
537
  }))));
252
538
  };
@@ -397,7 +683,8 @@ const checkIdsPerEntity = (requirements, maxIds) => {
397
683
  }
398
684
  };
399
685
  /** Why a live subscription asks more than a read may; `undefined` when it does not. */
400
- const liveRefusal = (requirements, maxIds) => {
686
+ const liveRefusal = ({ requirements, revisions }, maxIds) => {
687
+ if ((revisions?.length ?? 0) > requirements.length) return new RemoteLiveRefused({ message: `More revisions than rows in one live subscription (${requirements.length})` });
401
688
  const over = checkIdsPerEntity(requirements, maxIds);
402
689
  if (over !== void 0) return new RemoteLiveRefused({ message: `Too many "${over}" ids in one live subscription (at most ${maxIds})` });
403
690
  const paged = checkPagesPerRelation(requirements);
@@ -564,7 +851,8 @@ const liveHub = (entities, options = {}) => Effect.sync(() => {
564
851
  entity: ref.entity,
565
852
  id: ref.id,
566
853
  values,
567
- changed
854
+ changed,
855
+ ...record.revision === void 0 ? {} : { revision: record.revision }
568
856
  });
569
857
  }
570
858
  });
@@ -847,7 +1135,10 @@ function memory(config) {
847
1135
  values: Object.fromEntries(fields.flatMap((field) => Object.hasOwn(row, field) ? [[field, valueFor(refsShown(readable, name, field, row[field]), windows !== void 0 && Object.hasOwn(windows, field) ? windows[field] : void 0)]] : []))
848
1136
  }];
849
1137
  }),
850
- catch: (error) => new RemoteServerError({ message: error instanceof Error ? error.message : String(error) })
1138
+ catch: (cause) => new RemoteServerError({
1139
+ message: `${name} could not be read`,
1140
+ cause
1141
+ })
851
1142
  }))
852
1143
  })
853
1144
  }));
@@ -869,7 +1160,7 @@ function memory(config) {
869
1160
  });
870
1161
  const locate = (cursor) => {
871
1162
  const row = rows.find((candidate) => String(candidate.id) === cursor);
872
- if (row === void 0) throw new Error(`Cursor "${cursor}" names a row that no longer exists`);
1163
+ if (row === void 0) throw tell(`Cursor "${cursor}" names a row that no longer exists`);
873
1164
  return {
874
1165
  index: evaluate({
875
1166
  ...body,
@@ -895,7 +1186,10 @@ function memory(config) {
895
1186
  end: page.end
896
1187
  };
897
1188
  },
898
- catch: (error) => new RemoteServerError({ message: error instanceof Error ? error.message : String(error) })
1189
+ catch: (cause) => cause instanceof RemoteServerError ? cause : new RemoteServerError({
1190
+ message: `${query.name} could not be run`,
1191
+ cause
1192
+ })
899
1193
  })))
900
1194
  }))];
901
1195
  const server = RemoteServer.make({
@@ -913,14 +1207,67 @@ function memory(config) {
913
1207
  /** The entries of `record` whose key is in `keys`. */
914
1208
  const pickKeys = (record, keys) => Object.fromEntries(Object.entries(record).filter(([key]) => keys.has(key)));
915
1209
  /**
1210
+ * What a mutation's answer may say of the rows its handler patched (#578): of
1211
+ * each, the keys the caller may read, with the handler's own values. A source
1212
+ * with no `authorize`, `filter` or `visible` declares no reader rule, so its
1213
+ * rows are answered as they are, with no read. Otherwise each such entity is read as
1214
+ * the caller reads it, once, and a row the read does not return, or no field of
1215
+ * it, is not answered. A read that fails answers none of that entity's rows:
1216
+ * the write has committed, and the client reads what it lacks.
1217
+ */
1218
+ const readablePatches = (server, principal, options, mutation, patches) => Effect.gen(function* () {
1219
+ const ruled = /* @__PURE__ */ new Map();
1220
+ for (const patch of patches) {
1221
+ const source = server.entities.get(patch.entity);
1222
+ if (source === void 0 || source.authorize === void 0 && source.filter === void 0 && source.visible === void 0) continue;
1223
+ const group = ruled.get(patch.entity) ?? [];
1224
+ group.push(patch);
1225
+ ruled.set(patch.entity, group);
1226
+ }
1227
+ if (ruled.size === 0) return patches;
1228
+ const maxIds = Math.max(1, options.maxIdsPerEntity ?? DEFAULT_MAX_IDS_PER_ENTITY);
1229
+ const readable = /* @__PURE__ */ new Map();
1230
+ for (const [entity, group] of ruled) {
1231
+ const source = server.entities.get(entity);
1232
+ const ids = [...new Set(group.map((patch) => patch.id))];
1233
+ const fields = [...new Set(group.flatMap((patch) => Object.keys(patch.values)))];
1234
+ const rows = /* @__PURE__ */ new Map();
1235
+ yield* Effect.forEach(Array.from({ length: Math.ceil(ids.length / maxIds) }, (_, chunk) => ids.slice(chunk * maxIds, (chunk + 1) * maxIds)), (chunk) => Effect.map(readAs(source, {
1236
+ ids: chunk,
1237
+ fields,
1238
+ principal,
1239
+ viewer: viewerOf(server, principal)
1240
+ }), (records) => {
1241
+ if (Option.isNone(records)) return;
1242
+ for (const record of records.value) rows.set(record.id, new Set(Object.keys(record.values)));
1243
+ })).pipe(Effect.catchTag("RemoteServerError", failingAs(`read ${entity}`, (said) => new RemoteReadError(said)).source), Effect.matchEffect({
1244
+ onSuccess: () => Effect.sync(() => readable.set(entity, rows)),
1245
+ onFailure: (error) => Diagnostics.report(answerUnread(mutation, reasonOf(error))).pipe(Effect.andThen(Effect.sync(() => readable.set(entity, /* @__PURE__ */ new Map()))))
1246
+ }));
1247
+ }
1248
+ return patches.flatMap((patch) => {
1249
+ const rows = readable.get(patch.entity);
1250
+ if (rows === void 0) return [patch];
1251
+ const keys = rows.get(patch.id);
1252
+ if (keys === void 0) return [];
1253
+ const values = Object.create(null);
1254
+ for (const key of Object.keys(patch.values)) if (keys.has(key)) values[key] = patch.values[key];
1255
+ return Object.keys(values).length === 0 ? [] : [{
1256
+ ...patch,
1257
+ values
1258
+ }];
1259
+ });
1260
+ });
1261
+ /**
916
1262
  * A fresh read, after a mutation, of what the client shows of each row its
917
1263
  * outcome names: of each, the shown fields the answer left out, and every
918
1264
  * shown relation, since the answer's ref alone does not reach what the client
919
1265
  * reads of its target. Read as any read is, so `authorize` and `filter` hold.
920
1266
  * Only rows the read returned are answered: a row hidden from the asker keeps
921
- * what the answer gave it rather than reading as gone.
1267
+ * what the answer gave it rather than reading as gone. `sent` is what the
1268
+ * answer carries of the outcome's patches: a key cut from it is read, not answered.
922
1269
  */
923
- const answerRead = (server, principal, options, shown, outcome) => Effect.gen(function* () {
1270
+ const answerRead = (server, principal, options, shown, sent, outcome) => Effect.gen(function* () {
924
1271
  const slices = /* @__PURE__ */ new Map();
925
1272
  for (const slice of shown) {
926
1273
  const current = slices.get(slice.entity);
@@ -937,7 +1284,8 @@ const answerRead = (server, principal, options, shown, outcome) => Effect.gen(fu
937
1284
  for (const field of answered) row.answered.add(field);
938
1285
  named.set(key, row);
939
1286
  };
940
- for (const patch of outcome.entities) name(patch.entity, patch.id, Object.keys(patch.values));
1287
+ for (const patch of outcome.entities) name(patch.entity, patch.id, []);
1288
+ for (const patch of sent) name(patch.entity, patch.id, Object.keys(patch.values));
941
1289
  for (const change of outcome.connections) if (change._tag === "Insert") name(change.edge.entity, change.edge.id, []);
942
1290
  for (const row of outcome.pointed ?? []) name(row.entity, row.id, []);
943
1291
  for (const gone of outcome.deleted) named.delete(`${gone.entity}:${gone.id}`);
@@ -989,7 +1337,7 @@ const answerQuery = (server, caller, options, payload) => Effect.gen(function* (
989
1337
  principal: caller,
990
1338
  viewer: viewerOf(server, caller),
991
1339
  ...select === void 0 ? {} : { select }
992
- }).pipe(Effect.catchTag("RemoteServerError", (error) => Effect.fail(new RemoteQueryError({ message: error.message }))));
1340
+ }).pipe(Effect.catchTag("RemoteServerError", failingAs(`query ${payload.query}`, (said) => new RemoteQueryError(said)).source));
993
1341
  if (select === void 0) return {
994
1342
  edges: page.edges,
995
1343
  start: page.start,
@@ -1009,7 +1357,10 @@ const answerQuery = (server, caller, options, payload) => Effect.gen(function* (
1009
1357
  entities: [],
1010
1358
  settled: []
1011
1359
  };
1012
- const read = yield* RemoteServer.readHelper(server, caller, options, requirements).pipe(Effect.catchTag("RemoteReadError", (error) => Effect.fail(new RemoteQueryError({ message: error.message }))));
1360
+ const read = yield* RemoteServer.readHelper(server, caller, options, requirements).pipe(Effect.catchTag("RemoteReadError", ({ message, incident }) => Effect.fail(new RemoteQueryError({
1361
+ message,
1362
+ incident
1363
+ }))));
1013
1364
  return {
1014
1365
  edges: page.edges,
1015
1366
  start: page.start,
@@ -1042,12 +1393,12 @@ const admitLists = (server, lists, maxIds) => {
1042
1393
  /**
1043
1394
  * A Source's refusal as the client receives it: encoded by the mutation's own
1044
1395
  * `Refusal`. A refusal made for another mutation, or one the mutation does not
1045
- * declare, is this side's bug, and says so without the value.
1396
+ * declare, is this side's bug: reported with the value, and answered without it.
1046
1397
  */
1047
1398
  const refusalError = (Refusal, mutation, refused) => Effect.gen(function* () {
1048
- const invalid = new RemoteMutationError({ message: "Invalid mutation refusal" });
1049
- if (refused.mutation !== mutation) return yield* invalid;
1050
- const encoded = yield* Schema.encodeUnknownEffect(Refusal)(refused.refusal).pipe(Effect.mapError(() => invalid));
1399
+ const { internal } = failingAs(`mutate ${mutation}`, (said) => new RemoteMutationError(said));
1400
+ if (refused.mutation !== mutation) return yield* internal(Cause.fail(refused));
1401
+ const encoded = yield* Schema.encodeUnknownEffect(Refusal)(refused.refusal).pipe(Effect.catch((error) => internal(Cause.fail(error))));
1051
1402
  return yield* new RemoteMutationError({
1052
1403
  message: refused.message,
1053
1404
  refusal: encoded
@@ -1056,6 +1407,11 @@ const refusalError = (Refusal, mutation, refused) => Effect.gen(function* () {
1056
1407
  const RemoteServer = {
1057
1408
  /** A backend held in memory, for a first run, a test or a demo. See `memory`. */
1058
1409
  memory,
1410
+ /**
1411
+ * A declared write landed over a memory backend's rows (`MemoryStore`), as
1412
+ * `foldkit-remote-drizzle`'s writer lands it over a table. See `memoryWriter`.
1413
+ */
1414
+ memoryWriter,
1059
1415
  /** A mutation outcome's report that `ref` now heads the connection. */
1060
1416
  prepend: (connection, ref) => connectionChange(connection, ref, "prepend"),
1061
1417
  /** A mutation outcome's report that `ref` now ends the connection. */
@@ -1114,6 +1470,22 @@ const RemoteServer = {
1114
1470
  message
1115
1471
  }),
1116
1472
  /**
1473
+ * A failure whose `message` the caller reads as it is: fail a Source with it
1474
+ * (`yield* RemoteServer.tell('That report is still being built')`) for words
1475
+ * written for whoever asked. Every other `RemoteServerError` is this side's:
1476
+ * reported, and answered "Internal error". It takes text, not what was
1477
+ * caught: an error's own message may say anything.
1478
+ */
1479
+ tell,
1480
+ /**
1481
+ * Reports a failure on this side that no handler answers, as the server
1482
+ * reports its own: a scheduled job's, or an adapter's on a transport of its
1483
+ * own. `cause` goes to a `ServerDefect` under a new incident, with `during`
1484
+ * (what was being done: `publish due e3`). It answers what a caller may be
1485
+ * told of it, the fixed words and that id, and nothing of `cause`.
1486
+ */
1487
+ report: (during, cause) => internalFailure(during, Cause.isCause(cause) ? cause : Cause.fail(cause)),
1488
+ /**
1117
1489
  * A writer's refusal of a row that does not hold the write's `when`: fail
1118
1490
  * `update` or `delete` with it (`yield* RemoteServer.unmet()`), and
1119
1491
  * `RemoteServer.write` answers the mutation's `Unmet` refusal.
@@ -1170,7 +1542,10 @@ const RemoteServer = {
1170
1542
  * a row already gone succeeds. A row that moved past the revision the write
1171
1543
  * `expect`s is refused as a conflict, and one that does not hold its `when`
1172
1544
  * as unmet; a write with a `when` needs a writer that checks it
1173
- * (`preconditions`), and is refused here without one.
1545
+ * (`preconditions`), and is refused here without one. A row the write
1546
+ * would leave outside its postcondition (`ensures`) is refused as
1547
+ * invalid, as one breaking an invariant is; a write with one needs a
1548
+ * writer that judges it (`postconditions`).
1174
1549
  */
1175
1550
  write: (mutation, writer) => {
1176
1551
  const { write } = mutation;
@@ -1204,8 +1579,10 @@ const RemoteServer = {
1204
1579
  deletes: true
1205
1580
  })
1206
1581
  }));
1207
- const judged = Entity.invariants(write.input.entity).filter((held) => kind.hasBefore || !Entity.readsBefore(held));
1208
- if (judged.length > 0 && writer.invariants !== true) throw new Error(`[foldkit-remote-server] write "${mutation.name}" writes ${writer.entity}, which has invariants, but its writer does not judge them (invariants)`);
1582
+ const declared = Entity.invariants(write.input.entity).filter((held) => kind.hasBefore || !Entity.readsBefore(held));
1583
+ if (declared.length > 0 && writer.invariants !== true) throw new Error(`[foldkit-remote-server] write "${mutation.name}" writes ${writer.entity}, which has invariants, but its writer does not judge them (invariants)`);
1584
+ if (Option.isSome(write.ensures) && writer.postconditions !== true) throw new Error(`[foldkit-remote-server] write "${mutation.name}" ensures ${write.ensures.value.id}, which enumeration could not prove where it was declared, but its writer for ${writer.entity} does not judge one (postconditions)`);
1585
+ const judged = [...declared, ...Option.toArray(write.ensures)];
1209
1586
  if (kind.inserts) {
1210
1587
  const sets = /* @__PURE__ */ new Set([
1211
1588
  "id",
@@ -1362,7 +1739,7 @@ const RemoteServer = {
1362
1739
  }
1363
1740
  };
1364
1741
  const before = yield* pointedAt(bound.id, principal);
1365
- if (write.increments.length + write.assignments.length > 0 && write.expect === void 0 && Option.isNone(operation)) return yield* new RemoteServerError({ message: `${mutation.name} moves a field with no revision, so it needs an operation id` });
1742
+ if (write.increments.length + write.assignments.length > 0 && write.expect === void 0 && Option.isNone(operation)) return yield* tell(`${mutation.name} moves a field with no revision, so it needs an operation id`);
1366
1743
  const written = yield* invalid(unmet(bound, writer.update({
1367
1744
  id: bound.id,
1368
1745
  operation,
@@ -1373,10 +1750,11 @@ const RemoteServer = {
1373
1750
  links: bound.links,
1374
1751
  expect,
1375
1752
  when: yield* when,
1753
+ ensures: Option.getOrUndefined(write.ensures),
1376
1754
  principal
1377
1755
  })));
1378
1756
  if (Option.isSome(written)) return naming(yield* answered(bound, written.value), [...before, ...yield* pointedAt(bound.id, principal)]);
1379
- return yield* Option.isSome(expect) ? Effect.fail(conflict(bound)) : Effect.fail(new RemoteServerError({ message: `No ${bound.entity} ${bound.id} to update` }));
1757
+ return yield* Option.isSome(expect) ? Effect.fail(conflict(bound)) : Effect.fail(tell(`No ${bound.entity} ${bound.id} to update`));
1380
1758
  }),
1381
1759
  Insert: () => Effect.gen(function* () {
1382
1760
  const bound = Write.bind(write, given);
@@ -1394,6 +1772,7 @@ const RemoteServer = {
1394
1772
  },
1395
1773
  operation,
1396
1774
  request: yield* request,
1775
+ ensures: Option.getOrUndefined(write.ensures),
1397
1776
  principal
1398
1777
  }).pipe(Effect.catchTag("RemoteTaken", () => Effect.fail(RemoteServer.refuse(mutation, {
1399
1778
  _tag: "Taken",
@@ -1601,7 +1980,7 @@ const RemoteServer = {
1601
1980
  principal,
1602
1981
  viewer,
1603
1982
  ...windows
1604
- })), (chunks) => chunks.flat())).pipe(Effect.catchTag("RemoteServerError", (error) => Effect.fail(new RemoteReadError({ message: error.message }))));
1983
+ })), (chunks) => chunks.flat())).pipe(Effect.catchTag("RemoteServerError", failingAs(`read ${name}`, (said) => new RemoteReadError(said)).source));
1605
1984
  for (const record of records) {
1606
1985
  const values = Object.create(null);
1607
1986
  const omitted = [];
@@ -1611,7 +1990,8 @@ const RemoteServer = {
1611
1990
  entities.push({
1612
1991
  entity: name,
1613
1992
  id: record.id,
1614
- values
1993
+ values,
1994
+ ...record.revision === void 0 ? {} : { revision: record.revision }
1615
1995
  });
1616
1996
  settle(name, record.id, omitted);
1617
1997
  const key = `${name}:${record.id}`;
@@ -1651,8 +2031,9 @@ const RemoteServer = {
1651
2031
  * could not be told a 401; a refusal of who is asking a 403; a write made
1652
2032
  * for someone else (`RemotePrincipalChanged`) a 409; a mutation's
1653
2033
  * declared refusal a 422, or a 409 when it is `Refusal.taken`; a handler's
1654
- * failure a 500 with its message; a defect a 500 that says nothing of it,
1655
- * its cause reported as a `ServerDefect` (`Diagnostics`, by default the log).
2034
+ * failure a 500 with its message, and the `incident` it carries; a defect
2035
+ * a 500 that says nothing of it but the `incident` its cause was reported
2036
+ * under, as a `ServerDefect` (`Diagnostics`, by default the log).
1656
2037
  * `Remote.json` and `Remote.http` are the other end.
1657
2038
  */
1658
2039
  answer: (handlers, body) => {
@@ -1676,12 +2057,12 @@ const RemoteServer = {
1676
2057
  })), Effect.catchTag("Forbidden", (error) => Effect.succeed({
1677
2058
  status: 403,
1678
2059
  body: {
1679
- error: error.message,
2060
+ error: error.reason ?? "Forbidden",
1680
2061
  forbidden: error.reason === void 0 ? {} : { reason: error.reason }
1681
2062
  }
1682
2063
  })), Effect.catchTag("RemoteMutationError", (error) => Effect.succeed(error.refusal === void 0 ? {
1683
2064
  status: 500,
1684
- body: { error: error.message }
2065
+ body: failureBody(error)
1685
2066
  } : {
1686
2067
  status: Refusal.isTaken(error.refusal) || Refusal.isReferenced(error.refusal) ? 409 : 422,
1687
2068
  body: {
@@ -1690,10 +2071,10 @@ const RemoteServer = {
1690
2071
  }
1691
2072
  })), Effect.catch((error) => Effect.succeed({
1692
2073
  status: 500,
1693
- body: { error: error.message }
1694
- })), Effect.catchCause((cause) => Diagnostics.report(serverDefect(cause)).pipe(Effect.as({
2074
+ body: failureBody(error)
2075
+ })), Effect.catchCause((cause) => Effect.map(internalFailure("request", cause), (said) => ({
1695
2076
  status: 500,
1696
- body: { error: "Internal error" }
2077
+ body: failureBody(said)
1697
2078
  }))));
1698
2079
  },
1699
2080
  /**
@@ -1705,7 +2086,8 @@ const RemoteServer = {
1705
2086
  */
1706
2087
  handlers: (server, principal, options = {}) => {
1707
2088
  const asking = Context.isKey(principal) ? principal : Effect.succeed(principal);
1708
- return {
2089
+ const mutationFailing = (mutation) => failingAs(`mutate ${servedOf(server.mutations, [mutation])}`, (said) => new RemoteMutationError(said));
2090
+ const answering = {
1709
2091
  FoldkitRemoteRead: Effect.fn("RemoteServer.FoldkitRemoteRead")(function* (payload) {
1710
2092
  const mismatch = protocolMismatch(payload.version);
1711
2093
  if (mismatch !== void 0) return yield* mismatch;
@@ -1722,6 +2104,7 @@ const RemoteServer = {
1722
2104
  const lists = admitLists(server, payload.lists ?? [], Math.max(1, options.maxIdsPerEntity ?? DEFAULT_MAX_IDS_PER_ENTITY));
1723
2105
  const caller = yield* asking;
1724
2106
  yield* madeFor(server, caller, Option.fromUndefinedOr(payload.principal));
2107
+ const failed = mutationFailing(payload.mutation);
1725
2108
  const outcome = yield* source.run({
1726
2109
  input,
1727
2110
  principal: caller,
@@ -1731,13 +2114,14 @@ const RemoteServer = {
1731
2114
  now: yield* writeTime(server, payload.mutation, Option.fromUndefinedOr(payload.now)),
1732
2115
  read: withServices(rowAs(server, caller), yield* Effect.context()),
1733
2116
  keys: payload.keys
1734
- }).pipe(Effect.catchTag("RemoteServerError", (error) => Effect.fail(new RemoteMutationError({ message: error.message }))), Effect.catchTag("MutationRefused", (refused) => refusalError(source.Refusal, payload.mutation, refused)));
1735
- const output = yield* Schema.encodeUnknownEffect(source.Output)(outcome.output).pipe(Effect.catchTag("SchemaError", () => Effect.fail(new RemoteMutationError({ message: "Invalid mutation output" }))));
1736
- const read = yield* answerRead(server, caller, options, payload.shown ?? [], outcome).pipe(Effect.catchTag("RemoteReadError", (error) => Diagnostics.report(answerUnread(payload.mutation, error.message)).pipe(Effect.as(Option.none()))));
2117
+ }).pipe(Effect.catchTag("RemoteServerError", failed.source), Effect.catchTag("MutationRefused", (refused) => refusalError(source.Refusal, payload.mutation, refused)));
2118
+ const output = yield* Schema.encodeUnknownEffect(source.Output)(outcome.output).pipe(Effect.catchTag("SchemaError", (error) => failed.internal(Cause.fail(error))));
2119
+ const sent = yield* readablePatches(server, caller, options, payload.mutation, outcome.entities);
2120
+ const read = yield* answerRead(server, caller, options, payload.shown ?? [], sent, outcome).pipe(Effect.catchTag("RemoteReadError", (error) => Diagnostics.report(answerUnread(payload.mutation, reasonOf(error))).pipe(Effect.as(Option.none()))));
1737
2121
  const answered = yield* Effect.forEach(lists, (request) => answerQuery(server, caller, options, request).pipe(Effect.map((result) => [{
1738
2122
  request,
1739
2123
  result
1740
- }]), Effect.catchTag("RemoteQueryError", (error) => Diagnostics.report(answerUnread(payload.mutation, `list "${request.query}": ${error.message}`)).pipe(Effect.as([]))))).pipe(Effect.map((pages) => pages.flat()));
2124
+ }]), Effect.catchTag("RemoteQueryError", (error) => Diagnostics.report(answerUnread(payload.mutation, `list "${request.query}": ${reasonOf(error)}`)).pipe(Effect.as([]))))).pipe(Effect.map((pages) => pages.flat()));
1741
2125
  const hub = options.live;
1742
2126
  if (hub !== void 0) {
1743
2127
  const stored = source.writes !== void 0;
@@ -1748,7 +2132,7 @@ const RemoteServer = {
1748
2132
  }
1749
2133
  return {
1750
2134
  output,
1751
- entities: outcome.entities.map((patch) => ({
2135
+ entities: sent.map((patch) => ({
1752
2136
  entity: patch.entity,
1753
2137
  id: patch.id,
1754
2138
  values: patch.values
@@ -1777,8 +2161,9 @@ const RemoteServer = {
1777
2161
  const mismatch = protocolMismatch(payload.version);
1778
2162
  if (mismatch !== void 0) return Stream.fail(mismatch);
1779
2163
  const maxIds = Math.max(1, options.maxIdsPerEntity ?? DEFAULT_MAX_IDS_PER_ENTITY);
1780
- const refusal = liveRefusal(payload.requirements, maxIds);
2164
+ const refusal = liveRefusal(payload, maxIds);
1781
2165
  if (refusal !== void 0) return Stream.fail(refusal);
2166
+ const failed = failingAs(`live ${servedOf(server.entities, payload.requirements.map((request) => request.entity))}`, (said) => new RemoteLiveError(said));
1782
2167
  return Stream.unwrap(Effect.gen(function* () {
1783
2168
  const admitted = yield* admitQueries(server, payload.queries ?? [], payload.requirements, maxIds);
1784
2169
  const caller = yield* asking;
@@ -1814,12 +2199,18 @@ const RemoteServer = {
1814
2199
  return Stream.mergeAll(streams, { concurrency: "unbounded" }).pipe(Stream.mapAccum(() => payload.after, (cursor, change) => [cursor + 1, [{
1815
2200
  ...change,
1816
2201
  cursor: cursor + 1
1817
- }]]), Stream.mapError((error) => new RemoteLiveError({ message: error.message })));
1818
- }));
2202
+ }]]), Stream.catchTag("RemoteServerError", (error) => Stream.fromEffect(failed.source(error))));
2203
+ })).pipe(Stream.catchCauseIf(Cause.hasDies, (cause) => Stream.fromEffect(failed.internal(cause))));
1819
2204
  }
1820
2205
  };
2206
+ return {
2207
+ FoldkitRemoteRead: (payload) => Effect.catchCauseIf(answering.FoldkitRemoteRead(payload), Cause.hasDies, (cause) => failingAs(`read ${servedOf(server.entities, payload.requests.map((request) => request.entity))}`, (said) => new RemoteReadError(said)).internal(cause)),
2208
+ FoldkitRemoteMutate: (payload) => Effect.catchCauseIf(answering.FoldkitRemoteMutate(payload), Cause.hasDies, (cause) => mutationFailing(payload.mutation).internal(cause)),
2209
+ FoldkitRemoteQuery: (payload) => Effect.catchCauseIf(answering.FoldkitRemoteQuery(payload), Cause.hasDies, (cause) => failingAs(`query ${servedOf(server.queries, [payload.query])}`, (said) => new RemoteQueryError(said)).internal(cause)),
2210
+ FoldkitRemoteLive: answering.FoldkitRemoteLive
2211
+ };
1821
2212
  }
1822
2213
  };
1823
- export { evaluate$1 as _, RemoteServerError as a, cachedReadDiffers as b, RowRequirement as c, declaresTooLarge as d, discardBody as f, assertSupported$1 as g, QueryEvaluateError as h, RemoteServer as i, exprContext as l, tooLargeAnswer as m, MutationRefused as n, RemoteTaken as o, readJson as p, RemoteInvalid as r, RemoteUnmet as s, DeleteOutcome as t, bodyLimit as u, supported as v, serverDefect as x, unauthenticatedAnswer as y };
2214
+ export { evaluate$1 as _, RemoteServerError as a, cachedReadDiffers as b, RowRequirement as c, declaresTooLarge as d, discardBody as f, assertSupported$1 as g, QueryEvaluateError as h, RemoteServer as i, exprContext as l, tooLargeAnswer as m, MutationRefused as n, RemoteTaken as o, readJson as p, RemoteInvalid as r, RemoteUnmet as s, DeleteOutcome as t, bodyLimit as u, supported$1 as v, internalFailure as x, unauthenticatedAnswer as y };
1824
2215
 
1825
- //# sourceMappingURL=src-B1JAs_gH.mjs.map
2216
+ //# sourceMappingURL=src-6l1A9ww5.mjs.map