@x-otto/availability 0.0.0-stage → 0.4.0-beta.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/dist/build-revision.json +4 -0
- package/dist/index.d.ts +74 -0
- package/dist/index.js +524 -0
- package/package.json +24 -4
- package/README.md +0 -3
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { AvailabilityDecl, AvailabilityLimitDecl, FreezeEvidence, FreezeRecord, FreezeScope, ModelAvailabilityService } from "@x-otto/kernel";
|
|
2
|
+
import * as _$_x_otto_universal0 from "@x-otto/universal";
|
|
3
|
+
|
|
4
|
+
//#region src/store.d.ts
|
|
5
|
+
interface AvailabilityStoreOptions {
|
|
6
|
+
directory: string;
|
|
7
|
+
clock?: {
|
|
8
|
+
now(): number;
|
|
9
|
+
};
|
|
10
|
+
watchIntervalMs?: number;
|
|
11
|
+
isProviderRegistered?: (providerId: string) => boolean;
|
|
12
|
+
}
|
|
13
|
+
interface AvailabilityStore {
|
|
14
|
+
load(): Promise<readonly FreezeRecord[]>;
|
|
15
|
+
mutate(transform: (records: readonly FreezeRecord[]) => FreezeRecord[]): Promise<readonly FreezeRecord[]>;
|
|
16
|
+
watch(onChange: () => void): {
|
|
17
|
+
dispose(): void;
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
declare function createFileAvailabilityStore(options: AvailabilityStoreOptions): AvailabilityStore;
|
|
21
|
+
//#endregion
|
|
22
|
+
//#region src/component.d.ts
|
|
23
|
+
interface AvailabilityComponentOptions {
|
|
24
|
+
home: string;
|
|
25
|
+
clock?: {
|
|
26
|
+
now(): number;
|
|
27
|
+
};
|
|
28
|
+
store?: AvailabilityStore;
|
|
29
|
+
}
|
|
30
|
+
declare const Availability: _$_x_otto_universal0.ComponentDefinition<AvailabilityComponentOptions>;
|
|
31
|
+
//#endregion
|
|
32
|
+
//#region src/policy.d.ts
|
|
33
|
+
interface AvailabilityModelRef {
|
|
34
|
+
providerId: string;
|
|
35
|
+
modelId: string;
|
|
36
|
+
credentialKey?: string;
|
|
37
|
+
}
|
|
38
|
+
interface CooldownDefaults {
|
|
39
|
+
baseMs: number;
|
|
40
|
+
stepMs: number;
|
|
41
|
+
capMs: number;
|
|
42
|
+
recurrenceWindowMs: number;
|
|
43
|
+
}
|
|
44
|
+
declare function resolveScope(evidence: FreezeEvidence, limits: readonly AvailabilityLimitDecl[], ref: AvailabilityModelRef): {
|
|
45
|
+
scope: FreezeScope;
|
|
46
|
+
limitId?: string;
|
|
47
|
+
};
|
|
48
|
+
declare function nextCalendarBoundary(unit: 'month', timezone: string, now: number): number;
|
|
49
|
+
declare function resolveUntil(input: {
|
|
50
|
+
evidence: FreezeEvidence;
|
|
51
|
+
limit?: AvailabilityLimitDecl;
|
|
52
|
+
recurrence: number;
|
|
53
|
+
now: number;
|
|
54
|
+
defaults: CooldownDefaults;
|
|
55
|
+
}): number | undefined;
|
|
56
|
+
declare function recurrenceOf(records: readonly FreezeRecord[], scopeKeyStr: string, now: number, windowMs: number): number;
|
|
57
|
+
//#endregion
|
|
58
|
+
//#region src/service.d.ts
|
|
59
|
+
interface ModelAvailabilityServiceOptions {
|
|
60
|
+
store: AvailabilityStore;
|
|
61
|
+
clock?: {
|
|
62
|
+
now(): number;
|
|
63
|
+
};
|
|
64
|
+
disabled?: () => ReadonlySet<string>;
|
|
65
|
+
declOf?: (providerId: string) => AvailabilityDecl | undefined;
|
|
66
|
+
isProviderRegistered?: (providerId: string) => boolean;
|
|
67
|
+
onDiagnostic?: (severity: 'error' | 'warning' | 'info', code: string, message: string) => void;
|
|
68
|
+
}
|
|
69
|
+
declare function createModelAvailabilityService(options: ModelAvailabilityServiceOptions): ModelAvailabilityService & {
|
|
70
|
+
dispose(): void;
|
|
71
|
+
flush(): Promise<void>;
|
|
72
|
+
};
|
|
73
|
+
//#endregion
|
|
74
|
+
export { Availability, type AvailabilityComponentOptions, type AvailabilityModelRef, type AvailabilityStore, type AvailabilityStoreOptions, type CooldownDefaults, type ModelAvailabilityServiceOptions, createFileAvailabilityStore, createModelAvailabilityService, nextCalendarBoundary, recurrenceOf, resolveScope, resolveUntil };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,524 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { AVAILABILITY_DEFAULTS, MODEL_DISABLED_FIELD_SPEC, SLOTS, TIMINGS, scopeKey, settingValueOf } from "@x-otto/kernel";
|
|
3
|
+
import { createSignal, defineComponent } from "@x-otto/universal";
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
5
|
+
import { unwatchFile, watchFile } from "node:fs";
|
|
6
|
+
import { readFile } from "node:fs/promises";
|
|
7
|
+
import { ensurePrivateDir, withStoreMutex, writeJsonAtomic } from "@x-otto/atomic-fs";
|
|
8
|
+
|
|
9
|
+
//#region src/policy.ts
|
|
10
|
+
function modelScope(ref) {
|
|
11
|
+
return {
|
|
12
|
+
kind: "model",
|
|
13
|
+
providerId: ref.providerId,
|
|
14
|
+
modelId: ref.modelId,
|
|
15
|
+
...ref.credentialKey === void 0 ? {} : { credentialKey: ref.credentialKey }
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
function matches(modelMatch, modelId) {
|
|
19
|
+
if (modelMatch === void 0 || modelMatch === "") return true;
|
|
20
|
+
try {
|
|
21
|
+
return new RegExp(modelMatch).test(modelId);
|
|
22
|
+
} catch {
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
function resolveScope(evidence, limits, ref) {
|
|
27
|
+
const limit = limits.find((entry) => entry.id === evidence.limitId);
|
|
28
|
+
if (limit === void 0) return { scope: modelScope(ref) };
|
|
29
|
+
if (limit.scope === "model") {
|
|
30
|
+
if (!matches(limit.modelMatch, ref.modelId)) return { scope: modelScope(ref) };
|
|
31
|
+
return {
|
|
32
|
+
limitId: limit.id,
|
|
33
|
+
scope: modelScope(ref)
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
return {
|
|
37
|
+
limitId: limit.id,
|
|
38
|
+
scope: {
|
|
39
|
+
kind: "provider",
|
|
40
|
+
providerId: ref.providerId,
|
|
41
|
+
...ref.credentialKey === void 0 ? {} : { credentialKey: ref.credentialKey }
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
function partsOf(dtf, instant) {
|
|
46
|
+
const parts = {};
|
|
47
|
+
for (const part of dtf.formatToParts(instant)) parts[part.type] = part.value;
|
|
48
|
+
return parts;
|
|
49
|
+
}
|
|
50
|
+
function wallAt(instant, timezone) {
|
|
51
|
+
const parts = partsOf(new Intl.DateTimeFormat("en-US", {
|
|
52
|
+
timeZone: timezone,
|
|
53
|
+
year: "numeric",
|
|
54
|
+
month: "2-digit",
|
|
55
|
+
day: "2-digit",
|
|
56
|
+
hour: "2-digit",
|
|
57
|
+
minute: "2-digit",
|
|
58
|
+
second: "2-digit",
|
|
59
|
+
hour12: false
|
|
60
|
+
}), instant);
|
|
61
|
+
let hour = Number(parts.hour);
|
|
62
|
+
if (hour === 24) hour = 0;
|
|
63
|
+
return Date.UTC(Number(parts.year), Number(parts.month) - 1, Number(parts.day), hour, Number(parts.minute), Number(parts.second));
|
|
64
|
+
}
|
|
65
|
+
function instantFromWall(wall, timezone) {
|
|
66
|
+
let guess = wall;
|
|
67
|
+
for (let i = 0; i < 4; i += 1) {
|
|
68
|
+
const next = wall - (wallAt(guess, timezone) - guess);
|
|
69
|
+
if (next === guess) return next;
|
|
70
|
+
guess = next;
|
|
71
|
+
}
|
|
72
|
+
return guess;
|
|
73
|
+
}
|
|
74
|
+
function nextCalendarBoundary(unit, timezone, now) {
|
|
75
|
+
const monthParts = partsOf(new Intl.DateTimeFormat("en-US", {
|
|
76
|
+
timeZone: timezone,
|
|
77
|
+
year: "numeric",
|
|
78
|
+
month: "2-digit"
|
|
79
|
+
}), now);
|
|
80
|
+
let year = Number(monthParts.year);
|
|
81
|
+
let month = Number(monthParts.month);
|
|
82
|
+
if (month === 12) {
|
|
83
|
+
year += 1;
|
|
84
|
+
month = 1;
|
|
85
|
+
} else month += 1;
|
|
86
|
+
return instantFromWall(Date.UTC(year, month - 1, 1, 0, 0, 0), timezone);
|
|
87
|
+
}
|
|
88
|
+
function resolveUntil(input) {
|
|
89
|
+
const { evidence, limit, recurrence, now, defaults } = input;
|
|
90
|
+
if (limit?.advisory === true) return;
|
|
91
|
+
if (typeof evidence.resetAtMs === "number" && Number.isFinite(evidence.resetAtMs)) return evidence.resetAtMs;
|
|
92
|
+
if (limit?.calendar === "month") return nextCalendarBoundary("month", limit.timezone ?? "UTC", now);
|
|
93
|
+
if (typeof limit?.windowMs === "number" && Number.isFinite(limit.windowMs)) return now + limit.windowMs;
|
|
94
|
+
return now + Math.min(defaults.baseMs + defaults.stepMs * recurrence, defaults.capMs);
|
|
95
|
+
}
|
|
96
|
+
function recurrenceOf(records, scopeKeyStr, now, windowMs) {
|
|
97
|
+
let count = 0;
|
|
98
|
+
for (const record of records) {
|
|
99
|
+
if (scopeKey(record.scope) !== scopeKeyStr) continue;
|
|
100
|
+
const lifted = record.liftedAt ?? record.until ?? record.frozenAt;
|
|
101
|
+
if (lifted === void 0) continue;
|
|
102
|
+
const delta = now - lifted;
|
|
103
|
+
if (delta >= 0 && delta <= windowMs) count += 1;
|
|
104
|
+
}
|
|
105
|
+
return count;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
//#endregion
|
|
109
|
+
//#region src/service.ts
|
|
110
|
+
function messageOf(error) {
|
|
111
|
+
return error instanceof Error ? error.message : String(error);
|
|
112
|
+
}
|
|
113
|
+
function createModelAvailabilityService(options) {
|
|
114
|
+
const clock = options.clock ?? { now: () => Date.now() };
|
|
115
|
+
const disabled = options.disabled ?? (() => /* @__PURE__ */ new Set());
|
|
116
|
+
const declOf = options.declOf ?? (() => void 0);
|
|
117
|
+
const isProviderRegistered = options.isProviderRegistered ?? (() => true);
|
|
118
|
+
let records = [];
|
|
119
|
+
let stateVersion = 0;
|
|
120
|
+
let mutated = false;
|
|
121
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
122
|
+
let writeChain = Promise.resolve();
|
|
123
|
+
const notify = () => {
|
|
124
|
+
for (const listener of [...listeners]) try {
|
|
125
|
+
listener();
|
|
126
|
+
} catch {}
|
|
127
|
+
};
|
|
128
|
+
const flush = () => writeChain;
|
|
129
|
+
const persist = (next) => {
|
|
130
|
+
writeChain = writeChain.then(() => options.store.mutate(() => next)).then(() => void 0, (error) => {
|
|
131
|
+
options.onDiagnostic?.("error", "MODEL_STORE_WRITE_FAILED", messageOf(error));
|
|
132
|
+
});
|
|
133
|
+
};
|
|
134
|
+
const activeRecord = (scopeKeyStr) => {
|
|
135
|
+
const at = clock.now();
|
|
136
|
+
return records.find((record) => {
|
|
137
|
+
if (scopeKey(record.scope) !== scopeKeyStr) return false;
|
|
138
|
+
if (!isProviderRegistered(record.scope.providerId)) return false;
|
|
139
|
+
if (record.liftedAt !== void 0) return false;
|
|
140
|
+
return record.until === void 0 || record.until > at;
|
|
141
|
+
});
|
|
142
|
+
};
|
|
143
|
+
const limitOf = (record) => {
|
|
144
|
+
if (record.limitId === void 0) return;
|
|
145
|
+
return declOf(record.scope.providerId)?.limits?.find((entry) => entry.id === record.limitId);
|
|
146
|
+
};
|
|
147
|
+
const liftScope = (scopeKeyStr, at) => {
|
|
148
|
+
let changed = false;
|
|
149
|
+
records = records.map((record) => {
|
|
150
|
+
if (scopeKey(record.scope) !== scopeKeyStr) return record;
|
|
151
|
+
if (record.liftedAt !== void 0) return record;
|
|
152
|
+
if (record.until !== void 0 && record.until <= at) return record;
|
|
153
|
+
changed = true;
|
|
154
|
+
return {
|
|
155
|
+
...record,
|
|
156
|
+
liftedAt: at
|
|
157
|
+
};
|
|
158
|
+
});
|
|
159
|
+
return changed;
|
|
160
|
+
};
|
|
161
|
+
const scopedKeys = (ref) => {
|
|
162
|
+
const providerScope = {
|
|
163
|
+
kind: "provider",
|
|
164
|
+
providerId: ref.providerId,
|
|
165
|
+
...ref.credentialKey === void 0 ? {} : { credentialKey: ref.credentialKey }
|
|
166
|
+
};
|
|
167
|
+
const modelScopeRef = {
|
|
168
|
+
kind: "model",
|
|
169
|
+
providerId: ref.providerId,
|
|
170
|
+
modelId: ref.modelId,
|
|
171
|
+
...ref.credentialKey === void 0 ? {} : { credentialKey: ref.credentialKey }
|
|
172
|
+
};
|
|
173
|
+
return [scopeKey(providerScope), scopeKey(modelScopeRef)];
|
|
174
|
+
};
|
|
175
|
+
const observeFailure = (ref, evidence) => {
|
|
176
|
+
const decl = declOf(ref.providerId);
|
|
177
|
+
const limits = decl?.limits ?? [];
|
|
178
|
+
const resolved = resolveScope(evidence, limits, ref);
|
|
179
|
+
const key = scopeKey(resolved.scope);
|
|
180
|
+
const at = clock.now();
|
|
181
|
+
const existing = activeRecord(key);
|
|
182
|
+
if (existing !== void 0) {
|
|
183
|
+
records = records.map((record) => record === existing ? {
|
|
184
|
+
...record,
|
|
185
|
+
evidence: { ...evidence }
|
|
186
|
+
} : record);
|
|
187
|
+
mutated = true;
|
|
188
|
+
stateVersion += 1;
|
|
189
|
+
notify();
|
|
190
|
+
persist(records);
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
const defaults = {
|
|
194
|
+
...AVAILABILITY_DEFAULTS,
|
|
195
|
+
...decl?.escalation
|
|
196
|
+
};
|
|
197
|
+
const recurrence = recurrenceOf(records, key, at, defaults.recurrenceWindowMs);
|
|
198
|
+
const until = resolveUntil({
|
|
199
|
+
evidence,
|
|
200
|
+
limit: resolved.limitId === void 0 ? void 0 : limits.find((entry) => entry.id === resolved.limitId),
|
|
201
|
+
recurrence,
|
|
202
|
+
now: at,
|
|
203
|
+
defaults
|
|
204
|
+
});
|
|
205
|
+
const record = {
|
|
206
|
+
scope: resolved.scope,
|
|
207
|
+
...resolved.limitId === void 0 ? {} : { limitId: resolved.limitId },
|
|
208
|
+
frozenAt: at,
|
|
209
|
+
...until === void 0 ? {} : { until },
|
|
210
|
+
evidence: { ...evidence }
|
|
211
|
+
};
|
|
212
|
+
records = [...records, record];
|
|
213
|
+
mutated = true;
|
|
214
|
+
stateVersion += 1;
|
|
215
|
+
notify();
|
|
216
|
+
persist(records);
|
|
217
|
+
options.onDiagnostic?.("warning", "MODEL_FROZEN", `froze ${key}${until === void 0 ? " (advisory)" : ""}`);
|
|
218
|
+
};
|
|
219
|
+
const observeSuccess = (ref) => {
|
|
220
|
+
const at = clock.now();
|
|
221
|
+
const keys = scopedKeys(ref);
|
|
222
|
+
let changed = false;
|
|
223
|
+
for (const key of keys) if (liftScope(key, at)) changed = true;
|
|
224
|
+
if (!changed) return;
|
|
225
|
+
mutated = true;
|
|
226
|
+
stateVersion += 1;
|
|
227
|
+
notify();
|
|
228
|
+
persist(records);
|
|
229
|
+
options.onDiagnostic?.("info", "MODEL_UNFROZEN", `unfroze ${ref.providerId}/${ref.modelId}`);
|
|
230
|
+
};
|
|
231
|
+
const unfreeze = (scopeKeyStr) => {
|
|
232
|
+
if (!liftScope(scopeKeyStr, clock.now())) return;
|
|
233
|
+
mutated = true;
|
|
234
|
+
stateVersion += 1;
|
|
235
|
+
notify();
|
|
236
|
+
persist(records);
|
|
237
|
+
options.onDiagnostic?.("info", "MODEL_UNFROZEN", `unfroze ${scopeKeyStr}`);
|
|
238
|
+
};
|
|
239
|
+
const check = (ref) => {
|
|
240
|
+
const modelKey = scopedKeys(ref)[1];
|
|
241
|
+
if (disabled().has(ref.modelId)) return {
|
|
242
|
+
scopeKey: modelKey,
|
|
243
|
+
state: "disabled"
|
|
244
|
+
};
|
|
245
|
+
const [providerKey] = scopedKeys(ref);
|
|
246
|
+
const record = activeRecord(providerKey) ?? activeRecord(modelKey);
|
|
247
|
+
if (record === void 0) return {
|
|
248
|
+
scopeKey: modelKey,
|
|
249
|
+
state: "available"
|
|
250
|
+
};
|
|
251
|
+
const limit = limitOf(record);
|
|
252
|
+
return {
|
|
253
|
+
scopeKey: scopeKey(record.scope),
|
|
254
|
+
state: record.until === void 0 ? "advisory" : "frozen",
|
|
255
|
+
...record.limitId === void 0 ? {} : { limitId: record.limitId },
|
|
256
|
+
...limit?.label === void 0 ? {} : { label: limit.label },
|
|
257
|
+
...record.until === void 0 ? {} : { until: record.until }
|
|
258
|
+
};
|
|
259
|
+
};
|
|
260
|
+
const snapshot = () => {
|
|
261
|
+
const at = clock.now();
|
|
262
|
+
const out = [];
|
|
263
|
+
for (const record of records) {
|
|
264
|
+
if (!isProviderRegistered(record.scope.providerId)) continue;
|
|
265
|
+
if (record.liftedAt !== void 0) continue;
|
|
266
|
+
if (record.until !== void 0 && record.until <= at) continue;
|
|
267
|
+
const limit = limitOf(record);
|
|
268
|
+
out.push({
|
|
269
|
+
scopeKey: scopeKey(record.scope),
|
|
270
|
+
state: record.until === void 0 ? "advisory" : "frozen",
|
|
271
|
+
...record.limitId === void 0 ? {} : { limitId: record.limitId },
|
|
272
|
+
...limit?.label === void 0 ? {} : { label: limit.label },
|
|
273
|
+
...record.until === void 0 ? {} : { until: record.until }
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
return out;
|
|
277
|
+
};
|
|
278
|
+
const subscribe = (listener) => {
|
|
279
|
+
listeners.add(listener);
|
|
280
|
+
return { dispose() {
|
|
281
|
+
listeners.delete(listener);
|
|
282
|
+
} };
|
|
283
|
+
};
|
|
284
|
+
const unwatch = options.store.watch(() => {
|
|
285
|
+
options.store.load().then((loaded) => {
|
|
286
|
+
records = [...loaded];
|
|
287
|
+
stateVersion += 1;
|
|
288
|
+
notify();
|
|
289
|
+
}).catch((error) => {
|
|
290
|
+
options.onDiagnostic?.("error", "MODEL_STORE_CORRUPT", messageOf(error));
|
|
291
|
+
});
|
|
292
|
+
});
|
|
293
|
+
options.store.load().then((loaded) => {
|
|
294
|
+
if (mutated) return;
|
|
295
|
+
records = [...loaded];
|
|
296
|
+
stateVersion += 1;
|
|
297
|
+
notify();
|
|
298
|
+
}).catch((error) => {
|
|
299
|
+
options.onDiagnostic?.("error", "MODEL_STORE_CORRUPT", messageOf(error));
|
|
300
|
+
});
|
|
301
|
+
return {
|
|
302
|
+
version: () => stateVersion,
|
|
303
|
+
check,
|
|
304
|
+
snapshot,
|
|
305
|
+
observeFailure,
|
|
306
|
+
observeSuccess,
|
|
307
|
+
unfreeze,
|
|
308
|
+
subscribe,
|
|
309
|
+
flush,
|
|
310
|
+
dispose: () => unwatch.dispose()
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
//#endregion
|
|
315
|
+
//#region src/store.ts
|
|
316
|
+
const STATE_FILE = "state.json";
|
|
317
|
+
const PRUNE_AGE_MS = 10080 * 60 * 1e3;
|
|
318
|
+
const WATCH_INTERVAL_MS = 1e3;
|
|
319
|
+
const WATCH_SETTLE_MS = 200;
|
|
320
|
+
const STATE_WRITE_DEADLINE_MS = 5e3;
|
|
321
|
+
function corrupt() {
|
|
322
|
+
return /* @__PURE__ */ new Error("corrupt availability state file: expected {version:1, revision, records}");
|
|
323
|
+
}
|
|
324
|
+
function isRecord(raw) {
|
|
325
|
+
return typeof raw === "object" && raw !== null && !Array.isArray(raw);
|
|
326
|
+
}
|
|
327
|
+
function normalizeEvidence(raw) {
|
|
328
|
+
if (!isRecord(raw)) throw corrupt();
|
|
329
|
+
const evidence = {};
|
|
330
|
+
if (raw.limitId !== void 0) {
|
|
331
|
+
if (typeof raw.limitId !== "string") throw corrupt();
|
|
332
|
+
evidence.limitId = raw.limitId;
|
|
333
|
+
}
|
|
334
|
+
if (raw.resetAtMs !== void 0) {
|
|
335
|
+
if (typeof raw.resetAtMs !== "number" || !Number.isFinite(raw.resetAtMs)) throw corrupt();
|
|
336
|
+
evidence.resetAtMs = raw.resetAtMs;
|
|
337
|
+
}
|
|
338
|
+
if (raw.code !== void 0) {
|
|
339
|
+
if (typeof raw.code !== "string") throw corrupt();
|
|
340
|
+
evidence.code = raw.code;
|
|
341
|
+
}
|
|
342
|
+
if (raw.status !== void 0) {
|
|
343
|
+
if (typeof raw.status !== "number") throw corrupt();
|
|
344
|
+
evidence.status = raw.status;
|
|
345
|
+
}
|
|
346
|
+
return evidence;
|
|
347
|
+
}
|
|
348
|
+
function normalizeScope(raw) {
|
|
349
|
+
if (!isRecord(raw)) throw corrupt();
|
|
350
|
+
const credentialKey = typeof raw.credentialKey === "string" && raw.credentialKey !== "" ? raw.credentialKey : void 0;
|
|
351
|
+
if (raw.kind === "provider") {
|
|
352
|
+
if (typeof raw.providerId !== "string" || raw.providerId === "") throw corrupt();
|
|
353
|
+
return {
|
|
354
|
+
kind: "provider",
|
|
355
|
+
providerId: raw.providerId,
|
|
356
|
+
...credentialKey === void 0 ? {} : { credentialKey }
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
if (raw.kind === "model") {
|
|
360
|
+
if (typeof raw.providerId !== "string" || typeof raw.modelId !== "string") throw corrupt();
|
|
361
|
+
return {
|
|
362
|
+
kind: "model",
|
|
363
|
+
providerId: raw.providerId,
|
|
364
|
+
modelId: raw.modelId,
|
|
365
|
+
...credentialKey === void 0 ? {} : { credentialKey }
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
throw corrupt();
|
|
369
|
+
}
|
|
370
|
+
function normalizeRecord(raw) {
|
|
371
|
+
if (!isRecord(raw)) throw corrupt();
|
|
372
|
+
if (typeof raw.frozenAt !== "number" || !Number.isFinite(raw.frozenAt)) throw corrupt();
|
|
373
|
+
const record = {
|
|
374
|
+
scope: normalizeScope(raw.scope),
|
|
375
|
+
frozenAt: raw.frozenAt,
|
|
376
|
+
evidence: normalizeEvidence(raw.evidence)
|
|
377
|
+
};
|
|
378
|
+
if (raw.limitId !== void 0) {
|
|
379
|
+
if (typeof raw.limitId !== "string") throw corrupt();
|
|
380
|
+
record.limitId = raw.limitId;
|
|
381
|
+
}
|
|
382
|
+
if (raw.until !== void 0) {
|
|
383
|
+
if (typeof raw.until !== "number" || !Number.isFinite(raw.until)) throw corrupt();
|
|
384
|
+
record.until = raw.until;
|
|
385
|
+
}
|
|
386
|
+
if (raw.liftedAt !== void 0) {
|
|
387
|
+
if (typeof raw.liftedAt !== "number" || !Number.isFinite(raw.liftedAt)) throw corrupt();
|
|
388
|
+
record.liftedAt = raw.liftedAt;
|
|
389
|
+
}
|
|
390
|
+
return record;
|
|
391
|
+
}
|
|
392
|
+
function parseState(bytes) {
|
|
393
|
+
let raw;
|
|
394
|
+
try {
|
|
395
|
+
raw = JSON.parse(bytes.toString("utf8"));
|
|
396
|
+
} catch {
|
|
397
|
+
throw corrupt();
|
|
398
|
+
}
|
|
399
|
+
if (!isRecord(raw) || raw.version !== 1 || !Array.isArray(raw.records)) throw corrupt();
|
|
400
|
+
if (typeof raw.revision !== "string" || raw.revision === "") throw corrupt();
|
|
401
|
+
return {
|
|
402
|
+
revision: raw.revision,
|
|
403
|
+
records: raw.records.map(normalizeRecord)
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
function createFileAvailabilityStore(options) {
|
|
407
|
+
const directory = options.directory;
|
|
408
|
+
const clock = options.clock ?? { now: () => Date.now() };
|
|
409
|
+
const isProviderRegistered = options.isProviderRegistered ?? (() => true);
|
|
410
|
+
const statePath = join(directory, STATE_FILE);
|
|
411
|
+
let cache;
|
|
412
|
+
async function readState() {
|
|
413
|
+
let bytes;
|
|
414
|
+
try {
|
|
415
|
+
bytes = await readFile(statePath);
|
|
416
|
+
} catch (error) {
|
|
417
|
+
if (error.code === "ENOENT") return {
|
|
418
|
+
revision: "missing",
|
|
419
|
+
records: []
|
|
420
|
+
};
|
|
421
|
+
throw error;
|
|
422
|
+
}
|
|
423
|
+
return parseState(bytes);
|
|
424
|
+
}
|
|
425
|
+
function prune(records) {
|
|
426
|
+
const cutoff = clock.now();
|
|
427
|
+
const kept = [];
|
|
428
|
+
for (const record of records) {
|
|
429
|
+
if (!isProviderRegistered(record.scope.providerId)) continue;
|
|
430
|
+
if (record.liftedAt !== void 0 && cutoff - record.liftedAt > PRUNE_AGE_MS) continue;
|
|
431
|
+
if (record.until !== void 0 && record.until < cutoff && cutoff - record.until > PRUNE_AGE_MS) continue;
|
|
432
|
+
kept.push(record);
|
|
433
|
+
}
|
|
434
|
+
return kept;
|
|
435
|
+
}
|
|
436
|
+
return {
|
|
437
|
+
async load() {
|
|
438
|
+
if (cache !== void 0) return cache.records;
|
|
439
|
+
const parsed = await readState();
|
|
440
|
+
cache = parsed;
|
|
441
|
+
return parsed.records;
|
|
442
|
+
},
|
|
443
|
+
async mutate(transform) {
|
|
444
|
+
await ensurePrivateDir(directory);
|
|
445
|
+
const written = await withStoreMutex(directory, async () => {
|
|
446
|
+
const records = prune(transform((await readState()).records));
|
|
447
|
+
const state = {
|
|
448
|
+
version: 1,
|
|
449
|
+
revision: randomUUID(),
|
|
450
|
+
records,
|
|
451
|
+
updatedAt: clock.now()
|
|
452
|
+
};
|
|
453
|
+
await writeJsonAtomic(statePath, state);
|
|
454
|
+
return {
|
|
455
|
+
revision: state.revision,
|
|
456
|
+
records
|
|
457
|
+
};
|
|
458
|
+
}, { deadlineMs: STATE_WRITE_DEADLINE_MS });
|
|
459
|
+
cache = written;
|
|
460
|
+
return written.records;
|
|
461
|
+
},
|
|
462
|
+
watch(onChange) {
|
|
463
|
+
const interval = options.watchIntervalMs ?? WATCH_INTERVAL_MS;
|
|
464
|
+
let timer;
|
|
465
|
+
const handler = (current, previous) => {
|
|
466
|
+
if (current.mtimeMs === previous.mtimeMs && current.size === previous.size && current.ino === previous.ino) return;
|
|
467
|
+
cache = void 0;
|
|
468
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
469
|
+
timer = setTimeout(() => {
|
|
470
|
+
timer = void 0;
|
|
471
|
+
onChange();
|
|
472
|
+
}, WATCH_SETTLE_MS);
|
|
473
|
+
};
|
|
474
|
+
watchFile(statePath, { interval }, handler).unref();
|
|
475
|
+
return { dispose() {
|
|
476
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
477
|
+
unwatchFile(statePath, handler);
|
|
478
|
+
} };
|
|
479
|
+
}
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
//#endregion
|
|
484
|
+
//#region src/component.ts
|
|
485
|
+
const Availability = defineComponent("Availability", (ctx, options) => {
|
|
486
|
+
const settingsManager = ctx.consume(SLOTS.settings)();
|
|
487
|
+
const providers = ctx.maybe(SLOTS.providers);
|
|
488
|
+
const hooks = ctx.maybe(SLOTS.hooks);
|
|
489
|
+
const [disabled, setDisabled] = createSignal(/* @__PURE__ */ new Set());
|
|
490
|
+
const store = ctx.resource("availability-store", () => options.store ?? createFileAvailabilityStore({
|
|
491
|
+
directory: join(options.home, "availability"),
|
|
492
|
+
...options.clock === void 0 ? {} : { clock: options.clock },
|
|
493
|
+
isProviderRegistered: (id) => providers()?.get(id) !== void 0
|
|
494
|
+
}), () => {}, { hmr: "recreate" });
|
|
495
|
+
const service = ctx.resource("availability-service", () => createModelAvailabilityService({
|
|
496
|
+
store,
|
|
497
|
+
...options.clock === void 0 ? {} : { clock: options.clock },
|
|
498
|
+
disabled: () => disabled(),
|
|
499
|
+
declOf: (id) => providers()?.get(id)?.contribution.availability,
|
|
500
|
+
isProviderRegistered: (id) => providers()?.get(id) !== void 0,
|
|
501
|
+
onDiagnostic: (severity, code, message) => {
|
|
502
|
+
hooks()?.emitAndWait(TIMINGS.runtimeDiagnostic, {
|
|
503
|
+
source: "availability",
|
|
504
|
+
severity,
|
|
505
|
+
code,
|
|
506
|
+
message
|
|
507
|
+
}).catch(() => void 0);
|
|
508
|
+
}
|
|
509
|
+
}), async (instance) => {
|
|
510
|
+
await instance.flush();
|
|
511
|
+
instance.dispose();
|
|
512
|
+
}, { hmr: "recreate" });
|
|
513
|
+
ctx.provide(SLOTS.modelAvailability, () => service);
|
|
514
|
+
ctx.effect(() => {
|
|
515
|
+
const field = settingsManager.registerField(MODEL_DISABLED_FIELD_SPEC, "availability");
|
|
516
|
+
ctx.effect(() => {
|
|
517
|
+
setDisabled(new Set(settingValueOf(field, MODEL_DISABLED_FIELD_SPEC)));
|
|
518
|
+
});
|
|
519
|
+
return () => field.dispose();
|
|
520
|
+
});
|
|
521
|
+
});
|
|
522
|
+
|
|
523
|
+
//#endregion
|
|
524
|
+
export { Availability, createFileAvailabilityStore, createModelAvailabilityService, nextCalendarBoundary, recurrenceOf, resolveScope, resolveUntil };
|
package/package.json
CHANGED
|
@@ -1,6 +1,26 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@x-otto/availability",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.4.0-beta.0",
|
|
4
|
+
"description": "模型可用性域:冻结/禁止状态与策略(limit→作用域/时长/日历/递加)+ 单表持久化(lock+CAS+原子写+watch)+ 装配组件",
|
|
5
|
+
"files": [
|
|
6
|
+
"dist"
|
|
7
|
+
],
|
|
8
|
+
"type": "module",
|
|
9
|
+
"main": "./dist/index.js",
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"types": "./dist/index.d.ts",
|
|
14
|
+
"import": "./dist/index.js"
|
|
15
|
+
}
|
|
16
|
+
},
|
|
17
|
+
"dependencies": {
|
|
18
|
+
"@x-otto/atomic-fs": "^0.4.0-beta.0",
|
|
19
|
+
"@x-otto/kernel": "^0.4.0-beta.0",
|
|
20
|
+
"@x-otto/universal": "^0.4.0-beta.0"
|
|
21
|
+
},
|
|
22
|
+
"publishConfig": {
|
|
23
|
+
"access": "public",
|
|
24
|
+
"tag": "beta"
|
|
25
|
+
}
|
|
26
|
+
}
|
package/README.md
DELETED