@yaks/effects 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 +979 -2
- package/_dist/docs.d.ts +10 -0
- package/_dist/docs.d.ts.map +1 -0
- package/_dist/enqueue.d.ts +12 -0
- package/_dist/enqueue.d.ts.map +1 -0
- package/_dist/expire.d.ts +31 -0
- package/_dist/expire.d.ts.map +1 -0
- package/_dist/invocation.d.ts +36 -0
- package/_dist/invocation.d.ts.map +1 -0
- package/_dist/lease.d.ts +98 -0
- package/_dist/lease.d.ts.map +1 -0
- package/_dist/mod.d.ts +89 -0
- package/_dist/mod.d.ts.map +1 -0
- package/_dist/outage.d.ts +48 -0
- package/_dist/outage.d.ts.map +1 -0
- package/_dist/pool.d.ts +148 -0
- package/_dist/pool.d.ts.map +1 -0
- package/_dist/provisional.d.ts +8 -0
- package/_dist/provisional.d.ts.map +1 -0
- package/_dist/ready.d.ts +3 -0
- package/_dist/ready.d.ts.map +1 -0
- package/_dist/registration.d.ts +17 -0
- package/_dist/registration.d.ts.map +1 -0
- package/_dist/registry.d.ts +153 -0
- package/_dist/registry.d.ts.map +1 -0
- package/_dist/tools.d.ts +21 -0
- package/_dist/tools.d.ts.map +1 -0
- package/_dist/trace.d.ts +63 -0
- package/_dist/trace.d.ts.map +1 -0
- package/_dist/views.d.ts +15 -0
- package/_dist/views.d.ts.map +1 -0
- package/_dist/vocab.d.ts +11 -0
- package/_dist/vocab.d.ts.map +1 -0
- package/_dist/worker.d.ts +19 -0
- package/_dist/worker.d.ts.map +1 -0
- package/_dist/write.d.ts +25 -0
- package/_dist/write.d.ts.map +1 -0
- package/cleanup.js +75 -0
- package/cleanup.js.map +1 -0
- package/cleanup.ts +83 -0
- package/deno.json +1 -0
- package/docs.js +13 -0
- package/docs.js.map +1 -0
- package/docs.ts +13 -0
- package/enqueue.js +71 -0
- package/enqueue.js.map +1 -0
- package/enqueue.ts +86 -0
- package/expire.js +225 -0
- package/expire.js.map +1 -0
- package/expire.ts +244 -0
- package/invocation.js +245 -0
- package/invocation.js.map +1 -0
- package/invocation.ts +250 -0
- package/lease.js +343 -0
- package/lease.js.map +1 -0
- package/lease.ts +444 -0
- package/mod.js +89 -0
- package/mod.js.map +1 -0
- package/mod.ts +92 -0
- package/outage.js +77 -0
- package/outage.js.map +1 -0
- package/outage.ts +84 -0
- package/package.json +52 -4
- package/page.js +315 -0
- package/page.js.map +1 -0
- package/page.ts +524 -0
- package/pool.js +1474 -0
- package/pool.js.map +1 -0
- package/pool.ts +1635 -0
- package/provisional.js +20 -0
- package/provisional.js.map +1 -0
- package/provisional.ts +26 -0
- package/ready.js +48 -0
- package/ready.js.map +1 -0
- package/ready.ts +93 -0
- package/registration.js +21 -0
- package/registration.js.map +1 -0
- package/registration.ts +43 -0
- package/registry.js +872 -0
- package/registry.js.map +1 -0
- package/registry.ts +1196 -0
- package/tools.js +182 -0
- package/tools.js.map +1 -0
- package/tools.ts +229 -0
- package/trace.js +167 -0
- package/trace.js.map +1 -0
- package/trace.ts +217 -0
- package/views.js +18 -0
- package/views.js.map +1 -0
- package/views.ts +18 -0
- package/vocab.js +18 -0
- package/vocab.js.map +1 -0
- package/vocab.json +364 -0
- package/vocab.ts +20 -0
- package/worker.js +114 -0
- package/worker.js.map +1 -0
- package/worker.ts +146 -0
- package/write.js +38 -0
- package/write.js.map +1 -0
- package/write.ts +60 -0
package/enqueue.ts
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// Explicitly owed work uses the same durable rows as declared graph triggers.
|
|
2
|
+
import {
|
|
3
|
+
type Access,
|
|
4
|
+
type Bundle,
|
|
5
|
+
type Eid,
|
|
6
|
+
type Entity,
|
|
7
|
+
mint,
|
|
8
|
+
type Tx,
|
|
9
|
+
} from '@yaks/graph'
|
|
10
|
+
import type { HookContext } from 'jsr:@yaks/graph@0.2.36/plugin'
|
|
11
|
+
import { Refused } from '@yaks/graph/errors'
|
|
12
|
+
import { token } from '@yaks/graph/sha256'
|
|
13
|
+
import { effectsIn } from '@yaks/vocab'
|
|
14
|
+
|
|
15
|
+
/** Owe one fresh invocation independently of a component transition. */
|
|
16
|
+
export let enqueue = (
|
|
17
|
+
g: Access,
|
|
18
|
+
handler: string,
|
|
19
|
+
target: Eid,
|
|
20
|
+
): Bundle[] | Promise<Bundle[]> => {
|
|
21
|
+
if (!g.vocab.comp('effect')) throw new Refused('No durable effect pool')
|
|
22
|
+
if (!effectsIn(g.vocab.docs).some((effect) => effect.name == handler)) {
|
|
23
|
+
throw new Refused('No declared effect: ' + handler)
|
|
24
|
+
}
|
|
25
|
+
return g.apply([effectInvocation(handler, target)], { trusted: true })
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** The durable invocation patch, for a trusted writer already in a batch,
|
|
29
|
+
* due at `next` (an ISO time) or at once. */
|
|
30
|
+
export let effectInvocation = (
|
|
31
|
+
handler: string,
|
|
32
|
+
target: Eid,
|
|
33
|
+
next?: string,
|
|
34
|
+
): Bundle => ({
|
|
35
|
+
entity: { eid: mint() },
|
|
36
|
+
effect: {
|
|
37
|
+
handler,
|
|
38
|
+
target,
|
|
39
|
+
kind: 'matched',
|
|
40
|
+
state: 'pending',
|
|
41
|
+
attempts: 0,
|
|
42
|
+
generation: 0,
|
|
43
|
+
at: new Date().toISOString(),
|
|
44
|
+
...next ? { next } : {},
|
|
45
|
+
},
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
// Pending with a full allowance, as a run no one has started: the pool claims
|
|
49
|
+
// it, counts attempts and backs off exactly as it does a new one.
|
|
50
|
+
let RETRIED = {
|
|
51
|
+
state: 'pending',
|
|
52
|
+
attempts: 0,
|
|
53
|
+
next: null,
|
|
54
|
+
error: null,
|
|
55
|
+
waiting: null,
|
|
56
|
+
lease_owner: null,
|
|
57
|
+
lease_token: null,
|
|
58
|
+
lease_expiry: null,
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** The patch that puts a run back to pending with a fresh allowance, guarded
|
|
62
|
+
* on the state it was read in (`was`, failed unless said), so a run a worker
|
|
63
|
+
* has since touched is left alone. */
|
|
64
|
+
export let effectRetry = (run: Eid, was = 'failed'): Bundle => ({
|
|
65
|
+
entity: { eid: run },
|
|
66
|
+
effect: RETRIED,
|
|
67
|
+
$was: { effect: { state: token(was) } },
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
// The transactions a hook owed a run in (`owe`), whose commit wakes the pool
|
|
71
|
+
// as a run written in the batch itself does (./registry.ts).
|
|
72
|
+
export let owing: WeakSet<object> = new WeakSet()
|
|
73
|
+
|
|
74
|
+
/** Owe one fresh invocation from a hook inside a write's own transaction (a
|
|
75
|
+
* `commit` hook's `tx`), so the run commits or rolls back with the write that
|
|
76
|
+
* owes it, due at `next` or at once. */
|
|
77
|
+
export let owe = (
|
|
78
|
+
tx: Tx,
|
|
79
|
+
context: HookContext | undefined,
|
|
80
|
+
handler: string,
|
|
81
|
+
target: Eid,
|
|
82
|
+
next?: string,
|
|
83
|
+
): Entity[] | Promise<Entity[]> => {
|
|
84
|
+
if (context?.transaction) owing.add(context.transaction)
|
|
85
|
+
return tx.patch([effectInvocation(handler, target, next)])
|
|
86
|
+
}
|
package/expire.js
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
// One sweep over the composed vocabulary's regenerable cache declarations.
|
|
2
|
+
// Removal goes through apply so references, journal and subscribers see the
|
|
3
|
+
// ordinary component edit. Trash and its identities never expire.
|
|
4
|
+
import { expireOf } from "@yaks/vocab";
|
|
5
|
+
import { after as past, and, fields, limit, parse, present } from "@yaks/query";
|
|
6
|
+
import { comps } from "@yaks/graph/bundle";
|
|
7
|
+
import { Stale } from "@yaks/graph/errors";
|
|
8
|
+
import { token } from "@yaks/graph/sha256";
|
|
9
|
+
import { HOLD, LEASE, leaseEid, sleep, take } from "./lease.js";
|
|
10
|
+
/** The daily expiration duty shared by every effects worker. */ export let EXPIRE = '@yaks/effects/expire';
|
|
11
|
+
/** A day in milliseconds between successful expiration passes. */ export let DAY = 86_400_000;
|
|
12
|
+
/** The former tombstone retention, retained for callers that display it.
|
|
13
|
+
* Tombstones and their trash no longer expire. */ export let TOMBSTONES = 30 * DAY;
|
|
14
|
+
/** Remove matching regenerable component rows in bounded transactions.
|
|
15
|
+
* The returned count is component rows, not entities: another component keeps
|
|
16
|
+
* its owner alive. Trash is retained until a person chooses to purge it.
|
|
17
|
+
* Each declaration is constrained to its own component even when its query
|
|
18
|
+
* contains an OR. */ export let expire = async (g, opts = {})=>{
|
|
19
|
+
let batch = opts.batch ?? 100;
|
|
20
|
+
let page = opts.page ?? PAGE;
|
|
21
|
+
for (let [name, n] of [
|
|
22
|
+
[
|
|
23
|
+
'batch',
|
|
24
|
+
batch
|
|
25
|
+
],
|
|
26
|
+
[
|
|
27
|
+
'page',
|
|
28
|
+
page
|
|
29
|
+
]
|
|
30
|
+
]){
|
|
31
|
+
if (!Number.isInteger(n) || n < 1) {
|
|
32
|
+
throw Error(`expire ${name} must be a positive integer`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
let paced = pacer(opts.signal);
|
|
36
|
+
let removed = 0;
|
|
37
|
+
for (let comp of g.vocab.all){
|
|
38
|
+
let text = expireOf(g.vocab, comp);
|
|
39
|
+
if (!text) continue;
|
|
40
|
+
let query = parse(text, {
|
|
41
|
+
text: false
|
|
42
|
+
});
|
|
43
|
+
// Expiration selects a set, not a projected/aggregated/windowed answer.
|
|
44
|
+
let filters = (c)=>c.kind == 'pred' || (c.kind == 'and' || c.kind == 'or') && c.clauses.every(filters);
|
|
45
|
+
if (!query.clauses.every(filters)) {
|
|
46
|
+
throw Error(`${comp} expire must be a filter query`);
|
|
47
|
+
}
|
|
48
|
+
for await (let eids of owners(g, comp, page, paced, opts.signal)){
|
|
49
|
+
// A refusal reselects the page: what it refused may still expire.
|
|
50
|
+
for(let left = eids; left.length && !opts.signal?.aborted;){
|
|
51
|
+
let rows = await paced(()=>g.read(and(present(comp), query), {
|
|
52
|
+
now: opts.now,
|
|
53
|
+
eids: left
|
|
54
|
+
}));
|
|
55
|
+
if (!rows.length) break;
|
|
56
|
+
let some = rows.slice(0, batch);
|
|
57
|
+
try {
|
|
58
|
+
let applied = await paced(()=>g.apply(some.map((b)=>removal(g, comp, b)), {
|
|
59
|
+
trusted: true,
|
|
60
|
+
expiring: true
|
|
61
|
+
}));
|
|
62
|
+
let selected = new Set(some.map((b)=>b.entity.eid));
|
|
63
|
+
removed += applied.filter((b)=>selected.has(b.entity.eid) && (b[comp] === null || b.tombstone != null)).length;
|
|
64
|
+
left = rows.slice(batch).map((b)=>b.entity.eid);
|
|
65
|
+
} catch (err) {
|
|
66
|
+
if (!(err instanceof Stale)) throw err;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return removed;
|
|
72
|
+
};
|
|
73
|
+
// A row's removal, guarded by the values the selection read, not just the age
|
|
74
|
+
// of the expiring row: a concurrent completion or revival is not expired on
|
|
75
|
+
// the strength of a stale read.
|
|
76
|
+
let removal = (g, comp, b)=>{
|
|
77
|
+
let was = {};
|
|
78
|
+
for (let [c, v] of comps(b)){
|
|
79
|
+
if (v == null) continue;
|
|
80
|
+
let props = g.vocab.props(c).filter((p)=>!g.vocab.prop(c, p)?.computed);
|
|
81
|
+
if (props.length) {
|
|
82
|
+
was[c] = Object.fromEntries(props.map((p)=>[
|
|
83
|
+
p,
|
|
84
|
+
token(v[p] ?? null)
|
|
85
|
+
]));
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return {
|
|
89
|
+
entity: b.entity,
|
|
90
|
+
[comp]: null,
|
|
91
|
+
$was: was
|
|
92
|
+
};
|
|
93
|
+
};
|
|
94
|
+
/** How many of a component's owners one read of a sweep walks past. */ export let PAGE = 1000;
|
|
95
|
+
// A component's owners, a page at a time in the order its rows were stored.
|
|
96
|
+
// A declaration's query is tested against one page's owners at a time, so a
|
|
97
|
+
// read costs a page however large the table and however few of its rows
|
|
98
|
+
// expire: one read of the whole test walks every row in a single statement,
|
|
99
|
+
// and holds a read lane for as long as that takes on a cold disk. The cursor
|
|
100
|
+
// is the page's last owner, which a removal leaves standing (its tombstone
|
|
101
|
+
// outlives the pass), so the walk never loses its place.
|
|
102
|
+
async function* owners(g, comp, page, paced, signal) {
|
|
103
|
+
let after;
|
|
104
|
+
while(!signal?.aborted){
|
|
105
|
+
let rows = await paced(()=>g.read(and(present(comp), fields('entity.eid'), limit(page), ...after ? [
|
|
106
|
+
past(after)
|
|
107
|
+
] : []), {
|
|
108
|
+
storageOrder: true
|
|
109
|
+
}));
|
|
110
|
+
if (!rows.length) return;
|
|
111
|
+
let eids = rows.map((b)=>b.entity.eid);
|
|
112
|
+
after = eids.at(-1);
|
|
113
|
+
yield eids;
|
|
114
|
+
if (rows.length < page) return;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
// A pass's batches each hold the write lock while they apply, and its pages of
|
|
118
|
+
// graves each hold the thread while they are read. Before the next one the
|
|
119
|
+
// pass rests as long as the last one held: writers waiting on the file get in,
|
|
120
|
+
// where a sweep that took the lock straight back would starve them in their
|
|
121
|
+
// busy handlers, and lease renewals and the worker's other runs get their
|
|
122
|
+
// turn.
|
|
123
|
+
let pacer = (signal)=>{
|
|
124
|
+
let held = 0;
|
|
125
|
+
return async (step)=>{
|
|
126
|
+
if (held) await sleep(held, signal);
|
|
127
|
+
let since = performance.now();
|
|
128
|
+
try {
|
|
129
|
+
return await step();
|
|
130
|
+
} finally{
|
|
131
|
+
held = performance.now() - since;
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
};
|
|
135
|
+
/** One due daily pass, contended by the workers' existing lease mechanism.
|
|
136
|
+
* Leave the lease standing for a day after success. A crash or failure leaves
|
|
137
|
+
* only a short hold, so another worker can recover rather than skip the day. */ export let expireDaily = async (g, opts)=>{
|
|
138
|
+
let now = opts.now ?? Date.now;
|
|
139
|
+
if (opts.signal?.aborted) return;
|
|
140
|
+
let [lease] = await g.get([
|
|
141
|
+
leaseEid(EXPIRE)
|
|
142
|
+
], [
|
|
143
|
+
LEASE
|
|
144
|
+
]);
|
|
145
|
+
let held = lease?.[LEASE];
|
|
146
|
+
// A completed pass's day-long hold applies to its own worker too.
|
|
147
|
+
if (held?.until && Date.parse(String(held.until)) > now()) return;
|
|
148
|
+
if (!await take(g, EXPIRE, {
|
|
149
|
+
holder: opts.owner,
|
|
150
|
+
now
|
|
151
|
+
})) return;
|
|
152
|
+
let lost = new AbortController();
|
|
153
|
+
let error;
|
|
154
|
+
let renewing;
|
|
155
|
+
let beat = setInterval(()=>{
|
|
156
|
+
if (renewing) return;
|
|
157
|
+
renewing = take(g, EXPIRE, {
|
|
158
|
+
holder: opts.owner,
|
|
159
|
+
now
|
|
160
|
+
}).then((ours)=>{
|
|
161
|
+
if (!ours) lost.abort();
|
|
162
|
+
}).catch((err)=>{
|
|
163
|
+
error = err;
|
|
164
|
+
lost.abort();
|
|
165
|
+
}).finally(()=>{
|
|
166
|
+
renewing = undefined;
|
|
167
|
+
});
|
|
168
|
+
}, HOLD / 3);
|
|
169
|
+
try {
|
|
170
|
+
await expire(g, {
|
|
171
|
+
now: now(),
|
|
172
|
+
signal: opts.signal ? AbortSignal.any([
|
|
173
|
+
opts.signal,
|
|
174
|
+
lost.signal
|
|
175
|
+
]) : lost.signal
|
|
176
|
+
});
|
|
177
|
+
} finally{
|
|
178
|
+
clearInterval(beat);
|
|
179
|
+
await renewing;
|
|
180
|
+
}
|
|
181
|
+
if (error) throw error;
|
|
182
|
+
if (!opts.signal?.aborted && !lost.signal.aborted && g.vocab.comp(LEASE)) {
|
|
183
|
+
let [row] = await g.get([
|
|
184
|
+
leaseEid(EXPIRE)
|
|
185
|
+
], [
|
|
186
|
+
LEASE
|
|
187
|
+
]);
|
|
188
|
+
let held = row?.[LEASE];
|
|
189
|
+
if (held?.holder != opts.owner) return;
|
|
190
|
+
try {
|
|
191
|
+
await g.apply([
|
|
192
|
+
{
|
|
193
|
+
entity: {
|
|
194
|
+
eid: leaseEid(EXPIRE)
|
|
195
|
+
},
|
|
196
|
+
[LEASE]: {
|
|
197
|
+
holder: null,
|
|
198
|
+
until: new Date(now() + DAY).toISOString()
|
|
199
|
+
},
|
|
200
|
+
$was: {
|
|
201
|
+
[LEASE]: {
|
|
202
|
+
holder: token(held.holder),
|
|
203
|
+
until: token(held.until)
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
], {
|
|
208
|
+
trusted: true
|
|
209
|
+
});
|
|
210
|
+
} catch (error) {
|
|
211
|
+
if (!(error instanceof Stale)) throw error;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
};
|
|
215
|
+
/** Expiration's upkeep duty, independent of the pool's work selection. */ export let expiration = async (g, opts)=>{
|
|
216
|
+
while(!opts.signal.aborted){
|
|
217
|
+
try {
|
|
218
|
+
await expireDaily(g, opts);
|
|
219
|
+
} catch (error) {
|
|
220
|
+
opts.report(error);
|
|
221
|
+
}
|
|
222
|
+
await sleep(g.vocab.comp(LEASE) ? HOLD : DAY, opts.signal);
|
|
223
|
+
}
|
|
224
|
+
};
|
|
225
|
+
//# sourceMappingURL=expire.js.map
|
package/expire.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"expire.js","sources":["./expire.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,4EAA4E;AAC5E,kEAAkE;AAClE,SAAS,QAAQ,2BAAgC;AACjD,SACE,SAAS,IAAI,EACb,GAAG,EAEH,MAAM,EACN,KAAK,EACL,KAAK,EACL,OAAO,2BACsB;AAE/B,SAAS,KAAK,kCAAuC;AACrD,SAAS,KAAK,kCAAuC;AACrD,SAAS,KAAK,kCAAuC;AACrD,SAAS,IAAI,EAAE,KAAK,EAAE,QAAQ,EAAE,KAAK,EAAE,IAAI,qBAAoB;AAE/D,8DAA8D,GAC9D,OAAO,IAAI,SAAS,uBAAsB;AAC1C,gEA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AAM;cAAG,OAAO,MAAM,KAAK,KAAK;YAAE;UAClE;QACF;OAAE,EAAE;QAAE,SAAS;MAAK;IACtB,EAAE,OAAO,OAAO;MACd,IAAI,CAAC,CAAC,iBAAiB,KAAK,GAAG,MAAM;IACvC;EACF;AACF,EAAC;AAED,wEAAwE,GACxE,OAAO,IAAI,aAAa,OACtB,GACA;EAOA,MAAO,CAAC,KAAK,MAAM,CAAC,OAAO,CAAE;IAC3B,IAAI;MACF,MAAM,YAAY,GAAG;IACvB,EAAE,OAAO,OAAO;MACd,KAAK,MAAM,CAAC;IACd;IACA,MAAM,MAAM,EAAE,KAAK,CAAC,IAAI,CAAC,SAAS,OAAO,KAAK,KAAK,MAAM;EAC3D;AACF,EAAC"}
|
package/expire.ts
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
// One sweep over the composed vocabulary's regenerable cache declarations.
|
|
2
|
+
// Removal goes through apply so references, journal and subscribers see the
|
|
3
|
+
// ordinary component edit. Trash and its identities never expire.
|
|
4
|
+
import { expireOf } from '@yaks/vocab'
|
|
5
|
+
import {
|
|
6
|
+
after as past,
|
|
7
|
+
and,
|
|
8
|
+
type Clause,
|
|
9
|
+
fields,
|
|
10
|
+
limit,
|
|
11
|
+
parse,
|
|
12
|
+
present,
|
|
13
|
+
} from '@yaks/query'
|
|
14
|
+
import type { Access, Bundle, Comp } from 'jsr:@yaks/graph@0.2.36'
|
|
15
|
+
import { comps } from '@yaks/graph/bundle'
|
|
16
|
+
import { Stale } from '@yaks/graph/errors'
|
|
17
|
+
import { token } from '@yaks/graph/sha256'
|
|
18
|
+
import { HOLD, LEASE, leaseEid, sleep, take } from './lease.js'
|
|
19
|
+
|
|
20
|
+
/** The daily expiration duty shared by every effects worker. */
|
|
21
|
+
export let EXPIRE = '@yaks/effects/expire'
|
|
22
|
+
/** A day in milliseconds between successful expiration passes. */
|
|
23
|
+
export let DAY = 86_400_000
|
|
24
|
+
/** The former tombstone retention, retained for callers that display it.
|
|
25
|
+
* Tombstones and their trash no longer expire. */
|
|
26
|
+
export let TOMBSTONES = 30 * DAY
|
|
27
|
+
|
|
28
|
+
/** Remove matching regenerable component rows in bounded transactions.
|
|
29
|
+
* The returned count is component rows, not entities: another component keeps
|
|
30
|
+
* its owner alive. Trash is retained until a person chooses to purge it.
|
|
31
|
+
* Each declaration is constrained to its own component even when its query
|
|
32
|
+
* contains an OR. */
|
|
33
|
+
export let expire = async (
|
|
34
|
+
g: Access,
|
|
35
|
+
opts: {
|
|
36
|
+
batch?: number
|
|
37
|
+
now?: number
|
|
38
|
+
page?: number
|
|
39
|
+
signal?: AbortSignal
|
|
40
|
+
/** Ignored: retained trash has no automatic expiration. */
|
|
41
|
+
tombstones?: number
|
|
42
|
+
} = {},
|
|
43
|
+
): Promise<number> => {
|
|
44
|
+
let batch = opts.batch ?? 100
|
|
45
|
+
let page = opts.page ?? PAGE
|
|
46
|
+
for (let [name, n] of [['batch', batch], ['page', page]] as const) {
|
|
47
|
+
if (!Number.isInteger(n) || n < 1) {
|
|
48
|
+
throw Error(`expire ${name} must be a positive integer`)
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
let paced = pacer(opts.signal)
|
|
52
|
+
let removed = 0
|
|
53
|
+
for (let comp of g.vocab.all) {
|
|
54
|
+
let text = expireOf(g.vocab, comp)
|
|
55
|
+
if (!text) continue
|
|
56
|
+
let query = parse(text, { text: false })
|
|
57
|
+
// Expiration selects a set, not a projected/aggregated/windowed answer.
|
|
58
|
+
let filters = (c: Clause): boolean =>
|
|
59
|
+
c.kind == 'pred' ||
|
|
60
|
+
((c.kind == 'and' || c.kind == 'or') && c.clauses.every(filters))
|
|
61
|
+
if (!query.clauses.every(filters)) {
|
|
62
|
+
throw Error(`${comp} expire must be a filter query`)
|
|
63
|
+
}
|
|
64
|
+
for await (let eids of owners(g, comp, page, paced, opts.signal)) {
|
|
65
|
+
// A refusal reselects the page: what it refused may still expire.
|
|
66
|
+
for (let left = eids; left.length && !opts.signal?.aborted;) {
|
|
67
|
+
let rows = await paced(() =>
|
|
68
|
+
g.read(and(present(comp), query), { now: opts.now, eids: left })
|
|
69
|
+
)
|
|
70
|
+
if (!rows.length) break
|
|
71
|
+
let some = rows.slice(0, batch)
|
|
72
|
+
try {
|
|
73
|
+
let applied = await paced(() =>
|
|
74
|
+
g.apply(some.map((b) => removal(g, comp, b)), {
|
|
75
|
+
trusted: true,
|
|
76
|
+
expiring: true,
|
|
77
|
+
})
|
|
78
|
+
)
|
|
79
|
+
let selected = new Set(some.map((b) => b.entity.eid))
|
|
80
|
+
removed += applied.filter((b) =>
|
|
81
|
+
selected.has(b.entity.eid) &&
|
|
82
|
+
(b[comp] === null || b.tombstone != null)
|
|
83
|
+
).length
|
|
84
|
+
left = rows.slice(batch).map((b) => b.entity.eid)
|
|
85
|
+
} catch (err) {
|
|
86
|
+
if (!(err instanceof Stale)) throw err
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return removed
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// A row's removal, guarded by the values the selection read, not just the age
|
|
95
|
+
// of the expiring row: a concurrent completion or revival is not expired on
|
|
96
|
+
// the strength of a stale read.
|
|
97
|
+
let removal = (g: Access, comp: string, b: Bundle): Bundle => {
|
|
98
|
+
let was: NonNullable<Bundle['$was']> = {}
|
|
99
|
+
for (let [c, v] of comps(b)) {
|
|
100
|
+
if (v == null) continue
|
|
101
|
+
let props = g.vocab.props(c).filter((p) => !g.vocab.prop(c, p)?.computed)
|
|
102
|
+
if (props.length) {
|
|
103
|
+
was[c] = Object.fromEntries(
|
|
104
|
+
props.map((p) => [p, token((v as Comp)[p] ?? null)]),
|
|
105
|
+
)
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return { entity: b.entity, [comp]: null, $was: was }
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** How many of a component's owners one read of a sweep walks past. */
|
|
112
|
+
export let PAGE = 1000
|
|
113
|
+
|
|
114
|
+
// A component's owners, a page at a time in the order its rows were stored.
|
|
115
|
+
// A declaration's query is tested against one page's owners at a time, so a
|
|
116
|
+
// read costs a page however large the table and however few of its rows
|
|
117
|
+
// expire: one read of the whole test walks every row in a single statement,
|
|
118
|
+
// and holds a read lane for as long as that takes on a cold disk. The cursor
|
|
119
|
+
// is the page's last owner, which a removal leaves standing (its tombstone
|
|
120
|
+
// outlives the pass), so the walk never loses its place.
|
|
121
|
+
async function* owners(
|
|
122
|
+
g: Access,
|
|
123
|
+
comp: string,
|
|
124
|
+
page: number,
|
|
125
|
+
paced: ReturnType<typeof pacer>,
|
|
126
|
+
signal?: AbortSignal,
|
|
127
|
+
): AsyncGenerator<string[]> {
|
|
128
|
+
let after: string | undefined
|
|
129
|
+
while (!signal?.aborted) {
|
|
130
|
+
let rows = await paced(() =>
|
|
131
|
+
g.read(
|
|
132
|
+
and(
|
|
133
|
+
present(comp),
|
|
134
|
+
fields('entity.eid'),
|
|
135
|
+
limit(page),
|
|
136
|
+
...after ? [past(after)] : [],
|
|
137
|
+
),
|
|
138
|
+
{ storageOrder: true },
|
|
139
|
+
)
|
|
140
|
+
)
|
|
141
|
+
if (!rows.length) return
|
|
142
|
+
let eids = rows.map((b) => b.entity.eid)
|
|
143
|
+
after = eids.at(-1)
|
|
144
|
+
yield eids
|
|
145
|
+
if (rows.length < page) return
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// A pass's batches each hold the write lock while they apply, and its pages of
|
|
150
|
+
// graves each hold the thread while they are read. Before the next one the
|
|
151
|
+
// pass rests as long as the last one held: writers waiting on the file get in,
|
|
152
|
+
// where a sweep that took the lock straight back would starve them in their
|
|
153
|
+
// busy handlers, and lease renewals and the worker's other runs get their
|
|
154
|
+
// turn.
|
|
155
|
+
let pacer = (signal?: AbortSignal) => {
|
|
156
|
+
let held = 0
|
|
157
|
+
return async <T>(step: () => T | Promise<T>): Promise<T> => {
|
|
158
|
+
if (held) await sleep(held, signal)
|
|
159
|
+
let since = performance.now()
|
|
160
|
+
try {
|
|
161
|
+
return await step()
|
|
162
|
+
} finally {
|
|
163
|
+
held = performance.now() - since
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** One due daily pass, contended by the workers' existing lease mechanism.
|
|
169
|
+
* Leave the lease standing for a day after success. A crash or failure leaves
|
|
170
|
+
* only a short hold, so another worker can recover rather than skip the day. */
|
|
171
|
+
export let expireDaily = async (
|
|
172
|
+
g: Access,
|
|
173
|
+
opts: { owner: string; now?: () => number; signal?: AbortSignal },
|
|
174
|
+
): Promise<void> => {
|
|
175
|
+
let now = opts.now ?? Date.now
|
|
176
|
+
if (opts.signal?.aborted) return
|
|
177
|
+
let [lease] = await g.get([leaseEid(EXPIRE)], [LEASE])
|
|
178
|
+
let held = lease?.[LEASE] as Comp | undefined
|
|
179
|
+
// A completed pass's day-long hold applies to its own worker too.
|
|
180
|
+
if (held?.until && Date.parse(String(held.until)) > now()) return
|
|
181
|
+
if (!await take(g, EXPIRE, { holder: opts.owner, now })) return
|
|
182
|
+
let lost = new AbortController()
|
|
183
|
+
let error: unknown
|
|
184
|
+
let renewing: Promise<void> | undefined
|
|
185
|
+
let beat = setInterval(() => {
|
|
186
|
+
if (renewing) return
|
|
187
|
+
renewing = take(g, EXPIRE, { holder: opts.owner, now }).then((ours) => {
|
|
188
|
+
if (!ours) lost.abort()
|
|
189
|
+
}).catch((err) => {
|
|
190
|
+
error = err
|
|
191
|
+
lost.abort()
|
|
192
|
+
}).finally(() => {
|
|
193
|
+
renewing = undefined
|
|
194
|
+
})
|
|
195
|
+
}, HOLD / 3)
|
|
196
|
+
try {
|
|
197
|
+
await expire(g, {
|
|
198
|
+
now: now(),
|
|
199
|
+
signal: opts.signal
|
|
200
|
+
? AbortSignal.any([opts.signal, lost.signal])
|
|
201
|
+
: lost.signal,
|
|
202
|
+
})
|
|
203
|
+
} finally {
|
|
204
|
+
clearInterval(beat)
|
|
205
|
+
await renewing
|
|
206
|
+
}
|
|
207
|
+
if (error) throw error
|
|
208
|
+
if (!opts.signal?.aborted && !lost.signal.aborted && g.vocab.comp(LEASE)) {
|
|
209
|
+
let [row] = await g.get([leaseEid(EXPIRE)], [LEASE])
|
|
210
|
+
let held = row?.[LEASE] as Comp | undefined
|
|
211
|
+
if (held?.holder != opts.owner) return
|
|
212
|
+
try {
|
|
213
|
+
await g.apply([{
|
|
214
|
+
entity: { eid: leaseEid(EXPIRE) },
|
|
215
|
+
[LEASE]: { holder: null, until: new Date(now() + DAY).toISOString() },
|
|
216
|
+
$was: {
|
|
217
|
+
[LEASE]: { holder: token(held.holder), until: token(held.until) },
|
|
218
|
+
},
|
|
219
|
+
}], { trusted: true })
|
|
220
|
+
} catch (error) {
|
|
221
|
+
if (!(error instanceof Stale)) throw error
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Expiration's upkeep duty, independent of the pool's work selection. */
|
|
227
|
+
export let expiration = async (
|
|
228
|
+
g: Access,
|
|
229
|
+
opts: {
|
|
230
|
+
owner: string
|
|
231
|
+
signal: AbortSignal
|
|
232
|
+
now?: () => number
|
|
233
|
+
report: (error: unknown) => void
|
|
234
|
+
},
|
|
235
|
+
): Promise<void> => {
|
|
236
|
+
while (!opts.signal.aborted) {
|
|
237
|
+
try {
|
|
238
|
+
await expireDaily(g, opts)
|
|
239
|
+
} catch (error) {
|
|
240
|
+
opts.report(error)
|
|
241
|
+
}
|
|
242
|
+
await sleep(g.vocab.comp(LEASE) ? HOLD : DAY, opts.signal)
|
|
243
|
+
}
|
|
244
|
+
}
|