@git-stunts/git-cas 6.0.1 → 6.2.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/ARCHITECTURE.md +120 -6
- package/CHANGELOG.md +98 -1
- package/GUIDE.md +114 -13
- package/README.md +60 -4
- package/UPGRADING.md +71 -1
- package/build-info.json +2 -2
- package/docs/API.md +934 -7
- package/docs/WALKTHROUGH.md +46 -0
- package/docs/releases/v6.1.0.md +75 -0
- package/docs/releases/v6.2.0.md +131 -0
- package/index.d.ts +974 -1
- package/index.js +354 -1
- package/package.json +8 -6
- package/src/domain/errors/Codes.js +48 -0
- package/src/domain/helpers/assertCanonicalTimestamp.js +15 -0
- package/src/domain/helpers/handleTarget.js +48 -0
- package/src/domain/helpers/isCanonicalCollectionKey.js +35 -0
- package/src/domain/services/AssetService.js +213 -0
- package/src/domain/services/BundleDescriptorCodec.js +286 -0
- package/src/domain/services/BundleFanoutBuilder.js +247 -0
- package/src/domain/services/BundleService.js +848 -0
- package/src/domain/services/CacheCandidateHeap.js +71 -0
- package/src/domain/services/CacheIndex.js +362 -0
- package/src/domain/services/CacheMetadataCodec.js +164 -0
- package/src/domain/services/CachePolicyEnforcer.js +144 -0
- package/src/domain/services/CacheSet.js +703 -0
- package/src/domain/services/CacheSetRegistry.js +88 -0
- package/src/domain/services/CasService.d.ts +3 -1
- package/src/domain/services/ExpiringSet.js +496 -0
- package/src/domain/services/ExpiringSetIndex.js +254 -0
- package/src/domain/services/ExpiringSetMetadataCodec.js +160 -0
- package/src/domain/services/ExpiringSetRegistry.js +101 -0
- package/src/domain/services/PageService.js +175 -0
- package/src/domain/services/PublicationService.js +315 -0
- package/src/domain/services/RepositoryDoctor.js +649 -0
- package/src/domain/services/RetentionService.js +120 -0
- package/src/domain/services/RootSet.js +281 -0
- package/src/domain/services/RootSetMetadataCodec.js +259 -0
- package/src/domain/services/RootSetPersistence.js +335 -0
- package/src/domain/services/RootSetRegistry.js +44 -0
- package/src/domain/services/RootSetRetryPolicy.js +87 -0
- package/src/domain/services/RootSetTreeCodec.js +95 -0
- package/src/domain/services/StagingEvidence.js +39 -0
- package/src/domain/value-objects/ApplicationHandle.js +40 -0
- package/src/domain/value-objects/AssetHandle.js +163 -0
- package/src/domain/value-objects/BundleHandle.js +32 -0
- package/src/domain/value-objects/BundleLimits.js +80 -0
- package/src/domain/value-objects/BundlePath.js +78 -0
- package/src/domain/value-objects/CacheHit.js +93 -0
- package/src/domain/value-objects/CacheKey.js +32 -0
- package/src/domain/value-objects/CachePolicy.js +59 -0
- package/src/domain/value-objects/CacheSetRef.js +40 -0
- package/src/domain/value-objects/CollectionNamespace.js +54 -0
- package/src/domain/value-objects/ExpiringMarker.js +81 -0
- package/src/domain/value-objects/ExpiringSetKey.js +28 -0
- package/src/domain/value-objects/ExpiringSetRef.js +42 -0
- package/src/domain/value-objects/OpaqueHandle.js +171 -0
- package/src/domain/value-objects/PageHandle.js +34 -0
- package/src/domain/value-objects/RetentionWitness.js +101 -0
- package/src/domain/value-objects/RootSetRef.js +88 -0
- package/src/domain/value-objects/StagedAsset.js +63 -0
- package/src/domain/value-objects/StagedBundle.js +66 -0
- package/src/domain/value-objects/StagedPage.js +47 -0
- package/src/infrastructure/adapters/GitPersistenceAdapter.js +57 -0
- package/src/infrastructure/adapters/GitRefAdapter.js +26 -5
- package/src/infrastructure/adapters/GitRepositoryInspectionAdapter.js +164 -0
- package/src/package-version.js +1 -1
- package/src/ports/GitPersistencePort.js +20 -1
- package/src/ports/GitRefPort.js +10 -0
- package/src/ports/RepositoryInspectionPort.js +33 -0
|
@@ -0,0 +1,703 @@
|
|
|
1
|
+
import { utf8Encode } from '../encoding/utf8.js';
|
|
2
|
+
import createCasError from '../errors/createCasError.js';
|
|
3
|
+
import { ErrorCodes } from '../errors/index.js';
|
|
4
|
+
import parseApplicationHandle from '../value-objects/ApplicationHandle.js';
|
|
5
|
+
import CacheHit from '../value-objects/CacheHit.js';
|
|
6
|
+
import CacheKey from '../value-objects/CacheKey.js';
|
|
7
|
+
import CachePolicy, { MAX_CACHE_ENTRIES } from '../value-objects/CachePolicy.js';
|
|
8
|
+
import RetentionWitness from '../value-objects/RetentionWitness.js';
|
|
9
|
+
import CachePolicyEnforcer, {
|
|
10
|
+
cachePolicyReport,
|
|
11
|
+
createCacheState,
|
|
12
|
+
} from './CachePolicyEnforcer.js';
|
|
13
|
+
import RootSetMetadataCodec from './RootSetMetadataCodec.js';
|
|
14
|
+
|
|
15
|
+
const RETENTION = Object.freeze(['pinned', 'evictable']);
|
|
16
|
+
const DEFAULT_CLOCK = Object.freeze({ now: () => new Date() });
|
|
17
|
+
|
|
18
|
+
/** RootSet-backed lifecycle manager for application cache handles. */
|
|
19
|
+
export default class CacheSet {
|
|
20
|
+
#clock;
|
|
21
|
+
#configuredPolicy;
|
|
22
|
+
#crypto;
|
|
23
|
+
#enforcer;
|
|
24
|
+
#index;
|
|
25
|
+
#namespace;
|
|
26
|
+
#resolveHandle;
|
|
27
|
+
#rootSet;
|
|
28
|
+
|
|
29
|
+
constructor(options) {
|
|
30
|
+
CacheSet.#assertDependencies(options);
|
|
31
|
+
this.#namespace = options.namespace;
|
|
32
|
+
this.#rootSet = options.rootSet;
|
|
33
|
+
this.#index = options.index;
|
|
34
|
+
this.#resolveHandle = options.resolveHandle;
|
|
35
|
+
this.#crypto = options.crypto;
|
|
36
|
+
this.#clock = options.clock ?? DEFAULT_CLOCK;
|
|
37
|
+
this.#configuredPolicy = options.policy === undefined ? null : CachePolicy.from(options.policy);
|
|
38
|
+
this.#enforcer = new CachePolicyEnforcer({ index: this.#index, namespace: this.#namespace });
|
|
39
|
+
this.ref = this.#rootSet.ref;
|
|
40
|
+
Object.freeze(this);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async get(keyValue) {
|
|
44
|
+
const key = CacheKey.from(keyValue).toString();
|
|
45
|
+
const digest = await this.#digest(key);
|
|
46
|
+
const state = await this.#rootSet.read();
|
|
47
|
+
const handle = this.#index.fromRootEntries(state.entries);
|
|
48
|
+
const entry = await this.#index.getEntry(handle, digest);
|
|
49
|
+
const now = this.#now();
|
|
50
|
+
assertNoKeyCollision(entry, key);
|
|
51
|
+
if (!entry || isExpired(entry.metadata, now)) {
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
const target = await this.#resolveTarget(entry.targetHandle);
|
|
55
|
+
assertLogicalBytes(entry.metadata, target.logicalBytes);
|
|
56
|
+
return this.#hit(entry, state.headOid, now);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async put(key, handle, options = {}) {
|
|
60
|
+
return await this.#store({ key, handle, options, requireExisting: false });
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async replace(key, handle, options = {}) {
|
|
64
|
+
return await this.#store({ key, handle, options, requireExisting: true });
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async remove(keyValue) {
|
|
68
|
+
const key = CacheKey.from(keyValue).toString();
|
|
69
|
+
const digest = await this.#digest(key);
|
|
70
|
+
const now = this.#now();
|
|
71
|
+
let observed = null;
|
|
72
|
+
let lifecycle = null;
|
|
73
|
+
const mutation = await this.#mutateRoot(async (entries, root) => {
|
|
74
|
+
lifecycle = null;
|
|
75
|
+
const current = this.#index.fromRootEntries(entries);
|
|
76
|
+
const previous = await this.#index.getEntry(current, digest);
|
|
77
|
+
assertNoKeyCollision(previous, key);
|
|
78
|
+
observed = { previous, generation: root.headOid };
|
|
79
|
+
if (!previous) {
|
|
80
|
+
return entries;
|
|
81
|
+
}
|
|
82
|
+
lifecycle = await this.#rewriteRemoval(current, digest, now);
|
|
83
|
+
return [this.#index.toRootEntry(lifecycle.handle)];
|
|
84
|
+
});
|
|
85
|
+
const removed = observed?.previous
|
|
86
|
+
? this.#hit(observed.previous, observed.generation, now)
|
|
87
|
+
: null;
|
|
88
|
+
return Object.freeze({
|
|
89
|
+
changed: mutation.changed,
|
|
90
|
+
removed,
|
|
91
|
+
generation: mutation.commitOid,
|
|
92
|
+
policy: lifecycle?.policy ?? null,
|
|
93
|
+
witness: lifecycle ? this.#indexWitness(lifecycle.handle, mutation.commitOid, now) : null,
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async sweep() {
|
|
98
|
+
const now = this.#now();
|
|
99
|
+
let lifecycle = null;
|
|
100
|
+
let beforeCount = 0;
|
|
101
|
+
const mutation = await this.#mutateRoot(async (entries) => {
|
|
102
|
+
lifecycle = null;
|
|
103
|
+
beforeCount = 0;
|
|
104
|
+
const current = this.#index.fromRootEntries(entries);
|
|
105
|
+
if (current === null) {
|
|
106
|
+
return entries;
|
|
107
|
+
}
|
|
108
|
+
const scan = await this.#index.scan(current, { now });
|
|
109
|
+
this.#assertState(scan.state);
|
|
110
|
+
beforeCount = scan.summary.entryCount;
|
|
111
|
+
lifecycle = await this.#enforcer.enforce(current, {
|
|
112
|
+
policy: this.#policyFor(scan.state),
|
|
113
|
+
now,
|
|
114
|
+
});
|
|
115
|
+
return [this.#index.toRootEntry(lifecycle.handle)];
|
|
116
|
+
});
|
|
117
|
+
return Object.freeze({
|
|
118
|
+
changed: mutation.changed,
|
|
119
|
+
removed: lifecycle ? beforeCount - lifecycle.scan.summary.entryCount : 0,
|
|
120
|
+
generation: mutation.commitOid,
|
|
121
|
+
policy: lifecycle?.policy ?? null,
|
|
122
|
+
witness: lifecycle ? this.#indexWitness(lifecycle.handle, mutation.commitOid, now) : null,
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async touch(keyValue) {
|
|
127
|
+
const key = CacheKey.from(keyValue).toString();
|
|
128
|
+
const digest = await this.#digest(key);
|
|
129
|
+
const now = this.#now();
|
|
130
|
+
let observed = null;
|
|
131
|
+
let lifecycle = null;
|
|
132
|
+
const mutation = await this.#mutateRoot(async (entries, root) => {
|
|
133
|
+
lifecycle = null;
|
|
134
|
+
const current = this.#index.fromRootEntries(entries);
|
|
135
|
+
const previous = await this.#index.getEntry(current, digest);
|
|
136
|
+
assertNoKeyCollision(previous, key);
|
|
137
|
+
observed = { previous, generation: root.headOid };
|
|
138
|
+
if (!previous || isExpired(previous.metadata, now)) {
|
|
139
|
+
observed = { previous: null, generation: root.headOid };
|
|
140
|
+
return entries;
|
|
141
|
+
}
|
|
142
|
+
const state = await this.#index.getState(current);
|
|
143
|
+
const policy = this.#policyFor(state);
|
|
144
|
+
if (!touchIsDue(previous.metadata, now, policy.accessResolutionMs)) {
|
|
145
|
+
return entries;
|
|
146
|
+
}
|
|
147
|
+
const replacement = await this.#index.stageEntry({
|
|
148
|
+
...previous.metadata,
|
|
149
|
+
accessedAt: now,
|
|
150
|
+
});
|
|
151
|
+
lifecycle = await this.#rewriteReplacement(current, replacement, now);
|
|
152
|
+
observed = {
|
|
153
|
+
previous: { metadata: replacement.metadata, targetHandle: previous.targetHandle },
|
|
154
|
+
generation: root.headOid,
|
|
155
|
+
};
|
|
156
|
+
return [this.#index.toRootEntry(lifecycle.handle)];
|
|
157
|
+
});
|
|
158
|
+
const hit = observed?.previous
|
|
159
|
+
? this.#hit(observed.previous, mutation.commitOid, now)
|
|
160
|
+
: null;
|
|
161
|
+
return Object.freeze({
|
|
162
|
+
changed: mutation.changed,
|
|
163
|
+
hit,
|
|
164
|
+
generation: mutation.commitOid,
|
|
165
|
+
policy: lifecycle?.policy ?? null,
|
|
166
|
+
witness: hit?.evidence ?? null,
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
async inspect({ limit = 100, cursor = null } = {}) {
|
|
171
|
+
assertInspectOptions(limit, cursor);
|
|
172
|
+
const now = this.#now();
|
|
173
|
+
const root = await this.#rootSet.read();
|
|
174
|
+
const handle = this.#index.fromRootEntries(root.entries);
|
|
175
|
+
if (handle === null) {
|
|
176
|
+
return emptyInspection(this.#namespace, this.ref);
|
|
177
|
+
}
|
|
178
|
+
const scan = await this.#index.scan(handle, { now });
|
|
179
|
+
this.#assertState(scan.state);
|
|
180
|
+
const entries = [];
|
|
181
|
+
for await (const entry of this.#index.entries(handle)) {
|
|
182
|
+
if (isAfterCursor(entry.metadata.keyDigest, cursor)) {
|
|
183
|
+
entries.push(Object.freeze({ ...entry.metadata }));
|
|
184
|
+
}
|
|
185
|
+
if (entries.length > limit) {
|
|
186
|
+
break;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
const hasMore = entries.length > limit;
|
|
190
|
+
if (hasMore) {
|
|
191
|
+
entries.pop();
|
|
192
|
+
}
|
|
193
|
+
return Object.freeze({
|
|
194
|
+
namespace: this.#namespace,
|
|
195
|
+
ref: this.ref,
|
|
196
|
+
generation: root.headOid,
|
|
197
|
+
state: Object.freeze({ ...scan.state }),
|
|
198
|
+
observed: scan.summary,
|
|
199
|
+
policy: cachePolicyReport(scan.summary, this.#policyFor(scan.state)),
|
|
200
|
+
entries: Object.freeze(entries),
|
|
201
|
+
nextCursor: hasMore ? entries.at(-1).keyDigest : null,
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
async doctor() {
|
|
206
|
+
const root = await this.#rootSet.doctor();
|
|
207
|
+
if (!root.healthy) {
|
|
208
|
+
return Object.freeze({
|
|
209
|
+
healthy: false,
|
|
210
|
+
root,
|
|
211
|
+
issues: root.issues ?? (root.error ? [root.error] : []),
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
try {
|
|
215
|
+
const state = await this.#rootSet.read();
|
|
216
|
+
const handle = this.#index.fromRootEntries(state.entries);
|
|
217
|
+
if (handle === null) {
|
|
218
|
+
return Object.freeze({ healthy: true, root, issues: [] });
|
|
219
|
+
}
|
|
220
|
+
const persisted = await this.#index.getState(handle);
|
|
221
|
+
this.#assertState(persisted);
|
|
222
|
+
const scan = await this.#index.scan(handle, { now: persisted.updatedAt });
|
|
223
|
+
await this.#validateTargetAccounting(handle);
|
|
224
|
+
const expected = createCacheState({
|
|
225
|
+
namespace: this.#namespace,
|
|
226
|
+
policy: CachePolicy.from(persisted.policy),
|
|
227
|
+
summary: scan.summary,
|
|
228
|
+
previous: persisted,
|
|
229
|
+
now: persisted.updatedAt,
|
|
230
|
+
});
|
|
231
|
+
const consistent = JSON.stringify(expected) === JSON.stringify(persisted);
|
|
232
|
+
return Object.freeze({
|
|
233
|
+
healthy: consistent,
|
|
234
|
+
root,
|
|
235
|
+
state: Object.freeze({ ...persisted }),
|
|
236
|
+
observed: scan.summary,
|
|
237
|
+
policy: cachePolicyReport(scan.summary, persisted.policy),
|
|
238
|
+
issues: consistent ? [] : [{ code: ErrorCodes.CACHE_STATE_INVALID }],
|
|
239
|
+
});
|
|
240
|
+
} catch (error) {
|
|
241
|
+
return Object.freeze({
|
|
242
|
+
healthy: false,
|
|
243
|
+
root,
|
|
244
|
+
issues: [{
|
|
245
|
+
code: error?.code ?? ErrorCodes.CACHE_STATE_INVALID,
|
|
246
|
+
message: error instanceof Error ? error.message : String(error),
|
|
247
|
+
}],
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
async repair({ entries, policy: value } = {}) {
|
|
253
|
+
const now = this.#now();
|
|
254
|
+
const policy = value === undefined
|
|
255
|
+
? this.#configuredPolicy ?? new CachePolicy()
|
|
256
|
+
: CachePolicy.from(value);
|
|
257
|
+
const staged = await this.#stageRepairEntries(entries, now);
|
|
258
|
+
const summary = summarizeStaged(staged, now);
|
|
259
|
+
const state = createCacheState({
|
|
260
|
+
namespace: this.#namespace,
|
|
261
|
+
policy,
|
|
262
|
+
summary,
|
|
263
|
+
previous: null,
|
|
264
|
+
now,
|
|
265
|
+
});
|
|
266
|
+
const built = await this.#index.build({ entries: staged, state });
|
|
267
|
+
const lifecycle = await this.#enforcer.enforce(built, { policy, now });
|
|
268
|
+
const repaired = await this.#repairRoot({
|
|
269
|
+
entries: [this.#index.toRootEntry(lifecycle.handle)],
|
|
270
|
+
});
|
|
271
|
+
return Object.freeze({
|
|
272
|
+
repaired: true,
|
|
273
|
+
generation: repaired.commitOid,
|
|
274
|
+
policy: lifecycle.policy,
|
|
275
|
+
witness: this.#indexWitness(lifecycle.handle, repaired.commitOid, now),
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
async #stageRepairEntries(entries, now) {
|
|
280
|
+
if (!isIterable(entries)) {
|
|
281
|
+
throw createCasError('Cache repair entries must be iterable', ErrorCodes.CACHE_ENTRY_INVALID);
|
|
282
|
+
}
|
|
283
|
+
const byDigest = new Map();
|
|
284
|
+
for await (const entry of entries) {
|
|
285
|
+
const key = CacheKey.from(entry.key).toString();
|
|
286
|
+
const digest = await this.#digest(key);
|
|
287
|
+
const previous = byDigest.get(digest);
|
|
288
|
+
if (previous) {
|
|
289
|
+
const message = previous.metadata.key === key
|
|
290
|
+
? 'Cache repair contains a duplicate key'
|
|
291
|
+
: 'Cache repair contains a key digest collision';
|
|
292
|
+
throw createCasError(message, ErrorCodes.CACHE_ENTRY_INVALID);
|
|
293
|
+
}
|
|
294
|
+
if (byDigest.size >= MAX_CACHE_ENTRIES) {
|
|
295
|
+
throw createCasError('Cache repair exceeds the entry limit', ErrorCodes.CACHE_POLICY_INVALID);
|
|
296
|
+
}
|
|
297
|
+
const staged = await this.#prepareEntry({
|
|
298
|
+
key,
|
|
299
|
+
digest,
|
|
300
|
+
handle: entry.handle,
|
|
301
|
+
options: entry,
|
|
302
|
+
now,
|
|
303
|
+
});
|
|
304
|
+
byDigest.set(digest, staged);
|
|
305
|
+
}
|
|
306
|
+
return [...byDigest.values()].sort((left, right) => (
|
|
307
|
+
left.metadata.keyDigest < right.metadata.keyDigest ? -1 : 1
|
|
308
|
+
));
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
async #store({ key: keyValue, handle, options, requireExisting }) {
|
|
312
|
+
assertEntryOptions(options);
|
|
313
|
+
const key = CacheKey.from(keyValue).toString();
|
|
314
|
+
const digest = await this.#digest(key);
|
|
315
|
+
const now = this.#now();
|
|
316
|
+
assertFutureExpiry(options.expiresAt, now);
|
|
317
|
+
const target = await this.#resolveTarget(handle);
|
|
318
|
+
let replacement = null;
|
|
319
|
+
let observed = null;
|
|
320
|
+
let lifecycle = null;
|
|
321
|
+
const expectedHandle = normalizeExpectedHandle(options.expectedHandle);
|
|
322
|
+
const mutation = await this.#mutateRoot(async (entries, root) => {
|
|
323
|
+
lifecycle = null;
|
|
324
|
+
replacement = null;
|
|
325
|
+
const current = this.#index.fromRootEntries(entries);
|
|
326
|
+
const previous = await this.#index.getEntry(current, digest);
|
|
327
|
+
observed = { previous, generation: root.headOid };
|
|
328
|
+
assertNoKeyCollision(previous, key);
|
|
329
|
+
if (!canReplace({ previous, key, expectedHandle, requireExisting })) {
|
|
330
|
+
return entries;
|
|
331
|
+
}
|
|
332
|
+
replacement = await this.#stageEntry({ key, digest, target, options, now });
|
|
333
|
+
lifecycle = await this.#rewriteReplacement(current, replacement, now);
|
|
334
|
+
return [this.#index.toRootEntry(lifecycle.handle)];
|
|
335
|
+
});
|
|
336
|
+
return this.#storeResult({ mutation, observed, lifecycle, replacement, now });
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
async #prepareEntry({ key, digest, handle: value, options, now }) {
|
|
340
|
+
const target = await this.#resolveTarget(value);
|
|
341
|
+
return await this.#stageEntry({ key, digest, target, options, now });
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
async #resolveTarget(value) {
|
|
345
|
+
const handle = parseApplicationHandle(value);
|
|
346
|
+
const resolved = await this.#resolveHandle(handle);
|
|
347
|
+
const logicalBytes = resolved.logicalBytes ?? resolved.size;
|
|
348
|
+
if (!Number.isSafeInteger(logicalBytes) || logicalBytes < 0) {
|
|
349
|
+
throw createCasError(
|
|
350
|
+
'Cache target has no deterministic logical size',
|
|
351
|
+
ErrorCodes.CACHE_LOGICAL_SIZE_UNKNOWN,
|
|
352
|
+
{ handle: handle.toString(), logicalBytes },
|
|
353
|
+
);
|
|
354
|
+
}
|
|
355
|
+
return Object.freeze({ handle, logicalBytes });
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
async #validateTargetAccounting(handle) {
|
|
359
|
+
for await (const entry of this.#index.entries(handle)) {
|
|
360
|
+
await this.#index.assertEntryShape(entry.entryHandle);
|
|
361
|
+
const target = await this.#resolveTarget(entry.targetHandle);
|
|
362
|
+
assertLogicalBytes(entry.metadata, target.logicalBytes);
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
async #stageEntry({ key, digest, target, options, now }) {
|
|
367
|
+
const policy = options.retention ?? 'evictable';
|
|
368
|
+
if (!RETENTION.includes(policy)) {
|
|
369
|
+
throw createCasError('Cache retention must be pinned or evictable', ErrorCodes.CACHE_ENTRY_INVALID);
|
|
370
|
+
}
|
|
371
|
+
return await this.#index.stageEntry({
|
|
372
|
+
version: 1,
|
|
373
|
+
accountingVersion: 1,
|
|
374
|
+
key,
|
|
375
|
+
keyDigest: digest,
|
|
376
|
+
handle: target.handle,
|
|
377
|
+
policy,
|
|
378
|
+
expiresAt: normalizeExpiry(options.expiresAt),
|
|
379
|
+
logicalBytes: target.logicalBytes,
|
|
380
|
+
createdAt: normalizeDate(options.createdAt, now),
|
|
381
|
+
accessedAt: normalizeDate(options.accessedAt, now),
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
async #rewriteReplacement(current, replacement, now) {
|
|
386
|
+
const removeDigests = new Set([replacement.metadata.keyDigest]);
|
|
387
|
+
const projected = await this.#index.scan(current, {
|
|
388
|
+
now,
|
|
389
|
+
protectedDigest: replacement.metadata.keyDigest,
|
|
390
|
+
excludeDigests: removeDigests,
|
|
391
|
+
replacement,
|
|
392
|
+
});
|
|
393
|
+
this.#assertState(projected.state);
|
|
394
|
+
const policy = this.#policyFor(projected.state);
|
|
395
|
+
const state = createCacheState({
|
|
396
|
+
namespace: this.#namespace,
|
|
397
|
+
policy,
|
|
398
|
+
summary: projected.summary,
|
|
399
|
+
previous: projected.state,
|
|
400
|
+
now,
|
|
401
|
+
});
|
|
402
|
+
const provisional = await this.#index.rewrite({
|
|
403
|
+
handle: current,
|
|
404
|
+
removeDigests,
|
|
405
|
+
replacement,
|
|
406
|
+
state,
|
|
407
|
+
});
|
|
408
|
+
return await this.#enforcer.enforce(provisional, {
|
|
409
|
+
policy,
|
|
410
|
+
now,
|
|
411
|
+
protectedDigest: replacement.metadata.keyDigest,
|
|
412
|
+
});
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
async #rewriteRemoval(current, digest, now) {
|
|
416
|
+
const currentScan = await this.#index.scan(current, { now });
|
|
417
|
+
this.#assertState(currentScan.state);
|
|
418
|
+
const policy = this.#policyFor(currentScan.state);
|
|
419
|
+
const removeDigests = new Set([digest]);
|
|
420
|
+
const projected = await this.#index.scan(current, { now, excludeDigests: removeDigests });
|
|
421
|
+
const state = createCacheState({
|
|
422
|
+
namespace: this.#namespace,
|
|
423
|
+
policy,
|
|
424
|
+
summary: projected.summary,
|
|
425
|
+
previous: currentScan.state,
|
|
426
|
+
now,
|
|
427
|
+
});
|
|
428
|
+
const provisional = await this.#index.rewrite({
|
|
429
|
+
handle: current,
|
|
430
|
+
removeDigests,
|
|
431
|
+
replacement: null,
|
|
432
|
+
state,
|
|
433
|
+
});
|
|
434
|
+
return await this.#enforcer.enforce(provisional, { policy, now });
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
#storeResult({ mutation, observed, lifecycle, replacement, now }) {
|
|
438
|
+
const previous = observed?.previous
|
|
439
|
+
? this.#hit(observed.previous, observed.generation, now)
|
|
440
|
+
: null;
|
|
441
|
+
const accepted = lifecycle !== null;
|
|
442
|
+
const record = accepted
|
|
443
|
+
? { metadata: replacement.metadata, targetHandle: parseApplicationHandle(replacement.metadata.handle) }
|
|
444
|
+
: observed?.previous;
|
|
445
|
+
const hit = record ? this.#hit(record, mutation.commitOid, now) : null;
|
|
446
|
+
return Object.freeze({
|
|
447
|
+
changed: mutation.changed,
|
|
448
|
+
accepted,
|
|
449
|
+
hit,
|
|
450
|
+
previous,
|
|
451
|
+
generation: mutation.commitOid,
|
|
452
|
+
policy: lifecycle?.policy ?? null,
|
|
453
|
+
witness: hit?.evidence ?? null,
|
|
454
|
+
});
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
async #mutateRoot(mutator) {
|
|
458
|
+
try {
|
|
459
|
+
return await this.#rootSet.mutate(mutator);
|
|
460
|
+
} catch (error) {
|
|
461
|
+
throw mapConflict(error, this.ref);
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
async #repairRoot(options) {
|
|
466
|
+
try {
|
|
467
|
+
return await this.#rootSet.repair(options);
|
|
468
|
+
} catch (error) {
|
|
469
|
+
throw mapConflict(error, this.ref);
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
#hit(entry, generation, observedAt) {
|
|
474
|
+
const evidence = new RetentionWitness({
|
|
475
|
+
handle: entry.targetHandle,
|
|
476
|
+
policy: entry.metadata.policy,
|
|
477
|
+
reachability: 'anchored',
|
|
478
|
+
root: {
|
|
479
|
+
kind: 'cache-set',
|
|
480
|
+
namespace: this.#namespace,
|
|
481
|
+
ref: this.ref,
|
|
482
|
+
generation,
|
|
483
|
+
path: RootSetMetadataCodec.slotFor(0),
|
|
484
|
+
},
|
|
485
|
+
observedAt,
|
|
486
|
+
});
|
|
487
|
+
return new CacheHit({ ...entry.metadata, generation, evidence });
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
#indexWitness(handle, generation, observedAt) {
|
|
491
|
+
return new RetentionWitness({
|
|
492
|
+
handle,
|
|
493
|
+
policy: 'pinned',
|
|
494
|
+
reachability: 'anchored',
|
|
495
|
+
root: {
|
|
496
|
+
kind: 'cache-set',
|
|
497
|
+
namespace: this.#namespace,
|
|
498
|
+
ref: this.ref,
|
|
499
|
+
generation,
|
|
500
|
+
path: RootSetMetadataCodec.slotFor(0),
|
|
501
|
+
},
|
|
502
|
+
observedAt,
|
|
503
|
+
});
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
#policyFor(state) {
|
|
507
|
+
return this.#configuredPolicy ?? CachePolicy.from(state?.policy);
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
#assertState(state) {
|
|
511
|
+
if (state !== null && state.namespace !== this.#namespace) {
|
|
512
|
+
throw createCasError('Cache index namespace does not match its ref', ErrorCodes.CACHE_STATE_INVALID, {
|
|
513
|
+
expected: this.#namespace,
|
|
514
|
+
actual: state.namespace,
|
|
515
|
+
});
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
async #digest(key) {
|
|
520
|
+
const digest = await this.#crypto.sha256(utf8Encode(key));
|
|
521
|
+
if (typeof digest !== 'string' || !/^[0-9a-f]{64}$/.test(digest)) {
|
|
522
|
+
throw createCasError('Cache crypto adapter returned an invalid digest', ErrorCodes.INVALID_OPTIONS);
|
|
523
|
+
}
|
|
524
|
+
return digest;
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
#now() {
|
|
528
|
+
const value = this.#clock.now();
|
|
529
|
+
if (!(value instanceof Date) || Number.isNaN(value.getTime())) {
|
|
530
|
+
throw createCasError('CacheSet clock returned an invalid Date', ErrorCodes.INVALID_OPTIONS);
|
|
531
|
+
}
|
|
532
|
+
return value.toISOString();
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
static #assertDependencies(options) {
|
|
536
|
+
const dependencies = [
|
|
537
|
+
['rootSet', options?.rootSet?.mutate],
|
|
538
|
+
['index', options?.index?.scan],
|
|
539
|
+
['resolveHandle', options?.resolveHandle],
|
|
540
|
+
['crypto', options?.crypto?.sha256],
|
|
541
|
+
];
|
|
542
|
+
const missing = dependencies
|
|
543
|
+
.filter(([, value]) => typeof value !== 'function')
|
|
544
|
+
.map(([name]) => name);
|
|
545
|
+
if (missing.length > 0) {
|
|
546
|
+
throw createCasError('CacheSet requires complete lifecycle dependencies', ErrorCodes.INVALID_OPTIONS, {
|
|
547
|
+
missing,
|
|
548
|
+
});
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
function canReplace({ previous, key, expectedHandle, requireExisting }) {
|
|
554
|
+
if (!previous || previous.metadata.key !== key) {
|
|
555
|
+
return !requireExisting && expectedHandle === null;
|
|
556
|
+
}
|
|
557
|
+
return expectedHandle === null || previous.targetHandle.toString() === expectedHandle;
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
function normalizeExpectedHandle(value) {
|
|
561
|
+
return value === undefined ? null : parseApplicationHandle(value).toString();
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
function normalizeExpiry(value) {
|
|
565
|
+
if (value === undefined || value === null) {
|
|
566
|
+
return null;
|
|
567
|
+
}
|
|
568
|
+
return normalizeDate(value, null);
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
function normalizeDate(value, fallback) {
|
|
572
|
+
if (value === undefined) {
|
|
573
|
+
return fallback;
|
|
574
|
+
}
|
|
575
|
+
if (value instanceof Date) {
|
|
576
|
+
if (Number.isNaN(value.getTime())) {
|
|
577
|
+
throw createCasError('Cache timestamp is invalid', ErrorCodes.CACHE_ENTRY_INVALID);
|
|
578
|
+
}
|
|
579
|
+
return value.toISOString();
|
|
580
|
+
}
|
|
581
|
+
return value;
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
function isExpired(entry, now) {
|
|
585
|
+
return entry.expiresAt !== null && entry.expiresAt <= now;
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
function touchIsDue(entry, now, resolutionMs) {
|
|
589
|
+
return Date.parse(now) - Date.parse(entry.accessedAt) >= resolutionMs;
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
function assertInspectOptions(limit, cursor) {
|
|
593
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1000) {
|
|
594
|
+
throw createCasError('Cache inspection limit must be between 1 and 1000', ErrorCodes.INVALID_OPTIONS);
|
|
595
|
+
}
|
|
596
|
+
if (cursor !== null && !/^[0-9a-f]{64}$/.test(cursor)) {
|
|
597
|
+
throw createCasError('Cache inspection cursor is invalid', ErrorCodes.INVALID_OPTIONS);
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
function emptyInspection(namespace, ref) {
|
|
602
|
+
return Object.freeze({
|
|
603
|
+
namespace,
|
|
604
|
+
ref,
|
|
605
|
+
generation: null,
|
|
606
|
+
state: null,
|
|
607
|
+
observed: null,
|
|
608
|
+
policy: null,
|
|
609
|
+
entries: Object.freeze([]),
|
|
610
|
+
nextCursor: null,
|
|
611
|
+
});
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
function summarizeStaged(entries, now) {
|
|
615
|
+
const summary = {
|
|
616
|
+
entryCount: entries.length,
|
|
617
|
+
logicalBytes: 0,
|
|
618
|
+
pinnedEntries: 0,
|
|
619
|
+
evictableEntries: 0,
|
|
620
|
+
expiredEntries: 0,
|
|
621
|
+
oldestAccessedAt: null,
|
|
622
|
+
nextExpiry: null,
|
|
623
|
+
};
|
|
624
|
+
for (const entry of entries) {
|
|
625
|
+
addStagedSummary(summary, entry.metadata, now);
|
|
626
|
+
}
|
|
627
|
+
return Object.freeze(summary);
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
function addStagedSummary(summary, entry, now) {
|
|
631
|
+
const logicalBytes = summary.logicalBytes + entry.logicalBytes;
|
|
632
|
+
if (!Number.isSafeInteger(logicalBytes)) {
|
|
633
|
+
throw createCasError('Cache logical size exceeds safe integer accounting', ErrorCodes.CACHE_LOGICAL_SIZE_UNKNOWN);
|
|
634
|
+
}
|
|
635
|
+
summary.logicalBytes = logicalBytes;
|
|
636
|
+
summary[`${entry.policy}Entries`] += 1;
|
|
637
|
+
summary.expiredEntries += isExpired(entry, now) ? 1 : 0;
|
|
638
|
+
summary.oldestAccessedAt = minTimestamp(summary.oldestAccessedAt, entry.accessedAt);
|
|
639
|
+
summary.nextExpiry = minTimestamp(summary.nextExpiry, entry.expiresAt);
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
function minTimestamp(left, right) {
|
|
643
|
+
if (right === null) {
|
|
644
|
+
return left;
|
|
645
|
+
}
|
|
646
|
+
return left === null || right < left ? right : left;
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
function assertEntryOptions(options) {
|
|
650
|
+
if (!options || typeof options !== 'object' || Array.isArray(options)) {
|
|
651
|
+
throw createCasError('Cache entry options must be an object', ErrorCodes.CACHE_ENTRY_INVALID);
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
function assertFutureExpiry(value, now) {
|
|
656
|
+
if (value === undefined || value === null) {
|
|
657
|
+
return;
|
|
658
|
+
}
|
|
659
|
+
const timestamp = normalizeDate(value, now);
|
|
660
|
+
if (Number.isNaN(Date.parse(timestamp)) || new Date(timestamp).toISOString() !== timestamp) {
|
|
661
|
+
throw createCasError('Cache expiry must be a canonical UTC timestamp', ErrorCodes.CACHE_ENTRY_INVALID);
|
|
662
|
+
}
|
|
663
|
+
if (timestamp <= now) {
|
|
664
|
+
throw createCasError('Cache expiry must be later than the write time', ErrorCodes.CACHE_ENTRY_INVALID);
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
function assertNoKeyCollision(previous, key) {
|
|
669
|
+
if (previous && previous.metadata.key !== key) {
|
|
670
|
+
throw createCasError('Cache key digest collision detected', ErrorCodes.CACHE_ENTRY_INVALID, {
|
|
671
|
+
expectedKey: key,
|
|
672
|
+
actualKey: previous.metadata.key,
|
|
673
|
+
});
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
function assertLogicalBytes(metadata, logicalBytes) {
|
|
678
|
+
if (metadata.logicalBytes !== logicalBytes) {
|
|
679
|
+
throw createCasError(
|
|
680
|
+
'Cache entry logical size does not match its target',
|
|
681
|
+
ErrorCodes.CACHE_ENTRY_INVALID,
|
|
682
|
+
{ handle: metadata.handle, expected: metadata.logicalBytes, actual: logicalBytes },
|
|
683
|
+
);
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
function isIterable(value) {
|
|
688
|
+
return Boolean(value?.[Symbol.iterator] || value?.[Symbol.asyncIterator]);
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
function isAfterCursor(digest, cursor) {
|
|
692
|
+
return cursor === null || digest > cursor;
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
function mapConflict(error, ref) {
|
|
696
|
+
if (error?.code !== ErrorCodes.ROOT_SET_CONFLICT) {
|
|
697
|
+
return error;
|
|
698
|
+
}
|
|
699
|
+
return createCasError('Concurrent CacheSet update detected', ErrorCodes.CACHE_CONFLICT, {
|
|
700
|
+
ref,
|
|
701
|
+
originalError: error,
|
|
702
|
+
});
|
|
703
|
+
}
|