@yaks/api 0.0.0-stage → 0.2.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +956 -2
- package/_dist/actor.d.ts +59 -0
- package/_dist/actor.d.ts.map +1 -0
- package/_dist/address.d.ts +33 -0
- package/_dist/address.d.ts.map +1 -0
- package/_dist/asset.d.ts +15 -0
- package/_dist/asset.d.ts.map +1 -0
- package/_dist/batches.d.ts +4 -0
- package/_dist/batches.d.ts.map +1 -0
- package/_dist/body.d.ts +7 -0
- package/_dist/body.d.ts.map +1 -0
- package/_dist/deno.d.ts +38 -0
- package/_dist/deno.d.ts.map +1 -0
- package/_dist/doors.d.ts +134 -0
- package/_dist/doors.d.ts.map +1 -0
- package/_dist/graph.d.ts +17 -0
- package/_dist/graph.d.ts.map +1 -0
- package/_dist/headers.d.ts +5 -0
- package/_dist/headers.d.ts.map +1 -0
- package/_dist/log.d.ts +253 -0
- package/_dist/log.d.ts.map +1 -0
- package/_dist/mod.d.ts +71 -0
- package/_dist/mod.d.ts.map +1 -0
- package/_dist/publish.d.ts +7 -0
- package/_dist/publish.d.ts.map +1 -0
- package/_dist/reached.d.ts +145 -0
- package/_dist/reached.d.ts.map +1 -0
- package/_dist/receipts.d.ts +153 -0
- package/_dist/receipts.d.ts.map +1 -0
- package/_dist/refuse.d.ts +51 -0
- package/_dist/refuse.d.ts.map +1 -0
- package/_dist/relay.d.ts +3 -0
- package/_dist/relay.d.ts.map +1 -0
- package/_dist/request.d.ts +79 -0
- package/_dist/request.d.ts.map +1 -0
- package/_dist/requests.d.ts +7 -0
- package/_dist/requests.d.ts.map +1 -0
- package/_dist/route.d.ts +71 -0
- package/_dist/route.d.ts.map +1 -0
- package/_dist/routed.d.ts +33 -0
- package/_dist/routed.d.ts.map +1 -0
- package/_dist/routes.d.ts +46 -0
- package/_dist/routes.d.ts.map +1 -0
- package/_dist/save.d.ts +6 -0
- package/_dist/save.d.ts.map +1 -0
- package/_dist/socket.d.ts +73 -0
- package/_dist/socket.d.ts.map +1 -0
- package/_dist/subs.d.ts +134 -0
- package/_dist/subs.d.ts.map +1 -0
- package/_dist/timing.d.ts +8 -0
- package/_dist/timing.d.ts.map +1 -0
- package/_dist/tools.d.ts +80 -0
- package/_dist/tools.d.ts.map +1 -0
- package/_dist/vocab.d.ts +6 -0
- package/_dist/vocab.d.ts.map +1 -0
- package/access.js +32 -0
- package/access.js.map +1 -0
- package/access.ts +42 -0
- package/actor.js +75 -0
- package/actor.js.map +1 -0
- package/actor.ts +106 -0
- package/address.js +42 -0
- package/address.js.map +1 -0
- package/address.ts +49 -0
- package/admission.js +71 -0
- package/admission.js.map +1 -0
- package/admission.ts +64 -0
- package/asset.js +37 -0
- package/asset.js.map +1 -0
- package/asset.ts +47 -0
- package/batches.js +92 -0
- package/batches.js.map +1 -0
- package/batches.ts +96 -0
- package/body.js +51 -0
- package/body.js.map +1 -0
- package/body.ts +82 -0
- package/deno.js +88 -0
- package/deno.js.map +1 -0
- package/deno.json +1 -0
- package/deno.ts +150 -0
- package/doors.js +435 -0
- package/doors.js.map +1 -0
- package/doors.ts +570 -0
- package/graph.js +12 -0
- package/graph.js.map +1 -0
- package/graph.ts +23 -0
- package/headers.js +5 -0
- package/headers.js.map +1 -0
- package/headers.ts +9 -0
- package/interest.js +224 -0
- package/interest.js.map +1 -0
- package/interest.ts +264 -0
- package/log.js +1011 -0
- package/log.js.map +1 -0
- package/log.ts +1035 -0
- package/mod.js +69 -0
- package/mod.js.map +1 -0
- package/mod.ts +142 -0
- package/package.json +75 -4
- package/peer_query.js +164 -0
- package/peer_query.js.map +1 -0
- package/peer_query.ts +158 -0
- package/publish.js +7 -0
- package/publish.js.map +1 -0
- package/publish.ts +16 -0
- package/reached.js +456 -0
- package/reached.js.map +1 -0
- package/reached.ts +549 -0
- package/receipts.js +543 -0
- package/receipts.js.map +1 -0
- package/receipts.ts +749 -0
- package/refuse.js +120 -0
- package/refuse.js.map +1 -0
- package/refuse.ts +179 -0
- package/relay.js +249 -0
- package/relay.js.map +1 -0
- package/relay.ts +284 -0
- package/request.js +218 -0
- package/request.js.map +1 -0
- package/request.ts +235 -0
- package/requests.js +250 -0
- package/requests.js.map +1 -0
- package/requests.ts +257 -0
- package/route.js +139 -0
- package/route.js.map +1 -0
- package/route.ts +228 -0
- package/routed.js +25 -0
- package/routed.js.map +1 -0
- package/routed.ts +53 -0
- package/routes.js +154 -0
- package/routes.js.map +1 -0
- package/routes.ts +201 -0
- package/save.js +341 -0
- package/save.js.map +1 -0
- package/save.ts +393 -0
- package/socket.js +398 -0
- package/socket.js.map +1 -0
- package/socket.ts +496 -0
- package/subs.js +2295 -0
- package/subs.js.map +1 -0
- package/subs.ts +2979 -0
- package/timing.js +17 -0
- package/timing.js.map +1 -0
- package/timing.ts +26 -0
- package/tools.js +251 -0
- package/tools.js.map +1 -0
- package/tools.ts +315 -0
- package/vocab.js +18 -0
- package/vocab.js.map +1 -0
- package/vocab.json +93 -0
- package/vocab.ts +18 -0
package/log.ts
ADDED
|
@@ -0,0 +1,1035 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The write log: a host's keyed writes and their receipts, and the input it
|
|
3
|
+
* could not commit yet, kept in plain SQLite tables beside its graph.
|
|
4
|
+
*
|
|
5
|
+
* - A live keyed request commits its mutation and receipt in one graph
|
|
6
|
+
* transaction ({@link landing}). Successful input needs no earlier pending
|
|
7
|
+
* or running row: the caller holds it until acknowledged, and a resend after
|
|
8
|
+
* a reset either finds the exact committed answer or applies an uncommitted
|
|
9
|
+
* mutation.
|
|
10
|
+
* - Input that cannot commit is kept with its headers and body, so a host that
|
|
11
|
+
* is stopped (its row ceiling's window), cannot start, or cannot apply it
|
|
12
|
+
* recovers without asking the caller to send it again. Pending writes replay
|
|
13
|
+
* oldest first, one replay at a time (`./receipts.ts` `door`), each live
|
|
14
|
+
* caller answered as its write lands. Failed writes wait for another incarnation;
|
|
15
|
+
* interrupted and legacy unreviewed attempts need explicit review. Reviewed
|
|
16
|
+
* retries keep their input and complete outcome forever.
|
|
17
|
+
* - Every keyed write is kept under its writer's name for its key
|
|
18
|
+
* ({@link receiptKey}), whichever door it came in at. Ordinary receipts
|
|
19
|
+
* expire after the resend window; browser outbox receipts and held input
|
|
20
|
+
* never expire.
|
|
21
|
+
*
|
|
22
|
+
* The tables belong to no vocabulary or app migration. Their place beside
|
|
23
|
+
* the graph makes the receipt and the mutation atomic even when the graph
|
|
24
|
+
* above storage cannot stand. A Store keeps its batches here, a space's
|
|
25
|
+
* Builder the lines a person said while it could not answer them, and every
|
|
26
|
+
* door of @yaks/api its keyed writes' receipts (`./receipts.ts` `received`).
|
|
27
|
+
*
|
|
28
|
+
* ```ts
|
|
29
|
+
* import { equal } from '@yaks/testing'
|
|
30
|
+
* import { open } from '@yaks/sqlite/db'
|
|
31
|
+
* import { done, keep, next, raise, replayed } from './log.ts'
|
|
32
|
+
* let db = open(':memory:')
|
|
33
|
+
* raise(db)
|
|
34
|
+
* let sent = new Request('http://store/apply', { method: 'POST', body: '[]' })
|
|
35
|
+
* let seq = keep(db, sent, '[]')
|
|
36
|
+
* equal([next(db)?.seq, await replayed(next(db)!).text()], [seq, '[]'])
|
|
37
|
+
* done(db, seq)
|
|
38
|
+
* equal(next(db), null)
|
|
39
|
+
* ```
|
|
40
|
+
*
|
|
41
|
+
* @module
|
|
42
|
+
*/
|
|
43
|
+
import { type Actor, type Bundle, sha256, token } from '@yaks/graph'
|
|
44
|
+
import { composed } from '@yaks/graph/bundle'
|
|
45
|
+
import { derivedEid } from '@yaks/graph/identity'
|
|
46
|
+
import { Refused } from '@yaks/graph/errors'
|
|
47
|
+
import { fromBase64, toBase64 } from '@yaks/fp'
|
|
48
|
+
import {
|
|
49
|
+
among,
|
|
50
|
+
and,
|
|
51
|
+
as,
|
|
52
|
+
col,
|
|
53
|
+
type CreateTable,
|
|
54
|
+
desc,
|
|
55
|
+
type Driver,
|
|
56
|
+
eq,
|
|
57
|
+
type Expr,
|
|
58
|
+
ge,
|
|
59
|
+
gt,
|
|
60
|
+
isNull,
|
|
61
|
+
lit,
|
|
62
|
+
lt,
|
|
63
|
+
not,
|
|
64
|
+
op,
|
|
65
|
+
or,
|
|
66
|
+
select,
|
|
67
|
+
type Stmt,
|
|
68
|
+
table,
|
|
69
|
+
val,
|
|
70
|
+
} from '@yaks/sql'
|
|
71
|
+
import type { Vocab } from 'jsr:@yaks/vocab@0.2.36'
|
|
72
|
+
import { BINARY, decode, stringify, unpack } from '@yaks/vocab/wire'
|
|
73
|
+
import { poured, writeBytes } from './body.js'
|
|
74
|
+
import { IDEMPOTENCY } from './headers.js'
|
|
75
|
+
|
|
76
|
+
export { IDEMPOTENCY }
|
|
77
|
+
|
|
78
|
+
// ---- a body as the log keeps it ---------------------------------------------
|
|
79
|
+
|
|
80
|
+
// A binary apply is kept undecoded: decoding needs the words a store's start
|
|
81
|
+
// reads, and a write is kept before its store has started, while it may not
|
|
82
|
+
// and when it can't. The log holds the envelope as it came, in base64 beside
|
|
83
|
+
// the headers that say it is binary, and its store decodes it as it lands.
|
|
84
|
+
/** Whether headers say their body is a binary envelope. */
|
|
85
|
+
export let binaryHeaders = (headers: Headers): boolean =>
|
|
86
|
+
headers.get('content-type')?.split(';')[0].trim() == BINARY
|
|
87
|
+
|
|
88
|
+
/** A write's body as the log keeps it, and its bundles as it says them before
|
|
89
|
+
* any decoding, which is what a secret is looked for in. A JSON body is its
|
|
90
|
+
* text, both times; a binary one is its envelope in base64, and the
|
|
91
|
+
* envelope's header with its references. An envelope that can't be read is
|
|
92
|
+
* refused here, while its caller still holds it.
|
|
93
|
+
*
|
|
94
|
+
* ```ts
|
|
95
|
+
* import { equal } from '@yaks/testing'
|
|
96
|
+
* import { binary, BINARY } from '@yaks/vocab/wire'
|
|
97
|
+
* import { opened, taken } from './log.ts'
|
|
98
|
+
* let raw = binary([{ entity: { eid: 'a' }, photo: { bytes: Uint8Array.of(7) } }])
|
|
99
|
+
* let sent = (body: BodyInit, type = BINARY) =>
|
|
100
|
+
* new Request('http://store/apply', { method: 'POST', headers: { 'content-type': type }, body })
|
|
101
|
+
* let { body, told } = await taken(sent(raw))
|
|
102
|
+
* equal(told, '[{"entity":{"eid":"a"},"photo":{"bytes":{"$bytes":0,"length":1}}}]')
|
|
103
|
+
* equal(opened(new Headers({ 'content-type': BINARY }), body), raw)
|
|
104
|
+
* equal(await taken(sent('[]', 'application/json')), { body: '[]', told: '[]' })
|
|
105
|
+
* equal(opened(new Headers(), '[]'), '[]')
|
|
106
|
+
* ```
|
|
107
|
+
*/
|
|
108
|
+
export let taken = async (
|
|
109
|
+
request: Request,
|
|
110
|
+
): Promise<{ body: string; told: string }> => {
|
|
111
|
+
let raw = await writeBytes(request)
|
|
112
|
+
if (!binaryHeaders(request.headers)) {
|
|
113
|
+
let body = new TextDecoder().decode(raw)
|
|
114
|
+
return { body, told: body }
|
|
115
|
+
}
|
|
116
|
+
return { body: toBase64(raw), told: JSON.stringify(unpack(raw).value) }
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** A kept body as it was sent: the envelope of a binary one (`taken`), the
|
|
120
|
+
* text of any other. */
|
|
121
|
+
export let opened = (
|
|
122
|
+
headers: Headers,
|
|
123
|
+
body: string,
|
|
124
|
+
): string | Uint8Array<ArrayBuffer> =>
|
|
125
|
+
binaryHeaders(headers) ? fromBase64(body) : body
|
|
126
|
+
|
|
127
|
+
/** What a kept body says once its words are known: a binary one's envelope
|
|
128
|
+
* decoded in them, as a JSON one's base64 values are. Only declared binary
|
|
129
|
+
* properties interpret payload references.
|
|
130
|
+
*
|
|
131
|
+
* ```ts
|
|
132
|
+
* import { equal } from '@yaks/testing'
|
|
133
|
+
* import { loadVocab } from '@yaks/vocab'
|
|
134
|
+
* import { binary, BINARY } from '@yaks/vocab/wire'
|
|
135
|
+
* import { decoded, taken } from './log.ts'
|
|
136
|
+
* let vocab = loadVocab({ $defs: { photo: { component: true, type: 'object',
|
|
137
|
+
* properties: { bytes: { type: 'string', contentEncoding: 'base64' } } } } })
|
|
138
|
+
* let bundle = { entity: { eid: 'a' }, photo: { bytes: Uint8Array.of(7) } }
|
|
139
|
+
* let { body } = await taken(new Request('http://store/apply', {
|
|
140
|
+
* method: 'POST', headers: { 'content-type': BINARY }, body: binary([bundle]),
|
|
141
|
+
* }))
|
|
142
|
+
* equal(decoded(vocab, new Headers({ 'content-type': BINARY }), body), [bundle])
|
|
143
|
+
* equal(decoded(vocab, new Headers(), '[{"photo":{"bytes":{"$bytes":"Bw==","encoding":"base64"}}}]'),
|
|
144
|
+
* [{ photo: { bytes: Uint8Array.of(7) } }])
|
|
145
|
+
* ```
|
|
146
|
+
*/
|
|
147
|
+
export let decoded = (
|
|
148
|
+
vocab: Pick<Vocab, 'def'>,
|
|
149
|
+
headers: Headers,
|
|
150
|
+
body: string,
|
|
151
|
+
): unknown => {
|
|
152
|
+
if (!binaryHeaders(headers)) return decode(vocab, JSON.parse(body))
|
|
153
|
+
let packed = unpack(fromBase64(body))
|
|
154
|
+
return decode(vocab, packed.value, packed.payload)
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// ---- the log ----------------------------------------------------------------
|
|
158
|
+
|
|
159
|
+
let LOG = 'yak_writes'
|
|
160
|
+
let KEY = 'idempotency_key'
|
|
161
|
+
let ANSWERS = 'yak_write_answers'
|
|
162
|
+
|
|
163
|
+
export let WRITES: CreateTable = {
|
|
164
|
+
t: 'create table',
|
|
165
|
+
name: LOG,
|
|
166
|
+
ifNot: true,
|
|
167
|
+
cols: [
|
|
168
|
+
{ name: 'seq', type: 'integer', pk: true, autoincrement: true },
|
|
169
|
+
{ name: 'at', type: 'text', notNull: true },
|
|
170
|
+
{ name: 'headers', type: 'text', notNull: true },
|
|
171
|
+
{ name: 'body', type: 'text', notNull: true },
|
|
172
|
+
{ name: 'state', type: 'text', notNull: true, default: lit('pending') },
|
|
173
|
+
{ name: 'tries', type: 'integer', notNull: true, default: lit(0) },
|
|
174
|
+
{ name: 'why', type: 'text' },
|
|
175
|
+
{ name: KEY, type: 'text' },
|
|
176
|
+
{ name: 'answer', type: 'text' },
|
|
177
|
+
{ name: 'generation', type: 'integer' },
|
|
178
|
+
{ name: 'audit', type: 'integer', notNull: true, default: lit(0) },
|
|
179
|
+
{ name: 'status', type: 'integer' },
|
|
180
|
+
],
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
let PARTS: CreateTable = {
|
|
184
|
+
t: 'create table',
|
|
185
|
+
name: ANSWERS,
|
|
186
|
+
ifNot: true,
|
|
187
|
+
cols: [
|
|
188
|
+
{ name: 'seq', type: 'integer', notNull: true },
|
|
189
|
+
{ name: 'part', type: 'integer', notNull: true },
|
|
190
|
+
{ name: 'body', type: 'text', notNull: true },
|
|
191
|
+
],
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** The empty write log and its indexes, shared with prepared test stores. */
|
|
195
|
+
export let schema = (): Stmt[] => [
|
|
196
|
+
WRITES,
|
|
197
|
+
PARTS,
|
|
198
|
+
{
|
|
199
|
+
t: 'create index',
|
|
200
|
+
name: `${LOG}_${KEY}`,
|
|
201
|
+
on: LOG,
|
|
202
|
+
cols: [col(KEY)],
|
|
203
|
+
unique: true,
|
|
204
|
+
ifNot: true,
|
|
205
|
+
},
|
|
206
|
+
// Ordinary keyed receipts last ten minutes; outbox receipts last forever.
|
|
207
|
+
// Neither pending work nor expiry may scan that retained history.
|
|
208
|
+
{
|
|
209
|
+
t: 'create index',
|
|
210
|
+
name: `${LOG}_pending`,
|
|
211
|
+
on: LOG,
|
|
212
|
+
cols: [col('seq')],
|
|
213
|
+
where: eq(col('state'), lit('pending')),
|
|
214
|
+
ifNot: true,
|
|
215
|
+
},
|
|
216
|
+
{
|
|
217
|
+
t: 'create index',
|
|
218
|
+
name: `${LOG}_expiring`,
|
|
219
|
+
on: LOG,
|
|
220
|
+
cols: [col('at')],
|
|
221
|
+
where: EXPIRABLE,
|
|
222
|
+
ifNot: true,
|
|
223
|
+
},
|
|
224
|
+
{
|
|
225
|
+
t: 'create index',
|
|
226
|
+
name: `${ANSWERS}_seq_part`,
|
|
227
|
+
on: ANSWERS,
|
|
228
|
+
cols: [col('seq'), col('part')],
|
|
229
|
+
unique: true,
|
|
230
|
+
ifNot: true,
|
|
231
|
+
},
|
|
232
|
+
// Waking repairs only interrupted attempts, never successful history.
|
|
233
|
+
...['running', 'failed'].map((state): Stmt => ({
|
|
234
|
+
t: 'create index',
|
|
235
|
+
name: `${LOG}_${state}`,
|
|
236
|
+
on: LOG,
|
|
237
|
+
cols: [col('seq')],
|
|
238
|
+
where: eq(col('state'), lit(state)),
|
|
239
|
+
ifNot: true,
|
|
240
|
+
})),
|
|
241
|
+
]
|
|
242
|
+
|
|
243
|
+
/** The log, raised, with every column it predates added: an object keeps its
|
|
244
|
+
* log across code versions, and whichever code wakes it next reads it. */
|
|
245
|
+
export let raise = (db: Driver): void => {
|
|
246
|
+
db.query(WRITES)
|
|
247
|
+
db.query(PARTS)
|
|
248
|
+
let has = db.query({ t: 'pragma', name: 'table_info', arg: LOG })
|
|
249
|
+
.map((r) => String(r.name))
|
|
250
|
+
for (let add of WRITES.cols) {
|
|
251
|
+
if (!has.includes(add.name)) {
|
|
252
|
+
db.query({ t: 'alter table', table: LOG, add })
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
for (let stmt of schema().slice(2)) db.query(stmt)
|
|
256
|
+
// The old index included durable receipts: retire it after its replacement.
|
|
257
|
+
db.query({ t: 'drop', kind: 'index', name: `${LOG}_expiry`, ifExists: true })
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// How long an applied write keeps its answer for a resend. The kernel resends
|
|
261
|
+
// within half a minute (@yaks/durable-object `backoff`), so this is room to
|
|
262
|
+
// spare.
|
|
263
|
+
let WINDOW = 10 * 60_000
|
|
264
|
+
let BATCH = 16
|
|
265
|
+
|
|
266
|
+
// What a connection knows of its log without reading it: when it last expired
|
|
267
|
+
// receipts, and that it holds no waiting write, from the last look until
|
|
268
|
+
// something keeps one (`keep`, `retry`, `revived`). Every row in the log is
|
|
269
|
+
// written here, so a look is good until one of those runs.
|
|
270
|
+
let swept = new WeakMap<object, number>()
|
|
271
|
+
let idle = new WeakSet<object>()
|
|
272
|
+
let of = (db: Driver): object => db.connection ?? db
|
|
273
|
+
|
|
274
|
+
let PENDING: Expr = eq(col('state'), lit('pending'))
|
|
275
|
+
let FAILED: Expr = eq(col('state'), lit('failed'))
|
|
276
|
+
let APPLIED: Expr = eq(col('state'), lit('applied'))
|
|
277
|
+
let RUNNING: Expr = eq(col('state'), lit('running'))
|
|
278
|
+
let INTERRUPTED: Expr = eq(col('state'), lit('interrupted'))
|
|
279
|
+
let UNREVIEWED: Expr = eq(col('state'), lit('unreviewed'))
|
|
280
|
+
let AUDIT: Expr = eq(col('audit'), lit(1))
|
|
281
|
+
let REVIVABLE: Expr = and(FAILED, not(AUDIT))
|
|
282
|
+
// Case-sensitive, just like the browser's stable key prefix. Keep this in the
|
|
283
|
+
// partial index too, so expiry never walks indefinitely retained receipts.
|
|
284
|
+
let EXPIRABLE: Expr = and(
|
|
285
|
+
APPLIED,
|
|
286
|
+
not(AUDIT),
|
|
287
|
+
or(isNull(col(KEY)), not(op('glob', col(KEY), lit('outbox:*')))),
|
|
288
|
+
)
|
|
289
|
+
|
|
290
|
+
/** Browser outbox intents need the same answer even after hours offline. */
|
|
291
|
+
export let durable = (key: string | null): boolean =>
|
|
292
|
+
key?.startsWith('outbox:') ?? false
|
|
293
|
+
let at = (seq: number): Expr => eq(col('seq'), val(seq))
|
|
294
|
+
|
|
295
|
+
let outcome = (db: Driver, seq: number): string => {
|
|
296
|
+
let rows = db.query(select({
|
|
297
|
+
cols: [col('body')],
|
|
298
|
+
from: table(ANSWERS),
|
|
299
|
+
where: at(seq),
|
|
300
|
+
order: [col('part')],
|
|
301
|
+
}))
|
|
302
|
+
if (!rows.length) throw new Error(`audited write ${seq} has no outcome`)
|
|
303
|
+
return rows.map((r) => String(r.body)).join('')
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// A reset rolls the graph transaction back, but not this earlier marker. A
|
|
307
|
+
// committed write changes or removes its log row in the graph transaction.
|
|
308
|
+
export let started = (db: Driver, seq: number): void =>
|
|
309
|
+
void db.query({
|
|
310
|
+
t: 'update',
|
|
311
|
+
table: LOG,
|
|
312
|
+
set: { state: lit('running'), tries: op('+', col('tries'), lit(1)) },
|
|
313
|
+
where: and(at(seq), PENDING),
|
|
314
|
+
})
|
|
315
|
+
|
|
316
|
+
/** A started write its store stopped before it could apply it
|
|
317
|
+
* (`./receipts.ts` `replays`): waiting again, its try not counted, so the
|
|
318
|
+
* replay after the wait takes it as it was. Its transaction unwound, so
|
|
319
|
+
* nothing of it landed. Without `seq`, every write a reset cut off, for a
|
|
320
|
+
* host that hears a write only in the transaction that lands it, so a reset
|
|
321
|
+
* left nothing of one it started (a Builder's line). */
|
|
322
|
+
export let unstarted = (db: Driver, seq?: number): void => {
|
|
323
|
+
idle.delete(of(db))
|
|
324
|
+
db.query({
|
|
325
|
+
t: 'update',
|
|
326
|
+
table: LOG,
|
|
327
|
+
set: { state: lit('pending'), tries: op('-', col('tries'), lit(1)) },
|
|
328
|
+
where: seq == null ? RUNNING : and(at(seq), RUNNING),
|
|
329
|
+
})
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// A running marker survives a reset. Older code could leave a pending write
|
|
333
|
+
// after starting it, so every row it left is unreviewed until someone reads
|
|
334
|
+
// the body and deliberately retries. New writes carry a generation and retain
|
|
335
|
+
// ordinary automatic replay while they have not started.
|
|
336
|
+
export let interrupted = (
|
|
337
|
+
db: Driver,
|
|
338
|
+
): { running: number; unreviewed: number } => {
|
|
339
|
+
let running = db.query({
|
|
340
|
+
t: 'update',
|
|
341
|
+
table: LOG,
|
|
342
|
+
set: {
|
|
343
|
+
state: lit('interrupted'),
|
|
344
|
+
why: lit(
|
|
345
|
+
'the Store reset while applying this write; inspect before retrying',
|
|
346
|
+
),
|
|
347
|
+
},
|
|
348
|
+
where: RUNNING,
|
|
349
|
+
returning: [col('seq')],
|
|
350
|
+
})
|
|
351
|
+
let old = db.query({
|
|
352
|
+
t: 'update',
|
|
353
|
+
table: LOG,
|
|
354
|
+
set: {
|
|
355
|
+
state: lit('unreviewed'),
|
|
356
|
+
why: lit(
|
|
357
|
+
'this write predates attempt tracking; inspect before retrying',
|
|
358
|
+
),
|
|
359
|
+
},
|
|
360
|
+
where: and(PENDING, isNull(col('generation'))),
|
|
361
|
+
returning: [col('seq')],
|
|
362
|
+
})
|
|
363
|
+
return { running: running.length, unreviewed: old.length }
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/** Kept writes, with the body only when one is named for inspection. */
|
|
367
|
+
export let writes = (
|
|
368
|
+
db: Driver,
|
|
369
|
+
seq?: number,
|
|
370
|
+
recent = false,
|
|
371
|
+
): Record<string, unknown>[] =>
|
|
372
|
+
db.query(select({
|
|
373
|
+
cols: [
|
|
374
|
+
col('seq'),
|
|
375
|
+
col('at'),
|
|
376
|
+
col('state'),
|
|
377
|
+
col('tries'),
|
|
378
|
+
col('why'),
|
|
379
|
+
col('status'),
|
|
380
|
+
col('audit'),
|
|
381
|
+
col('headers'),
|
|
382
|
+
...(seq == null ? [] : [col('body'), col(KEY), col('answer')]),
|
|
383
|
+
],
|
|
384
|
+
from: table(LOG),
|
|
385
|
+
where: seq == null ? recent ? undefined : not(APPLIED) : at(seq),
|
|
386
|
+
order: [recent ? desc(col('seq')) : col('seq')],
|
|
387
|
+
limit: lit(seq == null ? 100 : 1),
|
|
388
|
+
})).map(({ headers, ...r }) => ({
|
|
389
|
+
...r,
|
|
390
|
+
kernel: new Headers(JSON.parse(String(headers))).get('x-yak-kernel') ==
|
|
391
|
+
'1',
|
|
392
|
+
...(seq != null && r.answer == null && r.state == 'applied'
|
|
393
|
+
? { answer: outcome(db, seq) }
|
|
394
|
+
: {}),
|
|
395
|
+
}))
|
|
396
|
+
|
|
397
|
+
/** Explicitly retry an interrupted or unreviewed write, keeping its body and
|
|
398
|
+
* key, and keeping its final answer beside them when it commits. */
|
|
399
|
+
export let retry = (db: Driver, seq: number): boolean => {
|
|
400
|
+
idle.delete(of(db))
|
|
401
|
+
return db.query({
|
|
402
|
+
t: 'update',
|
|
403
|
+
table: LOG,
|
|
404
|
+
set: {
|
|
405
|
+
state: lit('pending'),
|
|
406
|
+
generation: lit(1),
|
|
407
|
+
audit: lit(1),
|
|
408
|
+
why: lit(null),
|
|
409
|
+
answer: lit(null),
|
|
410
|
+
status: lit(null),
|
|
411
|
+
},
|
|
412
|
+
where: and(at(seq), or(INTERRUPTED, UNREVIEWED, and(FAILED, AUDIT))),
|
|
413
|
+
returning: [col('seq')],
|
|
414
|
+
}).length > 0
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/** One kept write. */
|
|
418
|
+
export type Kept = { seq: number; headers: string; body: string }
|
|
419
|
+
|
|
420
|
+
/** A write still held for review, without changing its state. */
|
|
421
|
+
export let kept = (db: Driver, seq: number): Kept | undefined => {
|
|
422
|
+
let [row] = db.query(select({
|
|
423
|
+
cols: [col('seq'), col('headers'), col('body')],
|
|
424
|
+
from: table(LOG),
|
|
425
|
+
where: and(at(seq), or(INTERRUPTED, UNREVIEWED, and(FAILED, AUDIT))),
|
|
426
|
+
limit: lit(1),
|
|
427
|
+
}))
|
|
428
|
+
return row
|
|
429
|
+
? {
|
|
430
|
+
seq: Number(row.seq),
|
|
431
|
+
headers: String(row.headers),
|
|
432
|
+
body: String(row.body),
|
|
433
|
+
}
|
|
434
|
+
: undefined
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/** Whether a request is a write the log keeps: a batch to apply. A dry run
|
|
438
|
+
* (`?check=1`) writes nothing. */
|
|
439
|
+
export let logged = (req: Request): boolean => {
|
|
440
|
+
let url = new URL(req.url)
|
|
441
|
+
return req.method == 'POST' && url.pathname == '/apply' &&
|
|
442
|
+
!url.searchParams.has('check') && !poured(req)
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
// A Durable Object's SQLite holds at most 2 MB in one row. A bigger body —
|
|
446
|
+
// an NDJSON import, which the caller holds as a file and is answered line by
|
|
447
|
+
// line — is applied as it comes, without a place in the log.
|
|
448
|
+
export let ROOM = 1_900_000
|
|
449
|
+
|
|
450
|
+
/** Whether a body fits in the log. */
|
|
451
|
+
export let fits = (body: string): boolean =>
|
|
452
|
+
body.length * 3 <= ROOM || new TextEncoder().encode(body).length <= ROOM
|
|
453
|
+
|
|
454
|
+
// A write is stamped, and its receipts expire, on the clock of the host that
|
|
455
|
+
// keeps the log; unset, the runtime's.
|
|
456
|
+
let stamp = (now: () => number) => new Date(now()).toISOString()
|
|
457
|
+
|
|
458
|
+
/** Expire a bounded batch of ordinary receipts, never held user input.
|
|
459
|
+
* A backlog is paid down by subsequent writes; an empty tail is checked at
|
|
460
|
+
* most once a tenth of the resend window. An app write never owes the whole
|
|
461
|
+
* directory's idle history. */
|
|
462
|
+
let expire = (db: Driver, now: () => number) => {
|
|
463
|
+
let t = now()
|
|
464
|
+
if (t - (swept.get(of(db)) ?? -Infinity) < WINDOW / 10) return
|
|
465
|
+
let gone = new Date(t - WINDOW).toISOString()
|
|
466
|
+
let rows = db.query({
|
|
467
|
+
t: 'delete',
|
|
468
|
+
from: LOG,
|
|
469
|
+
where: among(
|
|
470
|
+
col('seq'),
|
|
471
|
+
select({
|
|
472
|
+
cols: [col('seq')],
|
|
473
|
+
from: table(LOG),
|
|
474
|
+
where: and(EXPIRABLE, lt(col('at'), val(gone))),
|
|
475
|
+
order: [col('at')],
|
|
476
|
+
limit: lit(BATCH),
|
|
477
|
+
}),
|
|
478
|
+
),
|
|
479
|
+
// SQLite materializes RETURNING before yielding its first row. The
|
|
480
|
+
// inline receipt can occupy nearly a whole SQLite row.
|
|
481
|
+
returning: [col('seq'), as(isNull(col('answer')), 'chunked')],
|
|
482
|
+
})
|
|
483
|
+
for (let row of rows) {
|
|
484
|
+
if (row.chunked) {
|
|
485
|
+
db.query({ t: 'delete', from: ANSWERS, where: at(Number(row.seq)) })
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
if (rows.length < BATCH) swept.set(of(db), t)
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
/** Keep one write that cannot commit now; its place in the replay log. */
|
|
492
|
+
export let keep = (
|
|
493
|
+
db: Driver,
|
|
494
|
+
req: Request,
|
|
495
|
+
body: string,
|
|
496
|
+
now: () => number = Date.now,
|
|
497
|
+
): number => {
|
|
498
|
+
expire(db, now)
|
|
499
|
+
idle.delete(of(db))
|
|
500
|
+
let [row] = db.query({
|
|
501
|
+
t: 'insert',
|
|
502
|
+
into: LOG,
|
|
503
|
+
cols: ['at', 'headers', 'body', KEY, 'generation'],
|
|
504
|
+
rows: [[
|
|
505
|
+
val(stamp(now)),
|
|
506
|
+
val(JSON.stringify([...req.headers])),
|
|
507
|
+
val(body),
|
|
508
|
+
val(req.headers.get(IDEMPOTENCY)),
|
|
509
|
+
lit(1),
|
|
510
|
+
]],
|
|
511
|
+
returning: [col('seq')],
|
|
512
|
+
})
|
|
513
|
+
return Number(row.seq)
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
// Internal evidence binds both the routed bytes and the original spanning intent.
|
|
517
|
+
// Recompute at the host's door: a caller-supplied digest is never evidence.
|
|
518
|
+
export let INTENT = 'x-yak-outbox-intent'
|
|
519
|
+
let FINGERPRINT = 'x-yak-outbox-fingerprint'
|
|
520
|
+
export let fingerprinted = (request: Request, body: string): Request => {
|
|
521
|
+
if (!durable(request.headers.get(IDEMPOTENCY))) return request
|
|
522
|
+
let headers = new Headers(request.headers)
|
|
523
|
+
headers.set(
|
|
524
|
+
FINGERPRINT,
|
|
525
|
+
sha256(JSON.stringify([
|
|
526
|
+
body,
|
|
527
|
+
headers.get(INTENT),
|
|
528
|
+
headers.get('x-yak-person'),
|
|
529
|
+
])),
|
|
530
|
+
)
|
|
531
|
+
return new Request(request, { headers, body: opened(headers, body) })
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
/**
|
|
535
|
+
* The key the log keeps a write under: its writer's and its sender's key as
|
|
536
|
+
* one name, so one writer's key never reads another's receipt. An outbox
|
|
537
|
+
* key's name is an outbox key too, kept for good ({@link durable}); any
|
|
538
|
+
* other expires after the resend window.
|
|
539
|
+
*
|
|
540
|
+
* ```ts
|
|
541
|
+
* import { equal } from '@yaks/testing'
|
|
542
|
+
* import { durable, receiptKey } from './log.ts'
|
|
543
|
+
* let ada = { by: 'ada' }
|
|
544
|
+
* equal(receiptKey(ada, 'k') == receiptKey({ by: 'bob' }, 'k'), false)
|
|
545
|
+
* equal(receiptKey(ada, 'k') == receiptKey(ada, 'k'), true)
|
|
546
|
+
* equal([durable(receiptKey(ada, 'outbox:k')), durable(receiptKey(ada, 'k'))],
|
|
547
|
+
* [true, false])
|
|
548
|
+
* ```
|
|
549
|
+
*/
|
|
550
|
+
export let receiptKey = (writer: Actor | null, key: string): string => {
|
|
551
|
+
let id = derivedEid(
|
|
552
|
+
`api receipt|${token([writer?.by ?? null, writer?.via ?? null, key])}`,
|
|
553
|
+
)
|
|
554
|
+
return `${durable(key) ? 'outbox:' : ''}receipt:${id}`
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
// The keys a log names (`receiptKey`) sort in two runs, `outbox:receipt:…`
|
|
558
|
+
// and `receipt:…`; a key kept as its sender said it sorts outside both, so
|
|
559
|
+
// the key's index finds those alone. A row with no key compares as neither.
|
|
560
|
+
let UNNAMED: Expr = or(
|
|
561
|
+
lt(col(KEY), lit('outbox:receipt:')),
|
|
562
|
+
and(ge(col(KEY), lit('outbox:receipt;')), lt(col(KEY), lit('receipt:'))),
|
|
563
|
+
ge(col(KEY), lit('receipt;')),
|
|
564
|
+
)
|
|
565
|
+
|
|
566
|
+
/** A request with its key named by its writer ({@link receiptKey}), as the
|
|
567
|
+
* log keeps it; one with no key as it is. Its body is taken along unread. */
|
|
568
|
+
export let owned = (request: Request, writer: Actor | null): Request => {
|
|
569
|
+
let key = request.headers.get(IDEMPOTENCY)
|
|
570
|
+
if (!key) return request
|
|
571
|
+
let headers = new Headers(request.headers)
|
|
572
|
+
headers.set(IDEMPOTENCY, receiptKey(writer, key))
|
|
573
|
+
return new Request(request, { headers })
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
/**
|
|
577
|
+
* Every key the log holds as its sender said it, named by its writer
|
|
578
|
+
* ({@link receiptKey}), in its column and in the headers its write is
|
|
579
|
+
* replayed with: a log kept by code that took a key as it came. `writer` says
|
|
580
|
+
* who sent each, from its request's headers. How many it named; a log named
|
|
581
|
+
* already costs one look at the key's index.
|
|
582
|
+
*
|
|
583
|
+
* ```ts
|
|
584
|
+
* import { equal } from '@yaks/testing'
|
|
585
|
+
* import { open } from '@yaks/sqlite/db'
|
|
586
|
+
* import { first, keep, raise, receiptKey, rekey } from './log.ts'
|
|
587
|
+
* let db = open(':memory:')
|
|
588
|
+
* raise(db)
|
|
589
|
+
* let sent = new Request('http://store/apply', {
|
|
590
|
+
* method: 'POST', headers: { 'idempotency-key': 'k', 'x-by': 'ada' },
|
|
591
|
+
* })
|
|
592
|
+
* keep(db, sent, '[]')
|
|
593
|
+
* let writer = (r: Request) => ({ by: r.headers.get('x-by')! })
|
|
594
|
+
* equal([rekey(db, writer), rekey(db, writer)], [1, 0])
|
|
595
|
+
* equal(first(db, receiptKey({ by: 'ada' }, 'k'))?.seq, 1)
|
|
596
|
+
* ```
|
|
597
|
+
*/
|
|
598
|
+
export let rekey = (
|
|
599
|
+
db: Driver,
|
|
600
|
+
writer: (request: Request) => Actor | null,
|
|
601
|
+
): number => {
|
|
602
|
+
let rows = db.query(select({
|
|
603
|
+
cols: [col('seq'), col(KEY), col('headers')],
|
|
604
|
+
from: table(LOG),
|
|
605
|
+
where: UNNAMED,
|
|
606
|
+
}))
|
|
607
|
+
for (let row of rows) {
|
|
608
|
+
let headers = new Headers(JSON.parse(String(row.headers)))
|
|
609
|
+
let key = receiptKey(
|
|
610
|
+
writer(new Request('http://log/', { headers })),
|
|
611
|
+
String(row[KEY]),
|
|
612
|
+
)
|
|
613
|
+
headers.set(IDEMPOTENCY, key)
|
|
614
|
+
db.query({
|
|
615
|
+
t: 'update',
|
|
616
|
+
table: LOG,
|
|
617
|
+
set: { [KEY]: val(key), headers: val(JSON.stringify([...headers])) },
|
|
618
|
+
where: at(Number(row.seq)),
|
|
619
|
+
})
|
|
620
|
+
}
|
|
621
|
+
return rows.length
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
/** The request a door that names its writes itself keeps a receipt under
|
|
625
|
+
* (`./receipts.ts` `received`): its `key` for the write ({@link
|
|
626
|
+
* receiptKey}), bound to the body `digest` names. */
|
|
627
|
+
export let named = (key: string, digest: string): Request =>
|
|
628
|
+
new Request('http://receipt/apply', {
|
|
629
|
+
method: 'POST',
|
|
630
|
+
headers: { [IDEMPOTENCY]: key, [FINGERPRINT]: digest },
|
|
631
|
+
})
|
|
632
|
+
|
|
633
|
+
/** A write the log already holds under an idempotency key. */
|
|
634
|
+
export type Sent = {
|
|
635
|
+
seq: number
|
|
636
|
+
state: string
|
|
637
|
+
why: string
|
|
638
|
+
answer: string
|
|
639
|
+
audit: boolean
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
/** The write a key was first sent with, if the log holds it. */
|
|
643
|
+
export let first = (
|
|
644
|
+
db: Driver,
|
|
645
|
+
key: string,
|
|
646
|
+
request?: Request,
|
|
647
|
+
): Sent | null => {
|
|
648
|
+
let [row] = db.query(select({
|
|
649
|
+
cols: [
|
|
650
|
+
col('seq'),
|
|
651
|
+
col('state'),
|
|
652
|
+
col('why'),
|
|
653
|
+
col('answer'),
|
|
654
|
+
col('audit'),
|
|
655
|
+
...(durable(key) && request ? [col('headers')] : []),
|
|
656
|
+
],
|
|
657
|
+
from: table(LOG),
|
|
658
|
+
where: eq(col(KEY), val(key)),
|
|
659
|
+
}))
|
|
660
|
+
if (row && durable(key) && request) {
|
|
661
|
+
let before = new Headers(JSON.parse(String(row.headers)))
|
|
662
|
+
let digest = request.headers.get(FINGERPRINT)
|
|
663
|
+
if (!digest || before.get(FINGERPRINT) != digest) {
|
|
664
|
+
throw new Refused('outbox key was already used for a different intent')
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
return row
|
|
668
|
+
? {
|
|
669
|
+
seq: Number(row.seq),
|
|
670
|
+
state: String(row.state),
|
|
671
|
+
why: String(row.why ?? ''),
|
|
672
|
+
answer: row.state == 'applied' && row.answer == null
|
|
673
|
+
? outcome(db, Number(row.seq))
|
|
674
|
+
: String(row.answer ?? '[]'),
|
|
675
|
+
audit: row.audit == 1,
|
|
676
|
+
}
|
|
677
|
+
: null
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
/** Cached acceptance after the caller has checked current write authority.
|
|
681
|
+
* Durable requests must have been fingerprinted from their body at the door. */
|
|
682
|
+
export let remembered = (
|
|
683
|
+
db: Driver,
|
|
684
|
+
key: string,
|
|
685
|
+
request: Request,
|
|
686
|
+
): Response | null => {
|
|
687
|
+
let was = first(db, key, request)
|
|
688
|
+
return was?.state == 'applied'
|
|
689
|
+
? new Response(was.answer, {
|
|
690
|
+
headers: { 'content-type': 'application/json' },
|
|
691
|
+
})
|
|
692
|
+
: null
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
// Split on Unicode boundaries so every SQLite text value fits the host's
|
|
696
|
+
// row limit and joining the values reproduces the answer byte for byte.
|
|
697
|
+
let pieces = function* (text: string) {
|
|
698
|
+
for (let i = 0; i < text.length;) {
|
|
699
|
+
let end = Math.min(i + 300_000, text.length)
|
|
700
|
+
let last = text.charCodeAt(end - 1)
|
|
701
|
+
if (end < text.length && last >= 0xD800 && last <= 0xDBFF) end--
|
|
702
|
+
yield text.slice(i, end)
|
|
703
|
+
i = end
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
/** A successful live request has no earlier log row. The graph commit hook
|
|
708
|
+
* inserts its receipt in the same transaction as the mutation. With no receipt
|
|
709
|
+
* there is no committed mutation; the caller still holds its unacknowledged
|
|
710
|
+
* input and may resend after a reset. */
|
|
711
|
+
export type Receipt = { request: Request }
|
|
712
|
+
export let received = (
|
|
713
|
+
db: Driver,
|
|
714
|
+
receipt: Receipt,
|
|
715
|
+
answer: () => Bundle[],
|
|
716
|
+
now: () => number = Date.now,
|
|
717
|
+
) => {
|
|
718
|
+
let key = receipt.request.headers.get(IDEMPOTENCY)
|
|
719
|
+
if (!key) return
|
|
720
|
+
expire(db, now)
|
|
721
|
+
let text = stringify(composed(answer()))
|
|
722
|
+
let whole = fits(text)
|
|
723
|
+
// Its sequence number is asked back only for an answer kept in parts: a
|
|
724
|
+
// returned row is a row read.
|
|
725
|
+
let [row] = db.query({
|
|
726
|
+
t: 'insert',
|
|
727
|
+
into: LOG,
|
|
728
|
+
cols: [
|
|
729
|
+
'at',
|
|
730
|
+
'headers',
|
|
731
|
+
'body',
|
|
732
|
+
KEY,
|
|
733
|
+
'generation',
|
|
734
|
+
'state',
|
|
735
|
+
'answer',
|
|
736
|
+
'status',
|
|
737
|
+
],
|
|
738
|
+
rows: [[
|
|
739
|
+
val(stamp(now)),
|
|
740
|
+
val(JSON.stringify([...receipt.request.headers])),
|
|
741
|
+
lit(''),
|
|
742
|
+
val(key),
|
|
743
|
+
lit(1),
|
|
744
|
+
lit('applied'),
|
|
745
|
+
val(whole ? text : null),
|
|
746
|
+
lit(200),
|
|
747
|
+
]],
|
|
748
|
+
returning: whole ? undefined : [col('seq')],
|
|
749
|
+
})
|
|
750
|
+
if (!whole) chunks(db, Number(row.seq), text)
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
let chunks = (db: Driver, seq: number, text: string) => {
|
|
754
|
+
for (let [part, body] of [...pieces(text)].entries()) {
|
|
755
|
+
db.query({
|
|
756
|
+
t: 'insert',
|
|
757
|
+
into: ANSWERS,
|
|
758
|
+
cols: ['seq', 'part', 'body'],
|
|
759
|
+
rows: [[val(seq), val(part), val(body)]],
|
|
760
|
+
})
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
type RetainedWrite = {
|
|
765
|
+
seq: number
|
|
766
|
+
state: string
|
|
767
|
+
body: string
|
|
768
|
+
binary: boolean
|
|
769
|
+
answer: string | null
|
|
770
|
+
chunked: boolean
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
/** Walk the persisted input and outcome of writes without replaying them. */
|
|
774
|
+
export let retainedWrites = (
|
|
775
|
+
db: Driver,
|
|
776
|
+
after: number,
|
|
777
|
+
limit: number,
|
|
778
|
+
): RetainedWrite[] =>
|
|
779
|
+
db.query(select({
|
|
780
|
+
cols: [
|
|
781
|
+
col('seq'),
|
|
782
|
+
col('state'),
|
|
783
|
+
col('headers'),
|
|
784
|
+
col('body'),
|
|
785
|
+
col('answer'),
|
|
786
|
+
],
|
|
787
|
+
from: table(LOG),
|
|
788
|
+
where: gt(col('seq'), val(after)),
|
|
789
|
+
order: [col('seq')],
|
|
790
|
+
limit: val(limit),
|
|
791
|
+
})).map((r) => {
|
|
792
|
+
let seq = Number(r.seq)
|
|
793
|
+
let chunked = r.answer == null && r.state == 'applied'
|
|
794
|
+
return {
|
|
795
|
+
seq,
|
|
796
|
+
state: String(r.state),
|
|
797
|
+
body: String(r.body),
|
|
798
|
+
binary: binaryHeaders(new Headers(JSON.parse(String(r.headers)))),
|
|
799
|
+
answer: chunked
|
|
800
|
+
? outcome(db, seq)
|
|
801
|
+
: r.answer == null
|
|
802
|
+
? null
|
|
803
|
+
: String(r.answer),
|
|
804
|
+
chunked,
|
|
805
|
+
}
|
|
806
|
+
})
|
|
807
|
+
|
|
808
|
+
/** Rewrite an unchanged receipt inside the caller's transaction. */
|
|
809
|
+
export let rewriteWrite = (
|
|
810
|
+
db: Driver,
|
|
811
|
+
was: RetainedWrite,
|
|
812
|
+
body: string,
|
|
813
|
+
answer: string | null,
|
|
814
|
+
): boolean => {
|
|
815
|
+
let written = db.query({
|
|
816
|
+
t: 'update',
|
|
817
|
+
table: LOG,
|
|
818
|
+
set: { body: val(body), answer: val(was.chunked ? null : answer) },
|
|
819
|
+
where: and(
|
|
820
|
+
at(was.seq),
|
|
821
|
+
eq(col('state'), val(was.state)),
|
|
822
|
+
eq(col('body'), val(was.body)),
|
|
823
|
+
),
|
|
824
|
+
returning: [col('seq')],
|
|
825
|
+
}).length > 0
|
|
826
|
+
if (written && was.chunked && answer != null && answer != was.answer) {
|
|
827
|
+
db.query({ t: 'delete', from: ANSWERS, where: at(was.seq) })
|
|
828
|
+
chunks(db, was.seq, answer)
|
|
829
|
+
}
|
|
830
|
+
return written
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
/** A committed write, in its batch's own transaction: out of the log, or,
|
|
834
|
+
* sent with a key, kept as `applied` with its answer for a resend to be told.
|
|
835
|
+
* The hook receives phase patches; compose them here to keep exactly what
|
|
836
|
+
* `apply()` returns after the transaction. An audited retry keeps its original
|
|
837
|
+
* body and full answer in chunks. Ordinary large answers use chunks too,
|
|
838
|
+
* so every resend receives the complete canonical answer. */
|
|
839
|
+
export let landed = (
|
|
840
|
+
db: Driver,
|
|
841
|
+
seq: number,
|
|
842
|
+
answer: () => Bundle[],
|
|
843
|
+
now: () => number = Date.now,
|
|
844
|
+
): void => {
|
|
845
|
+
let [row] = db.query(select({
|
|
846
|
+
cols: [col(KEY), col('audit')],
|
|
847
|
+
from: table(LOG),
|
|
848
|
+
where: at(seq),
|
|
849
|
+
}))
|
|
850
|
+
if (row?.[KEY] == null && row?.audit != 1) return done(db, seq)
|
|
851
|
+
let all = composed(answer())
|
|
852
|
+
let text = stringify(all)
|
|
853
|
+
if (row.audit == 1 || !fits(text)) chunks(db, seq, text)
|
|
854
|
+
db.query({
|
|
855
|
+
t: 'update',
|
|
856
|
+
table: LOG,
|
|
857
|
+
set: {
|
|
858
|
+
state: lit('applied'),
|
|
859
|
+
...(row.audit == 1 ? {} : { at: val(stamp(now)), body: lit('') }),
|
|
860
|
+
answer: val(row.audit == 1 || !fits(text) ? null : text),
|
|
861
|
+
status: lit(200),
|
|
862
|
+
},
|
|
863
|
+
where: at(seq),
|
|
864
|
+
})
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
/** The oldest write still waiting after `seq`. A replay walks the log forward
|
|
868
|
+
* from one to the next, so it tries no write twice. */
|
|
869
|
+
export let next = (db: Driver, seq = 0): Kept | null => {
|
|
870
|
+
if (idle.has(of(db))) return null
|
|
871
|
+
let [row] = db.query(select({
|
|
872
|
+
cols: [col('seq'), col('headers'), col('body')],
|
|
873
|
+
from: table(LOG),
|
|
874
|
+
where: and(PENDING, gt(col('seq'), val(seq))),
|
|
875
|
+
order: [col('seq')],
|
|
876
|
+
limit: lit(1),
|
|
877
|
+
}))
|
|
878
|
+
if (!row && !seq) idle.add(of(db))
|
|
879
|
+
return row
|
|
880
|
+
? {
|
|
881
|
+
seq: Number(row.seq),
|
|
882
|
+
headers: String(row.headers),
|
|
883
|
+
body: String(row.body),
|
|
884
|
+
}
|
|
885
|
+
: null
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
/** Whether any write is waiting. */
|
|
889
|
+
export let waiting = (db: Driver): boolean => next(db) != null
|
|
890
|
+
|
|
891
|
+
/** Whether a new incarnation must settle writes before serving a read. */
|
|
892
|
+
export let recovering = (db: Driver): boolean =>
|
|
893
|
+
db.query(select({
|
|
894
|
+
cols: [lit(1)],
|
|
895
|
+
from: table(LOG),
|
|
896
|
+
where: or(PENDING, REVIVABLE),
|
|
897
|
+
limit: lit(1),
|
|
898
|
+
})).length > 0
|
|
899
|
+
|
|
900
|
+
/** The write is answered: it leaves the log, unless it is kept as `applied`
|
|
901
|
+
* for a resend (`landed`). */
|
|
902
|
+
export let done = (db: Driver, seq: number): void =>
|
|
903
|
+
void db.query({ t: 'delete', from: LOG, where: and(at(seq), not(APPLIED)) })
|
|
904
|
+
|
|
905
|
+
/** A write that failed on a store that started: set aside with why, so the
|
|
906
|
+
* writes behind it go on. */
|
|
907
|
+
export let aside = (db: Driver, seq: number, why: string): void =>
|
|
908
|
+
void db.query({
|
|
909
|
+
t: 'update',
|
|
910
|
+
table: LOG,
|
|
911
|
+
set: {
|
|
912
|
+
state: lit('failed'),
|
|
913
|
+
why: val(why),
|
|
914
|
+
},
|
|
915
|
+
where: and(at(seq), or(PENDING, RUNNING)),
|
|
916
|
+
})
|
|
917
|
+
|
|
918
|
+
/** Every write set aside, waiting again: a new incarnation may be new code. */
|
|
919
|
+
export let revived = (db: Driver): void => {
|
|
920
|
+
idle.delete(of(db))
|
|
921
|
+
db.query({
|
|
922
|
+
t: 'update',
|
|
923
|
+
table: LOG,
|
|
924
|
+
set: { state: lit('pending') },
|
|
925
|
+
where: REVIVABLE,
|
|
926
|
+
})
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
/** A replay the store refused: kept, with why, and never replayed again. */
|
|
930
|
+
export let dead = (db: Driver, seq: number, why: string): void =>
|
|
931
|
+
void db.query({
|
|
932
|
+
t: 'update',
|
|
933
|
+
table: LOG,
|
|
934
|
+
set: { state: lit('refused'), why: val(why) },
|
|
935
|
+
where: at(seq),
|
|
936
|
+
})
|
|
937
|
+
|
|
938
|
+
/** The request a kept write was, to send `at` its door again (a Store's
|
|
939
|
+
* `/apply` unless said): a binary one's envelope as it came, which its
|
|
940
|
+
* apply door decodes ({@link decoded}). */
|
|
941
|
+
export let replayed = (k: Kept, at = 'http://store/apply'): Request => {
|
|
942
|
+
let headers = new Headers(JSON.parse(k.headers))
|
|
943
|
+
return new Request(at, {
|
|
944
|
+
method: 'POST',
|
|
945
|
+
headers,
|
|
946
|
+
body: opened(headers, k.body),
|
|
947
|
+
})
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
/** A constraint the batch broke — a unique name already taken, a required
|
|
951
|
+
* column left empty — is the batch's own refusal, not the store failing, and
|
|
952
|
+
* SQLite says which in its message. Left a 500, such a write would wait in
|
|
953
|
+
* the log for code that can never apply it, and hold up every write behind
|
|
954
|
+
* it. */
|
|
955
|
+
export let constrained = (e: unknown): unknown =>
|
|
956
|
+
e instanceof Error && /constraint failed/i.test(e.message)
|
|
957
|
+
? new Refused(e.message)
|
|
958
|
+
: e
|
|
959
|
+
|
|
960
|
+
/** What an answer said, in its own words. */
|
|
961
|
+
export let said = async (r: Response): Promise<string> => {
|
|
962
|
+
let text = await r.text()
|
|
963
|
+
try {
|
|
964
|
+
return String(JSON.parse(text).message ?? text)
|
|
965
|
+
} catch {
|
|
966
|
+
return text
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
/** Whether a write is still in the log, waiting or set aside. */
|
|
971
|
+
export let held = (db: Driver, seq: number): boolean =>
|
|
972
|
+
db.query(select({
|
|
973
|
+
cols: [lit(1)],
|
|
974
|
+
from: table(LOG),
|
|
975
|
+
where: and(at(seq), or(PENDING, FAILED, RUNNING)),
|
|
976
|
+
})).length > 0
|
|
977
|
+
|
|
978
|
+
/** Every write still in the log, oldest first: waiting, under way or set
|
|
979
|
+
* aside, and how many times each was tried. What a host that keeps a
|
|
980
|
+
* person's own words shows them of those words (a Builder's kept lines).
|
|
981
|
+
* One read a state, each on its own index: a log also keeps receipts, and
|
|
982
|
+
* an outbox's for good.
|
|
983
|
+
*
|
|
984
|
+
* ```ts
|
|
985
|
+
* import { equal } from '@yaks/testing'
|
|
986
|
+
* import { open } from '@yaks/sqlite/db'
|
|
987
|
+
* import { aside, keep, raise, started, unanswered } from './log.ts'
|
|
988
|
+
* let db = open(':memory:')
|
|
989
|
+
* raise(db)
|
|
990
|
+
* let sent = new Request('http://builder/say', { method: 'POST' })
|
|
991
|
+
* let one = keep(db, sent, 'one'), two = keep(db, sent, 'two')
|
|
992
|
+
* started(db, one)
|
|
993
|
+
* aside(db, one, 'unreachable')
|
|
994
|
+
* equal(unanswered(db).map((k) => [k.seq, k.body, k.tries]), [[one, 'one', 1], [two, 'two', 0]])
|
|
995
|
+
* ```
|
|
996
|
+
*/
|
|
997
|
+
export let unanswered = (db: Driver): (Kept & { tries: number })[] =>
|
|
998
|
+
[PENDING, RUNNING, FAILED].flatMap((where) =>
|
|
999
|
+
db.query(select({
|
|
1000
|
+
cols: [col('seq'), col('headers'), col('body'), col('tries')],
|
|
1001
|
+
from: table(LOG),
|
|
1002
|
+
where,
|
|
1003
|
+
}))
|
|
1004
|
+
).map((r) => ({
|
|
1005
|
+
seq: Number(r.seq),
|
|
1006
|
+
headers: String(r.headers),
|
|
1007
|
+
body: String(r.body),
|
|
1008
|
+
tries: Number(r.tries),
|
|
1009
|
+
})).sort((a, b) => a.seq - b.seq)
|
|
1010
|
+
|
|
1011
|
+
/** A kept write, as the door that sent it hears it (meta.ts): not applied
|
|
1012
|
+
* yet, and not lost. The failure that held it back was reported where it
|
|
1013
|
+
* happened, so this is not a defect of its own (defects.ts `refused`). A
|
|
1014
|
+
* store that kept it while stopped says how long until it lands
|
|
1015
|
+
* (`retry.after`, in ms), which a door passes on as `retry-after`. */
|
|
1016
|
+
export class Pending extends Error {
|
|
1017
|
+
retry?: { after: number }
|
|
1018
|
+
constructor(message: string, after = 0) {
|
|
1019
|
+
super(message)
|
|
1020
|
+
this.name = 'Pending'
|
|
1021
|
+
if (after > 0) this.retry = { after }
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
/** What a caller is told when its write is kept but not yet applied. */
|
|
1026
|
+
export let parked = (seq: number, why: string, review = false): Response =>
|
|
1027
|
+
Response.json({
|
|
1028
|
+
error: 'Pending',
|
|
1029
|
+
message: `${why} — the write is kept and ${
|
|
1030
|
+
review
|
|
1031
|
+
? 'needs owner review before it can be retried'
|
|
1032
|
+
: 'will be applied when this app recovers'
|
|
1033
|
+
}; do not send it again`,
|
|
1034
|
+
pending: seq,
|
|
1035
|
+
}, { status: 202 })
|