foldkit-remote-server 0.22.0 → 0.24.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +210 -29
- package/dist/fetch.d.mts +1 -1
- package/dist/fetch.d.mts.map +1 -1
- package/dist/fetch.mjs +12 -6
- package/dist/fetch.mjs.map +1 -1
- package/dist/{index-lJvjBBDL.d.mts → index-Dq3fHdhH.d.mts} +125 -19
- package/dist/index-Dq3fHdhH.d.mts.map +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/{src-B1JAs_gH.mjs → src-6l1A9ww5.mjs} +444 -53
- package/dist/src-6l1A9ww5.mjs.map +1 -0
- package/package.json +6 -6
- package/dist/index-lJvjBBDL.d.mts.map +0 -1
- package/dist/src-B1JAs_gH.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -43,23 +43,11 @@ turning back into hand-written per-screen endpoints.
|
|
|
43
43
|
|
|
44
44
|
## What this package owns
|
|
45
45
|
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
requirement interpretation
|
|
52
|
-
field authorization
|
|
53
|
-
read grouping / de-duplication
|
|
54
|
-
nested selection traversal
|
|
55
|
-
normalized wire results
|
|
56
|
-
|
|
57
|
-
application Sources own
|
|
58
|
-
how those facts are actually loaded or changed
|
|
59
|
-
|
|
60
|
-
Effect RPC / application owns
|
|
61
|
-
transport + serialization + authentication
|
|
62
|
-
```
|
|
46
|
+
The client owns which server facts are required. This package owns interpreting
|
|
47
|
+
those requirements: field authorization, grouping and de-duplicating reads,
|
|
48
|
+
walking nested selections, and the normalized wire results. Your Sources own how
|
|
49
|
+
the facts are actually loaded or changed. Effect RPC and your application own
|
|
50
|
+
transport, serialization and authentication.
|
|
63
51
|
|
|
64
52
|
That separation matters. `RemoteServer` can decide that a client may read
|
|
65
53
|
`Project.name` but not `Project.privateNotes`; only your Source knows whether
|
|
@@ -394,7 +382,14 @@ const RenameProjectSource = RemoteServer.mutation(
|
|
|
394
382
|
```
|
|
395
383
|
|
|
396
384
|
The input is decoded before the Source runs and the output is encoded before it
|
|
397
|
-
crosses the wire.
|
|
385
|
+
crosses the wire. The `entities` are cache patches of rows the caller may read:
|
|
386
|
+
the answer carries your values, cut to what `authorize` and `filter` let the
|
|
387
|
+
caller read of each row, and none for a row they may not read at all (a source
|
|
388
|
+
with no `authorize`, `filter` or `visible` is answered as it is, with no read; if the read fails, none of
|
|
389
|
+
that entity's patches is sent and an `AnswerUnread` is reported, and the write
|
|
390
|
+
still succeeds). Live subscribers are told every patch and read each through
|
|
391
|
+
their own rules. What a handler must tell a caller who may not read the row goes
|
|
392
|
+
in `output`, which is its own Schema. A Source refuses with a value of the mutation's `Refusal`:
|
|
398
393
|
`Effect.fail(RemoteServer.refuse(SetPrice, { _tag: 'Field', key: 'price', reason: 'too low' }))`.
|
|
399
394
|
The value is type-checked against that mutation, encoded by its schema, and
|
|
400
395
|
sent beside a message (a 422 over JSON); a refusal made for another mutation,
|
|
@@ -550,6 +545,7 @@ wrongly:
|
|
|
550
545
|
| --- | --- | --- |
|
|
551
546
|
| `preconditions: true` | checks `when` in the statement | a write with a `when` |
|
|
552
547
|
| `invariants: true` | judges the Entity's invariants | a write of an Entity that has any |
|
|
548
|
+
| `postconditions: true` | judges the write's `ensures` (a `becomes` enumeration could not decide) beside them, handed to `update` and `insert` | a write with one |
|
|
553
549
|
| `increments: true` | adds `increments` in the statement | a write with an increment |
|
|
554
550
|
| `assignments: true` | computes `assignments` in the statement | a write with a computed assignment |
|
|
555
551
|
| `ledger: true` (with `recorded`) | records each update and insert under its `operation`, and answers a retry from the record | an increment or computed assignment with no `expect` |
|
|
@@ -1002,8 +998,10 @@ The handler applies bounded, protocol-level safeguards before or around Sources:
|
|
|
1002
998
|
answering a list cut short;
|
|
1003
999
|
- returned field names are copied with `Object.hasOwn` into null-prototype
|
|
1004
1000
|
objects, so names such as `__proto__` or `toString` cannot reach prototypes;
|
|
1005
|
-
- Source
|
|
1006
|
-
|
|
1001
|
+
- a Source's failure, a thrown error and a defect reach the caller as
|
|
1002
|
+
`Internal error` and an incident id, never in their own words, unless the
|
|
1003
|
+
Source wrote them for the caller with `RemoteServer.tell` (see
|
|
1004
|
+
[When the server fails](#when-the-server-fails)).
|
|
1007
1005
|
|
|
1008
1006
|
A live subscription is held to the same bounds, checked once by the handler
|
|
1009
1007
|
before any live Source or the hub sees it: more than `maxIdsPerEntity` ids of
|
|
@@ -1136,6 +1134,87 @@ const asVisitor = RemoteServer.handlers(server, { isAdmin: false })
|
|
|
1136
1134
|
that does not admit `undefined`), the backend has no `layer`, only its store
|
|
1137
1135
|
and `server`, so nothing can read the rows as nobody.
|
|
1138
1136
|
|
|
1137
|
+
### Declared writes over the rows: `memoryWriter`
|
|
1138
|
+
|
|
1139
|
+
A [declared write](#declared-writes-no-handler) needs no handler over the
|
|
1140
|
+
rows either. `RemoteServer.memoryWriter(store, entity, { operators? })` is the
|
|
1141
|
+
`EntityWriter` for one Entity's rows in a backend's store, and it decides what
|
|
1142
|
+
`foldkit-remote-drizzle`'s writer decides in its statement, so a write lands
|
|
1143
|
+
here as it would over a database:
|
|
1144
|
+
|
|
1145
|
+
<!-- docs-check standalone
|
|
1146
|
+
import { Schema } from 'effect'
|
|
1147
|
+
import { Entity, Expr, Write } from 'foldkit-entity'
|
|
1148
|
+
import { Mutation, Remote } from 'foldkit-remote'
|
|
1149
|
+
import { RemoteServer } from 'foldkit-remote-server'
|
|
1150
|
+
|
|
1151
|
+
const Stock = Entity.define(
|
|
1152
|
+
'Stock',
|
|
1153
|
+
Schema.Struct({
|
|
1154
|
+
id: Schema.String,
|
|
1155
|
+
status: Schema.String,
|
|
1156
|
+
quantity: Schema.Int,
|
|
1157
|
+
reserved: Schema.Int,
|
|
1158
|
+
revision: Schema.Int,
|
|
1159
|
+
}),
|
|
1160
|
+
).pipe(
|
|
1161
|
+
Entity.invariant('reservedWithinStock', ({ after }) => Expr.lte(after.reserved, after.quantity), {
|
|
1162
|
+
message: 'Reserved stock cannot exceed the quantity',
|
|
1163
|
+
}),
|
|
1164
|
+
)
|
|
1165
|
+
-->
|
|
1166
|
+
|
|
1167
|
+
```ts
|
|
1168
|
+
const Reserve = Mutation.write(
|
|
1169
|
+
'Reserve',
|
|
1170
|
+
Write.update(
|
|
1171
|
+
Entity.input(
|
|
1172
|
+
Stock,
|
|
1173
|
+
Schema.Struct({ id: Schema.String, revision: Schema.Int, quantity: Schema.Int }),
|
|
1174
|
+
{ quantity: Entity.unmapped },
|
|
1175
|
+
),
|
|
1176
|
+
{
|
|
1177
|
+
id: 'id',
|
|
1178
|
+
expect: 'revision',
|
|
1179
|
+
when: () => Expr.eq(Stock.fields.status, 'published'),
|
|
1180
|
+
increment: { reserved: 'quantity' },
|
|
1181
|
+
},
|
|
1182
|
+
),
|
|
1183
|
+
)
|
|
1184
|
+
|
|
1185
|
+
const shop = RemoteServer.memory({
|
|
1186
|
+
domain: Remote.define({ entities: [Stock], mutations: [Reserve] }),
|
|
1187
|
+
rows: { Stock: [{ id: 's1', status: 'published', quantity: 10, reserved: 5, revision: 1 }] },
|
|
1188
|
+
mutations: store => [RemoteServer.write(Reserve, RemoteServer.memoryWriter(store, Stock))],
|
|
1189
|
+
})
|
|
1190
|
+
```
|
|
1191
|
+
|
|
1192
|
+
An update lands only while the row is at the revision it `expect`s, holds its
|
|
1193
|
+
`when`, and the row it would leave keeps every invariant; amounts and computed
|
|
1194
|
+
fields read the row as it was before the write, and the revision moves on by
|
|
1195
|
+
one. An insert lands while its id is free and its row keeps the invariants; a
|
|
1196
|
+
revision and holds its `when`. Each refusal reaches the client as the
|
|
1197
|
+
mutation's own: `Conflict`, `Unmet`, `Invalid` naming the invariant, `Taken`.
|
|
1198
|
+
`operators` runs the `when`, computed fields and invariants, as a memory
|
|
1199
|
+
backend's `operators` runs its query bodies.
|
|
1200
|
+
|
|
1201
|
+
The rows are one process's, read and written in one step, so a write cannot
|
|
1202
|
+
interleave with another. What a database writer holds beyond that it does
|
|
1203
|
+
not: no ledger of operations, no rule that reads another row, nothing a
|
|
1204
|
+
delete takes, keeps or clears with it. `RemoteServer.write` refuses, by name,
|
|
1205
|
+
a write that needs one (an increment with no `expect` needs a ledger), and so
|
|
1206
|
+
does `GuardServer.writer` for a rule reading another row, where each is
|
|
1207
|
+
served, rather than landing what the database would refuse.
|
|
1208
|
+
|
|
1209
|
+
<!-- docs-check standalone
|
|
1210
|
+
import { Effect } from 'effect'
|
|
1211
|
+
import { RemoteServer, type ServerDefinition } from 'foldkit-remote-server'
|
|
1212
|
+
|
|
1213
|
+
type Principal = { readonly isAdmin: boolean }
|
|
1214
|
+
declare const Server: ServerDefinition<Principal>
|
|
1215
|
+
const handlers = RemoteServer.handlers(Server, { isAdmin: false })
|
|
1216
|
+
-->
|
|
1217
|
+
|
|
1139
1218
|
## Over a MessagePort
|
|
1140
1219
|
|
|
1141
1220
|
`servePort(handlers, port)` from `foldkit-remote-server/port` answers
|
|
@@ -1185,7 +1264,10 @@ const route = async (request: Request): Promise<Response> => {
|
|
|
1185
1264
|
tell who is asking (`RemoteServer.unauthenticated`). The client fails the
|
|
1186
1265
|
call, of whatever kind, with `_tag: 'Unauthenticated'`.
|
|
1187
1266
|
- **403** with `{ error, forbidden: { reason? } }`: who is asking may not do
|
|
1188
|
-
this (`RemoteServer.forbid`).
|
|
1267
|
+
this (`RemoteServer.forbid`). In both, `error` is the `reason`, or
|
|
1268
|
+
`Unauthenticated` or `Forbidden` when the refusal gave none: the
|
|
1269
|
+
refusal's own `message` is not sent, here or in a live stream's error
|
|
1270
|
+
frame.
|
|
1189
1271
|
- **409** with `{ error, refusal }`: a declared insert's id is already a
|
|
1190
1272
|
row's, refused as `Refusal.taken`.
|
|
1191
1273
|
- **409** with `{ error, principalChanged: {} }`: the write names someone
|
|
@@ -1194,11 +1276,15 @@ const route = async (request: Request): Promise<Response> => {
|
|
|
1194
1276
|
for them.
|
|
1195
1277
|
- **422** with `{ error, refusal }`: the mutation refused what was asked, in
|
|
1196
1278
|
its own `Refusal`.
|
|
1197
|
-
- **500** with `{ error }`:
|
|
1198
|
-
|
|
1199
|
-
nothing more
|
|
1200
|
-
[diagnostic](#diagnostics), by default to the
|
|
1201
|
-
(`wrangler tail`) shows what broke.
|
|
1279
|
+
- **500** with `{ error, incident }`: something on this side broke (a
|
|
1280
|
+
Source's failure, a thrown error, a defect). The message is `Internal
|
|
1281
|
+
error`, nothing more, and `incident` is the id the cause was reported
|
|
1282
|
+
under, as a `ServerDefect` [diagnostic](#diagnostics), by default to the
|
|
1283
|
+
log, so a Worker's log (`wrangler tail`) shows what broke.
|
|
1284
|
+
- **500** with `{ error }` and no `incident`: the server's own fixed sentence
|
|
1285
|
+
about the request (an unknown query or mutation, an input its Schema
|
|
1286
|
+
refuses, too many ids), or words a Source wrote for the caller with
|
|
1287
|
+
`RemoteServer.tell`. See [When the server fails](#when-the-server-fails).
|
|
1202
1288
|
|
|
1203
1289
|
It never answers 408, 429, 502, 503 or 504. Remote's client reads a body
|
|
1204
1290
|
under one of those, or one that is not JSON, as no answer at all
|
|
@@ -1299,7 +1385,8 @@ pass the limit, its stream cancelled there. Give the client the same number
|
|
|
1299
1385
|
(`Remote.clientLayer(Remote.http('/remote'), { maxBodyBytes })`) and it cuts its
|
|
1300
1386
|
reads to fit; `Remote.http` reads a 413 as the call's own error, so a durable
|
|
1301
1387
|
write is not resent. A body that is not UTF-8 JSON, or not a request, is a 400
|
|
1302
|
-
that reaches no handler; a
|
|
1388
|
+
that reaches no handler; a failure on this side a 500 that says `Internal error` and the
|
|
1389
|
+
`incident` its cause was reported under ([When the server fails](#when-the-server-fails)). Every response, refusals
|
|
1303
1390
|
and errors included, says `cache-control: private, no-store` unless `headers` gives a
|
|
1304
1391
|
`cache-control` of its own: each answer is one principal's rows (and `may`), so
|
|
1305
1392
|
no shared cache may keep one. The one exception is a read the server proves
|
|
@@ -1310,7 +1397,7 @@ A resolver refuses the caller by failing with
|
|
|
1310
1397
|
`{ error, unauthenticated: { reason? } }`, as `answer`'s 403 carries
|
|
1311
1398
|
`forbidden`, and whose `reason` is the only thing the caller learns. Anything
|
|
1312
1399
|
else this side breaks, the resolver's defects and the layer included, is a
|
|
1313
|
-
500 that says nothing of it
|
|
1400
|
+
500 that says nothing of it but its `incident`. A visitor is not a refusal: resolve one to the
|
|
1314
1401
|
principal your Sources treat as nobody, and refuse only a credential that was
|
|
1315
1402
|
sent and no longer holds.
|
|
1316
1403
|
|
|
@@ -1550,6 +1637,100 @@ export const checked = checkCache(
|
|
|
1550
1637
|
`Cheap` is a Query a server registers with `RemoteServer.query`; its answer
|
|
1551
1638
|
is kept for 30 seconds, the shorter of its own and `Price`'s.
|
|
1552
1639
|
|
|
1640
|
+
## When the server fails
|
|
1641
|
+
|
|
1642
|
+
A call that does not succeed tells its caller one of two kinds of thing, and
|
|
1643
|
+
which is decided by the type of the error where it is made, never by reading
|
|
1644
|
+
its message:
|
|
1645
|
+
|
|
1646
|
+
| What happened | What the caller reads |
|
|
1647
|
+
| --- | --- |
|
|
1648
|
+
| A refusal the application wrote: `RemoteServer.refuse`, `forbid`, `unauthenticated`, a writer's `unmet`, `taken` or `invalid` | the refusal, its message and its reason, as written; of a `forbid` or an `unauthenticated`, `answer` and `serveFetch` send the reason, or `Forbidden` or `Unauthenticated` when it has none |
|
|
1649
|
+
| `RemoteServer.tell(message)` | `message`, as written |
|
|
1650
|
+
| The request itself is at fault: an unknown query or mutation, an input its Schema refuses, too many ids, another protocol version | the server's fixed sentence, naming only what the request said |
|
|
1651
|
+
| Anything else: a `RemoteServerError` not made with `tell`, anything thrown in a Source, an `authorize`, a `filter`, `memory`'s `readable` or an operator, a defect, a mutation output its Schema refuses | `Internal error`, and an `incident` |
|
|
1652
|
+
|
|
1653
|
+
So a failure nobody classified is this side's: its message and cause are
|
|
1654
|
+
reported as a `ServerDefect` [diagnostic](#diagnostics) and never sent. A
|
|
1655
|
+
Source says which it means:
|
|
1656
|
+
|
|
1657
|
+
```ts standalone
|
|
1658
|
+
import { Effect, Schema } from 'effect'
|
|
1659
|
+
import { Entity } from 'foldkit-remote'
|
|
1660
|
+
import { RemoteServer, RemoteServerError } from 'foldkit-remote-server'
|
|
1661
|
+
|
|
1662
|
+
const Report = Entity.make('Report', Schema.Struct({ id: Schema.String, total: Schema.Number }))
|
|
1663
|
+
|
|
1664
|
+
declare const building: (id: string) => boolean
|
|
1665
|
+
declare const totals: (
|
|
1666
|
+
ids: ReadonlyArray<string>,
|
|
1667
|
+
) => Promise<ReadonlyArray<{ readonly id: string; readonly total: number }>>
|
|
1668
|
+
|
|
1669
|
+
const ReportSource = RemoteServer.entity(Report, {
|
|
1670
|
+
read: ({ ids }) =>
|
|
1671
|
+
ids.some(building)
|
|
1672
|
+
? // Words for whoever asked: sent as written.
|
|
1673
|
+
Effect.fail(RemoteServer.tell('That report is still being built'))
|
|
1674
|
+
: Effect.tryPromise({
|
|
1675
|
+
try: () => totals(ids),
|
|
1676
|
+
// What the driver said stays on this side: reported, never sent.
|
|
1677
|
+
catch: cause => new RemoteServerError({ message: 'The totals query failed', cause }),
|
|
1678
|
+
}).pipe(Effect.map(rows => rows.map(row => ({ id: row.id, values: row })))),
|
|
1679
|
+
})
|
|
1680
|
+
```
|
|
1681
|
+
|
|
1682
|
+
`RemoteServer.tell` takes text, not what was caught: an error's own message
|
|
1683
|
+
may say anything, so `tell(caught)` does not compile. Write what it says from
|
|
1684
|
+
what the caller may know.
|
|
1685
|
+
|
|
1686
|
+
The `incident` is 16 hex characters, made for each failure. The caller's
|
|
1687
|
+
error carries it (`{ error: 'Internal error', incident }` over JSON, the
|
|
1688
|
+
`incident` field of `RemoteReadError`, `RemoteQueryError`,
|
|
1689
|
+
`RemoteMutationError` and `RemoteLiveError` over RPC, and of a live stream's
|
|
1690
|
+
error frame), and the client reads it with `RemoteData.incident(error)`. The
|
|
1691
|
+
report carries the same id, what was asked (`during`), and the cause (its
|
|
1692
|
+
stack lines left out here):
|
|
1693
|
+
|
|
1694
|
+
```text
|
|
1695
|
+
[foldkit-remote-server] incident 3f9c2a7be01d4c55: read Report failed on this side. No caller is told more of it than this id.
|
|
1696
|
+
RemoteServerError: The totals query failed
|
|
1697
|
+
[cause]: Error: SQLITE_BUSY: database is locked
|
|
1698
|
+
```
|
|
1699
|
+
|
|
1700
|
+
What this does not cover: a refusal's message, a `forbid` reason, an
|
|
1701
|
+
invariant's message and `tell`'s text are sent as written, so nothing a
|
|
1702
|
+
caller may not know belongs in them; and a 400's `error` is the protocol
|
|
1703
|
+
Schema's own account of the request's payload. There is no switch that puts
|
|
1704
|
+
the cause in a response: read the report.
|
|
1705
|
+
|
|
1706
|
+
### Reporting from an adapter or a scheduled job
|
|
1707
|
+
|
|
1708
|
+
A failure outside a handler has no caller's error to carry an incident: a job
|
|
1709
|
+
a cron trigger runs, or an adapter answering on a transport of its own.
|
|
1710
|
+
`RemoteServer.report(during, cause)` reports it as the server reports its own,
|
|
1711
|
+
a `ServerDefect` under a new incident, and answers the only thing that may go
|
|
1712
|
+
further: `{ message: 'Internal error', incident }`.
|
|
1713
|
+
|
|
1714
|
+
```ts standalone
|
|
1715
|
+
import { Effect } from 'effect'
|
|
1716
|
+
import { RemoteServer } from 'foldkit-remote-server'
|
|
1717
|
+
|
|
1718
|
+
declare const publishDue: Effect.Effect<void, unknown>
|
|
1719
|
+
declare const remember: (shown: string) => Effect.Effect<void>
|
|
1720
|
+
|
|
1721
|
+
export const job = publishDue.pipe(
|
|
1722
|
+
Effect.catchCause(cause =>
|
|
1723
|
+
Effect.flatMap(RemoteServer.report('publish due', cause), ({ message, incident }) =>
|
|
1724
|
+
// What a reader of the job's outcome may see: the words and the id.
|
|
1725
|
+
remember(`${message} (incident ${incident})`),
|
|
1726
|
+
),
|
|
1727
|
+
),
|
|
1728
|
+
)
|
|
1729
|
+
```
|
|
1730
|
+
|
|
1731
|
+
It takes what was caught, or a `Cause`, and returns nothing of either. It
|
|
1732
|
+
reports through the `Diagnostics.Reporter` of the Effect it runs in.
|
|
1733
|
+
|
|
1553
1734
|
## Diagnostics
|
|
1554
1735
|
|
|
1555
1736
|
A server answers some failures without telling the caller why. Each is a
|
|
@@ -1558,7 +1739,7 @@ channel, re-exported by `foldkit-remote`), which by default is Effect's log:
|
|
|
1558
1739
|
|
|
1559
1740
|
| `_tag` | `level` | When |
|
|
1560
1741
|
| --- | --- | --- |
|
|
1561
|
-
| `ServerDefect` | `error` | Something on this side broke (a layer, a resolver, a handler's defect)
|
|
1742
|
+
| `ServerDefect` | `error` | Something on this side broke (a Source's failure not made with `RemoteServer.tell`, a thrown error, a layer, a resolver, a handler's defect). It carries the `cause`, the `incident` a caller was answered with, and `during`: what was asked (`read Note`, `query Notes`, `mutate SaveNote`, `live Note`, or `request` where no handler was reached). |
|
|
1562
1743
|
| `AnswerUnread` | `warning` | A mutation committed, but reading its answer failed: the client reads those rows again. |
|
|
1563
1744
|
| `PublishFailed` | `error` | A mutation committed, but its live publish failed: live subscribers do not hear it. |
|
|
1564
1745
|
| `ClockSkewed` | `warning` | A write's time was past `clockSkew` from the server's clock (a client clock that is off, or a durable write that waited), so the server wrote its own; it carries `sent`, `own` and `bound`. |
|
package/dist/fetch.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { M as ServerDefinition, u as LiveHub } from "./index-
|
|
1
|
+
import { M as ServerDefinition, u as LiveHub } from "./index-Dq3fHdhH.mjs";
|
|
2
2
|
import { Duration, Effect, Layer } from "effect";
|
|
3
3
|
import { CacheStore, Diagnostic, NavigationRequest, RemoteClient, RemoteUnauthenticated, ScriptedRequest } from "foldkit-remote";
|
|
4
4
|
/** What `serveFetch` needs of the host runtime, per request. */
|
package/dist/fetch.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch.d.mts","names":[],"sources":["../src/fetch.ts"],"mappings":";;;;iBAkEiB,YAAY,GAAG,GAAG,KAAK;;WAE7B,QAAQ,iBAAiB,GAAG;;;;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;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"}
|
package/dist/fetch.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { b as cachedReadDiffers, d as declaresTooLarge, f as discardBody, i as RemoteServer, m as tooLargeAnswer, p as readJson, x as
|
|
1
|
+
import { b as cachedReadDiffers, d as declaresTooLarge, f as discardBody, i as RemoteServer, m as tooLargeAnswer, p as readJson, x as internalFailure, y as unauthenticatedAnswer } from "./src-6l1A9ww5.mjs";
|
|
2
2
|
import { Cause, Deferred, Duration, Effect, Exit, Layer, Option, Result, Schedule, Schema, Scope, Stream } from "effect";
|
|
3
3
|
import { CacheStore, CachedRead, DEFAULT_MAX_BODY_BYTES, Diagnostics, LiveRequirement, MutationResult, PageReads, QueryRequest, QueryResult, ReadBatch, ReadBatchResult, Remote, RemoteJsonRequest, RemoteLiveError, RemoteMutationError, listTag, maxAgeSeconds, rowTag, shorterPolicy, stableStringify } from "foldkit-remote";
|
|
4
4
|
// src/edgeCache.ts
|
|
@@ -196,11 +196,14 @@ const errorFrame = (message, refusal = {}) => `event: error\ndata: ${JSON.string
|
|
|
196
196
|
const liveBytes = (handlers, payload, heartbeat, checked) => Stream.unwrap(Effect.gen(function* () {
|
|
197
197
|
const ended = yield* Deferred.make();
|
|
198
198
|
const events = Stream.merge(handlers.FoldkitRemoteLive(payload), checked, { haltStrategy: "left" }).pipe(Stream.map((change) => `data: ${JSON.stringify(change)}\n\n`), Stream.catchTags({
|
|
199
|
-
RemoteLiveError: (error) => Stream.succeed(errorFrame(error.message)),
|
|
199
|
+
RemoteLiveError: (error) => Stream.succeed(errorFrame(error.message, error.incident === void 0 ? {} : { incident: error.incident })),
|
|
200
200
|
RemoteLiveRefused: (error) => Stream.succeed(errorFrame(error.message, { refused: true })),
|
|
201
201
|
RemoteProtocolError: (error) => Stream.succeed(errorFrame(error.message)),
|
|
202
|
-
Unauthenticated: (error) =>
|
|
203
|
-
|
|
202
|
+
Unauthenticated: (error) => {
|
|
203
|
+
const { body } = unauthenticatedAnswer(error);
|
|
204
|
+
return Stream.succeed(errorFrame(body.error, { unauthenticated: body.unauthenticated }));
|
|
205
|
+
}
|
|
206
|
+
}), Stream.catchCause((cause) => Cause.hasInterruptsOnly(cause) ? Stream.failCause(cause) : Stream.fromEffect(Effect.map(internalFailure("live", cause), ({ message, incident }) => errorFrame(message, { incident })))), Stream.ensuring(Deferred.succeed(ended, void 0)));
|
|
204
207
|
const beats = Stream.concat(Stream.succeed(": ping\n\n"), Stream.fromSchedule(Schedule.spaced(heartbeat)).pipe(Stream.map(() => ": ping\n\n"))).pipe(Stream.interruptWhen(Deferred.await(ended)));
|
|
205
208
|
return Stream.merge(events, beats);
|
|
206
209
|
})).pipe(Stream.encodeText);
|
|
@@ -373,8 +376,11 @@ const serveFetch = (config) => {
|
|
|
373
376
|
return (yield* Layer.buildWithScope(config.layer(env), scope).pipe(Effect.flatMap((context) => Effect.provide(respond(request, env, scope), context)), Effect.onExit((exit) => Exit.isSuccess(exit) && exit.value.live ? Effect.void : Scope.close(scope, exit)))).response;
|
|
374
377
|
}).pipe(reportingFor(request)));
|
|
375
378
|
if (Exit.isSuccess(exit)) return exit.value;
|
|
376
|
-
await Effect.runPromise(
|
|
377
|
-
return Response.json({
|
|
379
|
+
const told = await Effect.runPromise(internalFailure("request", exit.cause).pipe(reportingFor(request)));
|
|
380
|
+
return Response.json({
|
|
381
|
+
error: told.message,
|
|
382
|
+
incident: told.incident
|
|
383
|
+
}, { status: 500 });
|
|
378
384
|
};
|
|
379
385
|
return async (request, env) => {
|
|
380
386
|
const response = await served(request, env);
|
package/dist/fetch.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch.mjs","names":[],"sources":["../src/edgeCache.ts","../src/fetch.ts"],"sourcesContent":["/**\n * Which reads a server may share between whoever asks, and the tags a store\n * keeps them under (#428).\n *\n * A read is public only where the server can prove nothing about it depends\n * on who asks: every source it passes through has no `authorize`, no\n * `filter`, no `visible` rule (a guard's, a binding's, `memory`'s\n * `readable`) and no member answered per viewer, and every one declares how\n * long it stays fresh. Those rules are functions of the principal this\n * module cannot read, so it does not try: a source with one is private,\n * even where its rule happens to read only the row. A public read is then\n * answered as the visitor, whoever asks, so even a source's own `read` that\n * looks at the principal gives everyone one answer, never someone's own.\n */\nimport { Effect, Option, Schema } from 'effect'\nimport {\n CachedRead,\n MutationResult,\n PageReads,\n QueryResult,\n ReadBatchResult,\n listTag,\n rowTag,\n shorterPolicy,\n type CachePolicy,\n type ReadBatch,\n type QueryRequest,\n type RelationRequirement,\n type RemoteRpcClient,\n} from 'foldkit-remote'\nimport type { EntitySource, ServerDefinition } from './index.js'\n\ntype Batch = Schema.Schema.Type<typeof ReadBatch>\ntype QueryAsked = Schema.Schema.Type<typeof QueryRequest>\n\n/** A source's freshness, where nothing it runs is a rule about who asks. */\nconst sourcePolicy = <P, R>(source: EntitySource<P, R> | undefined): Option.Option<CachePolicy> =>\n source === undefined ||\n source.authorize !== undefined ||\n source.filter !== undefined ||\n source.visible !== undefined ||\n (source.perViewer ?? []).length > 0\n ? Option.none()\n : Option.fromUndefinedOr(source.cache)\n\n/** Two policies' shorter, none when either is none. */\nconst both = (a: Option.Option<CachePolicy>, b: Option.Option<CachePolicy>) =>\n Option.flatMap(a, left => Option.map(b, right => shorterPolicy(left, right)))\n\n/** A slice's policy: its entity's, and every relation's it reaches. */\nconst slicePolicy = <P, R>(\n server: ServerDefinition<P, R>,\n slice: RelationRequirement,\n): Option.Option<CachePolicy> =>\n Object.values(slice.relations ?? {}).reduce(\n (policy, relation) => both(policy, slicePolicy(server, relation)),\n sourcePolicy(server.entities.get(slice.entity)),\n )\n\n/** A read batch's policy: none for an empty one, which keeps nothing worth a key. */\nexport const readPolicy = <P, R>(\n server: ServerDefinition<P, R>,\n batch: Batch,\n): Option.Option<CachePolicy> =>\n batch.requests.length === 0\n ? Option.none()\n : batch.requests.map(request => slicePolicy(server, request)).reduce(both)\n\n/** A query's policy: its own, its rows' and what its `select` reaches. */\nexport const queryPolicy = <P, R>(\n server: ServerDefinition<P, R>,\n request: QueryAsked,\n): Option.Option<CachePolicy> => {\n const source = server.queries.get(request.query)\n if (source === undefined || source.visible !== undefined) return Option.none()\n const own = both(\n Option.fromUndefinedOr(source.cache),\n sourcePolicy(server.entities.get(source.entity)),\n )\n return request.select === undefined ? own : both(own, slicePolicy(server, request.select))\n}\n\ntype Row = { readonly entity: string; readonly id: string }\n\nconst rowTags = (rows: ReadonlyArray<Row>): ReadonlyArray<string> =>\n rows.map(row => rowTag(row.entity, row.id))\n\n/** What a read's answer holds: each row asked for, found or not, and each it reached. */\nexport const readTags = (\n batch: Batch,\n result: Schema.Schema.Type<typeof ReadBatchResult>,\n): ReadonlyArray<string> => [\n ...new Set([...rowTags(batch.requests), ...rowTags(result.entities), ...rowTags(result.settled)]),\n]\n\n/** What a query's answer holds: every list of its entity, and each row on the page. */\nexport const queryTags = <P, R>(\n server: ServerDefinition<P, R>,\n request: QueryAsked,\n result: Schema.Schema.Type<typeof QueryResult>,\n): ReadonlyArray<string> => [\n ...new Set([\n ...Option.toArray(\n Option.map(Option.fromUndefinedOr(server.queries.get(request.query)), source =>\n listTag(source.entity),\n ),\n ),\n ...rowTags(result.edges),\n ...rowTags(result.entities ?? []),\n ]),\n]\n\nconst decodeMutationResult = Schema.decodeUnknownOption(MutationResult)\n\n/**\n * What a write's answer names, as tags to purge: each row it wrote, deleted,\n * moved in a list or read back, and every list of each of their entities,\n * which a changed row can join or leave. A write naming nothing purges nothing.\n */\nexport const writeTags = (result: unknown): ReadonlyArray<string> =>\n Option.match(decodeMutationResult(result), {\n onNone: () => [],\n onSome: answer => {\n const rows: ReadonlyArray<Row> = [\n ...answer.entities,\n ...(answer.deleted ?? []),\n ...(answer.connections ?? []).map(change => change.edge),\n ...(answer.read?.result.entities ?? []),\n ...(answer.lists ?? []).flatMap(list => [\n ...list.result.edges,\n ...(list.result.entities ?? []),\n ]),\n ]\n return [...new Set([...rowTags(rows), ...rows.map(row => listTag(row.entity))])]\n },\n })\n\n/** An answer as anyone may be given it: without whom it was for. */\nconst unaddressed = <A extends { readonly principal?: unknown }>(\n answer: A,\n): Omit<A, 'principal'> => {\n const { principal: _, ...rest } = answer\n return rest\n}\n\nconst hex = (bytes: ArrayBuffer): string =>\n [...new Uint8Array(bytes)].map(byte => byte.toString(16).padStart(2, '0')).join('')\n\n/**\n * The key a request's answer is kept under: the SHA-256 of `text` (the\n * request as stable JSON), under the request's own origin, since the Workers\n * Cache API keys by URL.\n */\nexport const cacheKey = (url: string, kind: string, text: string): Effect.Effect<string> =>\n Effect.promise(() => crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))).pipe(\n Effect.map(digest => `${new URL(url).origin}/__foldkit/cache/${kind}/${hex(digest)}`),\n )\n\n/** The most rows a private read names: a batch can ask for hundreds. */\nconst NAMED_ROWS = 3\n\n/** What a read batch asked for, as a refusal names it: its first rows, and how many more. */\nconst batchName = (batch: Batch): string => {\n const rows = batch.requests.map(request => `${request.entity} ${request.id}`)\n const more = rows.length - NAMED_ROWS\n return `${rows.slice(0, NAMED_ROWS).join(', ')}${more > 0 ? ` and ${more} more` : ''}`\n}\n\n/**\n * Handlers that answer every read and query proved public as `visitor`, and\n * note each read in the render's `PageReads`: public with its policy and\n * tags, or private. Without a visitor every read is private, and so is one\n * that fails, since a page drawn without its read is no page to keep.\n */\nexport const notingHandlers = <P, R>(\n server: ServerDefinition<P, R>,\n own: RemoteRpcClient<R>,\n visitor: Option.Option<RemoteRpcClient<R>>,\n): RemoteRpcClient<R> => {\n const note = (read: CachedRead) =>\n Effect.flatMap(Effect.service(PageReads), noted =>\n Effect.sync(() => Option.map(noted, add => add(read))),\n )\n return {\n ...own,\n FoldkitRemoteRead: batch => {\n const unshared = note(CachedRead.Private({ read: batchName(batch) }))\n return Option.match(\n Option.flatMap(visitor, handlers =>\n Option.map(readPolicy(server, batch), policy => ({ handlers, policy })),\n ),\n {\n onNone: () => Effect.ensuring(own.FoldkitRemoteRead(batch), unshared),\n onSome: ({ handlers, policy }) =>\n Effect.flatMap(handlers.FoldkitRemoteRead(batch), result =>\n Effect.as(\n note(CachedRead.Public({ policy, tags: readTags(batch, result) })),\n unaddressed(result),\n ),\n ).pipe(Effect.onError(() => unshared)),\n },\n )\n },\n FoldkitRemoteQuery: request => {\n const unshared = note(CachedRead.Private({ read: `query ${request.query}` }))\n return Option.match(\n Option.flatMap(visitor, handlers =>\n Option.map(queryPolicy(server, request), policy => ({ handlers, policy })),\n ),\n {\n onNone: () => Effect.ensuring(own.FoldkitRemoteQuery(request), unshared),\n onSome: ({ handlers, policy }) =>\n Effect.flatMap(handlers.FoldkitRemoteQuery(request), result =>\n Effect.as(\n note(CachedRead.Public({ policy, tags: queryTags(server, request, result) })),\n unaddressed(result),\n ),\n ).pipe(Effect.onError(() => unshared)),\n },\n )\n },\n }\n}\n","/**\n * `foldkit-remote-server/fetch`: `RemoteServer` over the Fetch API, for\n * Cloudflare Workers and any other runtime that speaks `Request`/`Response`.\n *\n * Reads, queries, and mutations ride one `POST` each, as `Remote.http` sends\n * them and `RemoteServer.answer` answers them. Live requirements ride one\n * `POST` that answers with a `text/event-stream` of `LiveChange` frames, one\n * `data:` frame per change and a terminal `event: error` frame when the\n * stream fails; `httpWithLive` (`foldkit-remote/live`) is the other end. The principal is\n * resolved per request, from whatever the runtime hands over (a header, a\n * binding, a session), and the Sources' requirements are provided per\n * request from the environment (a D1 binding, a connection string).\n */\nimport {\n Cause,\n Deferred,\n Duration,\n Effect,\n Exit,\n Layer,\n Option,\n Result,\n Schedule,\n Schema,\n Scope,\n Stream,\n} from 'effect'\nimport {\n DEFAULT_MAX_BODY_BYTES,\n CacheStore,\n Diagnostics,\n LiveRequirement,\n QueryRequest,\n QueryResult,\n ReadBatch,\n ReadBatchResult,\n Remote,\n RemoteJsonRequest,\n RemoteLiveError,\n RemoteMutationError,\n maxAgeSeconds,\n stableStringify,\n type CachePolicy,\n type Diagnostic,\n type RemoteClient,\n type NavigationRequest,\n type RemoteJsonAnswer,\n type RemoteRpcClient,\n type RemoteUnauthenticated,\n type ScriptedRequest,\n} from 'foldkit-remote'\nimport { declaresTooLarge, discardBody, readJson, tooLargeAnswer } from './body.js'\nimport { cachedReadDiffers, serverDefect } from './diagnostics.js'\nimport {\n cacheKey,\n notingHandlers,\n queryPolicy,\n queryTags,\n readPolicy,\n readTags,\n writeTags,\n} from './edgeCache.js'\nimport { RemoteServer, type LiveHub, type ServerDefinition } from './index.js'\nimport { unauthenticatedAnswer } from './refusal.js'\n\n/** What `serveFetch` needs of the host runtime, per request. */\nexport interface FetchConfig<P, R, Env, RP = never> {\n /** The server definition, as `RemoteServer.make` built it. */\n readonly server: ServerDefinition<P, R>\n /**\n * Who this request is, from the request and the environment. Fails with\n * `RemoteServer.unauthenticated(reason?)` to refuse the caller: a 401.\n * What it needs (a session store, an auth service) comes from `layer`.\n * A resolver taking any `Request` fits; one typed for a navigation\n * (`NavigationRequest`) does not, since `/remote` writes.\n */\n readonly resolvePrincipal: (\n request: ScriptedRequest,\n env: Env,\n ) => Effect.Effect<P, RemoteUnauthenticated, RP>\n /**\n * What the Sources and the resolver need, from the environment. Built per\n * request, so kept cheap, and closed when the answer is sent, or, for a\n * live stream, when the stream ends.\n */\n readonly layer: (env: Env) => Layer.Layer<R | RP>\n /** The path answered; anything else is a 404. Default `/remote`. */\n readonly path?: string | undefined\n /**\n * Headers every answer to `principal` carries, a live stream's included;\n * a refusal has no principal and carries none. Whom the request was\n * answered as, say, for a client to repeat (`foldkit-auth`'s\n * `AuthServer.answered`).\n */\n readonly headers?: ((principal: P) => Readonly<Record<string, string>>) | undefined\n /** A hub whose `changed`/`deleted` signals reach the live streams this serves. */\n readonly live?: LiveHub<P, R> | undefined\n /**\n * Asks `resolvePrincipal` again, of the same request, every `every` while a\n * live stream is open. A refusal ends the stream with `Unauthenticated`,\n * which the client reads as a lost session; a principal whose `key`\n * differs from the one the stream opened with (`Policy.keyOf`, as\n * `liveHub`'s `key`) ends it as a live error, which the client opens again\n * after, as the new principal; without `key` only a refusal ends it.\n * Without `revalidate` a stream serves the principal it opened with until\n * it closes, a revoked session included.\n * `every` must be longer than zero: each pass asks the session store.\n */\n readonly revalidate?:\n | {\n readonly every: Duration.Input\n readonly key?: ((principal: P) => unknown) | undefined\n }\n | undefined\n /** A heartbeat comment every this often, keeping idle streams alive through proxies. Default 15 seconds. */\n readonly liveHeartbeat?: Duration.Input | undefined\n /**\n * Where this request's diagnostics go, with the request: each failure\n * answered \"Internal error\" or ending a live stream (a `ServerDefect`: a\n * broken layer or resolver, a handler's defect), whose cause the caller is\n * never told, and what the handlers report. The reporter in the Effect\n * context (`Diagnostics.Reporter`) when not given, by default the log.\n */\n readonly diagnostics?:\n | ((diagnostic: Diagnostic, request: Request) => Effect.Effect<void>)\n | undefined\n /** A read batch 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 levels; default 8. */\n readonly maxDepth?: number | undefined\n /**\n * A request body may not be larger than this many bytes; default 1 MiB. A\n * larger one is a 413 with Remote's `tooLarge` answer, refused before it is\n * decoded: by its `content-length` before the principal is resolved, or\n * once the bytes read pass the limit. Give the client the same number\n * (`Remote.clientLayer(…, { maxBodyBytes })`), so it cuts its reads to fit.\n */\n readonly maxBodyBytes?: number | undefined\n /**\n * Keeps public reads in `store` (#428). A read or query is public where\n * none of the sources it passes through has a rule about who asks\n * (`authorize`, `filter`, `visible`, a member per viewer) and each declares\n * how long it stays fresh (`EdgeCache.of` on its Entity, `cache` on its\n * Query). A public read is answered as `visitor`, whoever asks, so one\n * answer is right for everyone, and kept for the shortest `maxAge` it\n * reaches; it says `cache-control: public, max-age=…`. Every other answer\n * says `private, no-store`. A write answered here purges the kept reads\n * holding a row it names, and every list of that row's entity.\n *\n * `store` is a `CacheStore`, which serves nothing past its `maxAge`: an\n * answer carries no age, so one kept longer would read as fresh. A\n * `PageCacheStore` (`CacheStore.kv` with `keep`) is refused.\n *\n * `visitor` is the principal of someone not signed in: refused when the\n * server's `viewer` names a row for it. With `check`, for development and\n * tests, each public read is also answered as who asks, and a difference\n * is reported (`CachedReadDiffers`) and answered with the asker's own.\n */\n readonly cache?:\n | {\n readonly store: CacheStore\n readonly visitor: P\n readonly check?: boolean | undefined\n }\n | undefined\n}\n\n/** A read or query a cache may keep: how long, and the tags of its answer. */\ninterface Shareable {\n readonly policy: CachePolicy\n readonly tagsOf: (result: unknown) => ReadonlyArray<string>\n}\n\nconst decodeRequest = Schema.decodeUnknownOption(RemoteJsonRequest)\nconst decodeBatch = Schema.decodeUnknownOption(ReadBatch)\nconst decodeQuery = Schema.decodeUnknownOption(QueryRequest)\nconst decodeReadResult = Schema.decodeUnknownOption(ReadBatchResult)\nconst decodeQueryResult = Schema.decodeUnknownOption(QueryResult)\n\n/** `body`, when it is a read or query every source of which is public. */\nconst shareableOf = <P, R>(\n server: ServerDefinition<P, R>,\n body: unknown,\n): Option.Option<Shareable> =>\n Option.flatMap(decodeRequest(body), ({ operation, payload }) =>\n ({\n read: () =>\n Option.flatMap(decodeBatch(payload), batch =>\n Option.map(readPolicy(server, batch), policy => ({\n policy,\n tagsOf: (result: unknown) =>\n Option.match(decodeReadResult(result), {\n onNone: () => [],\n onSome: read => readTags(batch, read),\n }),\n })),\n ),\n query: () =>\n Option.flatMap(decodeQuery(payload), request =>\n Option.map(queryPolicy(server, request), policy => ({\n policy,\n tagsOf: (result: unknown) =>\n Option.match(decodeQueryResult(result), {\n onNone: () => [],\n onSome: page => queryTags(server, request, page),\n }),\n })),\n ),\n mutate: () => Option.none<Shareable>(),\n })[operation](),\n )\n\n/** An answer as anyone may be given it: its result without whom it was for. */\nconst unaddressedAnswer = (answer: RemoteJsonAnswer): RemoteJsonAnswer => {\n if (!('result' in answer) || typeof answer.result !== 'object' || answer.result === null)\n return answer\n const { principal: _, ...result } = answer.result as Readonly<Record<string, unknown>>\n return { result }\n}\n\n/** Whether `body` is a write: what it names, a cache purges. */\nconst isWrite = (body: unknown): boolean =>\n Option.exists(decodeRequest(body), request => request.operation === 'mutate')\n\n/** A visitor the server's `viewer` names a row for is someone: their reads are their own. */\nconst refuseSomeone = <P, R>(\n server: ServerDefinition<P, R>,\n cache: { readonly visitor: P } | undefined,\n): void => {\n if (\n cache !== undefined &&\n server.viewer !== undefined &&\n Option.isSome(server.viewer(cache.visitor))\n )\n throw new Error(\n 'foldkit-remote-server: cache.visitor must be no one, but the server viewer names a row for it',\n )\n}\n\n/** A live open over fetch: the requirements and the cursor it resumes after. */\nconst LiveFetchRequest = Schema.Struct({\n operation: Schema.Literal('live'),\n payload: Schema.Unknown,\n})\n\n/**\n * A terminal stream failure, so the client fails with its message instead of\n * hanging; a refusal of who is asking says so, as a 401's body does.\n */\nconst errorFrame = (\n message: string,\n refusal: Partial<RemoteJsonAnswer> | { readonly refused: true } = {},\n): string => `event: error\\ndata: ${JSON.stringify({ message, ...refusal })}\\n\\n`\n\n/**\n * The live stream as SSE bytes: one `data:` frame per change, then a\n * terminal `event: error` frame when the stream fails rather than ends. A\n * `: ping` comment opens the stream, so headers and a first byte reach the\n * client at once, and rides along every `heartbeat` so a stream with nothing\n * to say still moves: workers cancel responses that go quiet, and proxies\n * drop idle connections. The heartbeat ends with the events, so a stream\n * with nothing to serve still ends. A client that disconnects interrupts\n * the subscription, as closing the RPC stream would.\n */\nconst liveBytes = <R, RC>(\n handlers: RemoteRpcClient<R>,\n payload: Schema.Schema.Type<typeof LiveRequirement>,\n heartbeat: Duration.Input,\n checked: Stream.Stream<never, RemoteUnauthenticated | RemoteLiveError, RC>,\n): Stream.Stream<Uint8Array, never, R | RC> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const ended = yield* Deferred.make<void>()\n // The checks fail the stream, or stop with it.\n const events = Stream.merge(handlers.FoldkitRemoteLive(payload), checked, {\n haltStrategy: 'left',\n }).pipe(\n Stream.map(change => `data: ${JSON.stringify(change)}\\n\\n`),\n Stream.catchTags({\n RemoteLiveError: error => Stream.succeed(errorFrame(error.message)),\n // The client reads `refused` as asking again being refused again.\n RemoteLiveRefused: error => Stream.succeed(errorFrame(error.message, { refused: true })),\n RemoteProtocolError: error => Stream.succeed(errorFrame(error.message)),\n Unauthenticated: error =>\n Stream.succeed(\n errorFrame(error.message, {\n unauthenticated: unauthenticatedAnswer(error).body.unauthenticated,\n }),\n ),\n }),\n // A defect says nothing of itself to the client, as a 500 does, and is\n // reported; an interruption is the client leaving, with no one to tell.\n Stream.catchCause(cause =>\n Cause.hasInterruptsOnly(cause)\n ? Stream.failCause(cause)\n : Stream.fromEffect(\n Effect.as(Diagnostics.report(serverDefect(cause)), errorFrame('Internal error')),\n ),\n ),\n Stream.ensuring(Deferred.succeed(ended, undefined)),\n )\n const beats = Stream.concat(\n Stream.succeed(': ping\\n\\n'),\n Stream.fromSchedule(Schedule.spaced(heartbeat)).pipe(Stream.map(() => ': ping\\n\\n')),\n ).pipe(Stream.interruptWhen(Deferred.await(ended)))\n return Stream.merge(events, beats)\n }),\n ).pipe(Stream.encodeText)\n\n/**\n * Whether the body opens a live stream rather than asking `answer`. Anything\n * else, including a body that is not a request at all, is `answer`'s to\n * refuse with a 400.\n */\nconst isLiveOpen = (body: unknown): body is Schema.Schema.Type<typeof LiveFetchRequest> => {\n try {\n return Schema.decodeUnknownSync(LiveFetchRequest)(body).operation === 'live'\n } catch {\n return false\n }\n}\n\n/** Heartbeats when the caller names none: under proxy idle timeouts. */\nconst DEFAULT_HEARTBEAT: Duration.Input = '15 seconds'\n\n/**\n * Answers a live open with the stream as `text/event-stream`. A payload no\n * live stream speaks is a 400 that subscribes to nothing. Once the stream\n * runs, its own failures are its terminal `event: error` frame.\n */\nconst liveResponse = <R, RC>(\n handlers: RemoteRpcClient<R>,\n payload: unknown,\n heartbeat: Duration.Input,\n checked: Stream.Stream<never, RemoteUnauthenticated | RemoteLiveError, RC>,\n release: Effect.Effect<void>,\n headers: Readonly<Record<string, string>>,\n): Effect.Effect<Response, never, R | RC> =>\n Schema.decodeUnknownEffect(LiveRequirement)(payload).pipe(\n Effect.matchEffect({\n onFailure: () =>\n Effect.succeed(\n Response.json(\n { error: 'The live payload is not a requirement' },\n { status: 400, headers },\n ),\n ),\n onSuccess: requirement =>\n Effect.map(\n Stream.toReadableStreamEffect(\n liveBytes(handlers, requirement, heartbeat, checked).pipe(Stream.ensuring(release)),\n ),\n body =>\n new Response(body, {\n headers: {\n ...headers,\n 'content-type': 'text/event-stream',\n },\n }),\n ),\n }),\n )\n\n/**\n * Answers Remote `POST`s with `Response`s: what a Worker's `fetch` hands to\n * the route. Each request is one Effect, with `layer` built once for it:\n * `resolvePrincipal` first, which refuses with `RemoteServer.unauthenticated`\n * (a 401, its `reason` the only words the caller reads); then the body. A\n * body that is not JSON, or not a request, is a 400 that reaches no handler;\n * a handler's failure a 500 with its message; anything else this side\n * breaks, the resolver's defects and the layer included, a 500 that says\n * nothing of it. A live open is answered with the stream instead. Each\n * answer is one principal's, so every response says `cache-control:\n * no-store`, unless `headers` gives a `cache-control` of its own.\n *\n * ```ts\n * export default {\n * fetch: serveFetch({\n * server,\n * resolvePrincipal: request =>\n * Effect.succeed({ actorId: request.headers.get('x-actor') ?? 'anon' }),\n * layer: env => databaseLayer(drizzle(env.DB)),\n * }),\n * }\n * ```\n */\nexport const serveFetch = <P, R, Env, RP = never>(\n config: FetchConfig<P, R, Env, RP>,\n): ((request: Request, env: Env) => Promise<Response>) => {\n const path = config.path ?? '/remote'\n refuseSomeone(config.server, config.cache)\n const maxBodyBytes = config.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES\n const heartbeat = config.liveHeartbeat ?? DEFAULT_HEARTBEAT\n if (\n config.revalidate !== undefined &&\n !Duration.isGreaterThan(Duration.fromInputUnsafe(config.revalidate.every), Duration.zero)\n )\n throw new Error('serveFetch: revalidate.every must be longer than zero')\n // Every request answered here is a `ScriptedRequest`: the brand is only what keeps a navigation's resolver out.\n const resolvePrincipal = config.resolvePrincipal as (\n request: Request,\n env: Env,\n ) => Effect.Effect<P, RemoteUnauthenticated, RP>\n /** `effect` reporting to `config.diagnostics` with `request`, when it is given. */\n const reportingFor =\n (request: Request) =>\n <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> => {\n const { diagnostics } = config\n return diagnostics === undefined\n ? effect\n : Effect.provideService(effect, Diagnostics.Reporter, diagnostic =>\n diagnostics(diagnostic, request),\n )\n }\n /** The live stream's principal, asked again of its request while it runs. */\n const revalidation = (\n request: Request,\n env: Env,\n opened: P,\n ): Stream.Stream<never, RemoteUnauthenticated | RemoteLiveError, RP> => {\n const { revalidate } = config\n if (revalidate === undefined) return Stream.empty\n return Stream.fromSchedule(Schedule.spaced(revalidate.every)).pipe(\n Stream.mapEffect(() => resolvePrincipal(request, env)),\n Stream.mapEffect(now =>\n revalidate.key === undefined || revalidate.key(opened) === revalidate.key(now)\n ? Effect.void\n : Effect.fail(\n new RemoteLiveError({ message: 'Who is asking changed: open the stream again' }),\n ),\n ),\n Stream.drain,\n )\n }\n /**\n * A public read: the visitor's answer, from the store or answered and kept.\n * Under `check`, also the asker's own, which is given instead where they differ.\n */\n const answerShared = (\n request: Request,\n body: unknown,\n cache: NonNullable<FetchConfig<P, R, Env, RP>['cache']>,\n shareable: Shareable,\n own: RemoteRpcClient<R>,\n headers: Readonly<Record<string, string>>,\n ): Effect.Effect<Response, never, R> =>\n Effect.gen(function* () {\n const asked = stableStringify(body)\n const key = yield* cacheKey(request.url, 'remote', asked)\n const kept = yield* cache.store.match(key)\n let text: string\n if (Option.isSome(kept)) {\n text = kept.value\n } else {\n const visitor = RemoteServer.handlers(config.server, cache.visitor, {\n maxIdsPerEntity: config.maxIdsPerEntity,\n maxDepth: config.maxDepth,\n })\n const answered = yield* RemoteServer.answer(visitor, body)\n // A refusal or a failure is nobody's to keep.\n if (answered.status !== 200) {\n return Response.json(answered.body, { status: answered.status, headers })\n }\n text = JSON.stringify(unaddressedAnswer(answered.body))\n yield* cache.store.put(key, text, {\n maxAge: shareable.policy.maxAge,\n tags: shareable.tagsOf('result' in answered.body ? answered.body.result : {}),\n })\n }\n if (cache.check === true) {\n const mine = yield* RemoteServer.answer(own, body)\n if (stableStringify(unaddressedAnswer(mine.body)) !== stableStringify(JSON.parse(text))) {\n yield* Diagnostics.report(cachedReadDiffers(asked))\n return Response.json(mine.body, { status: mine.status, headers })\n }\n }\n return new Response(text, {\n headers: {\n 'content-type': 'application/json',\n 'cache-control': `public, max-age=${maxAgeSeconds(shareable.policy)}`,\n ...headers,\n },\n })\n })\n /** `live` is whether the response streams, and so owns `scope` until it ends. */\n const respond = (\n request: Request,\n env: Env,\n scope: Scope.Closeable,\n ): Effect.Effect<{ readonly response: Response; readonly live: boolean }, never, R | RP> =>\n Effect.gen(function* () {\n const principal = yield* resolvePrincipal(request, env)\n const headers = config.headers?.(principal) ?? {}\n const body = yield* Effect.result(readJson(request, maxBodyBytes))\n if (Result.isFailure(body)) {\n const { status, answer } = body.failure\n return { response: Response.json(answer, { status, headers }), live: false }\n }\n // Bound per request: the principal is the request's own, as everywhere else.\n const handlers = RemoteServer.handlers(config.server, principal, {\n live: config.live,\n maxIdsPerEntity: config.maxIdsPerEntity,\n maxDepth: config.maxDepth,\n })\n if (isLiveOpen(body.success)) {\n const response = yield* liveResponse(\n handlers,\n body.success.payload,\n heartbeat,\n revalidation(request, env, principal),\n Scope.close(scope, Exit.void),\n headers,\n )\n // A 400 for a payload no stream speaks has no stream to close it.\n return { response, live: response.status === 200 }\n }\n const { cache } = config\n const shareable =\n cache === undefined ? Option.none<Shareable>() : shareableOf(config.server, body.success)\n if (cache !== undefined && Option.isSome(shareable)) {\n const response = yield* answerShared(\n request,\n body.success,\n cache,\n shareable.value,\n handlers,\n headers,\n )\n return { response, live: false }\n }\n const answered = yield* RemoteServer.answer(handlers, body.success)\n if (cache !== undefined && answered.status === 200 && isWrite(body.success)) {\n yield* cache.store.purge(writeTags('result' in answered.body ? answered.body.result : {}))\n }\n return {\n response: Response.json(answered.body, { status: answered.status, headers }),\n live: false,\n }\n }).pipe(\n Effect.catchTag('Unauthenticated', refusal => {\n const { status, body } = unauthenticatedAnswer(refusal)\n return Effect.succeed({ response: Response.json(body, { status }), live: false })\n }),\n )\n const served = async (request: Request, env: Env): Promise<Response> => {\n if (request.method !== 'POST' || new URL(request.url).pathname !== path) {\n return Response.json({ error: 'not found' }, { status: 404 })\n }\n // Refused on what it says of itself: no layer built, no principal asked, nothing read.\n if (declaresTooLarge(request, maxBodyBytes)) {\n return Response.json(tooLargeAnswer(maxBodyBytes), { status: 413 })\n }\n const exit = await Effect.runPromiseExit(\n Effect.gen(function* () {\n // Not Effect.provide(layer), which closes it when `respond` returns,\n // before a live stream has served a frame: the stream's re-reads and\n // revalidation would run on released resources.\n const scope = yield* Scope.make()\n const answered = yield* Layer.buildWithScope(config.layer(env), scope).pipe(\n Effect.flatMap(context => Effect.provide(respond(request, env, scope), context)),\n Effect.onExit(exit =>\n Exit.isSuccess(exit) && exit.value.live ? Effect.void : Scope.close(scope, exit),\n ),\n )\n return answered.response\n }).pipe(reportingFor(request)),\n )\n if (Exit.isSuccess(exit)) return exit.value\n // A failure of the layer, or a defect anywhere: this side broke, and the\n // caller learns that it did, not what; the diagnostics learn what. `answer`\n // already maps its own failures and defects to 400/500 answers.\n await Effect.runPromise(\n Diagnostics.report(serverDefect(exit.cause)).pipe(reportingFor(request)),\n )\n return Response.json({ error: 'Internal error' }, { status: 500 })\n }\n // Every answer but a public read's is read as one principal: no cache may\n // keep it for another. A `cache-control` of the application's own (`headers`) stands.\n return async (request, env) => {\n const response = await served(request, env)\n await discardBody(request, maxBodyBytes)\n if (!response.headers.has('cache-control')) {\n response.headers.set('cache-control', 'private, no-store')\n }\n return response\n }\n}\n\n/**\n * The cache's checker, for a test: serves each request twice through\n * `serveFetch` with `cache.check` and a store in memory, so every public read\n * is answered both as the visitor (kept, then from the store) and as whoever\n * the request resolves to. Rejects naming each read whose answers differ, and\n * when no read was public, which would check nothing. Give requests from at\n * least two principals, a visitor's and someone's; each is a function, since\n * a body is read once.\n */\nexport const checkCache = async <P, R, Env, RP = never>(\n config: Omit<FetchConfig<P, R, Env, RP>, 'cache' | 'diagnostics'> & {\n readonly cache: { readonly visitor: P }\n },\n requests: ReadonlyArray<() => Request>,\n env: Env,\n): Promise<void> => {\n const store = CacheStore.memory()\n const differs: Array<string> = []\n const serve = serveFetch({\n ...config,\n cache: { ...config.cache, store, check: true },\n diagnostics: diagnostic =>\n Effect.sync(() => {\n // tag-check: open -- a Diagnostic's tag is any package's; this one is ours.\n if (diagnostic._tag === 'CachedReadDiffers') differs.push(diagnostic.message)\n }),\n })\n for (const _round of [1, 2]) {\n for (const make of requests) await serve(make(), env)\n }\n if (differs.length > 0) throw new Error(differs.join('\\n'))\n if (store.size() === 0) {\n throw new Error('checkCache: no request was a public read, so nothing was checked')\n }\n}\n\n/**\n * What `pageReader` reads of a `serveFetch` config: the server, its Sources'\n * layer, its limits, and the cache's `visitor`.\n */\nexport type PageReaderConfig<P, R, Env, RP = never> = Pick<\n FetchConfig<P, R, Env, RP>,\n 'server' | 'layer' | 'maxIdsPerEntity' | 'maxDepth' | 'cache'\n> & {\n /**\n * Who a page request is. A resolver taking any `Request` fits; one typed\n * for a script's request (`ScriptedRequest`) does not, since a navigation\n * carries no header a script adds and that resolver would refuse every\n * signed-in reader.\n */\n readonly resolvePrincipal: (\n request: NavigationRequest,\n env: Env,\n ) => Effect.Effect<P, RemoteUnauthenticated, RP>\n}\n\n/**\n * The reader a page render reads through, in the same process: the request's\n * `RemoteClient`, answered by the server's own handlers with no HTTP between\n * them. Give it `serveFetch`'s config with the resolver a page's request\n * needs: a page `GET` is a navigation, which carries no header a script adds\n * (`AuthServer.resolver({ …, requests: 'navigation' })`).\n *\n * The principal is resolved, and `layer` built, when the reader is provided,\n * and `layer` closes when the Effect it was provided to ends, so provide it to\n * the pre-read itself (`Data.satisfy(…).pipe(Effect.provide(reader))`). A\n * refusal fails that Effect with `Unauthenticated`, as a 401 would. It only\n * reads: a mutation fails with `RemoteMutationError` and a live open with\n * `RemoteLiveError`, since a navigation can be started from another site.\n *\n * Each read is noted for a render `foldkit-ssr` may cache (`PageReads`):\n * with `cache`, one proved public as `serveFetch` proves it is answered as\n * `cache.visitor` and noted public; every other read, and every read without\n * `cache`, is noted private, which keeps the page from being cached.\n */\nexport const pageReader = <P, R, Env, RP = never>(config: PageReaderConfig<P, R, Env, RP>) => {\n refuseSomeone(config.server, config.cache)\n const limits = { maxIdsPerEntity: config.maxIdsPerEntity, maxDepth: config.maxDepth }\n const visitor = Option.map(Option.fromUndefinedOr(config.cache), cache =>\n RemoteServer.handlers(config.server, cache.visitor, limits),\n )\n // Every request read for is a page's: the brand is only what keeps a script's resolver out.\n const resolvePrincipal = config.resolvePrincipal as (\n request: Request,\n env: Env,\n ) => Effect.Effect<P, RemoteUnauthenticated, RP>\n return (request: Request, env: Env): Layer.Layer<RemoteClient, RemoteUnauthenticated> =>\n Layer.unwrap(\n Effect.map(resolvePrincipal(request, env), principal => {\n const handlers = notingHandlers(\n config.server,\n RemoteServer.handlers(config.server, principal, limits),\n visitor,\n )\n return Remote.clientLayer<R>({\n ...handlers,\n FoldkitRemoteMutate: () =>\n Effect.fail(\n new RemoteMutationError({ message: 'A page render reads; it does not write' }),\n ),\n FoldkitRemoteLive: () =>\n Stream.fail(new RemoteLiveError({ message: 'A page render keeps no live stream' })),\n })\n }),\n ).pipe(Layer.provide(config.layer(env)))\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAoCA,MAAM,g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O;EAAK;EAC7C,cAAa,eACX,OAAO,WAAW;GAEhB,IAAI,WAAW,SAAS,qBAAqB,QAAQ,KAAK,WAAW,OAAO;EAC9E,CAAC;CACL,CAAC;CACD,KAAK,MAAM,UAAU,CAAC,GAAG,CAAC,GACxB,KAAK,MAAM,QAAQ,UAAU,MAAM,MAAM,KAAK,GAAG,GAAG;CAEtD,IAAI,QAAQ,SAAS,GAAG,MAAM,IAAI,MAAM,QAAQ,KAAK,IAAI,CAAC;CAC1D,IAAI,MAAM,KAAK,MAAM,GACnB,MAAM,IAAI,MAAM,kEAAkE;AAEtF;;;;;;;;;;;;;;;;;;;;AAyCA,MAAa,cAAqC,WAA4C;CAC5F,cAAc,OAAO,QAAQ,OAAO,KAAK;CACzC,MAAM,SAAS;EAAE,iBAAiB,OAAO;EAAiB,UAAU,OAAO;CAAS;CACpF,MAAM,UAAU,OAAO,IAAI,OAAO,gBAAgB,OAAO,KAAK,IAAG,UAC/D,aAAa,SAAS,OAAO,QAAQ,MAAM,SAAS,MAAM,CAC5D;CAEA,MAAM,mBAAmB,OAAO;CAIhC,QAAQ,SAAkB,QACxB,MAAM,OACJ,OAAO,IAAI,iBAAiB,SAAS,GAAG,IAAG,cAAa;EACtD,MAAM,WAAW,eACf,OAAO,QACP,aAAa,SAAS,OAAO,QAAQ,WAAW,MAAM,GACtD,OACF;EACA,OAAO,OAAO,YAAe;GAC3B,GAAG;GACH,2BACE,OAAO,KACL,IAAI,oBAAoB,EAAE,SAAS,yCAAyC,CAAC,CAC/E;GACF,yBACE,OAAO,KAAK,IAAI,gBAAgB,EAAE,SAAS,qCAAqC,CAAC,CAAC;EACtF,CAAC;CACH,CAAC,CACH,CAAC,CAAC,KAAK,MAAM,QAAQ,OAAO,MAAM,GAAG,CAAC,CAAC;AAC3C"}
|
|
1
|
+
{"version":3,"file":"fetch.mjs","names":[],"sources":["../src/edgeCache.ts","../src/fetch.ts"],"sourcesContent":["/**\n * Which reads a server may share between whoever asks, and the tags a store\n * keeps them under (#428).\n *\n * A read is public only where the server can prove nothing about it depends\n * on who asks: every source it passes through has no `authorize`, no\n * `filter`, no `visible` rule (a guard's, a binding's, `memory`'s\n * `readable`) and no member answered per viewer, and every one declares how\n * long it stays fresh. Those rules are functions of the principal this\n * module cannot read, so it does not try: a source with one is private,\n * even where its rule happens to read only the row. A public read is then\n * answered as the visitor, whoever asks, so even a source's own `read` that\n * looks at the principal gives everyone one answer, never someone's own.\n */\nimport { Effect, Option, Schema } from 'effect'\nimport {\n CachedRead,\n MutationResult,\n PageReads,\n QueryResult,\n ReadBatchResult,\n listTag,\n rowTag,\n shorterPolicy,\n type CachePolicy,\n type ReadBatch,\n type QueryRequest,\n type RelationRequirement,\n type RemoteRpcClient,\n} from 'foldkit-remote'\nimport type { EntitySource, ServerDefinition } from './index.js'\n\ntype Batch = Schema.Schema.Type<typeof ReadBatch>\ntype QueryAsked = Schema.Schema.Type<typeof QueryRequest>\n\n/** A source's freshness, where nothing it runs is a rule about who asks. */\nconst sourcePolicy = <P, R>(source: EntitySource<P, R> | undefined): Option.Option<CachePolicy> =>\n source === undefined ||\n source.authorize !== undefined ||\n source.filter !== undefined ||\n source.visible !== undefined ||\n (source.perViewer ?? []).length > 0\n ? Option.none()\n : Option.fromUndefinedOr(source.cache)\n\n/** Two policies' shorter, none when either is none. */\nconst both = (a: Option.Option<CachePolicy>, b: Option.Option<CachePolicy>) =>\n Option.flatMap(a, left => Option.map(b, right => shorterPolicy(left, right)))\n\n/** A slice's policy: its entity's, and every relation's it reaches. */\nconst slicePolicy = <P, R>(\n server: ServerDefinition<P, R>,\n slice: RelationRequirement,\n): Option.Option<CachePolicy> =>\n Object.values(slice.relations ?? {}).reduce(\n (policy, relation) => both(policy, slicePolicy(server, relation)),\n sourcePolicy(server.entities.get(slice.entity)),\n )\n\n/** A read batch's policy: none for an empty one, which keeps nothing worth a key. */\nexport const readPolicy = <P, R>(\n server: ServerDefinition<P, R>,\n batch: Batch,\n): Option.Option<CachePolicy> =>\n batch.requests.length === 0\n ? Option.none()\n : batch.requests.map(request => slicePolicy(server, request)).reduce(both)\n\n/** A query's policy: its own, its rows' and what its `select` reaches. */\nexport const queryPolicy = <P, R>(\n server: ServerDefinition<P, R>,\n request: QueryAsked,\n): Option.Option<CachePolicy> => {\n const source = server.queries.get(request.query)\n if (source === undefined || source.visible !== undefined) return Option.none()\n const own = both(\n Option.fromUndefinedOr(source.cache),\n sourcePolicy(server.entities.get(source.entity)),\n )\n return request.select === undefined ? own : both(own, slicePolicy(server, request.select))\n}\n\ntype Row = { readonly entity: string; readonly id: string }\n\nconst rowTags = (rows: ReadonlyArray<Row>): ReadonlyArray<string> =>\n rows.map(row => rowTag(row.entity, row.id))\n\n/** What a read's answer holds: each row asked for, found or not, and each it reached. */\nexport const readTags = (\n batch: Batch,\n result: Schema.Schema.Type<typeof ReadBatchResult>,\n): ReadonlyArray<string> => [\n ...new Set([...rowTags(batch.requests), ...rowTags(result.entities), ...rowTags(result.settled)]),\n]\n\n/** What a query's answer holds: every list of its entity, and each row on the page. */\nexport const queryTags = <P, R>(\n server: ServerDefinition<P, R>,\n request: QueryAsked,\n result: Schema.Schema.Type<typeof QueryResult>,\n): ReadonlyArray<string> => [\n ...new Set([\n ...Option.toArray(\n Option.map(Option.fromUndefinedOr(server.queries.get(request.query)), source =>\n listTag(source.entity),\n ),\n ),\n ...rowTags(result.edges),\n ...rowTags(result.entities ?? []),\n ]),\n]\n\nconst decodeMutationResult = Schema.decodeUnknownOption(MutationResult)\n\n/**\n * What a write's answer names, as tags to purge: each row it wrote, deleted,\n * moved in a list or read back, and every list of each of their entities,\n * which a changed row can join or leave. A write naming nothing purges nothing.\n */\nexport const writeTags = (result: unknown): ReadonlyArray<string> =>\n Option.match(decodeMutationResult(result), {\n onNone: () => [],\n onSome: answer => {\n const rows: ReadonlyArray<Row> = [\n ...answer.entities,\n ...(answer.deleted ?? []),\n ...(answer.connections ?? []).map(change => change.edge),\n ...(answer.read?.result.entities ?? []),\n ...(answer.lists ?? []).flatMap(list => [\n ...list.result.edges,\n ...(list.result.entities ?? []),\n ]),\n ]\n return [...new Set([...rowTags(rows), ...rows.map(row => listTag(row.entity))])]\n },\n })\n\n/** An answer as anyone may be given it: without whom it was for. */\nconst unaddressed = <A extends { readonly principal?: unknown }>(\n answer: A,\n): Omit<A, 'principal'> => {\n const { principal: _, ...rest } = answer\n return rest\n}\n\nconst hex = (bytes: ArrayBuffer): string =>\n [...new Uint8Array(bytes)].map(byte => byte.toString(16).padStart(2, '0')).join('')\n\n/**\n * The key a request's answer is kept under: the SHA-256 of `text` (the\n * request as stable JSON), under the request's own origin, since the Workers\n * Cache API keys by URL.\n */\nexport const cacheKey = (url: string, kind: string, text: string): Effect.Effect<string> =>\n Effect.promise(() => crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))).pipe(\n Effect.map(digest => `${new URL(url).origin}/__foldkit/cache/${kind}/${hex(digest)}`),\n )\n\n/** The most rows a private read names: a batch can ask for hundreds. */\nconst NAMED_ROWS = 3\n\n/** What a read batch asked for, as a refusal names it: its first rows, and how many more. */\nconst batchName = (batch: Batch): string => {\n const rows = batch.requests.map(request => `${request.entity} ${request.id}`)\n const more = rows.length - NAMED_ROWS\n return `${rows.slice(0, NAMED_ROWS).join(', ')}${more > 0 ? ` and ${more} more` : ''}`\n}\n\n/**\n * Handlers that answer every read and query proved public as `visitor`, and\n * note each read in the render's `PageReads`: public with its policy and\n * tags, or private. Without a visitor every read is private, and so is one\n * that fails, since a page drawn without its read is no page to keep.\n */\nexport const notingHandlers = <P, R>(\n server: ServerDefinition<P, R>,\n own: RemoteRpcClient<R>,\n visitor: Option.Option<RemoteRpcClient<R>>,\n): RemoteRpcClient<R> => {\n const note = (read: CachedRead) =>\n Effect.flatMap(Effect.service(PageReads), noted =>\n Effect.sync(() => Option.map(noted, add => add(read))),\n )\n return {\n ...own,\n FoldkitRemoteRead: batch => {\n const unshared = note(CachedRead.Private({ read: batchName(batch) }))\n return Option.match(\n Option.flatMap(visitor, handlers =>\n Option.map(readPolicy(server, batch), policy => ({ handlers, policy })),\n ),\n {\n onNone: () => Effect.ensuring(own.FoldkitRemoteRead(batch), unshared),\n onSome: ({ handlers, policy }) =>\n Effect.flatMap(handlers.FoldkitRemoteRead(batch), result =>\n Effect.as(\n note(CachedRead.Public({ policy, tags: readTags(batch, result) })),\n unaddressed(result),\n ),\n ).pipe(Effect.onError(() => unshared)),\n },\n )\n },\n FoldkitRemoteQuery: request => {\n const unshared = note(CachedRead.Private({ read: `query ${request.query}` }))\n return Option.match(\n Option.flatMap(visitor, handlers =>\n Option.map(queryPolicy(server, request), policy => ({ handlers, policy })),\n ),\n {\n onNone: () => Effect.ensuring(own.FoldkitRemoteQuery(request), unshared),\n onSome: ({ handlers, policy }) =>\n Effect.flatMap(handlers.FoldkitRemoteQuery(request), result =>\n Effect.as(\n note(CachedRead.Public({ policy, tags: queryTags(server, request, result) })),\n unaddressed(result),\n ),\n ).pipe(Effect.onError(() => unshared)),\n },\n )\n },\n }\n}\n","/**\n * `foldkit-remote-server/fetch`: `RemoteServer` over the Fetch API, for\n * Cloudflare Workers and any other runtime that speaks `Request`/`Response`.\n *\n * Reads, queries, and mutations ride one `POST` each, as `Remote.http` sends\n * them and `RemoteServer.answer` answers them. Live requirements ride one\n * `POST` that answers with a `text/event-stream` of `LiveChange` frames, one\n * `data:` frame per change and a terminal `event: error` frame when the\n * stream fails; `httpWithLive` (`foldkit-remote/live`) is the other end. The principal is\n * resolved per request, from whatever the runtime hands over (a header, a\n * binding, a session), and the Sources' requirements are provided per\n * request from the environment (a D1 binding, a connection string).\n */\nimport {\n Cause,\n Deferred,\n Duration,\n Effect,\n Exit,\n Layer,\n Option,\n Result,\n Schedule,\n Schema,\n Scope,\n Stream,\n} from 'effect'\nimport {\n DEFAULT_MAX_BODY_BYTES,\n CacheStore,\n Diagnostics,\n LiveRequirement,\n QueryRequest,\n QueryResult,\n ReadBatch,\n ReadBatchResult,\n Remote,\n RemoteJsonRequest,\n RemoteLiveError,\n RemoteMutationError,\n maxAgeSeconds,\n stableStringify,\n type CachePolicy,\n type Diagnostic,\n type RemoteClient,\n type NavigationRequest,\n type RemoteJsonAnswer,\n type RemoteRpcClient,\n type RemoteUnauthenticated,\n type ScriptedRequest,\n} from 'foldkit-remote'\nimport { declaresTooLarge, discardBody, readJson, tooLargeAnswer } from './body.js'\nimport { cachedReadDiffers, internalFailure } from './diagnostics.js'\nimport {\n cacheKey,\n notingHandlers,\n queryPolicy,\n queryTags,\n readPolicy,\n readTags,\n writeTags,\n} from './edgeCache.js'\nimport { RemoteServer, type LiveHub, type ServerDefinition } from './index.js'\nimport { unauthenticatedAnswer } from './refusal.js'\n\n/** What `serveFetch` needs of the host runtime, per request. */\nexport interface FetchConfig<P, R, Env, RP = never> {\n /** The server definition, as `RemoteServer.make` built it. */\n readonly server: ServerDefinition<P, R>\n /**\n * Who this request is, from the request and the environment. Fails with\n * `RemoteServer.unauthenticated(reason?)` to refuse the caller: a 401.\n * What it needs (a session store, an auth service) comes from `layer`.\n * A resolver taking any `Request` fits; one typed for a navigation\n * (`NavigationRequest`) does not, since `/remote` writes.\n */\n readonly resolvePrincipal: (\n request: ScriptedRequest,\n env: Env,\n ) => Effect.Effect<P, RemoteUnauthenticated, RP>\n /**\n * What the Sources and the resolver need, from the environment. Built per\n * request, so kept cheap, and closed when the answer is sent, or, for a\n * live stream, when the stream ends.\n */\n readonly layer: (env: Env) => Layer.Layer<R | RP>\n /** The path answered; anything else is a 404. Default `/remote`. */\n readonly path?: string | undefined\n /**\n * Headers every answer to `principal` carries, a live stream's included;\n * a refusal has no principal and carries none. Whom the request was\n * answered as, say, for a client to repeat (`foldkit-auth`'s\n * `AuthServer.answered`).\n */\n readonly headers?: ((principal: P) => Readonly<Record<string, string>>) | undefined\n /** A hub whose `changed`/`deleted` signals reach the live streams this serves. */\n readonly live?: LiveHub<P, R> | undefined\n /**\n * Asks `resolvePrincipal` again, of the same request, every `every` while a\n * live stream is open. A refusal ends the stream with `Unauthenticated`,\n * which the client reads as a lost session; a principal whose `key`\n * differs from the one the stream opened with (`Policy.keyOf`, as\n * `liveHub`'s `key`) ends it as a live error, which the client opens again\n * after, as the new principal; without `key` only a refusal ends it.\n * Without `revalidate` a stream serves the principal it opened with until\n * it closes, a revoked session included.\n * `every` must be longer than zero: each pass asks the session store.\n */\n readonly revalidate?:\n | {\n readonly every: Duration.Input\n readonly key?: ((principal: P) => unknown) | undefined\n }\n | undefined\n /** A heartbeat comment every this often, keeping idle streams alive through proxies. Default 15 seconds. */\n readonly liveHeartbeat?: Duration.Input | undefined\n /**\n * Where this request's diagnostics go, with the request: each failure\n * answered \"Internal error\" or ending a live stream (a `ServerDefect`: a\n * broken layer or resolver, a handler's defect), whose cause the caller is\n * never told, and what the handlers report. The reporter in the Effect\n * context (`Diagnostics.Reporter`) when not given, by default the log.\n */\n readonly diagnostics?:\n | ((diagnostic: Diagnostic, request: Request) => Effect.Effect<void>)\n | undefined\n /** A read batch 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 levels; default 8. */\n readonly maxDepth?: number | undefined\n /**\n * A request body may not be larger than this many bytes; default 1 MiB. A\n * larger one is a 413 with Remote's `tooLarge` answer, refused before it is\n * decoded: by its `content-length` before the principal is resolved, or\n * once the bytes read pass the limit. Give the client the same number\n * (`Remote.clientLayer(…, { maxBodyBytes })`), so it cuts its reads to fit.\n */\n readonly maxBodyBytes?: number | undefined\n /**\n * Keeps public reads in `store` (#428). A read or query is public where\n * none of the sources it passes through has a rule about who asks\n * (`authorize`, `filter`, `visible`, a member per viewer) and each declares\n * how long it stays fresh (`EdgeCache.of` on its Entity, `cache` on its\n * Query). A public read is answered as `visitor`, whoever asks, so one\n * answer is right for everyone, and kept for the shortest `maxAge` it\n * reaches; it says `cache-control: public, max-age=…`. Every other answer\n * says `private, no-store`. A write answered here purges the kept reads\n * holding a row it names, and every list of that row's entity.\n *\n * `store` is a `CacheStore`, which serves nothing past its `maxAge`: an\n * answer carries no age, so one kept longer would read as fresh. A\n * `PageCacheStore` (`CacheStore.kv` with `keep`) is refused.\n *\n * `visitor` is the principal of someone not signed in: refused when the\n * server's `viewer` names a row for it. With `check`, for development and\n * tests, each public read is also answered as who asks, and a difference\n * is reported (`CachedReadDiffers`) and answered with the asker's own.\n */\n readonly cache?:\n | {\n readonly store: CacheStore\n readonly visitor: P\n readonly check?: boolean | undefined\n }\n | undefined\n}\n\n/** A read or query a cache may keep: how long, and the tags of its answer. */\ninterface Shareable {\n readonly policy: CachePolicy\n readonly tagsOf: (result: unknown) => ReadonlyArray<string>\n}\n\nconst decodeRequest = Schema.decodeUnknownOption(RemoteJsonRequest)\nconst decodeBatch = Schema.decodeUnknownOption(ReadBatch)\nconst decodeQuery = Schema.decodeUnknownOption(QueryRequest)\nconst decodeReadResult = Schema.decodeUnknownOption(ReadBatchResult)\nconst decodeQueryResult = Schema.decodeUnknownOption(QueryResult)\n\n/** `body`, when it is a read or query every source of which is public. */\nconst shareableOf = <P, R>(\n server: ServerDefinition<P, R>,\n body: unknown,\n): Option.Option<Shareable> =>\n Option.flatMap(decodeRequest(body), ({ operation, payload }) =>\n ({\n read: () =>\n Option.flatMap(decodeBatch(payload), batch =>\n Option.map(readPolicy(server, batch), policy => ({\n policy,\n tagsOf: (result: unknown) =>\n Option.match(decodeReadResult(result), {\n onNone: () => [],\n onSome: read => readTags(batch, read),\n }),\n })),\n ),\n query: () =>\n Option.flatMap(decodeQuery(payload), request =>\n Option.map(queryPolicy(server, request), policy => ({\n policy,\n tagsOf: (result: unknown) =>\n Option.match(decodeQueryResult(result), {\n onNone: () => [],\n onSome: page => queryTags(server, request, page),\n }),\n })),\n ),\n mutate: () => Option.none<Shareable>(),\n })[operation](),\n )\n\n/** An answer as anyone may be given it: its result without whom it was for. */\nconst unaddressedAnswer = (answer: RemoteJsonAnswer): RemoteJsonAnswer => {\n if (!('result' in answer) || typeof answer.result !== 'object' || answer.result === null)\n return answer\n const { principal: _, ...result } = answer.result as Readonly<Record<string, unknown>>\n return { result }\n}\n\n/** Whether `body` is a write: what it names, a cache purges. */\nconst isWrite = (body: unknown): boolean =>\n Option.exists(decodeRequest(body), request => request.operation === 'mutate')\n\n/** A visitor the server's `viewer` names a row for is someone: their reads are their own. */\nconst refuseSomeone = <P, R>(\n server: ServerDefinition<P, R>,\n cache: { readonly visitor: P } | undefined,\n): void => {\n if (\n cache !== undefined &&\n server.viewer !== undefined &&\n Option.isSome(server.viewer(cache.visitor))\n )\n throw new Error(\n 'foldkit-remote-server: cache.visitor must be no one, but the server viewer names a row for it',\n )\n}\n\n/** A live open over fetch: the requirements and the cursor it resumes after. */\nconst LiveFetchRequest = Schema.Struct({\n operation: Schema.Literal('live'),\n payload: Schema.Unknown,\n})\n\n/**\n * A terminal stream failure, so the client fails with its message instead of\n * hanging; a refusal of who is asking says so, as a 401's body does.\n */\nconst errorFrame = (\n message: string,\n refusal:\n | Partial<RemoteJsonAnswer>\n | { readonly refused: true }\n | { readonly incident?: string } = {},\n): string => `event: error\\ndata: ${JSON.stringify({ message, ...refusal })}\\n\\n`\n\n/**\n * The live stream as SSE bytes: one `data:` frame per change, then a\n * terminal `event: error` frame when the stream fails rather than ends. A\n * `: ping` comment opens the stream, so headers and a first byte reach the\n * client at once, and rides along every `heartbeat` so a stream with nothing\n * to say still moves: workers cancel responses that go quiet, and proxies\n * drop idle connections. The heartbeat ends with the events, so a stream\n * with nothing to serve still ends. A client that disconnects interrupts\n * the subscription, as closing the RPC stream would.\n */\nconst liveBytes = <R, RC>(\n handlers: RemoteRpcClient<R>,\n payload: Schema.Schema.Type<typeof LiveRequirement>,\n heartbeat: Duration.Input,\n checked: Stream.Stream<never, RemoteUnauthenticated | RemoteLiveError, RC>,\n): Stream.Stream<Uint8Array, never, R | RC> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const ended = yield* Deferred.make<void>()\n // The checks fail the stream, or stop with it.\n const events = Stream.merge(handlers.FoldkitRemoteLive(payload), checked, {\n haltStrategy: 'left',\n }).pipe(\n Stream.map(change => `data: ${JSON.stringify(change)}\\n\\n`),\n Stream.catchTags({\n RemoteLiveError: error =>\n Stream.succeed(\n errorFrame(\n error.message,\n error.incident === undefined ? {} : { incident: error.incident },\n ),\n ),\n // The client reads `refused` as asking again being refused again.\n RemoteLiveRefused: error => Stream.succeed(errorFrame(error.message, { refused: true })),\n RemoteProtocolError: error => Stream.succeed(errorFrame(error.message)),\n Unauthenticated: error => {\n const { body } = unauthenticatedAnswer(error)\n return Stream.succeed(errorFrame(body.error, { unauthenticated: body.unauthenticated }))\n },\n }),\n // A defect says nothing of itself to the client, as a 500 does, and is\n // reported; an interruption is the client leaving, with no one to tell.\n Stream.catchCause(cause =>\n Cause.hasInterruptsOnly(cause)\n ? Stream.failCause(cause)\n : Stream.fromEffect(\n Effect.map(internalFailure('live', cause), ({ message, incident }) =>\n errorFrame(message, { incident }),\n ),\n ),\n ),\n Stream.ensuring(Deferred.succeed(ended, undefined)),\n )\n const beats = Stream.concat(\n Stream.succeed(': ping\\n\\n'),\n Stream.fromSchedule(Schedule.spaced(heartbeat)).pipe(Stream.map(() => ': ping\\n\\n')),\n ).pipe(Stream.interruptWhen(Deferred.await(ended)))\n return Stream.merge(events, beats)\n }),\n ).pipe(Stream.encodeText)\n\n/**\n * Whether the body opens a live stream rather than asking `answer`. Anything\n * else, including a body that is not a request at all, is `answer`'s to\n * refuse with a 400.\n */\nconst isLiveOpen = (body: unknown): body is Schema.Schema.Type<typeof LiveFetchRequest> => {\n try {\n return Schema.decodeUnknownSync(LiveFetchRequest)(body).operation === 'live'\n } catch {\n return false\n }\n}\n\n/** Heartbeats when the caller names none: under proxy idle timeouts. */\nconst DEFAULT_HEARTBEAT: Duration.Input = '15 seconds'\n\n/**\n * Answers a live open with the stream as `text/event-stream`. A payload no\n * live stream speaks is a 400 that subscribes to nothing. Once the stream\n * runs, its own failures are its terminal `event: error` frame.\n */\nconst liveResponse = <R, RC>(\n handlers: RemoteRpcClient<R>,\n payload: unknown,\n heartbeat: Duration.Input,\n checked: Stream.Stream<never, RemoteUnauthenticated | RemoteLiveError, RC>,\n release: Effect.Effect<void>,\n headers: Readonly<Record<string, string>>,\n): Effect.Effect<Response, never, R | RC> =>\n Schema.decodeUnknownEffect(LiveRequirement)(payload).pipe(\n Effect.matchEffect({\n onFailure: () =>\n Effect.succeed(\n Response.json(\n { error: 'The live payload is not a requirement' },\n { status: 400, headers },\n ),\n ),\n onSuccess: requirement =>\n Effect.map(\n Stream.toReadableStreamEffect(\n liveBytes(handlers, requirement, heartbeat, checked).pipe(Stream.ensuring(release)),\n ),\n body =>\n new Response(body, {\n headers: {\n ...headers,\n 'content-type': 'text/event-stream',\n },\n }),\n ),\n }),\n )\n\n/**\n * Answers Remote `POST`s with `Response`s: what a Worker's `fetch` hands to\n * the route. Each request is one Effect, with `layer` built once for it:\n * `resolvePrincipal` first, which refuses with `RemoteServer.unauthenticated`\n * (a 401, its `reason` the only words the caller reads); then the body. A\n * body that is not JSON, or not a request, is a 400 that reaches no handler;\n * a handler's failure a 500 with its message; anything else this side\n * breaks, the resolver's defects and the layer included, a 500 that says\n * nothing of it. A live open is answered with the stream instead. Each\n * answer is one principal's, so every response says `cache-control:\n * no-store`, unless `headers` gives a `cache-control` of its own.\n *\n * ```ts\n * export default {\n * fetch: serveFetch({\n * server,\n * resolvePrincipal: request =>\n * Effect.succeed({ actorId: request.headers.get('x-actor') ?? 'anon' }),\n * layer: env => databaseLayer(drizzle(env.DB)),\n * }),\n * }\n * ```\n */\nexport const serveFetch = <P, R, Env, RP = never>(\n config: FetchConfig<P, R, Env, RP>,\n): ((request: Request, env: Env) => Promise<Response>) => {\n const path = config.path ?? '/remote'\n refuseSomeone(config.server, config.cache)\n const maxBodyBytes = config.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES\n const heartbeat = config.liveHeartbeat ?? DEFAULT_HEARTBEAT\n if (\n config.revalidate !== undefined &&\n !Duration.isGreaterThan(Duration.fromInputUnsafe(config.revalidate.every), Duration.zero)\n )\n throw new Error('serveFetch: revalidate.every must be longer than zero')\n // Every request answered here is a `ScriptedRequest`: the brand is only what keeps a navigation's resolver out.\n const resolvePrincipal = config.resolvePrincipal as (\n request: Request,\n env: Env,\n ) => Effect.Effect<P, RemoteUnauthenticated, RP>\n /** `effect` reporting to `config.diagnostics` with `request`, when it is given. */\n const reportingFor =\n (request: Request) =>\n <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> => {\n const { diagnostics } = config\n return diagnostics === undefined\n ? effect\n : Effect.provideService(effect, Diagnostics.Reporter, diagnostic =>\n diagnostics(diagnostic, request),\n )\n }\n /** The live stream's principal, asked again of its request while it runs. */\n const revalidation = (\n request: Request,\n env: Env,\n opened: P,\n ): Stream.Stream<never, RemoteUnauthenticated | RemoteLiveError, RP> => {\n const { revalidate } = config\n if (revalidate === undefined) return Stream.empty\n return Stream.fromSchedule(Schedule.spaced(revalidate.every)).pipe(\n Stream.mapEffect(() => resolvePrincipal(request, env)),\n Stream.mapEffect(now =>\n revalidate.key === undefined || revalidate.key(opened) === revalidate.key(now)\n ? Effect.void\n : Effect.fail(\n new RemoteLiveError({ message: 'Who is asking changed: open the stream again' }),\n ),\n ),\n Stream.drain,\n )\n }\n /**\n * A public read: the visitor's answer, from the store or answered and kept.\n * Under `check`, also the asker's own, which is given instead where they differ.\n */\n const answerShared = (\n request: Request,\n body: unknown,\n cache: NonNullable<FetchConfig<P, R, Env, RP>['cache']>,\n shareable: Shareable,\n own: RemoteRpcClient<R>,\n headers: Readonly<Record<string, string>>,\n ): Effect.Effect<Response, never, R> =>\n Effect.gen(function* () {\n const asked = stableStringify(body)\n const key = yield* cacheKey(request.url, 'remote', asked)\n const kept = yield* cache.store.match(key)\n let text: string\n if (Option.isSome(kept)) {\n text = kept.value\n } else {\n const visitor = RemoteServer.handlers(config.server, cache.visitor, {\n maxIdsPerEntity: config.maxIdsPerEntity,\n maxDepth: config.maxDepth,\n })\n const answered = yield* RemoteServer.answer(visitor, body)\n // A refusal or a failure is nobody's to keep.\n if (answered.status !== 200) {\n return Response.json(answered.body, { status: answered.status, headers })\n }\n text = JSON.stringify(unaddressedAnswer(answered.body))\n yield* cache.store.put(key, text, {\n maxAge: shareable.policy.maxAge,\n tags: shareable.tagsOf('result' in answered.body ? answered.body.result : {}),\n })\n }\n if (cache.check === true) {\n const mine = yield* RemoteServer.answer(own, body)\n if (stableStringify(unaddressedAnswer(mine.body)) !== stableStringify(JSON.parse(text))) {\n yield* Diagnostics.report(cachedReadDiffers(asked))\n return Response.json(mine.body, { status: mine.status, headers })\n }\n }\n return new Response(text, {\n headers: {\n 'content-type': 'application/json',\n 'cache-control': `public, max-age=${maxAgeSeconds(shareable.policy)}`,\n ...headers,\n },\n })\n })\n /** `live` is whether the response streams, and so owns `scope` until it ends. */\n const respond = (\n request: Request,\n env: Env,\n scope: Scope.Closeable,\n ): Effect.Effect<{ readonly response: Response; readonly live: boolean }, never, R | RP> =>\n Effect.gen(function* () {\n const principal = yield* resolvePrincipal(request, env)\n const headers = config.headers?.(principal) ?? {}\n const body = yield* Effect.result(readJson(request, maxBodyBytes))\n if (Result.isFailure(body)) {\n const { status, answer } = body.failure\n return { response: Response.json(answer, { status, headers }), live: false }\n }\n // Bound per request: the principal is the request's own, as everywhere else.\n const handlers = RemoteServer.handlers(config.server, principal, {\n live: config.live,\n maxIdsPerEntity: config.maxIdsPerEntity,\n maxDepth: config.maxDepth,\n })\n if (isLiveOpen(body.success)) {\n const response = yield* liveResponse(\n handlers,\n body.success.payload,\n heartbeat,\n revalidation(request, env, principal),\n Scope.close(scope, Exit.void),\n headers,\n )\n // A 400 for a payload no stream speaks has no stream to close it.\n return { response, live: response.status === 200 }\n }\n const { cache } = config\n const shareable =\n cache === undefined ? Option.none<Shareable>() : shareableOf(config.server, body.success)\n if (cache !== undefined && Option.isSome(shareable)) {\n const response = yield* answerShared(\n request,\n body.success,\n cache,\n shareable.value,\n handlers,\n headers,\n )\n return { response, live: false }\n }\n const answered = yield* RemoteServer.answer(handlers, body.success)\n if (cache !== undefined && answered.status === 200 && isWrite(body.success)) {\n yield* cache.store.purge(writeTags('result' in answered.body ? answered.body.result : {}))\n }\n return {\n response: Response.json(answered.body, { status: answered.status, headers }),\n live: false,\n }\n }).pipe(\n Effect.catchTag('Unauthenticated', refusal => {\n const { status, body } = unauthenticatedAnswer(refusal)\n return Effect.succeed({ response: Response.json(body, { status }), live: false })\n }),\n )\n const served = async (request: Request, env: Env): Promise<Response> => {\n if (request.method !== 'POST' || new URL(request.url).pathname !== path) {\n return Response.json({ error: 'not found' }, { status: 404 })\n }\n // Refused on what it says of itself: no layer built, no principal asked, nothing read.\n if (declaresTooLarge(request, maxBodyBytes)) {\n return Response.json(tooLargeAnswer(maxBodyBytes), { status: 413 })\n }\n const exit = await Effect.runPromiseExit(\n Effect.gen(function* () {\n // Not Effect.provide(layer), which closes it when `respond` returns,\n // before a live stream has served a frame: the stream's re-reads and\n // revalidation would run on released resources.\n const scope = yield* Scope.make()\n const answered = yield* Layer.buildWithScope(config.layer(env), scope).pipe(\n Effect.flatMap(context => Effect.provide(respond(request, env, scope), context)),\n Effect.onExit(exit =>\n Exit.isSuccess(exit) && exit.value.live ? Effect.void : Scope.close(scope, exit),\n ),\n )\n return answered.response\n }).pipe(reportingFor(request)),\n )\n if (Exit.isSuccess(exit)) return exit.value\n // A failure of the layer, or a defect anywhere: this side broke, and the\n // caller learns that it did, not what; the diagnostics learn what. `answer`\n // already maps its own failures and defects to 400/500 answers.\n const told = await Effect.runPromise(\n internalFailure('request', exit.cause).pipe(reportingFor(request)),\n )\n // The fixed words and the id the cause was reported under: nothing of `exit.cause`.\n return Response.json({ error: told.message, incident: told.incident }, { status: 500 })\n }\n // Every answer but a public read's is read as one principal: no cache may\n // keep it for another. A `cache-control` of the application's own (`headers`) stands.\n return async (request, env) => {\n const response = await served(request, env)\n await discardBody(request, maxBodyBytes)\n if (!response.headers.has('cache-control')) {\n response.headers.set('cache-control', 'private, no-store')\n }\n return response\n }\n}\n\n/**\n * The cache's checker, for a test: serves each request twice through\n * `serveFetch` with `cache.check` and a store in memory, so every public read\n * is answered both as the visitor (kept, then from the store) and as whoever\n * the request resolves to. Rejects naming each read whose answers differ, and\n * when no read was public, which would check nothing. Give requests from at\n * least two principals, a visitor's and someone's; each is a function, since\n * a body is read once.\n */\nexport const checkCache = async <P, R, Env, RP = never>(\n config: Omit<FetchConfig<P, R, Env, RP>, 'cache' | 'diagnostics'> & {\n readonly cache: { readonly visitor: P }\n },\n requests: ReadonlyArray<() => Request>,\n env: Env,\n): Promise<void> => {\n const store = CacheStore.memory()\n const differs: Array<string> = []\n const serve = serveFetch({\n ...config,\n cache: { ...config.cache, store, check: true },\n diagnostics: diagnostic =>\n Effect.sync(() => {\n // tag-check: open -- a Diagnostic's tag is any package's; this one is ours.\n if (diagnostic._tag === 'CachedReadDiffers') differs.push(diagnostic.message)\n }),\n })\n for (const _round of [1, 2]) {\n for (const make of requests) await serve(make(), env)\n }\n if (differs.length > 0) throw new Error(differs.join('\\n'))\n if (store.size() === 0) {\n throw new Error('checkCache: no request was a public read, so nothing was checked')\n }\n}\n\n/**\n * What `pageReader` reads of a `serveFetch` config: the server, its Sources'\n * layer, its limits, and the cache's `visitor`.\n */\nexport type PageReaderConfig<P, R, Env, RP = never> = Pick<\n FetchConfig<P, R, Env, RP>,\n 'server' | 'layer' | 'maxIdsPerEntity' | 'maxDepth' | 'cache'\n> & {\n /**\n * Who a page request is. A resolver taking any `Request` fits; one typed\n * for a script's request (`ScriptedRequest`) does not, since a navigation\n * carries no header a script adds and that resolver would refuse every\n * signed-in reader.\n */\n readonly resolvePrincipal: (\n request: NavigationRequest,\n env: Env,\n ) => Effect.Effect<P, RemoteUnauthenticated, RP>\n}\n\n/**\n * The reader a page render reads through, in the same process: the request's\n * `RemoteClient`, answered by the server's own handlers with no HTTP between\n * them. Give it `serveFetch`'s config with the resolver a page's request\n * needs: a page `GET` is a navigation, which carries no header a script adds\n * (`AuthServer.resolver({ …, requests: 'navigation' })`).\n *\n * The principal is resolved, and `layer` built, when the reader is provided,\n * and `layer` closes when the Effect it was provided to ends, so provide it to\n * the pre-read itself (`Data.satisfy(…).pipe(Effect.provide(reader))`). A\n * refusal fails that Effect with `Unauthenticated`, as a 401 would. It only\n * reads: a mutation fails with `RemoteMutationError` and a live open with\n * `RemoteLiveError`, since a navigation can be started from another site.\n *\n * Each read is noted for a render `foldkit-ssr` may cache (`PageReads`):\n * with `cache`, one proved public as `serveFetch` proves it is answered as\n * `cache.visitor` and noted public; every other read, and every read without\n * `cache`, is noted private, which keeps the page from being cached.\n */\nexport const pageReader = <P, R, Env, RP = never>(config: PageReaderConfig<P, R, Env, RP>) => {\n refuseSomeone(config.server, config.cache)\n const limits = { maxIdsPerEntity: config.maxIdsPerEntity, maxDepth: config.maxDepth }\n const visitor = Option.map(Option.fromUndefinedOr(config.cache), cache =>\n RemoteServer.handlers(config.server, cache.visitor, limits),\n )\n // Every request read for is a page's: the brand is only what keeps a script's resolver out.\n const resolvePrincipal = config.resolvePrincipal as (\n request: Request,\n env: Env,\n ) => Effect.Effect<P, RemoteUnauthenticated, RP>\n return (request: Request, env: Env): Layer.Layer<RemoteClient, RemoteUnauthenticated> =>\n Layer.unwrap(\n Effect.map(resolvePrincipal(request, env), principal => {\n const handlers = notingHandlers(\n config.server,\n RemoteServer.handlers(config.server, principal, limits),\n visitor,\n )\n return Remote.clientLayer<R>({\n ...handlers,\n FoldkitRemoteMutate: () =>\n Effect.fail(\n new RemoteMutationError({ message: 'A page render reads; it does not write' }),\n ),\n FoldkitRemoteLive: () =>\n Stream.fail(new RemoteLiveError({ message: 'A page render keeps no live stream' })),\n })\n }),\n ).pipe(Layer.provide(config.layer(env)))\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAoCA,MAAM,gBAAsB,WAC1B,WAAW,KAAA,KACX,OAAO,cAAc,KAAA,KACrB,OAAO,WAAW,KAAA,KAClB,OAAO,YAAY,KAAA,MAClB,OAAO,aAAa,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