@git-stunts/git-cas 6.2.0 → 6.4.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.
@@ -0,0 +1,88 @@
1
+ import createCasError from '../errors/createCasError.js';
2
+ import { ErrorCodes } from '../errors/index.js';
3
+ import assertCanonicalTimestamp from '../helpers/assertCanonicalTimestamp.js';
4
+ import CacheAcquisitionRef from './CacheAcquisitionRef.js';
5
+ import CacheHit from './CacheHit.js';
6
+ import RetentionWitness from './RetentionWitness.js';
7
+
8
+ /** One active, explicitly releasable cache-generation retention scope. */
9
+ export default class CacheAcquisition {
10
+ #release;
11
+ #releasePromise = null;
12
+ #releaseResult = null;
13
+
14
+ constructor({ id, hit, evidence, acquiredAt, release }) {
15
+ if (typeof id !== 'string' || id.length === 0) {
16
+ throw invalid('Cache acquisition ID is required', { id });
17
+ }
18
+ if (!(hit instanceof CacheHit)) {
19
+ throw invalid('Cache acquisition requires a CacheHit', { hit });
20
+ }
21
+ if (!(evidence instanceof RetentionWitness)) {
22
+ throw invalid('Cache acquisition requires retention evidence', { evidence });
23
+ }
24
+ assertCanonicalTimestamp(acquiredAt, {
25
+ invalid,
26
+ message: 'Cache acquisition time must be a canonical UTC timestamp',
27
+ });
28
+ assertEvidence({ id, hit, evidence, acquiredAt });
29
+ if (typeof release !== 'function') {
30
+ throw invalid('Cache acquisition requires a release function', { release });
31
+ }
32
+ this.id = id;
33
+ this.hit = hit;
34
+ this.evidence = evidence;
35
+ this.acquiredAt = acquiredAt;
36
+ this.#release = release;
37
+ Object.freeze(this);
38
+ }
39
+
40
+ async release() {
41
+ if (this.#releaseResult !== null) {
42
+ return Object.freeze({
43
+ ...this.#releaseResult,
44
+ changed: false,
45
+ });
46
+ }
47
+ if (this.#releasePromise !== null) {
48
+ return await this.#releasePromise;
49
+ }
50
+ this.#releasePromise = Promise.resolve(this.#release())
51
+ .then((result) => {
52
+ this.#releaseResult = result;
53
+ return result;
54
+ })
55
+ .finally(() => {
56
+ this.#releasePromise = null;
57
+ });
58
+ return await this.#releasePromise;
59
+ }
60
+ }
61
+
62
+ function invalid(message, meta) {
63
+ return createCasError(message, ErrorCodes.CACHE_ACQUISITION_INVALID, meta);
64
+ }
65
+
66
+ function assertEvidence({ id, hit, evidence, acquiredAt }) {
67
+ const acquisitionRef = CacheAcquisitionRef.forId({
68
+ namespace: evidence.root.namespace,
69
+ id,
70
+ });
71
+ const valid = evidence.policy === 'pinned'
72
+ && evidence.reachability === 'anchored'
73
+ && evidence.root.kind === 'cache-set'
74
+ && evidence.root.ref === acquisitionRef.toString()
75
+ && evidence.root.namespace === hit.evidence.root.namespace
76
+ && evidence.root.generation === hit.generation
77
+ && evidence.handle.toString() === hit.handle.toString()
78
+ && evidence.observedAt === acquiredAt
79
+ && acquisitionRef.acquiredAt === acquiredAt;
80
+ if (!valid) {
81
+ throw invalid('Cache acquisition retention evidence does not match its acquired hit', {
82
+ id,
83
+ acquiredAt,
84
+ generation: hit.generation,
85
+ evidence: evidence.toJSON(),
86
+ });
87
+ }
88
+ }
@@ -0,0 +1,129 @@
1
+ import createCasError from '../errors/createCasError.js';
2
+ import { ErrorCodes } from '../errors/index.js';
3
+ import assertCanonicalTimestamp from '../helpers/assertCanonicalTimestamp.js';
4
+ import CollectionNamespace from './CollectionNamespace.js';
5
+
6
+ export const CACHE_ACQUISITION_REF_PREFIX = 'refs/cas/cache-acquisitions/';
7
+
8
+ const ID_PATTERN = /^v1-(\d{13})-([0-9a-f]{64})-([0-9a-f]{32})$/u;
9
+
10
+ /** Immutable identity for one scoped cache-generation anchor. */
11
+ export default class CacheAcquisitionRef {
12
+ #acquiredAt;
13
+ #id;
14
+ #keyDigest;
15
+ #namespace;
16
+ #value;
17
+
18
+ constructor(value) {
19
+ if (typeof value !== 'string' || !value.startsWith(CACHE_ACQUISITION_REF_PREFIX)) {
20
+ throw invalid('Cache acquisition ref is outside its managed namespace', { ref: value });
21
+ }
22
+ const parts = value.slice(CACHE_ACQUISITION_REF_PREFIX.length).split('/');
23
+ if (parts.length !== 2) {
24
+ throw invalid('Cache acquisition ref must include a cache namespace and ID', { ref: value });
25
+ }
26
+ const [encodedNamespace, id] = parts;
27
+ const match = ID_PATTERN.exec(id);
28
+ if (!match) {
29
+ throw invalid('Cache acquisition ID is invalid', { ref: value, id });
30
+ }
31
+ const acquiredAt = new Date(Number(match[1])).toISOString();
32
+ this.#namespace = decodeNamespaceSegment(encodedNamespace, { ref: value, id });
33
+ this.#id = id;
34
+ this.#acquiredAt = acquiredAt;
35
+ this.#keyDigest = match[2];
36
+ this.#value = `${CacheAcquisitionRef.prefixForNamespace(this.#namespace)}${id}`;
37
+ Object.freeze(this);
38
+ }
39
+
40
+ static create({ namespace, keyDigest, acquiredAt, nonce }) {
41
+ assertCanonicalTimestamp(acquiredAt, {
42
+ invalid,
43
+ message: 'Cache acquisition time must be a canonical UTC timestamp',
44
+ });
45
+ if (typeof keyDigest !== 'string' || !/^[0-9a-f]{64}$/u.test(keyDigest)) {
46
+ throw invalid('Cache acquisition key digest is invalid', { keyDigest });
47
+ }
48
+ if (typeof nonce !== 'string' || !/^[0-9a-f]{32}$/u.test(nonce)) {
49
+ throw invalid('Cache acquisition nonce is invalid', { nonce });
50
+ }
51
+ const epoch = String(Date.parse(acquiredAt)).padStart(13, '0');
52
+ return new CacheAcquisitionRef(
53
+ `${CacheAcquisitionRef.prefixForNamespace(namespace)}v1-${epoch}-${keyDigest}-${nonce}`,
54
+ );
55
+ }
56
+
57
+ static from(value) {
58
+ return value instanceof CacheAcquisitionRef ? value : new CacheAcquisitionRef(value);
59
+ }
60
+
61
+ static forId({ namespace, id }) {
62
+ if (typeof id !== 'string' || !ID_PATTERN.test(id)) {
63
+ throw invalid('Cache acquisition ID is invalid', { namespace, id });
64
+ }
65
+ return new CacheAcquisitionRef(`${CacheAcquisitionRef.prefixForNamespace(namespace)}${id}`);
66
+ }
67
+
68
+ static prefixForNamespace(namespace) {
69
+ const canonical = acquisitionNamespace(namespace, { namespace }).toString();
70
+ return `${CACHE_ACQUISITION_REF_PREFIX}${encodeURIComponent(canonical)}/`;
71
+ }
72
+
73
+ get acquiredAt() {
74
+ return this.#acquiredAt;
75
+ }
76
+
77
+ get id() {
78
+ return this.#id;
79
+ }
80
+
81
+ get keyDigest() {
82
+ return this.#keyDigest;
83
+ }
84
+
85
+ get namespace() {
86
+ return this.#namespace.toString();
87
+ }
88
+
89
+ toString() {
90
+ return this.#value;
91
+ }
92
+ }
93
+
94
+ function invalid(message, meta) {
95
+ return createCasError(message, ErrorCodes.CACHE_ACQUISITION_INVALID, meta);
96
+ }
97
+
98
+ function acquisitionNamespace(value, meta) {
99
+ try {
100
+ return CollectionNamespace.from(value);
101
+ } catch (error) {
102
+ throw invalid('Cache acquisition namespace is invalid', {
103
+ ...meta,
104
+ namespace: value,
105
+ originalError: error,
106
+ });
107
+ }
108
+ }
109
+
110
+ function decodeNamespaceSegment(value, meta) {
111
+ let decoded;
112
+ try {
113
+ decoded = decodeURIComponent(value);
114
+ } catch (error) {
115
+ throw invalid('Cache acquisition namespace encoding is invalid', {
116
+ ...meta,
117
+ namespace: value,
118
+ originalError: error,
119
+ });
120
+ }
121
+ const namespace = acquisitionNamespace(decoded, meta);
122
+ if (encodeURIComponent(namespace.toString()) !== value) {
123
+ throw invalid('Cache acquisition namespace encoding is not canonical', {
124
+ ...meta,
125
+ namespace: value,
126
+ });
127
+ }
128
+ return namespace;
129
+ }
@@ -6,7 +6,12 @@ import Oid from './Oid.js';
6
6
 
