foldkit-remote-server 0.20.0 → 0.22.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 +323 -29
- package/dist/fetch.d.mts +62 -5
- package/dist/fetch.d.mts.map +1 -1
- package/dist/fetch.mjs +261 -16
- package/dist/fetch.mjs.map +1 -1
- package/dist/{index-B85UhEfk.d.mts → index-lJvjBBDL.d.mts} +78 -6
- package/dist/index-lJvjBBDL.d.mts.map +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/{src-D8azLxgd.mjs → src-B1JAs_gH.mjs} +57 -7
- package/dist/src-B1JAs_gH.mjs.map +1 -0
- package/package.json +4 -4
- package/dist/index-B85UhEfk.d.mts.map +0 -1
- package/dist/src-D8azLxgd.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -296,6 +296,17 @@ A Query Source answers the ordered connection itself. The client's `select`
|
|
|
296
296
|
travels with the request, and the handlers return the selected fields of the
|
|
297
297
|
page's items with the edges, so one response carries both:
|
|
298
298
|
|
|
299
|
+
<!-- docs-check
|
|
300
|
+
import { type QueryWindow } from 'foldkit-remote'
|
|
301
|
+
import { type QueryPage, type RemoteServerError } from 'foldkit-remote-server'
|
|
302
|
+
|
|
303
|
+
declare const projectsPage: (args: {
|
|
304
|
+
readonly ownerId: string
|
|
305
|
+
readonly window: QueryWindow
|
|
306
|
+
readonly principal: unknown
|
|
307
|
+
}) => Effect.Effect<QueryPage, RemoteServerError>
|
|
308
|
+
-->
|
|
309
|
+
|
|
299
310
|
```ts
|
|
300
311
|
import { Query } from 'foldkit-remote'
|
|
301
312
|
|
|
@@ -310,7 +321,7 @@ const ProjectsByOwnerSource = RemoteServer.query(
|
|
|
310
321
|
({ input, window, principal }) => projectsPage({ ownerId: input.ownerId, window, principal }),
|
|
311
322
|
)
|
|
312
323
|
|
|
313
|
-
const
|
|
324
|
+
const QueryServer = RemoteServer.make({
|
|
314
325
|
entities: [ProjectSource],
|
|
315
326
|
queries: [ProjectsByOwnerSource],
|
|
316
327
|
})
|
|
@@ -351,6 +362,13 @@ A Mutation Source changes server-owned state. It returns the protocol output
|
|
|
351
362
|
plus any normalized entity/connection changes that should settle the client's
|
|
352
363
|
cache immediately:
|
|
353
364
|
|
|
365
|
+
<!-- docs-check
|
|
366
|
+
declare const renameProject: (
|
|
367
|
+
input: { readonly id: string; readonly name: string },
|
|
368
|
+
principal: unknown,
|
|
369
|
+
) => Effect.Effect<{ readonly id: string }, RemoteServerError>
|
|
370
|
+
-->
|
|
371
|
+
|
|
354
372
|
```ts
|
|
355
373
|
import { Effect } from 'effect'
|
|
356
374
|
import { Mutation } from 'foldkit-remote'
|
|
@@ -396,6 +414,12 @@ refuse.
|
|
|
396
414
|
|
|
397
415
|
A Source may additionally return connection changes:
|
|
398
416
|
|
|
417
|
+
<!-- docs-check
|
|
418
|
+
import { type ConnectionIdentity } from 'foldkit-remote'
|
|
419
|
+
declare const connection: ConnectionIdentity
|
|
420
|
+
declare const id: string
|
|
421
|
+
-->
|
|
422
|
+
|
|
399
423
|
```ts
|
|
400
424
|
RemoteServer.prepend(connection, Project.ref(id))
|
|
401
425
|
RemoteServer.append(connection, Project.ref(id))
|
|
@@ -441,6 +465,14 @@ A mutation declared as a `Write` (`Mutation.write`) needs no handler.
|
|
|
441
465
|
keys the client named when it named some, and hands the row's id and new values
|
|
442
466
|
to an `EntityWriter`, which writes them and answers the row as written:
|
|
443
467
|
|
|
468
|
+
<!-- docs-check
|
|
469
|
+
import { type EntityWriter } from 'foldkit-remote-server'
|
|
470
|
+
|
|
471
|
+
declare const EditProject: Parameters<typeof RemoteServer.write>[0]
|
|
472
|
+
declare const writer: (binding: unknown) => EntityWriter<unknown>
|
|
473
|
+
declare const Db: { readonly Project: unknown }
|
|
474
|
+
-->
|
|
475
|
+
|
|
444
476
|
```ts
|
|
445
477
|
// `EditProject` is a Mutation.write; `writer` and the binding `Db` are foldkit-remote-drizzle's.
|
|
446
478
|
RemoteServer.write(EditProject, writer(Db.Project))
|
|
@@ -557,7 +589,7 @@ left out of it, keeping what the patch gave.
|
|
|
557
589
|
A Source whose write the server cannot see (a row of a join table, a count it
|
|
558
590
|
keeps itself) names the row with no values, and the read answers all of it:
|
|
559
591
|
|
|
560
|
-
```ts
|
|
592
|
+
```ts sketch
|
|
561
593
|
// Sketch, inside a mutation Source over a `Post` Entity: a like in a join table
|
|
562
594
|
// changes its post, so name the post and read nothing yourself.
|
|
563
595
|
return { output: { liked: true }, entities: [Remote.patch(Post, input.postId, {})] }
|
|
@@ -614,6 +646,14 @@ There are three ways to produce one:
|
|
|
614
646
|
|
|
615
647
|
### Write a live Source directly
|
|
616
648
|
|
|
649
|
+
<!-- docs-check
|
|
650
|
+
import { type LiveSource } from 'foldkit-remote-server'
|
|
651
|
+
|
|
652
|
+
declare const projectEvents: (
|
|
653
|
+
context: Parameters<LiveSource<unknown>['subscribe']>[0],
|
|
654
|
+
) => ReturnType<LiveSource<unknown>['subscribe']>
|
|
655
|
+
-->
|
|
656
|
+
|
|
617
657
|
```ts
|
|
618
658
|
// `projectEvents` is your own stream of `LiveChange`s.
|
|
619
659
|
const ProjectLive = RemoteServer.live(Project, {
|
|
@@ -683,17 +723,20 @@ fields it carries, each deletion as a deletion. A mutation Source names nothing
|
|
|
683
723
|
twice.
|
|
684
724
|
|
|
685
725
|
```ts
|
|
686
|
-
//
|
|
687
|
-
const
|
|
688
|
-
const
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
726
|
+
// Building a hub is an Effect.
|
|
727
|
+
const program = Effect.gen(function* () {
|
|
728
|
+
const entitySources = [ProjectSource]
|
|
729
|
+
const hub = yield* RemoteServer.liveHub(entitySources)
|
|
730
|
+
|
|
731
|
+
const handlers = RemoteServer.handlers(Server, principal, {
|
|
732
|
+
live: hub,
|
|
733
|
+
})
|
|
734
|
+
|
|
735
|
+
// Only for a write that is not a mutation: a database trigger consumer, a job.
|
|
736
|
+
yield* hub.changed(Project.ref('p1'), ['name'])
|
|
737
|
+
yield* hub.deleted(Project.ref('p1'))
|
|
738
|
+
return handlers
|
|
692
739
|
})
|
|
693
|
-
|
|
694
|
-
// Only for a write that is not a mutation: a database trigger consumer, a job.
|
|
695
|
-
yield* hub.changed(Project.ref('p1'), ['name'])
|
|
696
|
-
yield* hub.deleted(Project.ref('p1'))
|
|
697
740
|
```
|
|
698
741
|
|
|
699
742
|
A mutation's publish runs after its Source returned, so after a write that
|
|
@@ -727,8 +770,10 @@ the reader itself included when a Source answers a viewer-relative member (a
|
|
|
727
770
|
fits Sources that answer only by role:
|
|
728
771
|
|
|
729
772
|
```ts
|
|
730
|
-
const
|
|
731
|
-
|
|
773
|
+
const keyed = Effect.gen(function* () {
|
|
774
|
+
return yield* RemoteServer.liveHub([ProjectSource], {
|
|
775
|
+
key: (user: Principal) => (user.isAdmin ? 'admin' : 'member'),
|
|
776
|
+
})
|
|
732
777
|
})
|
|
733
778
|
```
|
|
734
779
|
|
|
@@ -798,12 +843,19 @@ The principal is a value, or a Context key that each call reads, so one
|
|
|
798
843
|
handler set (one RPC layer) answers every request and authentication provides
|
|
799
844
|
the key per request:
|
|
800
845
|
|
|
846
|
+
<!-- docs-check
|
|
847
|
+
declare const body: unknown
|
|
848
|
+
declare const user: Principal
|
|
849
|
+
-->
|
|
850
|
+
|
|
801
851
|
```ts
|
|
852
|
+
import { Context } from 'effect'
|
|
853
|
+
|
|
802
854
|
class CurrentUser extends Context.Service<CurrentUser, Principal>()('app/CurrentUser') {}
|
|
803
|
-
const
|
|
855
|
+
const answering = RemoteServer.handlers(Server, CurrentUser)
|
|
804
856
|
|
|
805
857
|
// per request, once authentication has resolved `user`
|
|
806
|
-
RemoteServer.answer(
|
|
858
|
+
RemoteServer.answer(answering, body).pipe(Effect.provideService(CurrentUser, user))
|
|
807
859
|
```
|
|
808
860
|
|
|
809
861
|
Every handler then needs `CurrentUser`, which the types carry: a key holding
|
|
@@ -827,7 +879,7 @@ application-specific rather than field-selection policy.
|
|
|
827
879
|
A complete server definition is just the collection of Sources:
|
|
828
880
|
|
|
829
881
|
```ts
|
|
830
|
-
const
|
|
882
|
+
const FullServer = RemoteServer.make({
|
|
831
883
|
entities: [ProjectSource],
|
|
832
884
|
queries: [ProjectsByOwnerSource],
|
|
833
885
|
mutations: [RenameProjectSource],
|
|
@@ -845,7 +897,7 @@ const Data = Remote.define({
|
|
|
845
897
|
mutations: [RenameProject],
|
|
846
898
|
})
|
|
847
899
|
|
|
848
|
-
RemoteServer.validate(Data,
|
|
900
|
+
RemoteServer.validate(Data, FullServer)
|
|
849
901
|
```
|
|
850
902
|
|
|
851
903
|
That catches an Entity, Query, or Mutation Source whose name is not declared by
|
|
@@ -878,8 +930,14 @@ it refuses a write that names one, which it cannot check.
|
|
|
878
930
|
Then compile it into handlers, once per principal, or once for every request
|
|
879
931
|
with a Context key as the principal (see Authentication vs authorization):
|
|
880
932
|
|
|
933
|
+
<!-- docs-check
|
|
934
|
+
import { type LiveHub } from 'foldkit-remote-server'
|
|
935
|
+
|
|
936
|
+
declare const hub: LiveHub<Principal>
|
|
937
|
+
-->
|
|
938
|
+
|
|
881
939
|
```ts
|
|
882
|
-
const
|
|
940
|
+
const bounded = RemoteServer.handlers(FullServer, principal, {
|
|
883
941
|
maxIdsPerEntity: 1000,
|
|
884
942
|
maxDepth: 8,
|
|
885
943
|
live: hub,
|
|
@@ -995,7 +1053,7 @@ it over a real transport to try a client against HTTP, or to test another
|
|
|
995
1053
|
server against it:
|
|
996
1054
|
|
|
997
1055
|
```ts
|
|
998
|
-
const
|
|
1056
|
+
const backendLayer = RemoteRpc.toLayer(RemoteServer.handlers(backend.server, undefined))
|
|
999
1057
|
```
|
|
1000
1058
|
|
|
1001
1059
|
- Rows are in their **wire shape**: a relation is its ref key (`'User:u1'`),
|
|
@@ -1087,6 +1145,10 @@ queries, mutations and live streams cross it with their typed errors, and an
|
|
|
1087
1145
|
interrupted call interrupts its handler. It returns once the client closes its
|
|
1088
1146
|
end; interrupt it to stop sooner:
|
|
1089
1147
|
|
|
1148
|
+
<!-- docs-check
|
|
1149
|
+
declare const port: MessagePort
|
|
1150
|
+
-->
|
|
1151
|
+
|
|
1090
1152
|
```ts
|
|
1091
1153
|
import { servePort } from 'foldkit-remote-server/port'
|
|
1092
1154
|
|
|
@@ -1159,9 +1221,9 @@ import { RpcSerialization, RpcServer } from 'effect/rpc'
|
|
|
1159
1221
|
import { RemoteRpc } from 'foldkit-remote'
|
|
1160
1222
|
import { RemoteServer, bodyLimit } from 'foldkit-remote-server'
|
|
1161
1223
|
|
|
1162
|
-
// `
|
|
1224
|
+
// `Server` is your RemoteServer.make; answered as a visitor here.
|
|
1163
1225
|
const RpcRoutes = RpcServer.layer(RemoteRpc).pipe(
|
|
1164
|
-
Layer.provide(RemoteRpc.toLayer(RemoteServer.handlers(
|
|
1226
|
+
Layer.provide(RemoteRpc.toLayer(RemoteServer.handlers(Server, { isAdmin: false }))),
|
|
1165
1227
|
Layer.provide(RpcServer.layerProtocolHttp({ path: '/rpc' })),
|
|
1166
1228
|
Layer.provide(RpcSerialization.layerJson),
|
|
1167
1229
|
Layer.provide(HttpRouter.middleware(bodyLimit(64 * 1024)).layer),
|
|
@@ -1175,6 +1237,12 @@ only over `Remote.rpcProtocolHttp(url)` in place of
|
|
|
1175
1237
|
and loses its status: a durable write would then read as unreachable and be
|
|
1176
1238
|
sent again for good.
|
|
1177
1239
|
|
|
1240
|
+
Decide who is asking from the HTTP request, in front of the route, never
|
|
1241
|
+
from the `headers` an `RpcMiddleware` or a handler is given. `RpcServer`
|
|
1242
|
+
puts the HTTP request's headers before those the request body carries and
|
|
1243
|
+
keeps the last of each name, so a body can claim another `cookie`, `origin`
|
|
1244
|
+
or CSRF header; over a WebSocket, every frame can.
|
|
1245
|
+
|
|
1178
1246
|
## Over fetch (Workers)
|
|
1179
1247
|
|
|
1180
1248
|
`serveFetch` from `foldkit-remote-server/fetch` is that route as a value: a
|
|
@@ -1184,6 +1252,31 @@ Effect: `layer` is built from the environment, then `resolvePrincipal` says
|
|
|
1184
1252
|
who is asking, then the request is answered as them. The resolver may need
|
|
1185
1253
|
what `layer` provides (a session store, an auth service):
|
|
1186
1254
|
|
|
1255
|
+
<!-- docs-check standalone
|
|
1256
|
+
import { Context, Effect, Layer } from 'effect'
|
|
1257
|
+
import { RemoteServer } from 'foldkit-remote-server'
|
|
1258
|
+
import { type RemoteClient, type RemoteUnauthenticated } from 'foldkit-remote'
|
|
1259
|
+
|
|
1260
|
+
type Principal = { readonly isAdmin: boolean }
|
|
1261
|
+
interface Env {
|
|
1262
|
+
readonly DB: unknown
|
|
1263
|
+
}
|
|
1264
|
+
class Database extends Context.Service<Database, unknown>()('readme/Database') {}
|
|
1265
|
+
const server = RemoteServer.make<Principal, Database>({ entities: [] })
|
|
1266
|
+
const drizzle = (db: unknown) => db
|
|
1267
|
+
const databaseLayer = (db: unknown) => Layer.succeed(Database, db)
|
|
1268
|
+
const resolvePrincipal = (request: Request) =>
|
|
1269
|
+
Effect.succeed<Principal>({ isAdmin: request.headers.has('x-admin') })
|
|
1270
|
+
const resolvePage = () => Effect.succeed<Principal>({ isAdmin: false })
|
|
1271
|
+
const PageContext = {
|
|
1272
|
+
attach: (
|
|
1273
|
+
request: Request,
|
|
1274
|
+
_: { readonly reader: Layer.Layer<RemoteClient, RemoteUnauthenticated> },
|
|
1275
|
+
) => request,
|
|
1276
|
+
}
|
|
1277
|
+
const pages = { fetch: (request: Request) => Promise.resolve(new Response(request.url)) }
|
|
1278
|
+
-->
|
|
1279
|
+
|
|
1187
1280
|
```ts
|
|
1188
1281
|
import { serveFetch } from 'foldkit-remote-server/fetch'
|
|
1189
1282
|
|
|
@@ -1192,8 +1285,8 @@ export default {
|
|
|
1192
1285
|
fetch: serveFetch({
|
|
1193
1286
|
server,
|
|
1194
1287
|
resolvePrincipal: request =>
|
|
1195
|
-
Effect.succeed({
|
|
1196
|
-
layer: env => databaseLayer(drizzle(env.DB)),
|
|
1288
|
+
Effect.succeed({ isAdmin: request.headers.get('x-role') === 'admin' }),
|
|
1289
|
+
layer: (env: Env) => databaseLayer(drizzle(env.DB)),
|
|
1197
1290
|
}),
|
|
1198
1291
|
}
|
|
1199
1292
|
```
|
|
@@ -1207,9 +1300,10 @@ pass the limit, its stream cancelled there. Give the client the same number
|
|
|
1207
1300
|
reads to fit; `Remote.http` reads a 413 as the call's own error, so a durable
|
|
1208
1301
|
write is not resent. A body that is not UTF-8 JSON, or not a request, is a 400
|
|
1209
1302
|
that reaches no handler; a handler's failure a 500 with its message. Every response, refusals
|
|
1210
|
-
and errors included, says `cache-control: no-store` unless `headers` gives a
|
|
1303
|
+
and errors included, says `cache-control: private, no-store` unless `headers` gives a
|
|
1211
1304
|
`cache-control` of its own: each answer is one principal's rows (and `may`), so
|
|
1212
|
-
no shared cache may keep one.
|
|
1305
|
+
no shared cache may keep one. The one exception is a read the server proves
|
|
1306
|
+
public, with `cache` (below).
|
|
1213
1307
|
|
|
1214
1308
|
A resolver refuses the caller by failing with
|
|
1215
1309
|
`RemoteServer.unauthenticated(reason?)`: a 401 whose body is
|
|
@@ -1261,6 +1355,31 @@ from the same config `serveFetch` takes: the request's `RemoteClient` as a
|
|
|
1261
1355
|
Layer, answered by the server's own handlers with no HTTP in between. The
|
|
1262
1356
|
server, its `layer` and its limits are the ones `/remote` answers with.
|
|
1263
1357
|
|
|
1358
|
+
<!-- docs-check standalone
|
|
1359
|
+
import { Context, Effect, Layer } from 'effect'
|
|
1360
|
+
import { RemoteServer } from 'foldkit-remote-server'
|
|
1361
|
+
import { type RemoteClient, type RemoteUnauthenticated } from 'foldkit-remote'
|
|
1362
|
+
|
|
1363
|
+
type Principal = { readonly isAdmin: boolean }
|
|
1364
|
+
interface Env {
|
|
1365
|
+
readonly DB: unknown
|
|
1366
|
+
}
|
|
1367
|
+
class Database extends Context.Service<Database, unknown>()('readme/Database') {}
|
|
1368
|
+
const server = RemoteServer.make<Principal, Database>({ entities: [] })
|
|
1369
|
+
const drizzle = (db: unknown) => db
|
|
1370
|
+
const databaseLayer = (db: unknown) => Layer.succeed(Database, db)
|
|
1371
|
+
const resolvePrincipal = (request: Request) =>
|
|
1372
|
+
Effect.succeed<Principal>({ isAdmin: request.headers.has('x-admin') })
|
|
1373
|
+
const resolvePage = () => Effect.succeed<Principal>({ isAdmin: false })
|
|
1374
|
+
const PageContext = {
|
|
1375
|
+
attach: (
|
|
1376
|
+
request: Request,
|
|
1377
|
+
_: { readonly reader: Layer.Layer<RemoteClient, RemoteUnauthenticated> },
|
|
1378
|
+
) => request,
|
|
1379
|
+
}
|
|
1380
|
+
const pages = { fetch: (request: Request) => Promise.resolve(new Response(request.url)) }
|
|
1381
|
+
-->
|
|
1382
|
+
|
|
1264
1383
|
```ts
|
|
1265
1384
|
import { pageReader, serveFetch } from 'foldkit-remote-server/fetch'
|
|
1266
1385
|
|
|
@@ -1282,8 +1401,11 @@ export default {
|
|
|
1282
1401
|
|
|
1283
1402
|
The resolver is the page's own: a page `GET` is a navigation, which carries
|
|
1284
1403
|
no header a script adds, so a resolver that asks for one (Yielded's CSRF
|
|
1285
|
-
header) refuses it. With `foldkit-auth`, give
|
|
1286
|
-
`
|
|
1404
|
+
header) refuses it. With `foldkit-auth`, give `AuthServer.host`'s
|
|
1405
|
+
`navigation`. `pageReader` hands its resolver a `NavigationRequest` and
|
|
1406
|
+
`serveFetch` a `ScriptedRequest` (types from `foldkit-remote`, nothing at run
|
|
1407
|
+
time): a resolver typed for one does not fit the other, while one taking any
|
|
1408
|
+
`Request`, as here, fits both. When the reader is
|
|
1287
1409
|
provided, the principal is resolved and `layer` built, and `layer` closes
|
|
1288
1410
|
when that Effect ends, so provide it to the pre-read itself
|
|
1289
1411
|
(`Data.satisfy(…).pipe(Effect.provide(reader))`). A refusal fails it with
|
|
@@ -1293,6 +1415,141 @@ The reader only reads. A mutation fails with `RemoteMutationError` and a live
|
|
|
1293
1415
|
open with `RemoteLiveError`: another site can start a navigation, so the
|
|
1294
1416
|
principal it resolves must never write, and a render keeps no stream.
|
|
1295
1417
|
|
|
1418
|
+
With `cache`, the reader answers each read it proves public as the visitor,
|
|
1419
|
+
and notes every read for the render (`PageReads`): public with its
|
|
1420
|
+
freshness and the rows it holds, or private, named by the rows or query it
|
|
1421
|
+
asked for (`Price a, Price b`, `query Search`). `foldkit-ssr`'s `SSR.entry`
|
|
1422
|
+
keeps a page only when every read it made was public, and refuses a
|
|
1423
|
+
prerendered page naming the first read that was not.
|
|
1424
|
+
|
|
1425
|
+
### Keeping public reads: `cache`
|
|
1426
|
+
|
|
1427
|
+
A read every visitor gets the same answer to costs the same work every
|
|
1428
|
+
time it is asked. With `cache`, `serveFetch` keeps such reads and answers
|
|
1429
|
+
them again from a store, without asking a Source:
|
|
1430
|
+
|
|
1431
|
+
```text
|
|
1432
|
+
a read -> public? (no rule about who asks, freshness declared)
|
|
1433
|
+
-> yes: answered as the visitor, kept by its body for maxAge
|
|
1434
|
+
-> no: answered as who asks, cache-control: private, no-store
|
|
1435
|
+
a write -> purges every kept read holding a row it names, and every list of that row's entity
|
|
1436
|
+
```
|
|
1437
|
+
|
|
1438
|
+
The domain declares how long a read stays fresh; it never says who may
|
|
1439
|
+
share it. An Entity says it with `EdgeCache.of`, a Query with `cache`:
|
|
1440
|
+
|
|
1441
|
+
```ts standalone
|
|
1442
|
+
import { Effect, Layer, Schema } from 'effect'
|
|
1443
|
+
import { Entity } from 'foldkit-entity'
|
|
1444
|
+
import { CacheStore, EdgeCache, Query, REMOTE_PROTOCOL_VERSION } from 'foldkit-remote'
|
|
1445
|
+
import { RemoteServer } from 'foldkit-remote-server'
|
|
1446
|
+
import { checkCache, serveFetch } from 'foldkit-remote-server/fetch'
|
|
1447
|
+
|
|
1448
|
+
const Price = Entity.define(
|
|
1449
|
+
'Price',
|
|
1450
|
+
Schema.Struct({ id: Schema.String, amount: Schema.Number }),
|
|
1451
|
+
).pipe(Entity.annotate(EdgeCache.of({ maxAge: '60 seconds' })))
|
|
1452
|
+
const Cheap = Query.make('Cheap', { Input: {}, Result: Price, cache: { maxAge: '30 seconds' } })
|
|
1453
|
+
|
|
1454
|
+
const server = RemoteServer.make({
|
|
1455
|
+
entities: [
|
|
1456
|
+
RemoteServer.entity(Price, {
|
|
1457
|
+
read: ({ ids }) => Effect.succeed(ids.map(id => ({ id, values: { id, amount: 12 } }))),
|
|
1458
|
+
}),
|
|
1459
|
+
],
|
|
1460
|
+
})
|
|
1461
|
+
|
|
1462
|
+
const config = {
|
|
1463
|
+
server,
|
|
1464
|
+
resolvePrincipal: (request: Request) =>
|
|
1465
|
+
Effect.succeed({ userId: request.headers.get('x-user') ?? undefined }),
|
|
1466
|
+
layer: () => Layer.empty,
|
|
1467
|
+
}
|
|
1468
|
+
export const fetch = serveFetch({
|
|
1469
|
+
...config,
|
|
1470
|
+
cache: { store: CacheStore.memory(), visitor: { userId: undefined } },
|
|
1471
|
+
})
|
|
1472
|
+
```
|
|
1473
|
+
|
|
1474
|
+
Whether a read is public is the server's to prove, from the Sources it
|
|
1475
|
+
passes through: a read or query is public only when no Source on its way
|
|
1476
|
+
(its Entity's, each relation's it reaches, a query's own and its `select`'s)
|
|
1477
|
+
has an `authorize`, a `filter`, a `visible` rule or a member answered per
|
|
1478
|
+
viewer (`Derived.exists`), and each declares a freshness. Those rules are
|
|
1479
|
+
functions of the principal the server cannot read, so a Source with one is
|
|
1480
|
+
private even where its rule happens to read only the row: a guarded Entity
|
|
1481
|
+
(`foldkit-guard`), a Drizzle binding with `visible`, a `memory` backend with
|
|
1482
|
+
`readable`. Nothing is cached that the server could not prove.
|
|
1483
|
+
|
|
1484
|
+
A public read is answered as `visitor`, whoever asks: one answer, right for
|
|
1485
|
+
everyone, and never someone's own, even from a Source whose `read` looks at
|
|
1486
|
+
the principal. `visitor` must be no one: `serveFetch` refuses one the
|
|
1487
|
+
server's `viewer` names a row for. The answer names nobody it was for (no
|
|
1488
|
+
`principal`), says `cache-control: public, max-age=…` for the shortest
|
|
1489
|
+
freshness it reaches, and is kept by the SHA-256 of its body under
|
|
1490
|
+
`/__foldkit/cache/remote/` on the request's origin. A refusal or a failure
|
|
1491
|
+
is not kept. Everything else (a write, a live stream, a read that is not
|
|
1492
|
+
public) says `private, no-store`.
|
|
1493
|
+
|
|
1494
|
+
A write answered here purges what its answer names: each row it wrote,
|
|
1495
|
+
deleted, moved in a list or read back (`shown`, carried `lists`), and every
|
|
1496
|
+
list of each of their entities, which a changed row can join or leave. A
|
|
1497
|
+
write that is not answered by this `serveFetch` (another server, a job, a
|
|
1498
|
+
database trigger) purges nothing: what it changed is served as it was kept
|
|
1499
|
+
until `maxAge`.
|
|
1500
|
+
|
|
1501
|
+
`CacheStore.memory({ limit })` keeps answers in the process, for Node, a dev
|
|
1502
|
+
server and tests (1,000 by default, the oldest dropped first).
|
|
1503
|
+
`CacheStore.workers(caches.default)` keeps them in the Workers Cache API;
|
|
1504
|
+
which answers a tag names is known to the isolate that kept them, so a
|
|
1505
|
+
write purges what this isolate kept, and another isolate's or data centre's
|
|
1506
|
+
copy stays until its `maxAge`. Give `pageReader` the same config, and pages
|
|
1507
|
+
read through it are judged the same way (`foldkit-ssr`'s `cache`).
|
|
1508
|
+
|
|
1509
|
+
`CacheStore.kv(env.CACHE)` keeps them in a Workers KV namespace: one copy for
|
|
1510
|
+
every isolate and data centre. KV's free plan allows 1,000 writes a day, so
|
|
1511
|
+
an answer is written only when it is asked for a second time; this isolate's
|
|
1512
|
+
memory counts the asking, since counting in KV would spend the write the
|
|
1513
|
+
count saves. What KV refuses or fails never fails a request: a failed read
|
|
1514
|
+
is a miss, a refused write (the day's writes spent, a key over 512 bytes)
|
|
1515
|
+
keeps nothing, and each is logged as a warning. KV keeps an entry a minute
|
|
1516
|
+
at least; the store serves it for its `maxAge` alone. Its purge, like the
|
|
1517
|
+
Workers store's, reaches what this isolate kept. Its `keep` option is for
|
|
1518
|
+
pages (`foldkit-ssr`): with it, `kv` returns a `PageCacheStore`, which
|
|
1519
|
+
`serveFetch`'s `cache.store` refuses as a type error, since a read's answer
|
|
1520
|
+
carries no age and one served past its `maxAge` would read as fresh.
|
|
1521
|
+
|
|
1522
|
+
The checker answers each public read as two principals. `cache.check`
|
|
1523
|
+
answers it as who asks too, and where the two differ reports
|
|
1524
|
+
`CachedReadDiffers` and gives the asker their own: a development mode.
|
|
1525
|
+
`checkCache(config, requests, env)` is the same, for a test: it serves each
|
|
1526
|
+
request twice with `check` and a store in memory, and rejects a difference,
|
|
1527
|
+
or a set of requests with no public read, which would check nothing:
|
|
1528
|
+
|
|
1529
|
+
```ts
|
|
1530
|
+
const asking = (user?: string) => () =>
|
|
1531
|
+
new Request('https://shop.test/remote', {
|
|
1532
|
+
method: 'POST',
|
|
1533
|
+
headers: user === undefined ? {} : { 'x-user': user },
|
|
1534
|
+
body: JSON.stringify({
|
|
1535
|
+
operation: 'read',
|
|
1536
|
+
payload: {
|
|
1537
|
+
version: REMOTE_PROTOCOL_VERSION,
|
|
1538
|
+
requests: [{ entity: 'Price', id: 'a', fields: ['amount'] }],
|
|
1539
|
+
},
|
|
1540
|
+
}),
|
|
1541
|
+
})
|
|
1542
|
+
|
|
1543
|
+
export const checked = checkCache(
|
|
1544
|
+
{ ...config, cache: { visitor: { userId: undefined } } },
|
|
1545
|
+
[asking(), asking('u1')],
|
|
1546
|
+
undefined,
|
|
1547
|
+
)
|
|
1548
|
+
```
|
|
1549
|
+
|
|
1550
|
+
`Cheap` is a Query a server registers with `RemoteServer.query`; its answer
|
|
1551
|
+
is kept for 30 seconds, the shorter of its own and `Price`'s.
|
|
1552
|
+
|
|
1296
1553
|
## Diagnostics
|
|
1297
1554
|
|
|
1298
1555
|
A server answers some failures without telling the caller why. Each is a
|
|
@@ -1311,7 +1568,34 @@ report)` in the layer the handlers run in. `serveFetch` takes one with the
|
|
|
1311
1568
|
request beside it, used for everything that request runs, a broken layer
|
|
1312
1569
|
included:
|
|
1313
1570
|
|
|
1571
|
+
<!-- docs-check standalone
|
|
1572
|
+
import { Context, Effect, Layer } from 'effect'
|
|
1573
|
+
import { RemoteServer } from 'foldkit-remote-server'
|
|
1574
|
+
import { type RemoteClient, type RemoteUnauthenticated } from 'foldkit-remote'
|
|
1575
|
+
|
|
1576
|
+
type Principal = { readonly isAdmin: boolean }
|
|
1577
|
+
interface Env {
|
|
1578
|
+
readonly DB: unknown
|
|
1579
|
+
}
|
|
1580
|
+
class Database extends Context.Service<Database, unknown>()('readme/Database') {}
|
|
1581
|
+
const server = RemoteServer.make<Principal, Database>({ entities: [] })
|
|
1582
|
+
const drizzle = (db: unknown) => db
|
|
1583
|
+
const databaseLayer = (env: Env) => Layer.succeed(Database, env.DB)
|
|
1584
|
+
const resolvePrincipal = (request: Request) =>
|
|
1585
|
+
Effect.succeed<Principal>({ isAdmin: request.headers.has('x-admin') })
|
|
1586
|
+
const resolvePage = () => Effect.succeed<Principal>({ isAdmin: false })
|
|
1587
|
+
const PageContext = {
|
|
1588
|
+
attach: (
|
|
1589
|
+
request: Request,
|
|
1590
|
+
_: { readonly reader: Layer.Layer<RemoteClient, RemoteUnauthenticated> },
|
|
1591
|
+
) => request,
|
|
1592
|
+
}
|
|
1593
|
+
const pages = { fetch: (request: Request) => Promise.resolve(new Response(request.url)) }
|
|
1594
|
+
-->
|
|
1595
|
+
|
|
1314
1596
|
```ts
|
|
1597
|
+
import { serveFetch } from 'foldkit-remote-server/fetch'
|
|
1598
|
+
|
|
1315
1599
|
serveFetch({
|
|
1316
1600
|
server,
|
|
1317
1601
|
resolvePrincipal,
|
|
@@ -1331,7 +1615,8 @@ A descriptor declared with
|
|
|
1331
1615
|
[`Query.define`](../remote#queries-and-pagination) carries its meaning as a
|
|
1332
1616
|
value (`body`), and `evaluate` runs a body directly:
|
|
1333
1617
|
|
|
1334
|
-
```ts
|
|
1618
|
+
```ts standalone
|
|
1619
|
+
import { Schema } from 'effect'
|
|
1335
1620
|
import { Entity, Expr, Order, Query, evaluate } from 'foldkit-entity'
|
|
1336
1621
|
|
|
1337
1622
|
const Post = Entity.define('Post', Schema.Struct({ id: Schema.String, slug: Schema.String }))
|
|
@@ -1383,7 +1668,16 @@ what it is a reference *to*: the conformance suite, exported so an interpreter
|
|
|
1383
1668
|
written elsewhere can be held to the same semantics. Here `run` is your
|
|
1384
1669
|
interpreter:
|
|
1385
1670
|
|
|
1671
|
+
<!-- docs-check
|
|
1672
|
+
declare const run: (
|
|
1673
|
+
body: (typeof cases)[number]['body'],
|
|
1674
|
+
input: (typeof cases)[number]['input'],
|
|
1675
|
+
held: typeof rows,
|
|
1676
|
+
) => ReadonlyArray<{ readonly id: string }>
|
|
1677
|
+
-->
|
|
1678
|
+
|
|
1386
1679
|
```ts
|
|
1680
|
+
import { expect } from 'vitest'
|
|
1387
1681
|
import { cases, rows } from 'foldkit-entity/conformance'
|
|
1388
1682
|
|
|
1389
1683
|
for (const { what, body, input, expected } of cases) {
|
package/dist/fetch.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { M as ServerDefinition, u as LiveHub } from "./index-lJvjBBDL.mjs";
|
|
2
2
|
import { Duration, Effect, Layer } from "effect";
|
|
3
|
-
import { Diagnostic, RemoteClient, RemoteUnauthenticated } from "foldkit-remote";
|
|
3
|
+
import { CacheStore, Diagnostic, NavigationRequest, RemoteClient, RemoteUnauthenticated, ScriptedRequest } from "foldkit-remote";
|
|
4
4
|
/** What `serveFetch` needs of the host runtime, per request. */
|
|
5
5
|
export interface FetchConfig<P, R, Env, RP = never> {
|
|
6
6
|
/** The server definition, as `RemoteServer.make` built it. */
|
|
@@ -9,8 +9,10 @@ export interface FetchConfig<P, R, Env, RP = never> {
|
|
|
9
9
|
* Who this request is, from the request and the environment. Fails with
|
|
10
10
|
* `RemoteServer.unauthenticated(reason?)` to refuse the caller: a 401.
|
|
11
11
|
* What it needs (a session store, an auth service) comes from `layer`.
|
|
12
|
+
* A resolver taking any `Request` fits; one typed for a navigation
|
|
13
|
+
* (`NavigationRequest`) does not, since `/remote` writes.
|
|
12
14
|
*/
|
|
13
|
-
readonly resolvePrincipal: (request:
|
|
15
|
+
readonly resolvePrincipal: (request: ScriptedRequest, env: Env) => Effect.Effect<P, RemoteUnauthenticated, RP>;
|
|
14
16
|
/**
|
|
15
17
|
* What the Sources and the resolver need, from the environment. Built per
|
|
16
18
|
* request, so kept cheap, and closed when the answer is sent, or, for a
|
|
@@ -65,6 +67,31 @@ export interface FetchConfig<P, R, Env, RP = never> {
|
|
|
65
67
|
* (`Remote.clientLayer(…, { maxBodyBytes })`), so it cuts its reads to fit.
|
|
66
68
|
*/
|
|
67
69
|
readonly maxBodyBytes?: number | undefined;
|
|
70
|
+
/**
|
|
71
|
+
* Keeps public reads in `store` (#428). A read or query is public where
|
|
72
|
+
* none of the sources it passes through has a rule about who asks
|
|
73
|
+
* (`authorize`, `filter`, `visible`, a member per viewer) and each declares
|
|
74
|
+
* how long it stays fresh (`EdgeCache.of` on its Entity, `cache` on its
|
|
75
|
+
* Query). A public read is answered as `visitor`, whoever asks, so one
|
|
76
|
+
* answer is right for everyone, and kept for the shortest `maxAge` it
|
|
77
|
+
* reaches; it says `cache-control: public, max-age=…`. Every other answer
|
|
78
|
+
* says `private, no-store`. A write answered here purges the kept reads
|
|
79
|
+
* holding a row it names, and every list of that row's entity.
|
|
80
|
+
*
|
|
81
|
+
* `store` is a `CacheStore`, which serves nothing past its `maxAge`: an
|
|
82
|
+
* answer carries no age, so one kept longer would read as fresh. A
|
|
83
|
+
* `PageCacheStore` (`CacheStore.kv` with `keep`) is refused.
|
|
84
|
+
*
|
|
85
|
+
* `visitor` is the principal of someone not signed in: refused when the
|
|
86
|
+
* server's `viewer` names a row for it. With `check`, for development and
|
|
87
|
+
* tests, each public read is also answered as who asks, and a difference
|
|
88
|
+
* is reported (`CachedReadDiffers`) and answered with the asker's own.
|
|
89
|
+
*/
|
|
90
|
+
readonly cache?: {
|
|
91
|
+
readonly store: CacheStore;
|
|
92
|
+
readonly visitor: P;
|
|
93
|
+
readonly check?: boolean | undefined;
|
|
94
|
+
} | undefined;
|
|
68
95
|
}
|
|
69
96
|
/**
|
|
70
97
|
* Answers Remote `POST`s with `Response`s: what a Worker's `fetch` hands to
|
|
@@ -90,8 +117,33 @@ export interface FetchConfig<P, R, Env, RP = never> {
|
|
|
90
117
|
* ```
|
|
91
118
|
*/
|
|
92
119
|
export declare const serveFetch: <P, R, Env, RP = never>(config: FetchConfig<P, R, Env, RP>) => ((request: Request, env: Env) => Promise<Response>);
|
|
93
|
-
/**
|
|
94
|
-
|
|
120
|
+
/**
|
|
121
|
+
* The cache's checker, for a test: serves each request twice through
|
|
122
|
+
* `serveFetch` with `cache.check` and a store in memory, so every public read
|
|
123
|
+
* is answered both as the visitor (kept, then from the store) and as whoever
|
|
124
|
+
* the request resolves to. Rejects naming each read whose answers differ, and
|
|
125
|
+
* when no read was public, which would check nothing. Give requests from at
|
|
126
|
+
* least two principals, a visitor's and someone's; each is a function, since
|
|
127
|
+
* a body is read once.
|
|
128
|
+
*/
|
|
129
|
+
export declare const checkCache: <P, R, Env, RP = never>(config: Omit<FetchConfig<P, R, Env, RP>, 'cache' | 'diagnostics'> & {
|
|
130
|
+
readonly cache: {
|
|
131
|
+
readonly visitor: P;
|
|
132
|
+
};
|
|
133
|
+
}, requests: ReadonlyArray<() => Request>, env: Env) => Promise<void>;
|
|
134
|
+
/**
|
|
135
|
+
* What `pageReader` reads of a `serveFetch` config: the server, its Sources'
|
|
136
|
+
* layer, its limits, and the cache's `visitor`.
|
|
137
|
+
*/
|
|
138
|
+
export type PageReaderConfig<P, R, Env, RP = never> = Pick<FetchConfig<P, R, Env, RP>, 'server' | 'layer' | 'maxIdsPerEntity' | 'maxDepth' | 'cache'> & {
|
|
139
|
+
/**
|
|
140
|
+
* Who a page request is. A resolver taking any `Request` fits; one typed
|
|
141
|
+
* for a script's request (`ScriptedRequest`) does not, since a navigation
|
|
142
|
+
* carries no header a script adds and that resolver would refuse every
|
|
143
|
+
* signed-in reader.
|
|
144
|
+
*/
|
|
145
|
+
readonly resolvePrincipal: (request: NavigationRequest, env: Env) => Effect.Effect<P, RemoteUnauthenticated, RP>;
|
|
146
|
+
};
|
|
95
147
|
/**
|
|
96
148
|
* The reader a page render reads through, in the same process: the request's
|
|
97
149
|
* `RemoteClient`, answered by the server's own handlers with no HTTP between
|
|
@@ -105,6 +157,11 @@ export type PageReaderConfig<P, R, Env, RP = never> = Pick<FetchConfig<P, R, Env
|
|
|
105
157
|
* refusal fails that Effect with `Unauthenticated`, as a 401 would. It only
|
|
106
158
|
* reads: a mutation fails with `RemoteMutationError` and a live open with
|
|
107
159
|
* `RemoteLiveError`, since a navigation can be started from another site.
|
|
160
|
+
*
|
|
161
|
+
* Each read is noted for a render `foldkit-ssr` may cache (`PageReads`):
|
|
162
|
+
* with `cache`, one proved public as `serveFetch` proves it is answered as
|
|
163
|
+
* `cache.visitor` and noted public; every other read, and every read without
|
|
164
|
+
* `cache`, is noted private, which keeps the page from being cached.
|
|
108
165
|
*/
|
|
109
166
|
export declare const pageReader: <P, R, Env, RP = never>(config: PageReaderConfig<P, R, Env, RP>) => (request: Request, env: Env) => Layer.Layer<RemoteClient, RemoteUnauthenticated>;
|
|
110
167
|
//# sourceMappingURL=fetch.d.mts.map
|
package/dist/fetch.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch.d.mts","names":[],"sources":["../src/fetch.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"fetch.d.mts","names":[],"sources":["../src/fetch.ts"],"mappings":";;;;iBAkEiB,YAAY,GAAG,GAAG,KAAK;;WAE7B,QAAQ,iBAAiB,GAAG;;;;;;;;WAQ5B,mBACP,SAAS,iBACT,KAAK,QACF,OAAO,OAAO,GAAG,uBAAuB;;;;;;WAMpC,QAAQ,KAAK,QAAQ,MAAM,MAAM,IAAI;;WAErC;;;;;;;WAOA,YAAY,WAAW,MAAM,SAAS;;WAEtC,OAAO,QAAQ,GAAG;;;;;;;;;;;;WAYlB;aAEM,OAAO,SAAS;aAChB,QAAQ,WAAW;;;WAIzB,gBAAgB,SAAS;;;;;;;;WAQzB,gBACH,YAAY,YAAY,SAAS,YAAY,OAAO;;WAGjD;;WAEA;;;;;;;;WAQA;;;;;;;;;;;;;;;;;;;;;WAqBA;aAEM,OAAO;aACP,SAAS;aACT;;;;;;;;;;;;;;;;;;;;;;;;;;qBAgOJ,aAAc,GAAG,GAAG,KAAK,YAAU,QACtC,YAAY,GAAG,GAAG,KAAK,UAC5B,SAAS,SAAS,KAAK,QAAQ,QAAQ;;;;;;;;;;qBAiN/B,aAAoB,GAAG,GAAG,KAAK,YAAU,QAC5C,KAAK,YAAY,GAAG,GAAG,KAAK;WACzB;aAAkB,SAAS;;GACrC,UACS,oBAAoB,UAAQ,KACjC,QACJ;;;;;YAyBS,iBAAiB,GAAG,GAAG,KAAK,cAAc,KACpD,YAAY,GAAG,GAAG,KAAK;;;;;;;WASd,mBACP,SAAS,mBACT,KAAK,QACF,OAAO,OAAO,GAAG,uBAAuB;;;;;;;;;;;;;;;;;;;;;qBAsBlC,aAAc,GAAG,GAAG,KAAK,YAAU,QAAU,iBAAiB,GAAG,GAAG,KAAK,SAAG,SAWtE,SAAO,KAAO,QAAM,MAAM,MAAM,cAAc"}
|