@git-stunts/git-cas 6.1.0 → 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.
Files changed (64) hide show
  1. package/ARCHITECTURE.md +108 -3
  2. package/CHANGELOG.md +80 -2
  3. package/GUIDE.md +114 -13
  4. package/README.md +51 -4
  5. package/UPGRADING.md +43 -0
  6. package/build-info.json +2 -2
  7. package/docs/API.md +751 -16
  8. package/docs/releases/v6.2.0.md +131 -0
  9. package/index.d.ts +879 -2
  10. package/index.js +326 -1
  11. package/package.json +3 -2
  12. package/src/domain/errors/Codes.js +35 -0
  13. package/src/domain/helpers/assertCanonicalTimestamp.js +15 -0
  14. package/src/domain/helpers/handleTarget.js +48 -0
  15. package/src/domain/helpers/isCanonicalCollectionKey.js +35 -0
  16. package/src/domain/services/AssetService.js +213 -0
  17. package/src/domain/services/BundleDescriptorCodec.js +286 -0
  18. package/src/domain/services/BundleFanoutBuilder.js +247 -0
  19. package/src/domain/services/BundleService.js +848 -0
  20. package/src/domain/services/CacheCandidateHeap.js +71 -0
  21. package/src/domain/services/CacheIndex.js +362 -0
  22. package/src/domain/services/CacheMetadataCodec.js +164 -0
  23. package/src/domain/services/CachePolicyEnforcer.js +144 -0
  24. package/src/domain/services/CacheSet.js +703 -0
  25. package/src/domain/services/CacheSetRegistry.js +88 -0
  26. package/src/domain/services/CasService.d.ts +2 -1
  27. package/src/domain/services/ExpiringSet.js +496 -0
  28. package/src/domain/services/ExpiringSetIndex.js +254 -0
  29. package/src/domain/services/ExpiringSetMetadataCodec.js +160 -0
  30. package/src/domain/services/ExpiringSetRegistry.js +101 -0
  31. package/src/domain/services/PageService.js +175 -0
  32. package/src/domain/services/PublicationService.js +315 -0
  33. package/src/domain/services/RepositoryDoctor.js +649 -0
  34. package/src/domain/services/RetentionService.js +120 -0
  35. package/src/domain/services/RootSet.js +10 -6
  36. package/src/domain/services/RootSetMetadataCodec.js +8 -2
  37. package/src/domain/services/RootSetPersistence.js +3 -2
  38. package/src/domain/services/StagingEvidence.js +39 -0
  39. package/src/domain/value-objects/ApplicationHandle.js +40 -0
  40. package/src/domain/value-objects/AssetHandle.js +163 -0
  41. package/src/domain/value-objects/BundleHandle.js +32 -0
  42. package/src/domain/value-objects/BundleLimits.js +80 -0
  43. package/src/domain/value-objects/BundlePath.js +78 -0
  44. package/src/domain/value-objects/CacheHit.js +93 -0
  45. package/src/domain/value-objects/CacheKey.js +32 -0
  46. package/src/domain/value-objects/CachePolicy.js +59 -0
  47. package/src/domain/value-objects/CacheSetRef.js +40 -0
  48. package/src/domain/value-objects/CollectionNamespace.js +54 -0
  49. package/src/domain/value-objects/ExpiringMarker.js +81 -0
  50. package/src/domain/value-objects/ExpiringSetKey.js +28 -0
  51. package/src/domain/value-objects/ExpiringSetRef.js +42 -0
  52. package/src/domain/value-objects/OpaqueHandle.js +171 -0
  53. package/src/domain/value-objects/PageHandle.js +34 -0
  54. package/src/domain/value-objects/RetentionWitness.js +101 -0
  55. package/src/domain/value-objects/StagedAsset.js +63 -0
  56. package/src/domain/value-objects/StagedBundle.js +66 -0
  57. package/src/domain/value-objects/StagedPage.js +47 -0
  58. package/src/infrastructure/adapters/GitPersistenceAdapter.js +48 -20
  59. package/src/infrastructure/adapters/GitRefAdapter.js +6 -5
  60. package/src/infrastructure/adapters/GitRepositoryInspectionAdapter.js +164 -0
  61. package/src/package-version.js +1 -1
  62. package/src/ports/GitPersistencePort.js +11 -1
  63. package/src/ports/GitRefPort.js +1 -0
  64. package/src/ports/RepositoryInspectionPort.js +33 -0