7
7
  const POLICIES = Object.freeze(['pinned', 'evictable']);
8
8
  const REACHABILITY = Object.freeze(['anchored', 'orphaned', 'volatile']);
9
- const ROOT_KINDS = Object.freeze(['root-set', 'publication', 'cache-set', 'expiring-set']);
9
+ const ROOT_KINDS = Object.freeze([
10
+ 'root-set',
11
+ 'publication',
12
+ 'cache-set',
13
+ 'expiring-set',
14
+ ]);
10
15
 
11
16
  /**
12
17
  * Immutable evidence that one observed Git generation retained a handle.
@@ -0,0 +1,151 @@
1
+ import createCasError from '../errors/createCasError.js';
2
+ import { ErrorCodes } from '../errors/index.js';
3
+ import CollectionNamespace from './CollectionNamespace.js';
4
+
5
+ export const WORKSPACE_REF_PREFIX = 'refs/cas/workspaces/';
6
+ const WORKSPACE_ID = /^v1-([a-z0-9]+)-([a-f0-9]{32})$/;
7
+ const NONCE_BYTES = 16;
8
+
9
+ /** Immutable ref identifying one scoped staging workspace. */
10
+ export default class WorkspaceRef {
11
+ #createdAt;
12
+ #id;
13
+ #namespace;
14
+ #value;
15
+
16
+ constructor(value) {
17
+ const parsed = WorkspaceRef.#parse(value);
18
+ this.#namespace = parsed.namespace;
19
+ this.#id = parsed.id;
20
+ this.#createdAt = parsed.createdAt;
21
+ this.#value = parsed.value;
22
+ Object.freeze(this);
23
+ }
24
+
25
+ static from(value) {
26
+ return value instanceof WorkspaceRef ? value : new WorkspaceRef(value);
27
+ }
28
+
29
+ static create({ namespace: value, createdAt, nonce }) {
30
+ const namespace = CollectionNamespace.from(value).toString();
31
+ const created = WorkspaceRef.#canonicalTimestamp(createdAt);
32
+ if (!(nonce instanceof Uint8Array) || nonce.length !== NONCE_BYTES) {
33
+ throw WorkspaceRef.#invalid('Workspace nonce must contain exactly 16 bytes', {
34
+ nonceLength: nonce?.length,
35
+ });
36
+ }
37
+ const epoch = String(created.getTime().toString(36));
38
+ const nonceHex = [...nonce]
39
+ .map((byte) => byte.toString(16).padStart(2, '0'))
40
+ .join('');
41
+ const id = `v1-${epoch}-${nonceHex}`;
42
+ return new WorkspaceRef(
43
+ `${WORKSPACE_REF_PREFIX}${WorkspaceRef.#encodeNamespace(namespace)}/${id}`,
44
+ );
45
+ }
46
+
47
+ static prefixForNamespace(value) {
48
+ const namespace = CollectionNamespace.from(value).toString();
49
+ return `${WORKSPACE_REF_PREFIX}${WorkspaceRef.#encodeNamespace(namespace)}/`;
50
+ }
51
+
52
+ get namespace() {
53
+ return this.#namespace;
54
+ }
55
+
56
+ get id() {
57
+ return this.#id;
58
+ }
59
+
60
+ get createdAt() {
61
+ return this.#createdAt;
62
+ }
63
+
64
+ toString() {
65
+ return this.#value;
66
+ }
67
+
68
+ static #parse(value) {
69
+ const [encodedNamespace, id] = WorkspaceRef.#split(value);
70
+ const namespace = WorkspaceRef.#decodeNamespace(encodedNamespace, value);
71
+ const createdAt = WorkspaceRef.#createdAtFromId(id, value);
72
+ return { namespace, id, createdAt, value };
73
+ }
74
+
75
+ static #split(value) {
76
+ if (typeof value !== 'string' || !value.startsWith(WORKSPACE_REF_PREFIX)) {
77
+ throw WorkspaceRef.#invalid(`Workspace ref must be below ${WORKSPACE_REF_PREFIX}`, {
78
+ ref: value,
79
+ });
80
+ }
81
+ const fields = value.slice(WORKSPACE_REF_PREFIX.length).split('/');
82
+ if (fields.length !== 2 || fields.some((field) => field.length === 0)) {
83
+ throw WorkspaceRef.#invalid('Workspace ref must contain one encoded namespace and ID', {
84
+ ref: value,
85
+ });
86
+ }
87
+ return fields;
88
+ }
89
+
90
+ static #decodeNamespace(encodedNamespace, value) {
91
+ if (encodedNamespace.includes('++')) {
92
+ throw WorkspaceRef.#invalid('Workspace ref contains a malformed encoded namespace', {
93
+ ref: value,
94
+ });
95
+ }
96
+ let namespace;
97
+ try {
98
+ namespace = CollectionNamespace.from(encodedNamespace.replaceAll('+', '/')).toString();
99
+ } catch (error) {
100
+ throw WorkspaceRef.#invalid('Workspace ref contains an invalid encoded namespace', {
101
+ ref: value,
102
+ originalError: error,
103
+ });
104
+ }
105
+ if (WorkspaceRef.#encodeNamespace(namespace) !== encodedNamespace) {
106
+ throw WorkspaceRef.#invalid('Workspace ref namespace is not canonical', { ref: value });
107
+ }
108
+ return namespace;
109
+ }
110
+
111
+ static #createdAtFromId(id, value) {
112
+ const idMatch = WORKSPACE_ID.exec(id);
113
+ if (!idMatch) {
114
+ throw WorkspaceRef.#invalid('Workspace ref contains an invalid workspace ID', { ref: value });
115
+ }
116
+ const epoch = Number.parseInt(idMatch[1], 36);
117
+ if (!Number.isSafeInteger(epoch) || epoch < 0 || epoch.toString(36) !== idMatch[1]) {
118
+ throw WorkspaceRef.#invalid('Workspace ref contains an invalid creation epoch', { ref: value });
119
+ }
120
+ const createdAt = new Date(epoch);
121
+ if (Number.isNaN(createdAt.getTime())) {
122
+ throw WorkspaceRef.#invalid('Workspace ref creation epoch is outside the Date range', {
123
+ ref: value,
124
+ });
125
+ }
126
+ return createdAt.toISOString();
127
+ }
128
+
129
+ static #canonicalTimestamp(value) {
130
+ if (typeof value !== 'string') {
131
+ throw WorkspaceRef.#invalid('Workspace creation time must be a canonical timestamp', {
132
+ createdAt: value,
133
+ });
134
+ }
135
+ const date = new Date(value);
136
+ if (Number.isNaN(date.getTime()) || date.toISOString() !== value) {
137
+ throw WorkspaceRef.#invalid('Workspace creation time must be a canonical timestamp', {
138
+ createdAt: value,
139
+ });
140
+ }
141
+ return date;
142
+ }
143
+
144
+ static #encodeNamespace(namespace) {
145
+ return namespace.replaceAll('/', '+');
146
+ }
147
+
148
+ static #invalid(message, meta) {
149
+ return createCasError(message, ErrorCodes.WORKSPACE_REF_INVALID, meta);
150
+ }
151
+ }