foldkit-remote-server 0.1.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/LICENSE +21 -0
- package/README.md +216 -0
- package/dist/index.d.mts +190 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +413 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +46 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Patrick Glenn
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
# `foldkit-remote-server`
|
|
2
|
+
|
|
3
|
+
The server half of [`foldkit-remote`](https://github.com/doeixd/foldkit-plus/tree/main/packages/remote).
|
|
4
|
+
It owns the semantic work Effect RPC does not know about: entity, query, and
|
|
5
|
+
mutation Sources, **selection authorization**, normalization, and compilation to
|
|
6
|
+
the `RemoteRpc` handlers.
|
|
7
|
+
|
|
8
|
+
It does not own HTTP, WebSockets, serialization, the authentication protocol, or
|
|
9
|
+
database connections. `principal` is resolved outside and passed in; runtime
|
|
10
|
+
dependencies stay in the Effect environment instead of being captured.
|
|
11
|
+
|
|
12
|
+
## Quick start
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
import { Effect, Schema } from 'effect'
|
|
16
|
+
import { Entity, Mutation, Query, RemoteRpc } from 'foldkit-remote'
|
|
17
|
+
import { RemoteServer } from 'foldkit-remote-server'
|
|
18
|
+
|
|
19
|
+
const Project = Entity.make(
|
|
20
|
+
'Project',
|
|
21
|
+
Schema.Struct({ id: Schema.String, name: Schema.String, privateNotes: Schema.String }),
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
const RenameProject = Mutation.make('RenameProject', {
|
|
25
|
+
Input: Schema.Struct({ id: Schema.String, name: Schema.String }),
|
|
26
|
+
Output: Schema.Struct({ id: Schema.String }),
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
const ProjectsByOwner = Query.make('ProjectsByOwner', {
|
|
30
|
+
Input: Schema.Struct({ ownerId: Schema.String }),
|
|
31
|
+
Result: Query.connection(Project),
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
const Server = RemoteServer.make({
|
|
35
|
+
entities: [
|
|
36
|
+
RemoteServer.entity(Project, {
|
|
37
|
+
authorize: (principal, fields) => fields.filter(field => principal.canRead(Project, field)),
|
|
38
|
+
read: ({ ids, fields, windows, principal }) => loadProjects({ ids, fields, windows, principal }),
|
|
39
|
+
}),
|
|
40
|
+
],
|
|
41
|
+
mutations: [
|
|
42
|
+
RemoteServer.mutation(RenameProject, ({ input, principal }) =>
|
|
43
|
+
renameProject(input, principal).pipe(
|
|
44
|
+
Effect.map(output => ({
|
|
45
|
+
output,
|
|
46
|
+
entities: [Entity.patch(Project.ref(input.id), { name: input.name })],
|
|
47
|
+
})),
|
|
48
|
+
),
|
|
49
|
+
),
|
|
50
|
+
],
|
|
51
|
+
queries: [
|
|
52
|
+
RemoteServer.query(ProjectsByOwner, ({ input, window, principal }) =>
|
|
53
|
+
projectsPage({ ownerId: input.ownerId, window, principal }),
|
|
54
|
+
),
|
|
55
|
+
],
|
|
56
|
+
live: [
|
|
57
|
+
RemoteServer.live(Project, {
|
|
58
|
+
subscribe: ({ requirements, after, principal }) =>
|
|
59
|
+
projectEvents({ ids: requirements.map(request => request.id), after, principal }),
|
|
60
|
+
}),
|
|
61
|
+
],
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
const handlers = RemoteServer.handlers(Server, principal)
|
|
65
|
+
const layer = RemoteRpc.toLayer(handlers)
|
|
66
|
+
// FoldkitRemoteRead, FoldkitRemoteMutate, FoldkitRemoteQuery, FoldkitRemoteLive
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
`handlers(server, principal, options?)` takes a `HandlerOptions<P, R>`:
|
|
70
|
+
`maxIdsPerEntity` (default 1000) bounds a read batch and a live subscription
|
|
71
|
+
per entity, `maxDepth` (default 8) bounds nested resolution, and `live` is the
|
|
72
|
+
hub whose signals reach the subscriptions this handler registers. In-process,
|
|
73
|
+
the handlers are a `RemoteClient` through `Remote.clientLayer(handlers)`, with
|
|
74
|
+
whatever the sources require supplied by `Layer.provide`.
|
|
75
|
+
|
|
76
|
+
## Sources
|
|
77
|
+
|
|
78
|
+
### `RemoteServer.entity`
|
|
79
|
+
|
|
80
|
+
```ts
|
|
81
|
+
RemoteServer.entity(Project, {
|
|
82
|
+
authorize?: (principal: P, fields: readonly string[]) => readonly string[],
|
|
83
|
+
read: (context: { ids; fields; windows?; principal }) =>
|
|
84
|
+
Effect.Effect<ReadonlyArray<{ id: string; values: Record<string, unknown> }>, RemoteServerError, R>,
|
|
85
|
+
})
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Given the Entity, a request for a field it does not declare never reaches
|
|
89
|
+
`read` or `authorize`; `RemoteServer.entity({ name: 'Project' }, …)` declares
|
|
90
|
+
no fields and passes every requested one through.
|
|
91
|
+
|
|
92
|
+
`read` is called once per entity, id batch, and window per read level: ids are
|
|
93
|
+
batched up to `maxIdsPerEntity`, ids that page a relation differently are read
|
|
94
|
+
separately, and a nested selection reads its next level after the refs arrive.
|
|
95
|
+
`windows` carries the pagination window for each requested relation field. The result may be a partial
|
|
96
|
+
entity: a field the source omits is simply not present, and presence metadata on
|
|
97
|
+
the client reflects that.
|
|
98
|
+
|
|
99
|
+
### `RemoteServer.query`
|
|
100
|
+
|
|
101
|
+
```ts
|
|
102
|
+
RemoteServer.query(ProjectsByOwner, ({ input, window, principal }) =>
|
|
103
|
+
Effect.Effect<QueryPage, RemoteServerError, R>,
|
|
104
|
+
)
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
`QueryPage` is `{ edges, start, end }`; `start`/`end` are `Boundary` values
|
|
108
|
+
(`Terminal`, `Cursor`, or `Unknown`) so the client can merge the page without
|
|
109
|
+
inferring adjacency from row count.
|
|
110
|
+
|
|
111
|
+
### `RemoteServer.mutation`
|
|
112
|
+
|
|
113
|
+
```ts
|
|
114
|
+
RemoteServer.mutation(RenameProject, ({ input, principal }) =>
|
|
115
|
+
Effect.Effect<
|
|
116
|
+
{ output: Output; entities?: NormalizedPatch[]; connections?: ConnectionChange[] },
|
|
117
|
+
RemoteServerError,
|
|
118
|
+
R
|
|
119
|
+
>,
|
|
120
|
+
)
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
`input` is decoded against the mutation's `Input` schema first, so the callback
|
|
124
|
+
receives the typed input. `output` is encoded against `Output`; `entities` are
|
|
125
|
+
the normalized cache patches the client will reconcile, and `connections` the
|
|
126
|
+
confirmed connection inserts and removes that replace the client's optimistic
|
|
127
|
+
ones in place: `RemoteServer.prepend(connection, ref)`, `append`, and
|
|
128
|
+
`remove`, where `connection` is a `QueryRef` or its identity.
|
|
129
|
+
|
|
130
|
+
### `RemoteServer.live`
|
|
131
|
+
|
|
132
|
+
```ts
|
|
133
|
+
RemoteServer.live(Project, {
|
|
134
|
+
subscribe: ({ requirements, after, principal }) =>
|
|
135
|
+
Stream.Stream<LiveChange, RemoteServerError, R>,
|
|
136
|
+
})
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
`after` is the client's resume cursor; events at or before it are duplicates. The
|
|
140
|
+
handler merges the requested entities' streams and maps a source failure onto the
|
|
141
|
+
wire error. An entity with no live source contributes nothing, so the client
|
|
142
|
+
plans a refetch instead of failing the stream. A `LiveChange` is an entity patch
|
|
143
|
+
or delete, or a connection insert/remove/invalidate.
|
|
144
|
+
|
|
145
|
+
### `RemoteServer.liveHub`
|
|
146
|
+
|
|
147
|
+
The higher-level signal. A hub tracks each live subscriber's requirements and
|
|
148
|
+
principal, so the server says *what changed* and the hub works out *who cares*:
|
|
149
|
+
|
|
150
|
+
```ts
|
|
151
|
+
const hub = yield* RemoteServer.liveHub(entitySources)
|
|
152
|
+
const handlers = RemoteServer.handlers(server, principal, { live: hub })
|
|
153
|
+
|
|
154
|
+
// Wherever the data changes (a mutation source, a database trigger):
|
|
155
|
+
yield* hub.changed(Project.ref(projectId), ['status', 'updatedAt'])
|
|
156
|
+
yield* hub.deleted(Project.ref(projectId))
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
`changed` intersects the fields with what each subscriber selects, re-reads
|
|
160
|
+
that intersection through the entity's own source under the subscriber's
|
|
161
|
+
principal (one read per principal value and window signature; subscribers
|
|
162
|
+
selecting none of the fields do no work), and streams an `EntityPatched`
|
|
163
|
+
carrying only the fields that subscriber may see. A record the source does not
|
|
164
|
+
return for the changed id reaches nobody. `deleted` streams an `EntityDeleted` to the entity's
|
|
165
|
+
subscribers. Cursors continue from the cursor each subscriber resumed at, so
|
|
166
|
+
the client's duplicate and gap handling is unchanged. A hub and hand-written
|
|
167
|
+
`RemoteServer.live` sources number their events independently; use one or the
|
|
168
|
+
other for a given subscription. Nested relation targets are not subscribed by
|
|
169
|
+
the hub, only the requirements' own entities.
|
|
170
|
+
|
|
171
|
+
## Authorization
|
|
172
|
+
|
|
173
|
+
Authentication and authorization are separate. Authentication answers *who is
|
|
174
|
+
this* (Effect RPC middleware → `Principal`); `RemoteServer` answers *may this
|
|
175
|
+
principal read this semantic field*. Authorization is mandatory, not opt-in:
|
|
176
|
+
|
|
177
|
+
- A field the Entity does not declare is dropped before `authorize` sees it.
|
|
178
|
+
- An entity with no `authorize` exposes the requested fields.
|
|
179
|
+
- An entity with `authorize` exposes only the returned fields, and a field the
|
|
180
|
+
principal may not see is dropped.
|
|
181
|
+
- **Never read or return a field the client did not request**, even if a
|
|
182
|
+
permissive `authorize` allows more.
|
|
183
|
+
- If no field survives authorization, the entity contributes nothing, so the
|
|
184
|
+
existence of an unauthorized entity is not leaked.
|
|
185
|
+
|
|
186
|
+
## Hardening
|
|
187
|
+
|
|
188
|
+
- Each read batch and live subscription is bounded per entity
|
|
189
|
+
(`maxIdsPerEntity`, default 1000, counted across the batch's window groups),
|
|
190
|
+
and an oversized one fails rather than loading unbounded rows.
|
|
191
|
+
- A selection nested past `MAX_RELATION_DEPTH` (8) or naming more than
|
|
192
|
+
`MAX_FIELDS_PER_REQUEST` (256) fields of one entity is refused at decode.
|
|
193
|
+
- Returned field names are filtered with `Object.hasOwn` and accumulated into a
|
|
194
|
+
null-prototype object, so a crafted field name such as `__proto__` or
|
|
195
|
+
`toString` cannot reach the prototype.
|
|
196
|
+
- Handler errors are remapped to the wire error types without echoing internals.
|
|
197
|
+
|
|
198
|
+
## What it owns
|
|
199
|
+
|
|
200
|
+
- Entity, query, mutation, and live Sources.
|
|
201
|
+
- Selection authorization and field filtering.
|
|
202
|
+
- Request grouping, id de-duplication, field unions, and window threading.
|
|
203
|
+
- Normalization of source results into wire entities.
|
|
204
|
+
- Source-name validation: `RemoteServer.validate(domain, server)` checks every
|
|
205
|
+
entity, query, and mutation source against the domain's `registry`, so an
|
|
206
|
+
undeclared name fails at startup rather than returning nothing at call time.
|
|
207
|
+
- Compilation to the `RemoteRpc` handlers.
|
|
208
|
+
|
|
209
|
+
## Limits
|
|
210
|
+
|
|
211
|
+
- Transport, serialization, and the authentication protocol are Effect RPC's; the
|
|
212
|
+
application provides the server protocol layer.
|
|
213
|
+
- The live wire carries a `LiveChange` union: entity patches and deletes, plus
|
|
214
|
+
connection insert/remove/invalidate events.
|
|
215
|
+
- Database and other runtime dependencies are the Source's Effect requirements,
|
|
216
|
+
not this package's.
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { Effect, Schema, Stream } from "effect";
|
|
2
|
+
import { Boundary, ConnectionChangeSchema, ConnectionIdentity, LiveChange, MutationDescriptor, NormalizedPatch, QueryDescriptor, QueryWindow, RemoteDescriptor, RemoteRpcClient } from "foldkit-remote";
|
|
3
|
+
import { Requirement } from "foldkit-surface";
|
|
4
|
+
//#region src/index.d.ts
|
|
5
|
+
declare const RemoteServerError_base: Schema.Class<RemoteServerError, Schema.TaggedStruct<"RemoteServerError", {
|
|
6
|
+
readonly message: Schema.String;
|
|
7
|
+
}>, import("effect/Cause").YieldableError>;
|
|
8
|
+
export declare class RemoteServerError extends RemoteServerError_base {}
|
|
9
|
+
export interface EntityRecord {
|
|
10
|
+
readonly id: string;
|
|
11
|
+
readonly values: Readonly<Record<string, unknown>>;
|
|
12
|
+
}
|
|
13
|
+
export interface EntitySourceContext<P> {
|
|
14
|
+
readonly ids: readonly string[];
|
|
15
|
+
readonly fields: readonly string[];
|
|
16
|
+
/** A pagination window per requested relation field. */
|
|
17
|
+
readonly windows?: Readonly<Record<string, QueryWindow>> | undefined;
|
|
18
|
+
readonly principal: P;
|
|
19
|
+
}
|
|
20
|
+
export interface EntitySource<P, R = never> {
|
|
21
|
+
readonly entity: string;
|
|
22
|
+
/** The fields the entity declares; a request for any other never reaches `read`. */
|
|
23
|
+
readonly fields?: ReadonlySet<string> | undefined;
|
|
24
|
+
readonly read: (context: EntitySourceContext<P>) => Effect.Effect<ReadonlyArray<EntityRecord>, RemoteServerError, R>;
|
|
25
|
+
/** Returns the fields this principal may read; omitted means all requested. */
|
|
26
|
+
readonly authorize?: (principal: P, fields: readonly string[]) => readonly string[];
|
|
27
|
+
}
|
|
28
|
+
/** A connection change a mutation made, as the wire carries it. */
|
|
29
|
+
export type ConnectionChange = Schema.Schema.Type<typeof ConnectionChangeSchema>;
|
|
30
|
+
export interface MutationOutcome<Output> {
|
|
31
|
+
readonly output: Output;
|
|
32
|
+
readonly entities?: ReadonlyArray<NormalizedPatch>;
|
|
33
|
+
/** Connection changes the mutation made; the client settles them with its patches. */
|
|
34
|
+
readonly connections?: ReadonlyArray<ConnectionChange>;
|
|
35
|
+
}
|
|
36
|
+
export interface MutationSource<P, R = never> {
|
|
37
|
+
readonly mutation: string;
|
|
38
|
+
readonly Input: Schema.Codec<unknown>;
|
|
39
|
+
readonly Output: Schema.Codec<unknown>;
|
|
40
|
+
readonly run: (context: {
|
|
41
|
+
readonly input: unknown;
|
|
42
|
+
readonly principal: P;
|
|
43
|
+
}) => Effect.Effect<{
|
|
44
|
+
readonly output: unknown;
|
|
45
|
+
readonly entities: ReadonlyArray<NormalizedPatch>;
|
|
46
|
+
readonly connections: ReadonlyArray<ConnectionChange>;
|
|
47
|
+
}, RemoteServerError, R>;
|
|
48
|
+
}
|
|
49
|
+
export interface QueryPage {
|
|
50
|
+
readonly edges: ReadonlyArray<{
|
|
51
|
+
readonly entity: string;
|
|
52
|
+
readonly id: string;
|
|
53
|
+
readonly key: string;
|
|
54
|
+
}>;
|
|
55
|
+
readonly start: Boundary;
|
|
56
|
+
readonly end: Boundary;
|
|
57
|
+
}
|
|
58
|
+
export interface QuerySource<P, R = never> {
|
|
59
|
+
readonly query: string;
|
|
60
|
+
readonly Input: Schema.Codec<unknown>;
|
|
61
|
+
readonly run: (context: {
|
|
62
|
+
readonly input: unknown;
|
|
63
|
+
readonly window: QueryWindow;
|
|
64
|
+
readonly principal: P;
|
|
65
|
+
}) => Effect.Effect<QueryPage, RemoteServerError, R>;
|
|
66
|
+
}
|
|
67
|
+
export interface LiveSource<P, R = never> {
|
|
68
|
+
readonly entity: string;
|
|
69
|
+
readonly subscribe: (context: {
|
|
70
|
+
readonly requirements: ReadonlyArray<Requirement>;
|
|
71
|
+
readonly after: number;
|
|
72
|
+
readonly principal: P;
|
|
73
|
+
}) => Stream.Stream<Schema.Schema.Type<typeof LiveChange>, RemoteServerError, R>;
|
|
74
|
+
}
|
|
75
|
+
export interface ServerDefinition<P, R = never> {
|
|
76
|
+
readonly entities: ReadonlyMap<string, EntitySource<P, R>>;
|
|
77
|
+
readonly mutations: ReadonlyMap<string, MutationSource<P, R>>;
|
|
78
|
+
readonly queries: ReadonlyMap<string, QuerySource<P, R>>;
|
|
79
|
+
readonly live: ReadonlyMap<string, LiveSource<P, R>>;
|
|
80
|
+
}
|
|
81
|
+
export interface HandlerOptions<P, R = never> {
|
|
82
|
+
/** A read or live subscription may not name more ids of one entity than this; default 1000. */
|
|
83
|
+
readonly maxIdsPerEntity?: number | undefined;
|
|
84
|
+
/** A nested selection may not reach further than this many relation levels; default 8. */
|
|
85
|
+
readonly maxDepth?: number | undefined;
|
|
86
|
+
/** A hub whose `changed`/`deleted` signals reach the subscribers this handler registers. */
|
|
87
|
+
readonly live?: LiveHub<P, R> | undefined;
|
|
88
|
+
}
|
|
89
|
+
type LiveChangeValue = Schema.Schema.Type<typeof LiveChange>;
|
|
90
|
+
interface LiveRef {
|
|
91
|
+
readonly entity: string;
|
|
92
|
+
readonly id: string;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* The server-side "these fields changed" signal. A hub tracks each live
|
|
96
|
+
* subscriber's requirements (entity, id, fields) and principal; `changed`
|
|
97
|
+
* re-reads the changed fields a subscriber selects through the entity's own
|
|
98
|
+
* source, under that subscriber's principal, and streams the patch to it.
|
|
99
|
+
* Subscribers that select none of the changed fields do no work. Cursors
|
|
100
|
+
* continue from the cursor each subscriber resumed at, so the client's
|
|
101
|
+
* duplicate and gap handling is unchanged.
|
|
102
|
+
*/
|
|
103
|
+
export interface LiveHub<P, R = never> {
|
|
104
|
+
readonly changed: (ref: LiveRef, fields: ReadonlyArray<string>) => Effect.Effect<void, RemoteServerError, R>;
|
|
105
|
+
readonly deleted: (ref: LiveRef) => Effect.Effect<void>;
|
|
106
|
+
/** Registers a subscriber for the stream's lifetime; `handlers` calls this. */
|
|
107
|
+
readonly subscribe: (context: {
|
|
108
|
+
readonly requirements: ReadonlyArray<Requirement>;
|
|
109
|
+
readonly after: number;
|
|
110
|
+
readonly principal: P;
|
|
111
|
+
/** Refuses a subscription naming more ids of one entity than this. */
|
|
112
|
+
readonly maxIdsPerEntity?: number | undefined;
|
|
113
|
+
}) => Stream.Stream<LiveChangeValue, RemoteServerError>;
|
|
114
|
+
/** How many subscribers are registered now. */
|
|
115
|
+
readonly size: Effect.Effect<number>;
|
|
116
|
+
}
|
|
117
|
+
/** A descriptor's name and, when it declares them, its fields. */
|
|
118
|
+
interface EntityName {
|
|
119
|
+
readonly name: string;
|
|
120
|
+
readonly fields?: Readonly<Record<string, unknown>> | undefined;
|
|
121
|
+
}
|
|
122
|
+
export declare const RemoteServer: {
|
|
123
|
+
/** A mutation outcome's report that `ref` now heads the connection. */
|
|
124
|
+
prepend: (connection: ConnectionIdentity, ref: {
|
|
125
|
+
readonly entity: string;
|
|
126
|
+
readonly id: string;
|
|
127
|
+
}) => ConnectionChange;
|
|
128
|
+
/** A mutation outcome's report that `ref` now ends the connection. */
|
|
129
|
+
append: (connection: ConnectionIdentity, ref: {
|
|
130
|
+
readonly entity: string;
|
|
131
|
+
readonly id: string;
|
|
132
|
+
}) => ConnectionChange;
|
|
133
|
+
/** A mutation outcome's report that `ref` left the connection. */
|
|
134
|
+
remove: (connection: ConnectionIdentity, ref: {
|
|
135
|
+
readonly entity: string;
|
|
136
|
+
readonly id: string;
|
|
137
|
+
}) => ConnectionChange;
|
|
138
|
+
/**
|
|
139
|
+
* An entity source. Given the Entity (or anything with its `name` and
|
|
140
|
+
* `fields`), a request for a field the entity does not declare never
|
|
141
|
+
* reaches `read` or `authorize`.
|
|
142
|
+
*/
|
|
143
|
+
entity: <P = unknown, R = never>(entity: EntityName, options: {
|
|
144
|
+
readonly read: EntitySource<P, R>["read"];
|
|
145
|
+
readonly authorize?: EntitySource<P, R>["authorize"];
|
|
146
|
+
}) => EntitySource<P, R>;
|
|
147
|
+
mutation: <P = unknown, R = never, Name extends string = string, Input = unknown, Output = unknown>(mutation: MutationDescriptor<Name, Input, Output>, run: (context: {
|
|
148
|
+
readonly input: Input;
|
|
149
|
+
readonly principal: P;
|
|
150
|
+
}) => Effect.Effect<MutationOutcome<Output>, RemoteServerError, R>) => MutationSource<P, R>;
|
|
151
|
+
query: <P = unknown, R = never, Input = unknown>(query: QueryDescriptor<string, Input, unknown>, run: (context: {
|
|
152
|
+
readonly input: Input;
|
|
153
|
+
readonly window: QueryWindow;
|
|
154
|
+
readonly principal: P;
|
|
155
|
+
}) => Effect.Effect<QueryPage, RemoteServerError, R>) => QuerySource<P, R>;
|
|
156
|
+
/** Streams live entity patches for a client's live requirements. */
|
|
157
|
+
live: <P = unknown, R = never>(entity: EntityName, options: {
|
|
158
|
+
readonly subscribe: LiveSource<P, R>["subscribe"];
|
|
159
|
+
}) => LiveSource<P, R>;
|
|
160
|
+
/**
|
|
161
|
+
* A `LiveHub` over entity sources. Pass it to `handlers` as `live`, then
|
|
162
|
+
* call `hub.changed(ref, fields)` from wherever the data changes (a mutation
|
|
163
|
+
* source, a database trigger); each subscriber that selects any of those
|
|
164
|
+
* fields receives them, re-read through the entity source under its own
|
|
165
|
+
* principal. It needs only the entity sources, so the mutation sources that
|
|
166
|
+
* signal it can be built after it.
|
|
167
|
+
*/
|
|
168
|
+
liveHub: <P, R>(entities: ReadonlyArray<EntitySource<P, R>>) => Effect.Effect<LiveHub<P, R>>;
|
|
169
|
+
make: <P = unknown, R = never>(config: {
|
|
170
|
+
readonly entities: readonly EntitySource<P, R>[];
|
|
171
|
+
readonly mutations?: readonly MutationSource<P, R>[];
|
|
172
|
+
readonly queries?: readonly QuerySource<P, R>[];
|
|
173
|
+
readonly live?: readonly LiveSource<P, R>[];
|
|
174
|
+
}) => ServerDefinition<P, R>;
|
|
175
|
+
/**
|
|
176
|
+
* Checks every source name against the declared domain, so an undeclared
|
|
177
|
+
* entity/query/mutation fails at startup rather than returning nothing at
|
|
178
|
+
* call time.
|
|
179
|
+
*/
|
|
180
|
+
validate: (domain: RemoteDescriptor, server: ServerDefinition<any, any>) => void;
|
|
181
|
+
/**
|
|
182
|
+
* Compiles the server into the `Read`/`Mutate` RPC handlers. `principal` is
|
|
183
|
+
* resolved outside (authentication middleware in a later phase); unknown
|
|
184
|
+
* entities, entities with no allowed fields, and unknown mutations return an
|
|
185
|
+
* error or nothing rather than leaking existence.
|
|
186
|
+
*/
|
|
187
|
+
handlers: <P, R>(server: ServerDefinition<P, R>, principal: P, options?: HandlerOptions<P, R>) => RemoteRpcClient<R>;
|
|
188
|
+
};
|
|
189
|
+
//#endregion
|
|
190
|
+
//# sourceMappingURL=index.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;;;qBAiCa,0BAA0B;iBAOtB;WACN;WACA,QAAQ,SAAS;;iBAGX,oBAAoB;WAC1B;WACA;;WAEA,UAAU,SAAS,eAAe;WAClC,WAAW;;iBAGL,aAAa,GAAG;WACtB;;WAEA,SAAS;WACT,OACP,SAAS,oBAAoB,OAC1B,OAAO,OAAO,cAAc,eAAe,mBAAmB;;WAE1D,aAAa,WAAW,GAAG;;;YAI1B,mBAAmB,OAAO,OAAO,YAAY;iBA8CxC,gBAAgB;WACtB,QAAQ;WACR,WAAW,cAAc;;WAEzB,cAAc,cAA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,GAAG;EAQjB,WAAA,aACA,WACA,8BACA,iBACA,kBAAM,UAEI,mBAAmB,MAAM,OAAO,SAAO,MAC3C;aACK,OAAO;aACP,WAAW;QAChB,OAAO,OAAO,gBAAgB,SAAS,mBAAmB,OAC/D,eAAe,GAAG;EAcb,QAAA,aAAa,WAAW,iBAAK,OAC5B,wBAAwB,iBAAe,MACxC;aACK,OAAO;aACP,QAAQ;aACR,WAAW;QAChB,OAAO,OAAO,WAAW,mBAAmB,OACjD,YAAY,GAAG;;EAQX,OAAA,aAAa,WAAC,QACX,YAAU;aACE,WAAW,WAAW,GAAG;QAC5C,WAAW,GAAG;;;;;;;;;EAxPF,UAAA,GAAG,GAAC,UAAY,cAAc,aAAa,GAAG,QAAM,OAAO,OAAO,QAAQ,GAAG;EAuQrF,OAAA,aAAa,WAAC;aACV,mBAAmB,aAAa,GAAG;aACnC,qBAAqB,eAAe,GAAG;aACvC,mBAAmB,YAAY,GAAG;aAClC,gBAAgB,WAAW,GAAG;QACrC,iBAAiB,GAAG;;;;;;EAYL,WAAA,QAAA,kBAAgB,QAAU;;;;;;;EAsBlC,WAAA,GAAG,GAAC,QACL,iBAAiB,GAAG,IAAE,WACnB,GAAC,UACH,eAAe,GAAG,OAC1B,gBAAgB"}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,413 @@
|
|
|
1
|
+
import { Effect, Queue, Schema, Stream } from "effect";
|
|
2
|
+
import { REMOTE_PROTOCOL_VERSION, RemoteLiveError, RemoteMutationError, RemoteProtocolError, RemoteQueryError, RemoteReadError, connectionIdentity, entityKey, refsIn, stableStringify } from "foldkit-remote";
|
|
3
|
+
import { Requirement } from "foldkit-surface";
|
|
4
|
+
//#region src/index.ts
|
|
5
|
+
/**
|
|
6
|
+
* `foldkit-remote-server` — server-side Sources and handler compilation.
|
|
7
|
+
*
|
|
8
|
+
* Owns entity/query Sources, **selection authorization**, normalization, and
|
|
9
|
+
* turning them into Effect RPC handlers. It does not own HTTP, serialization, or
|
|
10
|
+
* auth protocol; `principal` is resolved outside and passed in.
|
|
11
|
+
*/
|
|
12
|
+
var RemoteServerError = class extends Schema.TaggedError()("RemoteServerError", { message: Schema.String }) {};
|
|
13
|
+
const connectionChange = (connection, ref, position) => {
|
|
14
|
+
const edge = {
|
|
15
|
+
entity: ref.entity,
|
|
16
|
+
id: ref.id,
|
|
17
|
+
key: entityKey(ref.entity, ref.id)
|
|
18
|
+
};
|
|
19
|
+
return position === "remove" ? {
|
|
20
|
+
_tag: "Remove",
|
|
21
|
+
connection: connectionIdentity(connection),
|
|
22
|
+
edge
|
|
23
|
+
} : {
|
|
24
|
+
_tag: "Insert",
|
|
25
|
+
connection: connectionIdentity(connection),
|
|
26
|
+
position,
|
|
27
|
+
edge
|
|
28
|
+
};
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* The requested fields, in request order, that the source declares and the
|
|
32
|
+
* principal may read. Never a field the client did not request, even if a
|
|
33
|
+
* permissive `authorize` returns more.
|
|
34
|
+
*/
|
|
35
|
+
const allowedFields = (source, principal, requested) => {
|
|
36
|
+
const declared = source.fields === void 0 ? requested : requested.filter((field) => source.fields.has(field));
|
|
37
|
+
if (declared.length === 0) return [];
|
|
38
|
+
const permitted = new Set(source.authorize === void 0 ? declared : source.authorize(principal, declared));
|
|
39
|
+
return declared.filter((field) => permitted.has(field));
|
|
40
|
+
};
|
|
41
|
+
/** The windows of the fields being read; only a field being read carries its window. */
|
|
42
|
+
const windowsOf = (windows, fields) => {
|
|
43
|
+
if (windows === void 0) return {};
|
|
44
|
+
const kept = Object.fromEntries(fields.flatMap((field) => Object.hasOwn(windows, field) ? [[field, windows[field]]] : []));
|
|
45
|
+
return Object.keys(kept).length === 0 ? {} : { windows: kept };
|
|
46
|
+
};
|
|
47
|
+
/** A read batch may not carry more than this many distinct ids per entity. */
|
|
48
|
+
const DEFAULT_MAX_IDS_PER_ENTITY = 1e3;
|
|
49
|
+
/** A nested selection may not reach further than this many relation levels. */
|
|
50
|
+
const DEFAULT_MAX_DEPTH = 8;
|
|
51
|
+
/** Fails when the requirements name more distinct ids of one entity than `maxIds`. */
|
|
52
|
+
const checkIdsPerEntity = (requirements, maxIds) => {
|
|
53
|
+
const ids = /* @__PURE__ */ new Map();
|
|
54
|
+
for (const requirement of requirements) {
|
|
55
|
+
const seen = ids.get(requirement.entity) ?? /* @__PURE__ */ new Set();
|
|
56
|
+
seen.add(requirement.id);
|
|
57
|
+
ids.set(requirement.entity, seen);
|
|
58
|
+
if (seen.size > maxIds) return requirement.entity;
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
const liveHub = (entities) => Effect.sync(() => {
|
|
62
|
+
const sources = new Map(entities.map((source) => [source.entity, source]));
|
|
63
|
+
const subscribers = /* @__PURE__ */ new Set();
|
|
64
|
+
const emit = (subscriber, change) => {
|
|
65
|
+
subscriber.cursor += 1;
|
|
66
|
+
return Queue.offer(subscriber.queue, {
|
|
67
|
+
...change,
|
|
68
|
+
cursor: subscriber.cursor
|
|
69
|
+
});
|
|
70
|
+
};
|
|
71
|
+
return {
|
|
72
|
+
subscribe: ({ requirements, after, principal, maxIdsPerEntity }) => Stream.unwrap(Effect.gen(function* () {
|
|
73
|
+
const over = checkIdsPerEntity(requirements, Math.max(1, maxIdsPerEntity ?? DEFAULT_MAX_IDS_PER_ENTITY));
|
|
74
|
+
if (over !== void 0) return yield* new RemoteServerError({ message: `Too many "${over}" ids in one live subscription` });
|
|
75
|
+
const selected = /* @__PURE__ */ new Map();
|
|
76
|
+
for (const requirement of requirements) {
|
|
77
|
+
const key = `${requirement.entity}:${requirement.id}`;
|
|
78
|
+
const entry = selected.get(key) ?? {
|
|
79
|
+
fields: /* @__PURE__ */ new Set(),
|
|
80
|
+
windows: /* @__PURE__ */ new Map()
|
|
81
|
+
};
|
|
82
|
+
for (const field of requirement.fields) entry.fields.add(field);
|
|
83
|
+
for (const [field, window] of Object.entries(requirement.windows ?? {})) entry.windows.set(field, window);
|
|
84
|
+
selected.set(key, entry);
|
|
85
|
+
}
|
|
86
|
+
const subscriber = {
|
|
87
|
+
selected,
|
|
88
|
+
principal,
|
|
89
|
+
queue: yield* Queue.unbounded(),
|
|
90
|
+
cursor: after
|
|
91
|
+
};
|
|
92
|
+
subscribers.add(subscriber);
|
|
93
|
+
return Stream.fromQueue(subscriber.queue).pipe(Stream.ensuring(Effect.sync(() => void subscribers.delete(subscriber))));
|
|
94
|
+
})),
|
|
95
|
+
changed: (ref, fields) => Effect.gen(function* () {
|
|
96
|
+
const key = `${ref.entity}:${ref.id}`;
|
|
97
|
+
const source = sources.get(ref.entity);
|
|
98
|
+
if (source === void 0) return;
|
|
99
|
+
const groups = /* @__PURE__ */ new Map();
|
|
100
|
+
for (const subscriber of subscribers) {
|
|
101
|
+
const selected = subscriber.selected.get(key);
|
|
102
|
+
if (selected === void 0) continue;
|
|
103
|
+
const wanted = fields.filter((field) => selected.fields.has(field));
|
|
104
|
+
if (wanted.length === 0) continue;
|
|
105
|
+
const windows = Object.fromEntries(wanted.flatMap((field) => {
|
|
106
|
+
const window = selected.windows.get(field);
|
|
107
|
+
return window === void 0 ? [] : [[field, window]];
|
|
108
|
+
}));
|
|
109
|
+
const byWindows = groups.get(subscriber.principal) ?? /* @__PURE__ */ new Map();
|
|
110
|
+
groups.set(subscriber.principal, byWindows);
|
|
111
|
+
const windowKey = stableStringify(windows);
|
|
112
|
+
const group = byWindows.get(windowKey) ?? {
|
|
113
|
+
windows,
|
|
114
|
+
entries: []
|
|
115
|
+
};
|
|
116
|
+
byWindows.set(windowKey, group);
|
|
117
|
+
group.entries.push({
|
|
118
|
+
subscriber,
|
|
119
|
+
fields: wanted
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
for (const [principal, byWindows] of groups) for (const { windows, entries: group } of byWindows.values()) {
|
|
123
|
+
const requested = [...new Set(group.flatMap((entry) => entry.fields))];
|
|
124
|
+
const allowed = allowedFields(source, principal, requested);
|
|
125
|
+
if (allowed.length === 0) continue;
|
|
126
|
+
const allowedSet = new Set(allowed);
|
|
127
|
+
const record = (yield* source.read({
|
|
128
|
+
ids: [ref.id],
|
|
129
|
+
fields: allowed,
|
|
130
|
+
principal,
|
|
131
|
+
...windowsOf(windows, allowed)
|
|
132
|
+
})).find((candidate) => candidate.id === ref.id);
|
|
133
|
+
if (record === void 0) continue;
|
|
134
|
+
for (const { subscriber, fields: wanted } of group) {
|
|
135
|
+
const values = Object.create(null);
|
|
136
|
+
for (const field of wanted) if (allowedSet.has(field) && Object.hasOwn(record.values, field)) values[field] = record.values[field];
|
|
137
|
+
const changed = Object.keys(values);
|
|
138
|
+
if (changed.length === 0) continue;
|
|
139
|
+
yield* emit(subscriber, {
|
|
140
|
+
_tag: "EntityPatched",
|
|
141
|
+
entity: ref.entity,
|
|
142
|
+
id: ref.id,
|
|
143
|
+
values,
|
|
144
|
+
changed
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}),
|
|
149
|
+
deleted: (ref) => Effect.gen(function* () {
|
|
150
|
+
const key = `${ref.entity}:${ref.id}`;
|
|
151
|
+
for (const subscriber of subscribers) {
|
|
152
|
+
if (!subscriber.selected.has(key)) continue;
|
|
153
|
+
yield* emit(subscriber, {
|
|
154
|
+
_tag: "EntityDeleted",
|
|
155
|
+
entity: ref.entity,
|
|
156
|
+
id: ref.id
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
}),
|
|
160
|
+
size: Effect.sync(() => subscribers.size)
|
|
161
|
+
};
|
|
162
|
+
});
|
|
163
|
+
const protocolMismatch = (received) => received === REMOTE_PROTOCOL_VERSION ? void 0 : new RemoteProtocolError({
|
|
164
|
+
message: `Remote protocol version ${received} is not ${REMOTE_PROTOCOL_VERSION}`,
|
|
165
|
+
expected: REMOTE_PROTOCOL_VERSION,
|
|
166
|
+
received
|
|
167
|
+
});
|
|
168
|
+
/**
|
|
169
|
+
* One level's requests grouped per entity and window signature: ids and
|
|
170
|
+
* slices unioned. Requests that page a relation differently are separate
|
|
171
|
+
* groups, so one window never answers for another id.
|
|
172
|
+
*/
|
|
173
|
+
const groupByEntity = (requests) => {
|
|
174
|
+
const grouped = /* @__PURE__ */ new Map();
|
|
175
|
+
for (const request of requests) {
|
|
176
|
+
const groupKey = `${request.entity}\u0000${stableStringify(request.windows ?? null)}`;
|
|
177
|
+
const group = grouped.get(groupKey);
|
|
178
|
+
if (group === void 0) grouped.set(groupKey, {
|
|
179
|
+
ids: /* @__PURE__ */ new Set([request.id]),
|
|
180
|
+
slice: Requirement.mergeRelation({
|
|
181
|
+
entity: request.entity,
|
|
182
|
+
fields: []
|
|
183
|
+
}, request)
|
|
184
|
+
});
|
|
185
|
+
else {
|
|
186
|
+
group.ids.add(request.id);
|
|
187
|
+
group.slice = Requirement.mergeRelation(group.slice, request);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
return [...grouped.values()];
|
|
191
|
+
};
|
|
192
|
+
const RemoteServer = {
|
|
193
|
+
/** A mutation outcome's report that `ref` now heads the connection. */
|
|
194
|
+
prepend: (connection, ref) => connectionChange(connection, ref, "prepend"),
|
|
195
|
+
/** A mutation outcome's report that `ref` now ends the connection. */
|
|
196
|
+
append: (connection, ref) => connectionChange(connection, ref, "append"),
|
|
197
|
+
/** A mutation outcome's report that `ref` left the connection. */
|
|
198
|
+
remove: (connection, ref) => connectionChange(connection, ref, "remove"),
|
|
199
|
+
/**
|
|
200
|
+
* An entity source. Given the Entity (or anything with its `name` and
|
|
201
|
+
* `fields`), a request for a field the entity does not declare never
|
|
202
|
+
* reaches `read` or `authorize`.
|
|
203
|
+
*/
|
|
204
|
+
entity: (entity, options) => ({
|
|
205
|
+
entity: entity.name,
|
|
206
|
+
...entity.fields === void 0 ? {} : { fields: new Set(Object.keys(entity.fields)) },
|
|
207
|
+
read: options.read,
|
|
208
|
+
...options.authorize === void 0 ? {} : { authorize: options.authorize }
|
|
209
|
+
}),
|
|
210
|
+
mutation: (mutation, run) => ({
|
|
211
|
+
mutation: mutation.name,
|
|
212
|
+
Input: mutation.Input,
|
|
213
|
+
Output: mutation.Output,
|
|
214
|
+
run: (context) => run({
|
|
215
|
+
input: context.input,
|
|
216
|
+
principal: context.principal
|
|
217
|
+
}).pipe(Effect.map((outcome) => ({
|
|
218
|
+
output: outcome.output,
|
|
219
|
+
entities: outcome.entities ?? [],
|
|
220
|
+
connections: outcome.connections ?? []
|
|
221
|
+
})))
|
|
222
|
+
}),
|
|
223
|
+
query: (query, run) => ({
|
|
224
|
+
query: query.name,
|
|
225
|
+
Input: query.Input,
|
|
226
|
+
run: (context) => run({
|
|
227
|
+
input: context.input,
|
|
228
|
+
window: context.window,
|
|
229
|
+
principal: context.principal
|
|
230
|
+
})
|
|
231
|
+
}),
|
|
232
|
+
/** Streams live entity patches for a client's live requirements. */
|
|
233
|
+
live: (entity, options) => ({
|
|
234
|
+
entity: entity.name,
|
|
235
|
+
subscribe: options.subscribe
|
|
236
|
+
}),
|
|
237
|
+
/**
|
|
238
|
+
* A `LiveHub` over entity sources. Pass it to `handlers` as `live`, then
|
|
239
|
+
* call `hub.changed(ref, fields)` from wherever the data changes (a mutation
|
|
240
|
+
* source, a database trigger); each subscriber that selects any of those
|
|
241
|
+
* fields receives them, re-read through the entity source under its own
|
|
242
|
+
* principal. It needs only the entity sources, so the mutation sources that
|
|
243
|
+
* signal it can be built after it.
|
|
244
|
+
*/
|
|
245
|
+
liveHub,
|
|
246
|
+
make: (config) => ({
|
|
247
|
+
entities: new Map(config.entities.map((source) => [source.entity, source])),
|
|
248
|
+
mutations: new Map((config.mutations ?? []).map((source) => [source.mutation, source])),
|
|
249
|
+
queries: new Map((config.queries ?? []).map((source) => [source.query, source])),
|
|
250
|
+
live: new Map((config.live ?? []).map((source) => [source.entity, source]))
|
|
251
|
+
}),
|
|
252
|
+
/**
|
|
253
|
+
* Checks every source name against the declared domain, so an undeclared
|
|
254
|
+
* entity/query/mutation fails at startup rather than returning nothing at
|
|
255
|
+
* call time.
|
|
256
|
+
*/
|
|
257
|
+
validate: (domain, server) => {
|
|
258
|
+
const assertDeclared = (kind, declared, names) => {
|
|
259
|
+
for (const name of names) if (!declared.has(name)) throw new Error(`RemoteServer: ${kind} "${name}" is not declared in the Remote domain`);
|
|
260
|
+
};
|
|
261
|
+
assertDeclared("entity", domain.registry.entities, server.entities.keys());
|
|
262
|
+
assertDeclared("query", domain.registry.queries, server.queries.keys());
|
|
263
|
+
assertDeclared("mutation", domain.registry.mutations, server.mutations.keys());
|
|
264
|
+
},
|
|
265
|
+
/**
|
|
266
|
+
* Compiles the server into the `Read`/`Mutate` RPC handlers. `principal` is
|
|
267
|
+
* resolved outside (authentication middleware in a later phase); unknown
|
|
268
|
+
* entities, entities with no allowed fields, and unknown mutations return an
|
|
269
|
+
* error or nothing rather than leaking existence.
|
|
270
|
+
*/
|
|
271
|
+
handlers: (server, principal, options = {}) => ({
|
|
272
|
+
FoldkitRemoteRead: Effect.fn("RemoteServer.FoldkitRemoteRead")(function* (payload) {
|
|
273
|
+
const mismatch = protocolMismatch(payload.version);
|
|
274
|
+
if (mismatch !== void 0) return yield* mismatch;
|
|
275
|
+
const entities = [];
|
|
276
|
+
const fetched = /* @__PURE__ */ new Map();
|
|
277
|
+
const fetchedValues = /* @__PURE__ */ new Map();
|
|
278
|
+
const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH;
|
|
279
|
+
const maxIds = Math.max(1, options.maxIdsPerEntity ?? DEFAULT_MAX_IDS_PER_ENTITY);
|
|
280
|
+
const over = checkIdsPerEntity(payload.requests, maxIds);
|
|
281
|
+
if (over !== void 0) return yield* new RemoteReadError({ message: `Too many "${over}" ids in one read batch` });
|
|
282
|
+
let pending = payload.requests;
|
|
283
|
+
for (let depth = 0; pending.length > 0; depth++) {
|
|
284
|
+
if (depth > maxDepth) return yield* new RemoteReadError({ message: `Nested selection deeper than ${maxDepth} relation levels` });
|
|
285
|
+
const next = [];
|
|
286
|
+
/**
|
|
287
|
+
* Follows each relation's refs in `values` into the next level, asking
|
|
288
|
+
* only for fields this batch has not read of the target; a target read
|
|
289
|
+
* in full already is followed further from its fetched values.
|
|
290
|
+
*/
|
|
291
|
+
const follow = (values, relations) => {
|
|
292
|
+
for (const [field, relation] of Object.entries(relations)) {
|
|
293
|
+
if (!Object.hasOwn(values, field)) continue;
|
|
294
|
+
for (const ref of refsIn(values[field])) {
|
|
295
|
+
if (ref.entity !== relation.entity) continue;
|
|
296
|
+
const key = `${relation.entity}:${ref.id}`;
|
|
297
|
+
const read = fetched.get(key);
|
|
298
|
+
const fields = relation.fields.filter((name) => read?.has(name) !== true);
|
|
299
|
+
if (fields.length > 0) next.push({
|
|
300
|
+
entity: relation.entity,
|
|
301
|
+
id: ref.id,
|
|
302
|
+
fields,
|
|
303
|
+
...relation.windows === void 0 ? {} : { windows: relation.windows },
|
|
304
|
+
...relation.relations === void 0 ? {} : { relations: relation.relations }
|
|
305
|
+
});
|
|
306
|
+
else if (relation.relations !== void 0) follow(fetchedValues.get(key) ?? {}, relation.relations);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
};
|
|
310
|
+
for (const { ids, slice } of groupByEntity(pending)) {
|
|
311
|
+
const name = slice.entity;
|
|
312
|
+
const source = server.entities.get(name);
|
|
313
|
+
if (source === void 0) continue;
|
|
314
|
+
const allowed = allowedFields(source, principal, slice.fields);
|
|
315
|
+
if (allowed.length === 0) continue;
|
|
316
|
+
const windows = windowsOf(slice.windows, allowed);
|
|
317
|
+
const idList = [...ids];
|
|
318
|
+
const records = [];
|
|
319
|
+
for (let start = 0; start < idList.length; start += maxIds) records.push(...yield* source.read({
|
|
320
|
+
ids: idList.slice(start, start + maxIds),
|
|
321
|
+
fields: allowed,
|
|
322
|
+
principal,
|
|
323
|
+
...windows
|
|
324
|
+
}).pipe(Effect.catchTag("RemoteServerError", (error) => Effect.fail(new RemoteReadError({ message: error.message })))));
|
|
325
|
+
for (const record of records) {
|
|
326
|
+
const values = Object.create(null);
|
|
327
|
+
for (const field of allowed) if (Object.hasOwn(record.values, field)) values[field] = record.values[field];
|
|
328
|
+
entities.push({
|
|
329
|
+
entity: name,
|
|
330
|
+
id: record.id,
|
|
331
|
+
values
|
|
332
|
+
});
|
|
333
|
+
const key = `${name}:${record.id}`;
|
|
334
|
+
const known = fetched.get(key) ?? /* @__PURE__ */ new Set();
|
|
335
|
+
for (const field of allowed) known.add(field);
|
|
336
|
+
fetched.set(key, known);
|
|
337
|
+
fetchedValues.set(key, {
|
|
338
|
+
...fetchedValues.get(key),
|
|
339
|
+
...values
|
|
340
|
+
});
|
|
341
|
+
follow(values, slice.relations ?? {});
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
pending = next.flatMap((request) => {
|
|
345
|
+
const read = fetched.get(`${request.entity}:${request.id}`);
|
|
346
|
+
const fields = request.fields.filter((field) => read?.has(field) !== true);
|
|
347
|
+
return fields.length === 0 ? [] : [{
|
|
348
|
+
...request,
|
|
349
|
+
fields
|
|
350
|
+
}];
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
return { entities };
|
|
354
|
+
}),
|
|
355
|
+
FoldkitRemoteMutate: Effect.fn("RemoteServer.FoldkitRemoteMutate")(function* (payload) {
|
|
356
|
+
const source = server.mutations.get(payload.mutation);
|
|
357
|
+
if (source === void 0) return yield* new RemoteMutationError({ message: `Unknown mutation: ${payload.mutation}` });
|
|
358
|
+
const input = yield* Schema.decodeUnknownEffect(source.Input)(payload.input).pipe(Effect.catchTag("SchemaError", () => Effect.fail(new RemoteMutationError({ message: "Invalid mutation input" }))));
|
|
359
|
+
const outcome = yield* source.run({
|
|
360
|
+
input,
|
|
361
|
+
principal
|
|
362
|
+
}).pipe(Effect.catchTag("RemoteServerError", (error) => Effect.fail(new RemoteMutationError({ message: error.message }))));
|
|
363
|
+
return {
|
|
364
|
+
output: yield* Schema.encodeUnknownEffect(source.Output)(outcome.output).pipe(Effect.catchTag("SchemaError", () => Effect.fail(new RemoteMutationError({ message: "Invalid mutation output" })))),
|
|
365
|
+
entities: outcome.entities.map((patch) => ({
|
|
366
|
+
entity: patch.entity,
|
|
367
|
+
id: patch.id,
|
|
368
|
+
values: patch.values
|
|
369
|
+
})),
|
|
370
|
+
connections: outcome.connections
|
|
371
|
+
};
|
|
372
|
+
}),
|
|
373
|
+
FoldkitRemoteQuery: Effect.fn("RemoteServer.FoldkitRemoteQuery")(function* (payload) {
|
|
374
|
+
const source = server.queries.get(payload.query);
|
|
375
|
+
if (source === void 0) return yield* new RemoteQueryError({ message: `Unknown query: ${payload.query}` });
|
|
376
|
+
const input = yield* Schema.decodeUnknownEffect(source.Input)(payload.input).pipe(Effect.catchTag("SchemaError", () => Effect.fail(new RemoteQueryError({ message: "Invalid query input" }))));
|
|
377
|
+
const page = yield* source.run({
|
|
378
|
+
input,
|
|
379
|
+
window: payload.window,
|
|
380
|
+
principal
|
|
381
|
+
}).pipe(Effect.catchTag("RemoteServerError", (error) => Effect.fail(new RemoteQueryError({ message: error.message }))));
|
|
382
|
+
return {
|
|
383
|
+
edges: page.edges,
|
|
384
|
+
start: page.start,
|
|
385
|
+
end: page.end
|
|
386
|
+
};
|
|
387
|
+
}),
|
|
388
|
+
FoldkitRemoteLive: (payload) => {
|
|
389
|
+
const mismatch = protocolMismatch(payload.version);
|
|
390
|
+
if (mismatch !== void 0) return Stream.fail(mismatch);
|
|
391
|
+
const streams = [...new Set(payload.requirements.map((request) => request.entity))].flatMap((entity) => {
|
|
392
|
+
const source = server.live.get(entity);
|
|
393
|
+
if (source === void 0) return [];
|
|
394
|
+
return [source.subscribe({
|
|
395
|
+
requirements: payload.requirements.filter((request) => request.entity === entity),
|
|
396
|
+
after: payload.after,
|
|
397
|
+
principal
|
|
398
|
+
})];
|
|
399
|
+
});
|
|
400
|
+
if (options.live !== void 0) streams.push(options.live.subscribe({
|
|
401
|
+
requirements: payload.requirements,
|
|
402
|
+
after: payload.after,
|
|
403
|
+
principal,
|
|
404
|
+
maxIdsPerEntity: options.maxIdsPerEntity
|
|
405
|
+
}));
|
|
406
|
+
return Stream.mergeAll(streams, { concurrency: "unbounded" }).pipe(Stream.mapError((error) => new RemoteLiveError({ message: error.message })));
|
|
407
|
+
}
|
|
408
|
+
})
|
|
409
|
+
};
|
|
410
|
+
//#endregion
|
|
411
|
+
export { RemoteServer, RemoteServerError };
|
|
412
|
+
|
|
413
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * `foldkit-remote-server` — server-side Sources and handler compilation.\n *\n * Owns entity/query Sources, **selection authorization**, normalization, and\n * turning them into Effect RPC handlers. It does not own HTTP, serialization, or\n * auth protocol; `principal` is resolved outside and passed in.\n */\nimport { Effect, Queue, Schema, Stream } from 'effect'\nimport {\n REMOTE_PROTOCOL_VERSION,\n RemoteLiveError,\n RemoteMutationError,\n RemoteProtocolError,\n RemoteQueryError,\n RemoteReadError,\n connectionIdentity,\n entityKey,\n refsIn,\n stableStringify,\n type Boundary,\n type ConnectionChangeSchema,\n type ConnectionIdentity,\n type LiveChange,\n type MutationDescriptor,\n type NormalizedPatch,\n type QueryDescriptor,\n type QueryWindow,\n type RelationRequirement,\n type RemoteDescriptor,\n type RemoteRpcClient,\n} from 'foldkit-remote'\nimport { Requirement } from 'foldkit-surface'\n\nexport class RemoteServerError extends Schema.TaggedError<RemoteServerError>()(\n 'RemoteServerError',\n {\n message: Schema.String,\n },\n) {}\n\nexport interface EntityRecord {\n readonly id: string\n readonly values: Readonly<Record<string, unknown>>\n}\n\nexport interface EntitySourceContext<P> {\n readonly ids: readonly string[]\n readonly fields: readonly string[]\n /** A pagination window per requested relation field. */\n readonly windows?: Readonly<Record<string, QueryWindow>> | undefined\n readonly principal: P\n}\n\nexport interface EntitySource<P, R = never> {\n readonly entity: string\n /** The fields the entity declares; a request for any other never reaches `read`. */\n readonly fields?: ReadonlySet<string> | undefined\n readonly read: (\n context: EntitySourceContext<P>,\n ) => Effect.Effect<ReadonlyArray<EntityRecord>, RemoteServerError, R>\n /** Returns the fields this principal may read; omitted means all requested. */\n readonly authorize?: (principal: P, fields: readonly string[]) => readonly string[]\n}\n\n/** A connection change a mutation made, as the wire carries it. */\nexport type ConnectionChange = Schema.Schema.Type<typeof ConnectionChangeSchema>\n\nconst connectionChange = (\n connection: ConnectionIdentity,\n ref: { readonly entity: string; readonly id: string },\n position: 'prepend' | 'append' | 'remove',\n): ConnectionChange => {\n const edge = { entity: ref.entity, id: ref.id, key: entityKey(ref.entity, ref.id) }\n return position === 'remove'\n ? { _tag: 'Remove', connection: connectionIdentity(connection), edge }\n : { _tag: 'Insert', connection: connectionIdentity(connection), position, edge }\n}\n\n/**\n * The requested fields, in request order, that the source declares and the\n * principal may read. Never a field the client did not request, even if a\n * permissive `authorize` returns more.\n */\nconst allowedFields = <P, R>(\n source: EntitySource<P, R>,\n principal: P,\n requested: ReadonlyArray<string>,\n): ReadonlyArray<string> => {\n const declared =\n source.fields === undefined ? requested : requested.filter(field => source.fields!.has(field))\n if (declared.length === 0) return []\n const permitted = new Set(\n source.authorize === undefined ? declared : source.authorize(principal, declared),\n )\n return declared.filter(field => permitted.has(field))\n}\n\n/** The windows of the fields being read; only a field being read carries its window. */\nconst windowsOf = (\n windows: Readonly<Record<string, QueryWindow>> | undefined,\n fields: ReadonlyArray<string>,\n): { readonly windows?: Readonly<Record<string, QueryWindow>> } => {\n if (windows === undefined) return {}\n const kept = Object.fromEntries(\n fields.flatMap(field =>\n Object.hasOwn(windows, field) ? [[field, windows[field]!] as const] : [],\n ),\n )\n return Object.keys(kept).length === 0 ? {} : { windows: kept }\n}\n\nexport interface MutationOutcome<Output> {\n readonly output: Output\n readonly entities?: ReadonlyArray<NormalizedPatch>\n /** Connection changes the mutation made; the client settles them with its patches. */\n readonly connections?: ReadonlyArray<ConnectionChange>\n}\n\nexport interface MutationSource<P, R = never> {\n readonly mutation: string\n readonly Input: Schema.Codec<unknown>\n readonly Output: Schema.Codec<unknown>\n readonly run: (context: { readonly input: unknown; readonly principal: P }) => Effect.Effect<\n {\n readonly output: unknown\n readonly entities: ReadonlyArray<NormalizedPatch>\n readonly connections: ReadonlyArray<ConnectionChange>\n },\n RemoteServerError,\n R\n >\n}\n\nexport interface QueryPage {\n readonly edges: ReadonlyArray<{\n readonly entity: string\n readonly id: string\n readonly key: string\n }>\n readonly start: Boundary\n readonly end: Boundary\n}\n\nexport interface QuerySource<P, R = never> {\n readonly query: string\n readonly Input: Schema.Codec<unknown>\n readonly run: (context: {\n readonly input: unknown\n readonly window: QueryWindow\n readonly principal: P\n }) => Effect.Effect<QueryPage, RemoteServerError, R>\n}\n\nexport interface LiveSource<P, R = never> {\n readonly entity: string\n readonly subscribe: (context: {\n readonly requirements: ReadonlyArray<Requirement>\n readonly after: number\n readonly principal: P\n }) => Stream.Stream<Schema.Schema.Type<typeof LiveChange>, RemoteServerError, R>\n}\n\nexport interface ServerDefinition<P, R = never> {\n readonly entities: ReadonlyMap<string, EntitySource<P, R>>\n readonly mutations: ReadonlyMap<string, MutationSource<P, R>>\n readonly queries: ReadonlyMap<string, QuerySource<P, R>>\n readonly live: ReadonlyMap<string, LiveSource<P, R>>\n}\n\n/** A read batch may not carry more than this many distinct ids per entity. */\nconst DEFAULT_MAX_IDS_PER_ENTITY = 1000\n\n/** A nested selection may not reach further than this many relation levels. */\nconst DEFAULT_MAX_DEPTH = 8\n\nexport interface HandlerOptions<P, R = never> {\n /** A read or live subscription may not name more ids of one entity than this; default 1000. */\n readonly maxIdsPerEntity?: number | undefined\n /** A nested selection may not reach further than this many relation levels; default 8. */\n readonly maxDepth?: number | undefined\n /** A hub whose `changed`/`deleted` signals reach the subscribers this handler registers. */\n readonly live?: LiveHub<P, R> | undefined\n}\n\n/** Fails when the requirements name more distinct ids of one entity than `maxIds`. */\nconst checkIdsPerEntity = (\n requirements: ReadonlyArray<Requirement>,\n maxIds: number,\n): string | undefined => {\n const ids = new Map<string, Set<string>>()\n for (const requirement of requirements) {\n const seen = ids.get(requirement.entity) ?? new Set<string>()\n seen.add(requirement.id)\n ids.set(requirement.entity, seen)\n if (seen.size > maxIds) return requirement.entity\n }\n return undefined\n}\n\ntype LiveChangeValue = Schema.Schema.Type<typeof LiveChange>\ntype Uncursored<T> = T extends unknown ? Omit<T, 'cursor'> : never\n\ninterface LiveRef {\n readonly entity: string\n readonly id: string\n}\n\n/**\n * The server-side \"these fields changed\" signal. A hub tracks each live\n * subscriber's requirements (entity, id, fields) and principal; `changed`\n * re-reads the changed fields a subscriber selects through the entity's own\n * source, under that subscriber's principal, and streams the patch to it.\n * Subscribers that select none of the changed fields do no work. Cursors\n * continue from the cursor each subscriber resumed at, so the client's\n * duplicate and gap handling is unchanged.\n */\nexport interface LiveHub<P, R = never> {\n readonly changed: (\n ref: LiveRef,\n fields: ReadonlyArray<string>,\n ) => Effect.Effect<void, RemoteServerError, R>\n readonly deleted: (ref: LiveRef) => Effect.Effect<void>\n /** Registers a subscriber for the stream's lifetime; `handlers` calls this. */\n readonly subscribe: (context: {\n readonly requirements: ReadonlyArray<Requirement>\n readonly after: number\n readonly principal: P\n /** Refuses a subscription naming more ids of one entity than this. */\n readonly maxIdsPerEntity?: number | undefined\n }) => Stream.Stream<LiveChangeValue, RemoteServerError>\n /** How many subscribers are registered now. */\n readonly size: Effect.Effect<number>\n}\n\ninterface Selected {\n readonly fields: Set<string>\n /** The window each paged field was subscribed with, so a re-read pages the same way. */\n readonly windows: Map<string, QueryWindow>\n}\n\n/** The subscribers one source read answers, and the fields each wants of it. */\ninterface ReadGroup<P> {\n readonly windows: Readonly<Record<string, QueryWindow>>\n readonly entries: Array<{ readonly subscriber: Subscriber<P>; readonly fields: string[] }>\n}\n\ninterface Subscriber<P> {\n /** Per entity:id, the fields (and their windows) this subscriber selects. */\n readonly selected: ReadonlyMap<string, Selected>\n readonly principal: P\n readonly queue: Queue.Queue<LiveChangeValue>\n cursor: number\n}\n\nconst liveHub = <P, R>(entities: ReadonlyArray<EntitySource<P, R>>): Effect.Effect<LiveHub<P, R>> =>\n Effect.sync(() => {\n const sources = new Map(entities.map(source => [source.entity, source]))\n const subscribers = new Set<Subscriber<P>>()\n const emit = (subscriber: Subscriber<P>, change: Uncursored<LiveChangeValue>) => {\n subscriber.cursor += 1\n return Queue.offer(subscriber.queue, {\n ...change,\n cursor: subscriber.cursor,\n } as LiveChangeValue)\n }\n\n return {\n subscribe: ({ requirements, after, principal, maxIdsPerEntity }) =>\n Stream.unwrap(\n Effect.gen(function* () {\n const over = checkIdsPerEntity(\n requirements,\n Math.max(1, maxIdsPerEntity ?? DEFAULT_MAX_IDS_PER_ENTITY),\n )\n if (over !== undefined) {\n return yield* new RemoteServerError({\n message: `Too many \"${over}\" ids in one live subscription`,\n })\n }\n const selected = new Map<string, Selected>()\n for (const requirement of requirements) {\n const key = `${requirement.entity}:${requirement.id}`\n const entry = selected.get(key) ?? { fields: new Set<string>(), windows: new Map() }\n for (const field of requirement.fields) entry.fields.add(field)\n for (const [field, window] of Object.entries(requirement.windows ?? {})) {\n entry.windows.set(field, window)\n }\n selected.set(key, entry)\n }\n const subscriber: Subscriber<P> = {\n selected,\n principal,\n queue: yield* Queue.unbounded<LiveChangeValue>(),\n cursor: after,\n }\n subscribers.add(subscriber)\n return Stream.fromQueue(subscriber.queue).pipe(\n Stream.ensuring(Effect.sync(() => void subscribers.delete(subscriber))),\n )\n }),\n ),\n\n changed: (ref, fields) =>\n Effect.gen(function* () {\n const key = `${ref.entity}:${ref.id}`\n const source = sources.get(ref.entity)\n if (source === undefined) return\n // One source read per principal (by identity) and window signature:\n // subscribers sharing both share the read, and a paged field is\n // re-read with the window the subscriber selected it with.\n const groups = new Map<P, Map<string, ReadGroup<P>>>()\n for (const subscriber of subscribers) {\n const selected = subscriber.selected.get(key)\n if (selected === undefined) continue\n const wanted = fields.filter(field => selected.fields.has(field))\n if (wanted.length === 0) continue\n const windows = Object.fromEntries(\n wanted.flatMap(field => {\n const window = selected.windows.get(field)\n return window === undefined ? [] : [[field, window] as const]\n }),\n )\n const byWindows = groups.get(subscriber.principal) ?? new Map<string, ReadGroup<P>>()\n groups.set(subscriber.principal, byWindows)\n const windowKey = stableStringify(windows)\n const group = byWindows.get(windowKey) ?? { windows, entries: [] }\n byWindows.set(windowKey, group)\n group.entries.push({ subscriber, fields: wanted })\n }\n for (const [principal, byWindows] of groups) {\n for (const { windows, entries: group } of byWindows.values()) {\n const requested = [...new Set(group.flatMap(entry => entry.fields))]\n const allowed = allowedFields(source, principal, requested)\n if (allowed.length === 0) continue\n const allowedSet = new Set(allowed)\n const records = yield* source.read({\n ids: [ref.id],\n fields: allowed,\n principal,\n ...windowsOf(windows, allowed),\n })\n const record = records.find(candidate => candidate.id === ref.id)\n if (record === undefined) continue\n for (const { subscriber, fields: wanted } of group) {\n const values: Record<string, unknown> = Object.create(null)\n for (const field of wanted) {\n if (allowedSet.has(field) && Object.hasOwn(record.values, field)) {\n values[field] = record.values[field]\n }\n }\n const changed = Object.keys(values)\n if (changed.length === 0) continue\n yield* emit(subscriber, {\n _tag: 'EntityPatched',\n entity: ref.entity,\n id: ref.id,\n values,\n changed,\n })\n }\n }\n }\n }),\n\n deleted: ref =>\n Effect.gen(function* () {\n const key = `${ref.entity}:${ref.id}`\n for (const subscriber of subscribers) {\n if (!subscriber.selected.has(key)) continue\n yield* emit(subscriber, { _tag: 'EntityDeleted', entity: ref.entity, id: ref.id })\n }\n }),\n\n size: Effect.sync(() => subscribers.size),\n }\n })\n\nconst protocolMismatch = (received: number): RemoteProtocolError | undefined =>\n received === REMOTE_PROTOCOL_VERSION\n ? undefined\n : new RemoteProtocolError({\n message: `Remote protocol version ${received} is not ${REMOTE_PROTOCOL_VERSION}`,\n expected: REMOTE_PROTOCOL_VERSION,\n received,\n })\n\ninterface EntityGroup {\n readonly ids: Set<string>\n /** The union of the requests' fields, windows, and relations. */\n slice: RelationRequirement\n}\n\n/**\n * One level's requests grouped per entity and window signature: ids and\n * slices unioned. Requests that page a relation differently are separate\n * groups, so one window never answers for another id.\n */\nconst groupByEntity = (requests: ReadonlyArray<Requirement>): EntityGroup[] => {\n const grouped = new Map<string, EntityGroup>()\n for (const request of requests) {\n const groupKey = `${request.entity}\\u0000${stableStringify(request.windows ?? null)}`\n const group = grouped.get(groupKey)\n if (group === undefined) {\n grouped.set(groupKey, {\n ids: new Set([request.id]),\n slice: Requirement.mergeRelation({ entity: request.entity, fields: [] }, request),\n })\n } else {\n group.ids.add(request.id)\n group.slice = Requirement.mergeRelation(group.slice, request)\n }\n }\n return [...grouped.values()]\n}\n\n/** A descriptor's name and, when it declares them, its fields. */\ninterface EntityName {\n readonly name: string\n readonly fields?: Readonly<Record<string, unknown>> | undefined\n}\n\nexport const RemoteServer = {\n /** A mutation outcome's report that `ref` now heads the connection. */\n prepend: (\n connection: ConnectionIdentity,\n ref: { readonly entity: string; readonly id: string },\n ): ConnectionChange => connectionChange(connection, ref, 'prepend'),\n\n /** A mutation outcome's report that `ref` now ends the connection. */\n append: (\n connection: ConnectionIdentity,\n ref: { readonly entity: string; readonly id: string },\n ): ConnectionChange => connectionChange(connection, ref, 'append'),\n\n /** A mutation outcome's report that `ref` left the connection. */\n remove: (\n connection: ConnectionIdentity,\n ref: { readonly entity: string; readonly id: string },\n ): ConnectionChange => connectionChange(connection, ref, 'remove'),\n\n /**\n * An entity source. Given the Entity (or anything with its `name` and\n * `fields`), a request for a field the entity does not declare never\n * reaches `read` or `authorize`.\n */\n entity: <P = unknown, R = never>(\n entity: EntityName,\n options: {\n readonly read: EntitySource<P, R>['read']\n readonly authorize?: EntitySource<P, R>['authorize']\n },\n ): EntitySource<P, R> => ({\n entity: entity.name,\n ...(entity.fields === undefined ? {} : { fields: new Set(Object.keys(entity.fields)) }),\n read: options.read,\n ...(options.authorize === undefined ? {} : { authorize: options.authorize }),\n }),\n\n mutation: <\n P = unknown,\n R = never,\n Name extends string = string,\n Input = unknown,\n Output = unknown,\n >(\n mutation: MutationDescriptor<Name, Input, Output>,\n run: (context: {\n readonly input: Input\n readonly principal: P\n }) => Effect.Effect<MutationOutcome<Output>, RemoteServerError, R>,\n ): MutationSource<P, R> => ({\n mutation: mutation.name,\n Input: mutation.Input,\n Output: mutation.Output,\n run: context =>\n run({ input: context.input as Input, principal: context.principal }).pipe(\n Effect.map(outcome => ({\n output: outcome.output,\n entities: outcome.entities ?? [],\n connections: outcome.connections ?? [],\n })),\n ),\n }),\n\n query: <P = unknown, R = never, Input = unknown>(\n query: QueryDescriptor<string, Input, unknown>,\n run: (context: {\n readonly input: Input\n readonly window: QueryWindow\n readonly principal: P\n }) => Effect.Effect<QueryPage, RemoteServerError, R>,\n ): QuerySource<P, R> => ({\n query: query.name,\n Input: query.Input,\n run: context =>\n run({ input: context.input as Input, window: context.window, principal: context.principal }),\n }),\n\n /** Streams live entity patches for a client's live requirements. */\n live: <P = unknown, R = never>(\n entity: EntityName,\n options: { readonly subscribe: LiveSource<P, R>['subscribe'] },\n ): LiveSource<P, R> => ({\n entity: entity.name,\n subscribe: options.subscribe,\n }),\n\n /**\n * A `LiveHub` over entity sources. Pass it to `handlers` as `live`, then\n * call `hub.changed(ref, fields)` from wherever the data changes (a mutation\n * source, a database trigger); each subscriber that selects any of those\n * fields receives them, re-read through the entity source under its own\n * principal. It needs only the entity sources, so the mutation sources that\n * signal it can be built after it.\n */\n liveHub,\n\n make: <P = unknown, R = never>(config: {\n readonly entities: readonly EntitySource<P, R>[]\n readonly mutations?: readonly MutationSource<P, R>[]\n readonly queries?: readonly QuerySource<P, R>[]\n readonly live?: readonly LiveSource<P, R>[]\n }): ServerDefinition<P, R> => ({\n entities: new Map(config.entities.map(source => [source.entity, source])),\n mutations: new Map((config.mutations ?? []).map(source => [source.mutation, source])),\n queries: new Map((config.queries ?? []).map(source => [source.query, source])),\n live: new Map((config.live ?? []).map(source => [source.entity, source])),\n }),\n\n /**\n * Checks every source name against the declared domain, so an undeclared\n * entity/query/mutation fails at startup rather than returning nothing at\n * call time.\n */\n validate: (domain: RemoteDescriptor, server: ServerDefinition<any, any>): void => {\n const assertDeclared = (\n kind: string,\n declared: ReadonlyMap<string, unknown>,\n names: Iterable<string>,\n ): void => {\n for (const name of names) {\n if (!declared.has(name))\n throw new Error(`RemoteServer: ${kind} \"${name}\" is not declared in the Remote domain`)\n }\n }\n assertDeclared('entity', domain.registry.entities, server.entities.keys())\n assertDeclared('query', domain.registry.queries, server.queries.keys())\n assertDeclared('mutation', domain.registry.mutations, server.mutations.keys())\n },\n\n /**\n * Compiles the server into the `Read`/`Mutate` RPC handlers. `principal` is\n * resolved outside (authentication middleware in a later phase); unknown\n * entities, entities with no allowed fields, and unknown mutations return an\n * error or nothing rather than leaking existence.\n */\n handlers: <P, R>(\n server: ServerDefinition<P, R>,\n principal: P,\n options: HandlerOptions<P, R> = {},\n ): RemoteRpcClient<R> => ({\n FoldkitRemoteRead: Effect.fn('RemoteServer.FoldkitRemoteRead')(function* (payload) {\n const mismatch = protocolMismatch(payload.version)\n if (mismatch !== undefined) return yield* mismatch\n\n const entities: Array<{\n readonly entity: string\n readonly id: string\n readonly values: Record<string, unknown>\n }> = []\n // What this batch has already read per entity:id (fields and values), so\n // a target several relations share is fetched once, a later spec's nested\n // relation is followed from the values already in hand, and a cyclic\n // selection stays finite.\n const fetched = new Map<string, Set<string>>()\n const fetchedValues = new Map<string, Record<string, unknown>>()\n const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH\n const maxIds = Math.max(1, options.maxIdsPerEntity ?? DEFAULT_MAX_IDS_PER_ENTITY)\n\n // The limit guards the client's batch, whatever windows split it into;\n // a nested level's fan-out is the server's own doing, so it is chunked\n // rather than refused.\n const over = checkIdsPerEntity(payload.requests, maxIds)\n if (over !== undefined) {\n return yield* new RemoteReadError({ message: `Too many \"${over}\" ids in one read batch` })\n }\n\n // Level by level: a level's relation refs become the next level's requests.\n let pending: ReadonlyArray<Requirement> = payload.requests\n for (let depth = 0; pending.length > 0; depth++) {\n if (depth > maxDepth) {\n return yield* new RemoteReadError({\n message: `Nested selection deeper than ${maxDepth} relation levels`,\n })\n }\n const next: Requirement[] = []\n\n /**\n * Follows each relation's refs in `values` into the next level, asking\n * only for fields this batch has not read of the target; a target read\n * in full already is followed further from its fetched values.\n */\n const follow = (\n values: Record<string, unknown>,\n relations: Readonly<Record<string, RelationRequirement>>,\n ): void => {\n for (const [field, relation] of Object.entries(relations)) {\n if (!Object.hasOwn(values, field)) continue\n for (const ref of refsIn(values[field])) {\n if (ref.entity !== relation.entity) continue\n const key = `${relation.entity}:${ref.id}`\n const read = fetched.get(key)\n const fields = relation.fields.filter(name => read?.has(name) !== true)\n if (fields.length > 0) {\n next.push({\n entity: relation.entity,\n id: ref.id,\n fields,\n ...(relation.windows === undefined ? {} : { windows: relation.windows }),\n ...(relation.relations === undefined ? {} : { relations: relation.relations }),\n })\n } else if (relation.relations !== undefined) {\n follow(fetchedValues.get(key) ?? {}, relation.relations)\n }\n }\n }\n }\n\n for (const { ids, slice } of groupByEntity(pending)) {\n const name = slice.entity\n const source = server.entities.get(name)\n if (source === undefined) continue\n const allowed = allowedFields(source, principal, slice.fields)\n if (allowed.length === 0) continue\n\n const windows = windowsOf(slice.windows, allowed)\n const idList = [...ids]\n const records: EntityRecord[] = []\n for (let start = 0; start < idList.length; start += maxIds) {\n records.push(\n ...(yield* source\n .read({\n ids: idList.slice(start, start + maxIds),\n fields: allowed,\n principal,\n ...windows,\n })\n .pipe(\n Effect.catchTag('RemoteServerError', error =>\n Effect.fail(new RemoteReadError({ message: error.message })),\n ),\n )),\n )\n }\n\n for (const record of records) {\n // Null-prototype so a crafted field name (`__proto__`) cannot reach\n // the prototype, and `Object.hasOwn` so inherited names are ignored.\n const values: Record<string, unknown> = Object.create(null)\n for (const field of allowed) {\n if (Object.hasOwn(record.values, field)) values[field] = record.values[field]\n }\n entities.push({ entity: name, id: record.id, values })\n\n const key = `${name}:${record.id}`\n const known = fetched.get(key) ?? new Set<string>()\n for (const field of allowed) known.add(field)\n fetched.set(key, known)\n fetchedValues.set(key, { ...fetchedValues.get(key), ...values })\n\n // `values` holds only allowed fields, so a relation the principal\n // may not read is never followed.\n follow(values, slice.relations ?? {})\n }\n }\n // A target read by this level (as another group's request) is not\n // read again by the next.\n pending = next.flatMap(request => {\n const read = fetched.get(`${request.entity}:${request.id}`)\n const fields = request.fields.filter(field => read?.has(field) !== true)\n return fields.length === 0 ? [] : [{ ...request, fields }]\n })\n }\n\n return { entities }\n }),\n\n FoldkitRemoteMutate: Effect.fn('RemoteServer.FoldkitRemoteMutate')(function* (payload) {\n const source = server.mutations.get(payload.mutation)\n if (source === undefined) {\n return yield* new RemoteMutationError({\n message: `Unknown mutation: ${payload.mutation}`,\n })\n }\n\n const input = yield* Schema.decodeUnknownEffect(source.Input)(payload.input).pipe(\n Effect.catchTag('SchemaError', () =>\n Effect.fail(new RemoteMutationError({ message: 'Invalid mutation input' })),\n ),\n )\n\n const outcome = yield* source\n .run({ input, principal })\n .pipe(\n Effect.catchTag('RemoteServerError', error =>\n Effect.fail(new RemoteMutationError({ message: error.message })),\n ),\n )\n\n const output = yield* Schema.encodeUnknownEffect(source.Output)(outcome.output).pipe(\n Effect.catchTag('SchemaError', () =>\n Effect.fail(new RemoteMutationError({ message: 'Invalid mutation output' })),\n ),\n )\n\n return {\n output,\n entities: outcome.entities.map(patch => ({\n entity: patch.entity,\n id: patch.id,\n values: patch.values,\n })),\n connections: outcome.connections,\n }\n }),\n\n FoldkitRemoteQuery: Effect.fn('RemoteServer.FoldkitRemoteQuery')(function* (payload) {\n const source = server.queries.get(payload.query)\n if (source === undefined) {\n return yield* new RemoteQueryError({ message: `Unknown query: ${payload.query}` })\n }\n\n const input = yield* Schema.decodeUnknownEffect(source.Input)(payload.input).pipe(\n Effect.catchTag('SchemaError', () =>\n Effect.fail(new RemoteQueryError({ message: 'Invalid query input' })),\n ),\n )\n\n const page = yield* source\n .run({ input, window: payload.window, principal })\n .pipe(\n Effect.catchTag('RemoteServerError', error =>\n Effect.fail(new RemoteQueryError({ message: error.message })),\n ),\n )\n\n return { edges: page.edges, start: page.start, end: page.end }\n }),\n\n FoldkitRemoteLive: payload => {\n const mismatch = protocolMismatch(payload.version)\n if (mismatch !== undefined) return Stream.fail(mismatch)\n const entities = [...new Set(payload.requirements.map(request => request.entity))]\n const streams: Array<Stream.Stream<LiveChangeValue, RemoteServerError, R>> = entities.flatMap(\n entity => {\n const source = server.live.get(entity)\n if (source === undefined) return []\n return [\n source.subscribe({\n requirements: payload.requirements.filter(request => request.entity === entity),\n after: payload.after,\n principal,\n }),\n ]\n },\n )\n if (options.live !== undefined) {\n streams.push(\n options.live.subscribe({\n requirements: payload.requirements,\n after: payload.after,\n principal,\n maxIdsPerEntity: options.maxIdsPerEntity,\n }),\n )\n }\n // An entity with no live source simply contributes nothing; the client's\n // planner refetches it rather than the stream failing.\n return Stream.mergeAll(streams, { concurrency: 'unbounded' }).pipe(\n Stream.mapError(error => new RemoteLiveError({ message: error.message })),\n )\n },\n }),\n}\n"],"mappings":";;;;;;;;;;;AAiCA,IAAa,oBAAb,cAAuC,OAAO,YAA+B,CAAC,CAC5E,qBACA,EACE,SAAS,OAAO,OAClB,CACF,CAAC,CAAC,CAAC;AA6BH,MAAM,oBACJ,YACA,KACA,aACqB;CACrB,MAAM,OAAO;EAAE,QAAQ,IAAI;EAAQ,IAAI,IAAI;EAAI,KAAK,UAAU,IAAI,QAAQ,IAAI,EAAE;CAAE;CAClF,OAAO,aAAa,WAChB;EAAE,MAAM;EAAU,YAAY,mBAAmB,UAAU;EAAG;CAAK,IACnE;EAAE,MAAM;EAAU,YAAY,mBAAmB,UAAU;EAAG;EAAU;CAAK;AACnF;;;;;;AAOA,MAAM,iBACJ,QACA,WACA,cAC0B;CAC1B,MAAM,WACJ,OAAO,WAAW,KAAA,IAAY,YAAY,UAAU,QAAO,UAAS,OAAO,OAAQ,IAAI,KAAK,CAAC;CAC/F,IAAI,SAAS,WAAW,GAAG,OAAO,CAAC;CACnC,MAAM,YAAY,IAAI,IACpB,OAAO,cAAc,KAAA,IAAY,WAAW,OAAO,UAAU,WAAW,QAAQ,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;GAEvD,MAAM,UAAuE,CAD3D,GAAG,IAAI,IAAI,QAAQ,aAAa,KAAI,YAAW,QAAQ,MAAM,CAAC,CACI,CAAC,CAAC,SACpF,WAAU;IACR,MAAM,SAAS,OAAO,KAAK,IAAI,MAAM;IACrC,IAAI,WAAW,KAAA,GAAW,OAAO,CAAC;IAClC,OAAO,CACL,OAAO,UAAU;KACf,cAAc,QAAQ,aAAa,QAAO,YAAW,QAAQ,WAAW,MAAM;KAC9E,OAAO,QAAQ;KACf;IACF,CAAC,CACH;GACF,CACF;GACA,IAAI,QAAQ,SAAS,KAAA,GACnB,QAAQ,KACN,QAAQ,KAAK,UAAU;IACrB,cAAc,QAAQ;IACtB,OAAO,QAAQ;IACf;IACA,iBAAiB,QAAQ;GAC3B,CAAC,CACH;GAIF,OAAO,OAAO,SAAS,SAAS,EAAE,aAAa,YAAY,CAAC,CAAC,CAAC,KAC5D,OAAO,UAAS,UAAS,IAAI,gBAAgB,EAAE,SAAS,MAAM,QAAQ,CAAC,CAAC,CAC1E;EACF;CACF;AACF"}
|
package/package.json
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "foldkit-remote-server",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Server sources and handler compilation for foldkit-remote: entities, selection authorization, and normalization.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"author": "Patrick Glenn <doeixd@gmail.com>",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/doeixd/foldkit-plus.git",
|
|
11
|
+
"directory": "packages/remote-server"
|
|
12
|
+
},
|
|
13
|
+
"homepage": "https://github.com/doeixd/foldkit-plus/tree/main/packages/remote-server#readme",
|
|
14
|
+
"bugs": {
|
|
15
|
+
"url": "https://github.com/doeixd/foldkit-plus/issues"
|
|
16
|
+
},
|
|
17
|
+
"sideEffects": false,
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"types": "./dist/index.d.mts",
|
|
21
|
+
"import": "./dist/index.mjs"
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"dist",
|
|
26
|
+
"README.md",
|
|
27
|
+
"LICENSE"
|
|
28
|
+
],
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"foldkit-remote": "0.1.0",
|
|
31
|
+
"foldkit-surface": "0.1.0"
|
|
32
|
+
},
|
|
33
|
+
"peerDependencies": {
|
|
34
|
+
"effect": "^4.0.0-rc.112"
|
|
35
|
+
},
|
|
36
|
+
"devDependencies": {
|
|
37
|
+
"effect": "4.0.0-rc.112",
|
|
38
|
+
"foldkit": "0.158.2",
|
|
39
|
+
"tsdown": "^0.23.0",
|
|
40
|
+
"typescript": "^5.7.2"
|
|
41
|
+
},
|
|
42
|
+
"scripts": {
|
|
43
|
+
"build": "tsdown",
|
|
44
|
+
"typecheck": "tsc -b"
|
|
45
|
+
}
|
|
46
|
+
}
|