@@ -0,0 +1,315 @@
1
+ import createCasError from '../errors/createCasError.js';
2
+ import { ErrorCodes } from '../errors/index.js';
3
+ import { utf8Encode } from '../encoding/utf8.js';
4
+ import Oid from '../value-objects/Oid.js';
5
+ import RetentionWitness from '../value-objects/RetentionWitness.js';
6
+
7
+ const DEFAULT_CLOCK = Object.freeze({ now: () => new Date() });
8
+ const FORBIDDEN_REF_CHARS = '~^:?*[\\';
9
+ const MAX_COMMIT_MESSAGE_BYTES = 1024 * 1024;
10
+ const MAX_PARENTS = 64;
11
+ const RESERVED_REF_NAMESPACES = Object.freeze([
12
+ 'refs/bisect',
13
+ 'refs/cas',
14
+ 'refs/heads',
15
+ 'refs/notes',
16
+ 'refs/remotes',
17
+ 'refs/replace',
18
+ 'refs/rewritten',
19
+ 'refs/stash',
20
+ 'refs/tags',
21
+ 'refs/worktree',
22
+ ]);
23
+
24
+ /**
25
+ * Publishes validated content roots through application-owned Git refs.
26
+ */
27
+ export default class PublicationService {
28
+ #applicationRefPrefixes;
29
+ #clock;
30
+ #ref;
31
+ #resolveRoot;
32
+
33
+ /**
34
+ * @param {object} options
35
+ * @param {import('../../ports/GitRefPort.js').default} options.ref
36
+ * @param {(handle: unknown) => Promise<object>} options.resolveRoot
37
+ * @param {string[]} [options.applicationRefPrefixes]
38
+ * @param {{ now(): Date }} [options.clock]
39
+ */
40
+ constructor({ ref, resolveRoot, applicationRefPrefixes = [], clock = DEFAULT_CLOCK }) {
41
+ PublicationService.#assertDependencies(ref, resolveRoot, clock);
42
+ this.#applicationRefPrefixes = PublicationService.#normalizePrefixes(applicationRefPrefixes);
43
+ this.#ref = ref;
44
+ this.#resolveRoot = resolveRoot;
45
+ this.#clock = clock;
46
+ }
47
+
48
+ /**
49
+ * @param {object} options
50
+ * @param {unknown} options.root
51
+ * @param {{ message: string, parents?: string[] }} options.commit
52
+ * @param {{ name: string, expected: string|null }} options.ref
53
+ * @returns {Promise<object>}
54
+ */
55
+ async commit({ root: handle, commit, ref }) {
56
+ const namespace = this.#authorizeRef(ref?.name);
57
+ const expected = PublicationService.#normalizeExpected(ref);
58
+ const message = PublicationService.#normalizeMessage(commit?.message);
59
+ const parentOids = await this.#normalizeParents(commit?.parents ?? []);
60
+ const target = await this.#resolveRoot(handle);
61
+ PublicationService.#assertTreeRoot(target);
62
+
63
+ const commitId = await this.#ref.createCommit({
64
+ treeOid: target.oid,
65
+ parentOids,
66
+ message,
67
+ });
68
+ await this.#updateRef({ ref: ref.name, commitId, expected });
69
+
70
+ const witness = new RetentionWitness({
71
+ handle: target.handle,
72
+ policy: 'pinned',
73
+ reachability: 'anchored',
74
+ root: {
75
+ kind: 'publication',
76
+ namespace,
77
+ ref: ref.name,
78
+ generation: commitId,
79
+ path: '/',
80
+ },
81
+ observedAt: this.#observedAt(),
82
+ });
83
+ return Object.freeze({
84
+ operation: 'publication',
85
+ commitId,
86
+ ref: ref.name,
87
+ root: target.handle,
88
+ witness,
89
+ });
90
+ }
91
+
92
+ async #normalizeParents(values) {
93
+ if (!Array.isArray(values) || values.length > MAX_PARENTS) {
94
+ throw PublicationService.#invalid('Publication parents must be a bounded array', {
95
+ parentCount: values?.length,
96
+ maxParents: MAX_PARENTS,
97
+ });
98
+ }
99
+ const parents = values.map((value) => PublicationService.#normalizeOid(value, 'parent'));
100
+ for (const parent of parents) {
101
+ try {
102
+ await this.#ref.resolveParents(parent);
103
+ } catch (error) {
104
+ throw PublicationService.#invalid('Publication parent is not a readable commit', {
105
+ parent,
106
+ originalError: error,
107
+ });
108
+ }
109
+ }
110
+ return parents;
111
+ }
112
+
113
+ async #updateRef({ ref, commitId, expected }) {
114
+ try {
115
+ await this.#ref.updateRef({
116
+ ref,
117
+ newOid: commitId,
118
+ expectedOldOid: expected,
119
+ });
120
+ } catch (error) {
121
+ let observed;
122
+ try {
123
+ observed = await this.#resolveObserved(ref);
124
+ } catch (observationError) {
125
+ throw createCasError(
126
+ 'Application publication ref update failed and the current head could not be observed',
127
+ ErrorCodes.PUBLICATION_REF_UPDATE_FAILED,
128
+ { ref, expected, attemptedCommitId: commitId, originalError: error, observationError }
129
+ );
130
+ }
131
+ if (observed !== expected) {
132
+ throw createCasError('Application publication conflict', ErrorCodes.PUBLICATION_CONFLICT, {
133
+ ref,
134
+ expected,
135
+ observed,
136
+ attemptedCommitId: commitId,
137
+ originalError: error,
138
+ });
139
+ }
140
+ throw createCasError(
141
+ 'Application publication ref update failed',
142
+ ErrorCodes.PUBLICATION_REF_UPDATE_FAILED,
143
+ { ref, expected, observed, attemptedCommitId: commitId, originalError: error }
144
+ );
145
+ }
146
+ }
147
+
148
+ async #resolveObserved(ref) {
149
+ try {
150
+ return await this.#ref.resolveRef(ref);
151
+ } catch (error) {
152
+ if (error?.code === ErrorCodes.GIT_REF_NOT_FOUND) {
153
+ return null;
154
+ }
155
+ throw error;
156
+ }
157
+ }
158
+
159
+ #authorizeRef(value) {
160
+ if (!PublicationService.#isValidRef(value) || PublicationService.#isReservedRef(value)) {
161
+ throw PublicationService.#forbidden(value);
162
+ }
163
+ const namespace = this.#applicationRefPrefixes.find((prefix) => value.startsWith(prefix));
164
+ if (!namespace) {
165
+ throw PublicationService.#forbidden(value);
166
+ }
167
+ return namespace;
168
+ }
169
+
170
+ #observedAt() {
171
+ const now = this.#clock.now();
172
+ if (!(now instanceof Date) || Number.isNaN(now.getTime())) {
173
+ throw PublicationService.#invalid('PublicationService clock returned an invalid Date');
174
+ }
175
+ return now.toISOString();
176
+ }
177
+
178
+ static #normalizeExpected(ref) {
179
+ if (!ref || !Object.hasOwn(ref, 'expected')) {
180
+ throw PublicationService.#invalid('Publication ref requires an explicit expected head', {
181
+ ref,
182
+ });
183
+ }
184
+ return ref.expected === null
185
+ ? null
186
+ : PublicationService.#normalizeOid(ref.expected, 'expected');
187
+ }
188
+
189
+ static #normalizeMessage(value) {
190
+ const size = typeof value === 'string' ? utf8Encode(value).length : -1;
191
+ if (size < 1 || size > MAX_COMMIT_MESSAGE_BYTES || value.includes('\0')) {
192
+ throw PublicationService.#invalid('Publication commit message is invalid', {
193
+ messageBytes: size,
194
+ maxMessageBytes: MAX_COMMIT_MESSAGE_BYTES,
195
+ });
196
+ }
197
+ return value;
198
+ }
199
+
200
+ static #normalizePrefixes(prefixes) {
201
+ if (!Array.isArray(prefixes)) {
202
+ throw PublicationService.#invalid('Application ref prefixes must be an array', { prefixes });
203
+ }
204
+ const normalized = [...new Set(prefixes)];
205
+ for (const prefix of normalized) {
206
+ if (
207
+ !PublicationService.#isValidRef(`${prefix}placeholder`) ||
208
+ !prefix.endsWith('/') ||
209
+ PublicationService.#isReservedRef(prefix.slice(0, -1))
210
+ ) {
211
+ throw PublicationService.#invalid('Application ref prefix is invalid or reserved', {
212
+ prefix,
213
+ });
214
+ }
215
+ }
216
+ normalized.sort((left, right) => {
217
+ const lengthOrder = right.length - left.length;
218
+ if (lengthOrder !== 0) {
219
+ return lengthOrder;
220
+ }
221
+ return left < right ? -1 : left > right ? 1 : 0;
222
+ });
223
+ return Object.freeze(normalized);
224
+ }
225
+
226
+ static #isValidRef(value) {
227
+ if (
228
+ PublicationService.#hasInvalidRefShape(value) ||
229
+ PublicationService.#hasForbiddenRefCharacter(value)
230
+ ) {
231
+ return false;
232
+ }
233
+ return value
234
+ .split('/')
235
+ .every((part) => part.length > 0 && part !== '.' && part !== '..' && !part.endsWith('.lock'));
236
+ }
237
+
238
+ static #isReservedRef(value) {
239
+ return RESERVED_REF_NAMESPACES.some(
240
+ (namespace) => value === namespace || value.startsWith(`${namespace}/`)
241
+ );
242
+ }
243
+
244
+ static #hasInvalidRefShape(value) {
245
+ return (
246
+ typeof value !== 'string' ||
247
+ !value.startsWith('refs/') ||
248
+ value.endsWith('/') ||
249
+ value.endsWith('.') ||
250
+ value.includes('//') ||
251
+ value.includes('..') ||
252
+ value.includes('@{')
253
+ );
254
+ }
255
+
256
+ static #hasForbiddenRefCharacter(value) {
257
+ if (typeof value !== 'string') {
258
+ return true;
259
+ }
260
+ for (const character of value) {
261
+ const codePoint = character.codePointAt(0);
262
+ if (codePoint <= 0x20 || codePoint === 0x7f || FORBIDDEN_REF_CHARS.includes(character)) {
263
+ return true;
264
+ }
265
+ }
266
+ return false;
267
+ }
268
+
269
+ static #normalizeOid(value, field) {
270
+ try {
271
+ return Oid.from(value).toString();
272
+ } catch (error) {
273
+ throw PublicationService.#invalid(`Publication ${field} is not a valid object identifier`, {
274
+ field,
275
+ value,
276
+ originalError: error,
277
+ });
278
+ }
279
+ }
280
+
281
+ static #assertTreeRoot(target) {
282
+ if (!target || target.type !== 'tree') {
283
+ throw createCasError(
284
+ 'Publication root must resolve to a Git tree',
285
+ ErrorCodes.HANDLE_TARGET_TYPE_MISMATCH,
286
+ { expectedType: 'tree', actualType: target?.type ?? null }
287
+ );
288
+ }
289
+ }
290
+
291
+ static #assertDependencies(ref, resolveRoot, clock) {
292
+ const methods = ['resolveRef', 'resolveParents', 'createCommit', 'updateRef'];
293
+ if (!ref || methods.some((method) => typeof ref[method] !== 'function')) {
294
+ throw PublicationService.#invalid('PublicationService requires a complete Git ref port');
295
+ }
296
+ if (typeof resolveRoot !== 'function') {
297
+ throw PublicationService.#invalid('PublicationService requires a handle resolver');
298
+ }
299
+ if (!clock || typeof clock.now !== 'function') {
300
+ throw PublicationService.#invalid('PublicationService clock must provide now()');
301
+ }
302
+ }
303
+
304
+ static #forbidden(ref) {
305
+ return createCasError(
306
+ 'Application publication ref is invalid, reserved, or not configured',
307
+ ErrorCodes.PUBLICATION_REF_FORBIDDEN,
308
+ { ref }
309
+ );
310
+ }
311
+
312
+ static #invalid(message, meta = {}) {
313
+ return createCasError(message, ErrorCodes.PUBLICATION_INVALID, meta);
314
+ }
315
+ }