foldkit-remote-server 0.19.0 → 0.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +215 -11
- package/dist/fetch.d.mts +55 -4
- package/dist/fetch.d.mts.map +1 -1
- package/dist/fetch.mjs +259 -26
- package/dist/fetch.mjs.map +1 -1
- package/dist/{index-BnaRbvjr.d.mts → index-pMrHmWZt.d.mts} +116 -18
- package/dist/index-pMrHmWZt.d.mts.map +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/{src-ZV9pARkU.mjs → src-CHkHaItI.mjs} +313 -74
- package/dist/src-CHkHaItI.mjs.map +1 -0
- package/package.json +7 -7
- package/dist/index-BnaRbvjr.d.mts.map +0 -1
- package/dist/src-ZV9pARkU.mjs.map +0 -1
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { Cause, Clock, Context, Data, Duration, Effect, Match, Option, Queue, Schema, Stream } from "effect";
|
|
2
2
|
import { Derivation, Entity, Held, Operators, Query, QueryEvaluateError, SchemaShape, Write, assertSupported, assertSupported as assertSupported$1, evaluate, evaluate as evaluate$1, supported } from "foldkit-entity";
|
|
3
|
-
import { Diagnostics, MutationRequest, QueryRequest, RELATION_ALIAS, REMOTE_PROTOCOL_VERSION, ReadBatch, Refusal, Remote, RemoteForbidden, RemoteJsonRequest, RemoteLiveError, RemoteLiveRefused, RemoteMutationError, RemoteProtocolError, RemoteQueryError, RemoteReadError, RemoteUnauthenticated, Requirement, aliasedField, connectionIdentity, entityKey, queryIdentity, refParts, refsIn, relationShape, stableStringify } from "foldkit-remote";
|
|
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
|
+
import { HttpServerRequest, HttpServerResponse } from "effect/http";
|
|
4
5
|
// src/diagnostics.ts
|
|
5
6
|
/**
|
|
6
7
|
* What a Remote server answers past without telling the caller why: a defect
|
|
@@ -21,7 +22,7 @@ const answerUnread = (mutation, reason) => ({
|
|
|
21
22
|
_tag: "AnswerUnread",
|
|
22
23
|
source,
|
|
23
24
|
level: "warning",
|
|
24
|
-
message: `${mutation} committed, but reading its answer failed (${reason}): the client reads
|
|
25
|
+
message: `${mutation} committed, but reading its answer failed (${reason}): the client reads what it lacks again.`,
|
|
25
26
|
mutation,
|
|
26
27
|
reason
|
|
27
28
|
});
|
|
@@ -40,6 +41,13 @@ const clockSkewed = (facts) => ({
|
|
|
40
41
|
message: `${facts.mutation} was sent at ${facts.sent}, ${Math.abs(facts.sent - facts.own)} ms from this server's clock (${facts.own}), past its clockSkew of ${facts.bound} ms: it was written at the server's time, so the client's prediction of it moves when the answer lands. The client's clock is off, or the request waited that long.`,
|
|
41
42
|
...facts
|
|
42
43
|
});
|
|
44
|
+
const cachedReadDiffers = (request) => ({
|
|
45
|
+
_tag: "CachedReadDiffers",
|
|
46
|
+
source,
|
|
47
|
+
level: "error",
|
|
48
|
+
message: `a read judged public was answered otherwise for who asked than for a visitor, so it is not the same for everyone and must not be cached; find what in its sources depends on who asks: ${request}`,
|
|
49
|
+
request
|
|
50
|
+
});
|
|
43
51
|
// src/refusal.ts
|
|
44
52
|
/** A caller who could not be told, as a 401 body: the twin of `answer`'s 403. */
|
|
45
53
|
const unauthenticatedAnswer = (refusal) => ({
|
|
@@ -49,6 +57,105 @@ const unauthenticatedAnswer = (refusal) => ({
|
|
|
49
57
|
unauthenticated: refusal.reason === void 0 ? {} : { reason: refusal.reason }
|
|
50
58
|
}
|
|
51
59
|
});
|
|
60
|
+
// src/body.ts
|
|
61
|
+
/**
|
|
62
|
+
* A request body read up to a limit, refused past it before anything decodes
|
|
63
|
+
* it: what `serveFetch` and `bodyLimit` share. The limit is checked against
|
|
64
|
+
* `content-length` before a byte is read, and against the bytes as they
|
|
65
|
+
* arrive, so a body without one, or with one that lies, is cancelled the
|
|
66
|
+
* moment it passes the limit rather than buffered whole.
|
|
67
|
+
*/
|
|
68
|
+
/** The body passed the limit; nothing past it was kept. */
|
|
69
|
+
var BodyTooLarge = class extends Error {};
|
|
70
|
+
/** Remote's answer to a body over `limit`, sent as a 413. */
|
|
71
|
+
const tooLargeAnswer = (limit) => ({
|
|
72
|
+
error: `The request body is larger than ${limit} bytes`,
|
|
73
|
+
tooLarge: { limit }
|
|
74
|
+
});
|
|
75
|
+
/** Whether `request` says it is larger than `limit`, before any of it is read. */
|
|
76
|
+
const declaresTooLarge = (request, limit) => {
|
|
77
|
+
const length = Number(request.headers.get("content-length") ?? NaN);
|
|
78
|
+
return Number.isFinite(length) && length > limit;
|
|
79
|
+
};
|
|
80
|
+
/**
|
|
81
|
+
* `request`'s body, at most `limit` bytes of it. Rejects with `BodyTooLarge`
|
|
82
|
+
* once more arrive, having cancelled the rest, or with the stream's own error.
|
|
83
|
+
*/
|
|
84
|
+
const readBounded = async (request, limit) => {
|
|
85
|
+
if (declaresTooLarge(request, limit)) throw new BodyTooLarge();
|
|
86
|
+
if (request.body === null) return /* @__PURE__ */ new Uint8Array();
|
|
87
|
+
const reader = request.body.getReader();
|
|
88
|
+
const chunks = [];
|
|
89
|
+
let total = 0;
|
|
90
|
+
for (;;) {
|
|
91
|
+
const { done, value } = await reader.read();
|
|
92
|
+
if (done) break;
|
|
93
|
+
total += value.byteLength;
|
|
94
|
+
if (total > limit) {
|
|
95
|
+
reader.cancel().catch(() => {});
|
|
96
|
+
throw new BodyTooLarge();
|
|
97
|
+
}
|
|
98
|
+
chunks.push(value);
|
|
99
|
+
}
|
|
100
|
+
const body = new Uint8Array(total);
|
|
101
|
+
let offset = 0;
|
|
102
|
+
for (const chunk of chunks) {
|
|
103
|
+
body.set(chunk, offset);
|
|
104
|
+
offset += chunk.byteLength;
|
|
105
|
+
}
|
|
106
|
+
return body;
|
|
107
|
+
};
|
|
108
|
+
const BoundedBody = Data.taggedEnum();
|
|
109
|
+
/** `request`'s body read up to `limit` bytes; never fails. */
|
|
110
|
+
const readBody = (request, limit) => Effect.tryPromise(() => readBounded(request, limit)).pipe(Effect.match({
|
|
111
|
+
onSuccess: (bytes) => BoundedBody.Read({ bytes }),
|
|
112
|
+
onFailure: (error) => error.cause instanceof BodyTooLarge ? BoundedBody.TooLarge() : BoundedBody.Unreadable()
|
|
113
|
+
}));
|
|
114
|
+
/** A body refused before any handler: the status and Remote's answer. */
|
|
115
|
+
var BodyRefused = class extends Data.TaggedError("BodyRefused") {};
|
|
116
|
+
/** Decodes a body as UTF-8, refusing bytes that are not, as `JSON.parse` would refuse the text. */
|
|
117
|
+
const utf8 = new TextDecoder("utf-8", { fatal: true });
|
|
118
|
+
/** `request`'s body read up to `limit` bytes and parsed as JSON, or refused. */
|
|
119
|
+
const readJson = (request, limit) => {
|
|
120
|
+
const notJson = new BodyRefused({
|
|
121
|
+
status: 400,
|
|
122
|
+
answer: { error: "The body is not JSON" }
|
|
123
|
+
});
|
|
124
|
+
return Effect.flatMap(readBody(request, limit), (body) => BoundedBody.$match(body, {
|
|
125
|
+
Read: ({ bytes }) => Effect.try({
|
|
126
|
+
try: () => JSON.parse(utf8.decode(bytes)),
|
|
127
|
+
catch: () => notJson
|
|
128
|
+
}),
|
|
129
|
+
TooLarge: () => Effect.fail(new BodyRefused({
|
|
130
|
+
status: 413,
|
|
131
|
+
answer: tooLargeAnswer(limit)
|
|
132
|
+
})),
|
|
133
|
+
Unreadable: () => Effect.fail(notJson)
|
|
134
|
+
}));
|
|
135
|
+
};
|
|
136
|
+
/**
|
|
137
|
+
* Effect HTTP middleware refusing a request body over `maxBytes` (default
|
|
138
|
+
* 1 MiB, `serveFetch`'s) with a 413 and Remote's `tooLarge` answer, before
|
|
139
|
+
* the endpoint reads it. For an endpoint that serves `RemoteRpc` through
|
|
140
|
+
* `RpcServer`, where Effect's own `MaxBodySize` fails the body read as a
|
|
141
|
+
* defect, a 500:
|
|
142
|
+
*
|
|
143
|
+
* ```ts
|
|
144
|
+
* HttpRouter.add('POST', '/rpc', bodyLimit(64 * 1024)(rpcHttpEffect))
|
|
145
|
+
* ```
|
|
146
|
+
*
|
|
147
|
+
* A body within the limit reaches the endpoint whole, read once.
|
|
148
|
+
*/
|
|
149
|
+
const bodyLimit = (maxBytes = DEFAULT_MAX_BODY_BYTES) => (endpoint) => Effect.gen(function* () {
|
|
150
|
+
const request = yield* HttpServerRequest.HttpServerRequest;
|
|
151
|
+
const web = yield* Effect.orDie(HttpServerRequest.toWeb(request));
|
|
152
|
+
const body = yield* readBody(web, maxBytes);
|
|
153
|
+
return yield* BoundedBody.$match(body, {
|
|
154
|
+
TooLarge: () => Effect.succeed(HttpServerResponse.jsonUnsafe(tooLargeAnswer(maxBytes), { status: 413 })),
|
|
155
|
+
Unreadable: () => Effect.succeed(HttpServerResponse.jsonUnsafe({ error: "The body could not be read" }, { status: 400 })),
|
|
156
|
+
Read: ({ bytes }) => Effect.provideService(endpoint, HttpServerRequest.HttpServerRequest, HttpServerRequest.fromWeb(new Request(web, { body: bytes })))
|
|
157
|
+
});
|
|
158
|
+
});
|
|
52
159
|
// src/index.ts
|
|
53
160
|
/**
|
|
54
161
|
* `foldkit-remote-server` — server-side Sources and handler compilation.
|
|
@@ -122,6 +229,7 @@ const readAs = (source, context) => {
|
|
|
122
229
|
}))));
|
|
123
230
|
};
|
|
124
231
|
const RowRequirement = Data.taggedEnum();
|
|
232
|
+
const DeleteOutcome = Data.taggedEnum();
|
|
125
233
|
const connectionChange = (connection, ref, position) => {
|
|
126
234
|
const edge = {
|
|
127
235
|
entity: ref.entity,
|
|
@@ -192,6 +300,30 @@ const exprContext = (body, viewer, now) => {
|
|
|
192
300
|
/** Who asks, as the server's `viewer` says: none for a visitor, or on a server with no viewer. */
|
|
193
301
|
const viewerOf = (server, principal) => server.viewer === void 0 ? Option.none() : server.viewer(principal);
|
|
194
302
|
/**
|
|
303
|
+
* Whom an answer is for, as the wire says it (#405): the key of who asks
|
|
304
|
+
* (their `viewer`), `null` for a visitor, and nothing from a server that
|
|
305
|
+
* names no `viewer`, which keeps no keys.
|
|
306
|
+
*/
|
|
307
|
+
const answeredFor = (server, principal) => server.viewer === void 0 ? {} : { principal: Option.match(server.viewer(principal), {
|
|
308
|
+
onNone: () => null,
|
|
309
|
+
onSome: (viewer) => entityKey(viewer.entity, viewer.id)
|
|
310
|
+
}) };
|
|
311
|
+
/**
|
|
312
|
+
* Refuses a write made for someone other than who asks, before anything of
|
|
313
|
+
* it runs (#405): one made for someone, asked by a visitor, is asked to sign
|
|
314
|
+
* in; any other told who is signed in changed, a visitor's (`null`) asked by
|
|
315
|
+
* someone signed in included. A server that keeps no keys cannot tell, and
|
|
316
|
+
* refuses any write that names one.
|
|
317
|
+
*/
|
|
318
|
+
const madeFor = (server, principal, expected) => Option.match(expected, {
|
|
319
|
+
onNone: () => Effect.void,
|
|
320
|
+
onSome: (key) => {
|
|
321
|
+
const asking = answeredFor(server, principal).principal;
|
|
322
|
+
if (asking === key) return Effect.void;
|
|
323
|
+
return asking === null ? Effect.fail(RemoteServer.unauthenticated()) : Effect.fail(new RemotePrincipalChanged({ message: "The write was made for someone other than who is signed in now" }));
|
|
324
|
+
}
|
|
325
|
+
});
|
|
326
|
+
/**
|
|
195
327
|
* One row as `principal` may see it, through the server's own source for its
|
|
196
328
|
* Entity: the fields its `authorize` allows, filtered as the source filters.
|
|
197
329
|
* None for a row hidden or not there.
|
|
@@ -209,8 +341,6 @@ const rowAs = (server, principal) => (ref, fields) => {
|
|
|
209
341
|
};
|
|
210
342
|
/** `read` with the services the request already runs with, so its caller needs none. */
|
|
211
343
|
const withServices = (read, services) => (...args) => Effect.provideContext(read(...args), services);
|
|
212
|
-
/** A read batch may not carry more than this many distinct ids per entity. */
|
|
213
|
-
const DEFAULT_MAX_IDS_PER_ENTITY = 1e3;
|
|
214
344
|
/** A nested selection may not reach further than this many relation levels. */
|
|
215
345
|
const DEFAULT_MAX_DEPTH = 8;
|
|
216
346
|
/**
|
|
@@ -678,6 +808,10 @@ function memory(config) {
|
|
|
678
808
|
const visible = config.readable === void 0 ? {} : { visible: config.readable };
|
|
679
809
|
const entities = [...config.domain.registry.entities.keys()].map((name) => ({
|
|
680
810
|
...visible,
|
|
811
|
+
...Option.match(Option.fromUndefinedOr(config.domain.registry.cached.get(name)), {
|
|
812
|
+
onNone: () => ({}),
|
|
813
|
+
onSome: (cache) => ({ cache })
|
|
814
|
+
}),
|
|
681
815
|
...RemoteServer.entity({ name }, {
|
|
682
816
|
...Object.hasOwn(authorize, name) ? { authorize: authorize[name] } : {},
|
|
683
817
|
...Object.hasOwn(filter, name) ? { filter: filter[name] } : {},
|
|
@@ -814,6 +948,76 @@ const answerRead = (server, principal, options, shown, outcome) => Effect.gen(fu
|
|
|
814
948
|
});
|
|
815
949
|
});
|
|
816
950
|
/**
|
|
951
|
+
* A query's page as `FoldkitRemoteQuery` answers it: the source's edges, and
|
|
952
|
+
* with a select, what the page's items select, read through `readHelper`, so
|
|
953
|
+
* `authorize` and `filter` hold. A mutation's answer reads its lists with it.
|
|
954
|
+
*/
|
|
955
|
+
const answerQuery = (server, caller, options, payload) => Effect.gen(function* () {
|
|
956
|
+
const source = server.queries.get(payload.query);
|
|
957
|
+
if (source === void 0) return yield* new RemoteQueryError({ message: `Unknown query: ${payload.query}` });
|
|
958
|
+
const input = yield* Schema.decodeUnknownEffect(source.Input)(payload.input).pipe(Effect.catchTag("SchemaError", () => Effect.fail(new RemoteQueryError({ message: "Invalid query input" }))));
|
|
959
|
+
const select = payload.select;
|
|
960
|
+
if (select !== void 0) {
|
|
961
|
+
const paged = checkPagesPerRelation([select]);
|
|
962
|
+
if (paged !== void 0) return yield* new RemoteQueryError({ message: `Too many pages of "${paged}" in one query select` });
|
|
963
|
+
}
|
|
964
|
+
const page = yield* source.run({
|
|
965
|
+
input,
|
|
966
|
+
window: payload.window,
|
|
967
|
+
principal: caller,
|
|
968
|
+
viewer: viewerOf(server, caller),
|
|
969
|
+
...select === void 0 ? {} : { select }
|
|
970
|
+
}).pipe(Effect.catchTag("RemoteServerError", (error) => Effect.fail(new RemoteQueryError({ message: error.message }))));
|
|
971
|
+
if (select === void 0) return {
|
|
972
|
+
edges: page.edges,
|
|
973
|
+
start: page.start,
|
|
974
|
+
end: page.end
|
|
975
|
+
};
|
|
976
|
+
const requirements = page.edges.flatMap((edge) => edge.entity === select.entity ? [{
|
|
977
|
+
entity: select.entity,
|
|
978
|
+
id: edge.id,
|
|
979
|
+
fields: [...select.fields],
|
|
980
|
+
...select.windows === void 0 ? {} : { windows: select.windows },
|
|
981
|
+
...select.relations === void 0 ? {} : { relations: select.relations }
|
|
982
|
+
}] : []);
|
|
983
|
+
if (requirements.length === 0) return {
|
|
984
|
+
edges: page.edges,
|
|
985
|
+
start: page.start,
|
|
986
|
+
end: page.end,
|
|
987
|
+
entities: [],
|
|
988
|
+
settled: []
|
|
989
|
+
};
|
|
990
|
+
const read = yield* RemoteServer.readHelper(server, caller, options, requirements).pipe(Effect.catchTag("RemoteReadError", (error) => Effect.fail(new RemoteQueryError({ message: error.message }))));
|
|
991
|
+
return {
|
|
992
|
+
edges: page.edges,
|
|
993
|
+
start: page.start,
|
|
994
|
+
end: page.end,
|
|
995
|
+
...read
|
|
996
|
+
};
|
|
997
|
+
});
|
|
998
|
+
/**
|
|
999
|
+
* The lists of a mutation request the server answers after the write, judged
|
|
1000
|
+
* before it runs: each a first page (`first`, no `after`) of a query it serves,
|
|
1001
|
+
* selecting that query's entity, within the select's page bound, while the
|
|
1002
|
+
* rows every admitted list may return stay within `maxIds` per entity. One
|
|
1003
|
+
* past these is not answered, and the client asks for it again; the write
|
|
1004
|
+
* runs either way.
|
|
1005
|
+
*/
|
|
1006
|
+
const admitLists = (server, lists, maxIds) => {
|
|
1007
|
+
const rows = /* @__PURE__ */ new Map();
|
|
1008
|
+
return lists.filter((request) => {
|
|
1009
|
+
const source = server.queries.get(request.query);
|
|
1010
|
+
const { select, window } = request;
|
|
1011
|
+
if (source === void 0 || select === void 0 || select.entity !== source.entity) return false;
|
|
1012
|
+
if (window.first === void 0 || window.after !== void 0) return false;
|
|
1013
|
+
if (checkPagesPerRelation([select]) !== void 0) return false;
|
|
1014
|
+
const listed = (rows.get(select.entity) ?? 0) + window.first;
|
|
1015
|
+
if (listed > maxIds) return false;
|
|
1016
|
+
rows.set(select.entity, listed);
|
|
1017
|
+
return true;
|
|
1018
|
+
});
|
|
1019
|
+
};
|
|
1020
|
+
/**
|
|
817
1021
|
* A Source's refusal as the client receives it: encoded by the mutation's own
|
|
818
1022
|
* `Refusal`. A refusal made for another mutation, or one the mutation does not
|
|
819
1023
|
* declare, is this side's bug, and says so without the value.
|
|
@@ -845,6 +1049,7 @@ const RemoteServer = {
|
|
|
845
1049
|
entity: (entity, options) => {
|
|
846
1050
|
const declared = entity.members ?? entity.fields;
|
|
847
1051
|
const fields = declared === void 0 ? void 0 : new Set(Object.keys(declared));
|
|
1052
|
+
const cache = EdgeCache.policyOf(entity);
|
|
848
1053
|
const unserved = (options.shared ?? []).filter((field) => fields !== void 0 && !fields.has(field));
|
|
849
1054
|
if (unserved.length > 0) throw new Error(`[foldkit-remote-server] ${entity.name}'s shared fields name no member: ${unserved.join(", ")}`);
|
|
850
1055
|
return {
|
|
@@ -853,7 +1058,8 @@ const RemoteServer = {
|
|
|
853
1058
|
read: options.read,
|
|
854
1059
|
...options.authorize === void 0 ? {} : { authorize: options.authorize },
|
|
855
1060
|
...options.filter === void 0 ? {} : { filter: options.filter },
|
|
856
|
-
...options.shared === void 0 ? {} : { shared: new Set(options.shared) }
|
|
1061
|
+
...options.shared === void 0 ? {} : { shared: new Set(options.shared) },
|
|
1062
|
+
...Option.isSome(cache) ? { cache: cache.value } : {}
|
|
857
1063
|
};
|
|
858
1064
|
},
|
|
859
1065
|
mutation: (mutation, run) => ({
|
|
@@ -922,8 +1128,10 @@ const RemoteServer = {
|
|
|
922
1128
|
/**
|
|
923
1129
|
* A refusal of a caller who could not be told: a `serveFetch` or
|
|
924
1130
|
* `defineDocumentHost` resolver fails with it (`RemoteServer.unauthenticated()`)
|
|
925
|
-
* when the credential it was sent no longer holds
|
|
926
|
-
* `
|
|
1131
|
+
* when the credential it was sent no longer holds, and a write refused to a
|
|
1132
|
+
* visitor fails with it (`GuardServer` does), so a client can tell a session
|
|
1133
|
+
* that ended from a refusal. It answers 401, with `reason`, when given, for
|
|
1134
|
+
* the person who asked; a durable write so answered waits for a sign-in.
|
|
927
1135
|
*/
|
|
928
1136
|
unauthenticated: (reason) => new RemoteUnauthenticated({
|
|
929
1137
|
message: reason ?? "Unauthenticated",
|
|
@@ -957,30 +1165,67 @@ const RemoteServer = {
|
|
|
957
1165
|
}
|
|
958
1166
|
const refused = writer.refuses?.(write) ?? [];
|
|
959
1167
|
if (refused.length > 0) throw new Error(`[foldkit-remote-server] write "${mutation.name}" cannot land through its writer for ${writer.entity}: ${refused.join("; ")}`);
|
|
960
|
-
const
|
|
1168
|
+
const kind = Match.value(write).pipe(Match.tagsExhaustive({
|
|
1169
|
+
Insert: () => ({
|
|
1170
|
+
hasBefore: false,
|
|
1171
|
+
inserts: true,
|
|
1172
|
+
deletes: false
|
|
1173
|
+
}),
|
|
1174
|
+
Update: () => ({
|
|
1175
|
+
hasBefore: true,
|
|
1176
|
+
inserts: false,
|
|
1177
|
+
deletes: false
|
|
1178
|
+
}),
|
|
1179
|
+
Delete: () => ({
|
|
1180
|
+
hasBefore: false,
|
|
1181
|
+
inserts: false,
|
|
1182
|
+
deletes: true
|
|
1183
|
+
})
|
|
1184
|
+
}));
|
|
1185
|
+
const judged = Entity.invariants(write.input.entity).filter((held) => kind.hasBefore || !Entity.readsBefore(held));
|
|
961
1186
|
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)`);
|
|
962
|
-
|
|
963
|
-
if (write._tag === "Insert") {
|
|
1187
|
+
if (kind.inserts) {
|
|
964
1188
|
const sets = /* @__PURE__ */ new Set([
|
|
965
1189
|
"id",
|
|
966
1190
|
...write.sets.map((set) => set.field.key),
|
|
967
|
-
...
|
|
1191
|
+
...write.links.map((link) => link.relation.key),
|
|
1192
|
+
...write.context.map(({ member }) => member.key)
|
|
968
1193
|
]);
|
|
969
1194
|
const unset = judged.flatMap((held) => held.after.filter((key) => !sets.has(key)).map((key) => `${held.id} reads ${key}`));
|
|
970
1195
|
if (unset.length > 0) throw new Error(`[foldkit-remote-server] insert "${mutation.name}" leaves unset a field an invariant reads (${unset.join("; ")})`);
|
|
971
1196
|
}
|
|
972
1197
|
if (Option.isSome(write.when) && writer.preconditions !== true) throw new Error(`[foldkit-remote-server] write "${mutation.name}" has a precondition, but its writer for ${writer.entity} does not check one (preconditions)`);
|
|
973
1198
|
const encodeInput = Schema.encodeUnknownEffect(write.input.schema);
|
|
974
|
-
const
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
1199
|
+
const pointersOf = (entity) => {
|
|
1200
|
+
const relations = entity.relations;
|
|
1201
|
+
return Object.values(relations).flatMap((relation) => {
|
|
1202
|
+
if (relation._tag !== "Relation" || relation.cardinality !== "one") return [];
|
|
1203
|
+
const isThis = (read) => read.owner.token === relation.owner.token && read.key === relation.key;
|
|
1204
|
+
return Object.values(relation.target().derived).some((member) => member._tag === "Derived" && Derivation.$match(member.derives, {
|
|
1205
|
+
Supplied: () => true,
|
|
1206
|
+
Count: ({ relation: read }) => isThis(read),
|
|
1207
|
+
Exists: ({ relation: read }) => isThis(read)
|
|
1208
|
+
})) ? [relation.key] : [];
|
|
1209
|
+
});
|
|
1210
|
+
};
|
|
1211
|
+
const pointers = pointersOf(write.input.entity);
|
|
1212
|
+
const cascadePointers = /* @__PURE__ */ new Map();
|
|
1213
|
+
if (kind.deletes) {
|
|
1214
|
+
const reach = (entity) => {
|
|
1215
|
+
for (const { owner } of Entity.cascading(entity)) {
|
|
1216
|
+
if (cascadePointers.has(owner.name)) continue;
|
|
1217
|
+
cascadePointers.set(owner.name, pointersOf(owner));
|
|
1218
|
+
reach(owner);
|
|
1219
|
+
}
|
|
1220
|
+
};
|
|
1221
|
+
reach(write.input.entity);
|
|
1222
|
+
if (cascadePointers.size > 0 && writer.cascades !== true) throw new Error(`[foldkit-remote-server] delete "${mutation.name}" removes ${write.input.entity.name}, whose rows take ${[...cascadePointers.keys()].join(", ")} with them (onDelete: 'cascade'), but its writer does not remove them (cascades)`);
|
|
1223
|
+
}
|
|
1224
|
+
/** What a removed row pointed at that its removal moves, as refs. */
|
|
1225
|
+
const pointedBy = (row) => (cascadePointers.get(row.entity) ?? []).flatMap((key) => Option.match(Option.flatten(Option.fromUndefinedOr(row.links[key])), {
|
|
1226
|
+
onNone: () => [],
|
|
1227
|
+
onSome: (ref) => [ref]
|
|
1228
|
+
}));
|
|
984
1229
|
const seenLinks = (id, principal) => writer.read !== void 0 ? writer.read({
|
|
985
1230
|
id,
|
|
986
1231
|
fields: pointers,
|
|
@@ -1019,6 +1264,7 @@ const RemoteServer = {
|
|
|
1019
1264
|
onNone: () => null,
|
|
1020
1265
|
onSome: (values) => Object.hasOwn(values, key) ? values[key] : void 0
|
|
1021
1266
|
}))));
|
|
1267
|
+
const unfilled = Option.isNone(viewer) ? RemoteServer.unauthenticated() : RemoteServer.forbid();
|
|
1022
1268
|
const given = input;
|
|
1023
1269
|
const expect = Write.expected(write, given);
|
|
1024
1270
|
const conflict = (bound) => RemoteServer.refuse(mutation, { _tag: "Conflict" }, `${bound.entity} ${bound.id} changed since it was read`);
|
|
@@ -1075,7 +1321,7 @@ const RemoteServer = {
|
|
|
1075
1321
|
Update: () => Effect.gen(function* () {
|
|
1076
1322
|
const named = Write.bind(write, given, keys);
|
|
1077
1323
|
const set = yield* context;
|
|
1078
|
-
if (set.unfilled.length > 0) return yield* Effect.fail(
|
|
1324
|
+
if (set.unfilled.length > 0) return yield* Effect.fail(unfilled);
|
|
1079
1325
|
const bound = {
|
|
1080
1326
|
...named,
|
|
1081
1327
|
values: {
|
|
@@ -1107,7 +1353,7 @@ const RemoteServer = {
|
|
|
1107
1353
|
Insert: () => Effect.gen(function* () {
|
|
1108
1354
|
const bound = Write.bind(write, given);
|
|
1109
1355
|
const set = yield* context;
|
|
1110
|
-
if (set.unfilled.length > 0) return yield* Effect.fail(
|
|
1356
|
+
if (set.unfilled.length > 0) return yield* Effect.fail(unfilled);
|
|
1111
1357
|
const row = yield* invalid(writer.insert({
|
|
1112
1358
|
id: bound.id,
|
|
1113
1359
|
values: {
|
|
@@ -1137,17 +1383,23 @@ const RemoteServer = {
|
|
|
1137
1383
|
when: yield* when,
|
|
1138
1384
|
principal
|
|
1139
1385
|
})));
|
|
1140
|
-
|
|
1141
|
-
const gone = {
|
|
1386
|
+
const gone = (cascaded) => ({
|
|
1142
1387
|
output: {},
|
|
1143
1388
|
entities: [],
|
|
1144
1389
|
connections: [],
|
|
1145
1390
|
deleted: [{
|
|
1146
1391
|
entity: bound.entity,
|
|
1147
1392
|
id: bound.id
|
|
1148
|
-
}
|
|
1149
|
-
|
|
1150
|
-
|
|
1393
|
+
}, ...cascaded.map(({ entity, id }) => ({
|
|
1394
|
+
entity,
|
|
1395
|
+
id
|
|
1396
|
+
}))]
|
|
1397
|
+
});
|
|
1398
|
+
return yield* DeleteOutcome.$match(outcome, {
|
|
1399
|
+
Moved: () => Effect.fail(conflict(bound)),
|
|
1400
|
+
Absent: () => Effect.succeed(gone([])),
|
|
1401
|
+
Deleted: ({ cascaded }) => Effect.succeed(naming(gone(cascaded), [...before, ...cascaded.flatMap(pointedBy)]))
|
|
1402
|
+
});
|
|
1151
1403
|
})
|
|
1152
1404
|
}));
|
|
1153
1405
|
}
|
|
@@ -1157,6 +1409,7 @@ const RemoteServer = {
|
|
|
1157
1409
|
query: query.name,
|
|
1158
1410
|
entity: query.Result.entity,
|
|
1159
1411
|
Input: query.Input,
|
|
1412
|
+
...query.cache === void 0 ? {} : { cache: query.cache },
|
|
1160
1413
|
run: (context) => run({
|
|
1161
1414
|
input: context.input,
|
|
1162
1415
|
window: context.window,
|
|
@@ -1197,7 +1450,12 @@ const RemoteServer = {
|
|
|
1197
1450
|
* The server: its sources by name. `viewer` says who asks, as a row
|
|
1198
1451
|
* (`principal => Option.some(Remote.ref(User, principal.id))`), or none for
|
|
1199
1452
|
* a visitor: what a declared write's `Expr.viewer` sets. A server
|
|
1200
|
-
* registering such an insert without one is refused here.
|
|
1453
|
+
* registering such an insert without one is refused here. It is also whom
|
|
1454
|
+
* each answer says it is for (`principal`, the row's key), which a durable
|
|
1455
|
+
* write carries back: one made for another viewer than who asks is refused
|
|
1456
|
+
* before it runs (`RemotePrincipalChanged`). A server without `viewer`
|
|
1457
|
+
* names no one in its answers, and refuses a write that names someone,
|
|
1458
|
+
* since it cannot check it; a write that names no one runs (#405).
|
|
1201
1459
|
*
|
|
1202
1460
|
* `clockSkew` is how far from this server's clock a client's time (the
|
|
1203
1461
|
* `now` a write is sent with, when the reader acted) may be and still be
|
|
@@ -1354,7 +1612,8 @@ const RemoteServer = {
|
|
|
1354
1612
|
* The request and its payload are decoded by the protocol's own schemas
|
|
1355
1613
|
* before a handler sees them, so an operation name is one of Remote's three
|
|
1356
1614
|
* and nothing else. A body that is not a request is a 400; a caller who
|
|
1357
|
-
* could not be told a 401; a refusal of who is asking a 403; a
|
|
1615
|
+
* could not be told a 401; a refusal of who is asking a 403; a write made
|
|
1616
|
+
* for someone else (`RemotePrincipalChanged`) a 409; a mutation's
|
|
1358
1617
|
* declared refusal a 422, or a 409 when it is `Refusal.taken`; a handler's
|
|
1359
1618
|
* failure a 500 with its message; a defect a 500 that says nothing of it,
|
|
1360
1619
|
* its cause reported as a `ServerDefect` (`Diagnostics`, by default the log).
|
|
@@ -1372,7 +1631,13 @@ const RemoteServer = {
|
|
|
1372
1631
|
})), Effect.catchTag("SchemaError", (error) => Effect.succeed({
|
|
1373
1632
|
status: 400,
|
|
1374
1633
|
body: { error: error.message }
|
|
1375
|
-
})), Effect.catchTag("Unauthenticated", (error) => Effect.succeed(unauthenticatedAnswer(error))), Effect.catchTag("
|
|
1634
|
+
})), Effect.catchTag("Unauthenticated", (error) => Effect.succeed(unauthenticatedAnswer(error))), Effect.catchTag("PrincipalChanged", (error) => Effect.succeed({
|
|
1635
|
+
status: 409,
|
|
1636
|
+
body: {
|
|
1637
|
+
error: error.message,
|
|
1638
|
+
principalChanged: {}
|
|
1639
|
+
}
|
|
1640
|
+
})), Effect.catchTag("Forbidden", (error) => Effect.succeed({
|
|
1376
1641
|
status: 403,
|
|
1377
1642
|
body: {
|
|
1378
1643
|
error: error.message,
|
|
@@ -1409,13 +1674,18 @@ const RemoteServer = {
|
|
|
1409
1674
|
const mismatch = protocolMismatch(payload.version);
|
|
1410
1675
|
if (mismatch !== void 0) return yield* mismatch;
|
|
1411
1676
|
const caller = yield* asking;
|
|
1412
|
-
return
|
|
1677
|
+
return {
|
|
1678
|
+
...yield* RemoteServer.readHelper(server, caller, options, payload.requests),
|
|
1679
|
+
...answeredFor(server, caller)
|
|
1680
|
+
};
|
|
1413
1681
|
}),
|
|
1414
1682
|
FoldkitRemoteMutate: Effect.fn("RemoteServer.FoldkitRemoteMutate")(function* (payload) {
|
|
1415
1683
|
const source = server.mutations.get(payload.mutation);
|
|
1416
1684
|
if (source === void 0) return yield* new RemoteMutationError({ message: `Unknown mutation: ${payload.mutation}` });
|
|
1417
1685
|
const input = yield* Schema.decodeUnknownEffect(source.Input)(payload.input).pipe(Effect.catchTag("SchemaError", () => Effect.fail(new RemoteMutationError({ message: "Invalid mutation input" }))));
|
|
1686
|
+
const lists = admitLists(server, payload.lists ?? [], Math.max(1, options.maxIdsPerEntity ?? DEFAULT_MAX_IDS_PER_ENTITY));
|
|
1418
1687
|
const caller = yield* asking;
|
|
1688
|
+
yield* madeFor(server, caller, Option.fromUndefinedOr(payload.principal));
|
|
1419
1689
|
const outcome = yield* source.run({
|
|
1420
1690
|
input,
|
|
1421
1691
|
principal: caller,
|
|
@@ -1428,6 +1698,10 @@ const RemoteServer = {
|
|
|
1428
1698
|
}).pipe(Effect.catchTag("RemoteServerError", (error) => Effect.fail(new RemoteMutationError({ message: error.message }))), Effect.catchTag("MutationRefused", (refused) => refusalError(source.Refusal, payload.mutation, refused)));
|
|
1429
1699
|
const output = yield* Schema.encodeUnknownEffect(source.Output)(outcome.output).pipe(Effect.catchTag("SchemaError", () => Effect.fail(new RemoteMutationError({ message: "Invalid mutation output" }))));
|
|
1430
1700
|
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()))));
|
|
1701
|
+
const answered = yield* Effect.forEach(lists, (request) => answerQuery(server, caller, options, request).pipe(Effect.map((result) => [{
|
|
1702
|
+
request,
|
|
1703
|
+
result
|
|
1704
|
+
}]), Effect.catchTag("RemoteQueryError", (error) => Diagnostics.report(answerUnread(payload.mutation, `list "${request.query}": ${error.message}`)).pipe(Effect.as([]))))).pipe(Effect.map((pages) => pages.flat()));
|
|
1431
1705
|
const hub = options.live;
|
|
1432
1706
|
if (hub !== void 0) {
|
|
1433
1707
|
const stored = source.writes !== void 0;
|
|
@@ -1451,51 +1725,16 @@ const RemoteServer = {
|
|
|
1451
1725
|
...Option.match(read, {
|
|
1452
1726
|
onNone: () => ({}),
|
|
1453
1727
|
onSome: (value) => ({ read: value })
|
|
1454
|
-
})
|
|
1728
|
+
}),
|
|
1729
|
+
...answered.length === 0 ? {} : { lists: answered },
|
|
1730
|
+
...answeredFor(server, caller)
|
|
1455
1731
|
};
|
|
1456
1732
|
}),
|
|
1457
1733
|
FoldkitRemoteQuery: Effect.fn("RemoteServer.FoldkitRemoteQuery")(function* (payload) {
|
|
1458
|
-
const source = server.queries.get(payload.query);
|
|
1459
|
-
if (source === void 0) return yield* new RemoteQueryError({ message: `Unknown query: ${payload.query}` });
|
|
1460
|
-
const input = yield* Schema.decodeUnknownEffect(source.Input)(payload.input).pipe(Effect.catchTag("SchemaError", () => Effect.fail(new RemoteQueryError({ message: "Invalid query input" }))));
|
|
1461
|
-
const select = payload.select;
|
|
1462
|
-
if (select !== void 0) {
|
|
1463
|
-
const paged = checkPagesPerRelation([select]);
|
|
1464
|
-
if (paged !== void 0) return yield* new RemoteQueryError({ message: `Too many pages of "${paged}" in one query select` });
|
|
1465
|
-
}
|
|
1466
1734
|
const caller = yield* asking;
|
|
1467
|
-
const page = yield* source.run({
|
|
1468
|
-
input,
|
|
1469
|
-
window: payload.window,
|
|
1470
|
-
principal: caller,
|
|
1471
|
-
viewer: viewerOf(server, caller),
|
|
1472
|
-
...select === void 0 ? {} : { select }
|
|
1473
|
-
}).pipe(Effect.catchTag("RemoteServerError", (error) => Effect.fail(new RemoteQueryError({ message: error.message }))));
|
|
1474
|
-
if (select === void 0) return {
|
|
1475
|
-
edges: page.edges,
|
|
1476
|
-
start: page.start,
|
|
1477
|
-
end: page.end
|
|
1478
|
-
};
|
|
1479
|
-
const requirements = page.edges.flatMap((edge) => edge.entity === select.entity ? [{
|
|
1480
|
-
entity: select.entity,
|
|
1481
|
-
id: edge.id,
|
|
1482
|
-
fields: [...select.fields],
|
|
1483
|
-
...select.windows === void 0 ? {} : { windows: select.windows },
|
|
1484
|
-
...select.relations === void 0 ? {} : { relations: select.relations }
|
|
1485
|
-
}] : []);
|
|
1486
|
-
if (requirements.length === 0) return {
|
|
1487
|
-
edges: page.edges,
|
|
1488
|
-
start: page.start,
|
|
1489
|
-
end: page.end,
|
|
1490
|
-
entities: [],
|
|
1491
|
-
settled: []
|
|
1492
|
-
};
|
|
1493
|
-
const read = yield* RemoteServer.readHelper(server, caller, options, requirements).pipe(Effect.catchTag("RemoteReadError", (error) => Effect.fail(new RemoteQueryError({ message: error.message }))));
|
|
1494
1735
|
return {
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
end: page.end,
|
|
1498
|
-
...read
|
|
1736
|
+
...yield* answerQuery(server, caller, options, payload),
|
|
1737
|
+
...answeredFor(server, caller)
|
|
1499
1738
|
};
|
|
1500
1739
|
}),
|
|
1501
1740
|
FoldkitRemoteLive: (payload) => {
|
|
@@ -1545,6 +1784,6 @@ const RemoteServer = {
|
|
|
1545
1784
|
};
|
|
1546
1785
|
}
|
|
1547
1786
|
};
|
|
1548
|
-
export {
|
|
1787
|
+
export { supported as _, RemoteServerError as a, serverDefect as b, RowRequirement as c, declaresTooLarge as d, readJson as f, evaluate$1 as g, assertSupported$1 as h, RemoteServer as i, exprContext as l, QueryEvaluateError as m, MutationRefused as n, RemoteTaken as o, tooLargeAnswer as p, RemoteInvalid as r, RemoteUnmet as s, DeleteOutcome as t, bodyLimit as u, unauthenticatedAnswer as v, cachedReadDiffers as y };
|
|
1549
1788
|
|
|
1550
|
-
//# sourceMappingURL=src-
|
|
1789
|
+
//# sourceMappingURL=src-CHkHaItI.mjs.map
|