@cortexkit/common-auth 0.33.0 → 0.35.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/claustrum/consumer.d.ts +12 -0
- package/dist/claustrum/consumer.js +36 -0
- package/dist/claustrum/custody.d.ts +16 -4
- package/dist/claustrum/custody.js +74 -9
- package/dist/claustrum/hub.d.ts +3 -2
- package/dist/claustrum/hub.js +8 -0
- package/dist/claustrum/index.d.ts +1 -0
- package/dist/claustrum/roster.d.ts +2 -0
- package/dist/claustrum/roster.js +2 -0
- package/dist/claustrum/usage.d.ts +41 -0
- package/dist/claustrum/usage.js +145 -0
- package/dist/commands/builtins.d.ts +5 -0
- package/dist/commands/builtins.js +38 -0
- package/dist/fs/private-files.d.ts +5 -0
- package/dist/fs/private-files.js +7 -0
- package/dist/fs/refresh-file-lock.js +142 -47
- package/dist/fs/with-lock.js +2 -5
- package/dist/limits/activity.d.ts +26 -0
- package/dist/limits/activity.js +52 -0
- package/dist/limits/axes.d.ts +69 -0
- package/dist/limits/axes.js +7 -0
- package/dist/limits/bridge.d.ts +4 -0
- package/dist/limits/bridge.js +10 -0
- package/dist/limits/decide.d.ts +146 -0
- package/dist/limits/decide.js +425 -0
- package/dist/limits/duration.d.ts +8 -0
- package/dist/limits/duration.js +20 -0
- package/dist/limits/envelope-loss.d.ts +29 -0
- package/dist/limits/envelope-loss.js +150 -0
- package/dist/limits/families.d.ts +59 -0
- package/dist/limits/families.js +149 -0
- package/dist/limits/header-classifier.d.ts +9 -0
- package/dist/limits/header-classifier.js +121 -0
- package/dist/limits/hold.d.ts +13 -0
- package/dist/limits/hold.js +25 -0
- package/dist/limits/identity.d.ts +14 -0
- package/dist/limits/identity.js +21 -0
- package/dist/limits/index.d.ts +45 -0
- package/dist/limits/index.js +26 -0
- package/dist/limits/jitter.d.ts +2 -0
- package/dist/limits/jitter.js +9 -0
- package/dist/limits/labels.d.ts +3 -0
- package/dist/limits/labels.js +11 -0
- package/dist/limits/marker.d.ts +69 -0
- package/dist/limits/marker.js +107 -0
- package/dist/limits/merge-laws.d.ts +15 -0
- package/dist/limits/merge-laws.js +31 -0
- package/dist/limits/namespace.d.ts +92 -0
- package/dist/limits/namespace.js +191 -0
- package/dist/limits/persistence.d.ts +33 -0
- package/dist/limits/persistence.js +9 -0
- package/dist/limits/pi-wait.d.ts +16 -0
- package/dist/limits/pi-wait.js +51 -0
- package/dist/limits/pool-adapter.d.ts +16 -0
- package/dist/limits/pool-adapter.js +162 -0
- package/dist/limits/presets.d.ts +11 -0
- package/dist/limits/presets.js +240 -0
- package/dist/limits/registry.d.ts +61 -0
- package/dist/limits/registry.js +478 -0
- package/dist/limits/request-history.d.ts +79 -0
- package/dist/limits/request-history.js +120 -0
- package/dist/limits/reset.d.ts +21 -0
- package/dist/limits/reset.js +44 -0
- package/dist/limits/routing-hold.d.ts +16 -0
- package/dist/limits/routing-hold.js +23 -0
- package/dist/limits/scope.d.ts +12 -0
- package/dist/limits/scope.js +10 -0
- package/dist/limits/signal.d.ts +41 -0
- package/dist/limits/signal.js +1 -0
- package/dist/limits/terminal.d.ts +52 -0
- package/dist/limits/terminal.js +133 -0
- package/dist/limits/unconfirmed-retain-counter.d.ts +13 -0
- package/dist/limits/unconfirmed-retain-counter.js +41 -0
- package/dist/limits/vault-adapter.d.ts +16 -0
- package/dist/limits/vault-adapter.js +123 -0
- package/dist/limits/vault.d.ts +1 -0
- package/dist/limits/vault.js +1 -0
- package/dist/limits/wake.d.ts +21 -0
- package/dist/limits/wake.js +47 -0
- package/dist/limits/wording.d.ts +25 -0
- package/dist/limits/wording.js +114 -0
- package/dist/opencode2/index.d.ts +1 -1
- package/dist/opencode2/install.d.ts +2 -2
- package/dist/opencode2/install.js +161 -18
- package/dist/opencode2/types.d.ts +95 -9
- package/dist/routing/admission.d.ts +7 -2
- package/dist/routing/admission.js +17 -7
- package/dist/routing-accessor/handle.d.ts +1 -0
- package/dist/routing-accessor/handle.js +10 -0
- package/dist/routing-accessor/index.d.ts +13 -3
- package/dist/routing-accessor/index.js +11 -10
- package/dist/rpc/port-file.d.ts +12 -3
- package/dist/rpc/port-file.js +46 -4
- package/dist/store/attribution.js +3 -2
- package/dist/store/errors.d.ts +1 -1
- package/dist/store/hooks.d.ts +5 -1
- package/dist/store/hooks.js +20 -5
- package/dist/store/index.d.ts +1 -0
- package/dist/store/limits-namespace.d.ts +7 -0
- package/dist/store/limits-namespace.js +34 -0
- package/dist/store/pool.d.ts +10 -1
- package/dist/store/pool.js +2 -0
- package/dist/store/provider-state.js +5 -5
- package/dist/store/refresh.js +1 -1
- package/dist/store/schema.js +9 -4
- package/dist/store/settings.d.ts +2 -0
- package/dist/store/settings.js +11 -4
- package/package.json +10 -2
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
export const ANTIGRAVITY_FAILURE_LADDER = Object.freeze({
|
|
2
|
+
kind: 'failure-ladder',
|
|
3
|
+
mergeLaw: 'max-until',
|
|
4
|
+
hintFloorMs: 2000,
|
|
5
|
+
quotaSteps: Object.freeze([60000, 300000, 1800000, 7200000]),
|
|
6
|
+
byKind: Object.freeze({ 'rate-limit': 30000 }),
|
|
7
|
+
byReason: Object.freeze({ 'server-error': 20000, unknown: 60000 }),
|
|
8
|
+
capacity: Object.freeze({ baseMs: 45000, spreadMs: 15000 }),
|
|
9
|
+
defaultMs: 60000,
|
|
10
|
+
});
|
|
11
|
+
function accountKey(account) {
|
|
12
|
+
return JSON.stringify([
|
|
13
|
+
account.namespace,
|
|
14
|
+
account.accountId,
|
|
15
|
+
account.incarnation,
|
|
16
|
+
]);
|
|
17
|
+
}
|
|
18
|
+
/** Feed committed marker events, not repeated reducer evaluations, into history. */
|
|
19
|
+
export function reduceFailureHistory(history, event, ttlMs = 3600000) {
|
|
20
|
+
const next = new Map(history);
|
|
21
|
+
const key = accountKey(event.account);
|
|
22
|
+
if (event.type === 'success') {
|
|
23
|
+
next.delete(key);
|
|
24
|
+
}
|
|
25
|
+
else {
|
|
26
|
+
const previous = history.get(key);
|
|
27
|
+
const count = !previous || event.at - previous.lastFailureAt > ttlMs
|
|
28
|
+
? 1
|
|
29
|
+
: previous.count + 1;
|
|
30
|
+
next.set(key, { count, lastFailureAt: event.at });
|
|
31
|
+
}
|
|
32
|
+
return next;
|
|
33
|
+
}
|
|
34
|
+
function ladderMs(signal, axes, history) {
|
|
35
|
+
const hint = signal.retryAfterMs;
|
|
36
|
+
if (hint !== undefined && Number.isFinite(hint) && hint > 0) {
|
|
37
|
+
return Math.max(axes.hintFloorMs, hint);
|
|
38
|
+
}
|
|
39
|
+
const reasonDuration = Object.hasOwn(axes.byReason, signal.reason)
|
|
40
|
+
? axes.byReason[signal.reason]
|
|
41
|
+
: undefined;
|
|
42
|
+
if (reasonDuration !== undefined)
|
|
43
|
+
return reasonDuration;
|
|
44
|
+
if (signal.kind === 'quota-exhausted') {
|
|
45
|
+
const count = history.failures?.get(accountKey(signal.account))?.count ?? 1;
|
|
46
|
+
const index = Math.min(axes.quotaSteps.length - 1, Math.max(0, count - 1));
|
|
47
|
+
const step = axes.quotaSteps[index];
|
|
48
|
+
if (step !== undefined)
|
|
49
|
+
return step;
|
|
50
|
+
}
|
|
51
|
+
const duration = axes.byKind[signal.kind];
|
|
52
|
+
if (duration !== undefined)
|
|
53
|
+
return duration;
|
|
54
|
+
if (signal.kind === 'capacity') {
|
|
55
|
+
return (axes.capacity.baseMs +
|
|
56
|
+
(2 * (history.random ?? 0.5) - 1) * axes.capacity.spreadMs);
|
|
57
|
+
}
|
|
58
|
+
return axes.defaultMs;
|
|
59
|
+
}
|
|
60
|
+
/** No clocks, random draws, state updates or I/O occur while producing a mark. */
|
|
61
|
+
export function markFromSignal(signal, axes, history) {
|
|
62
|
+
if (!signal || axes.kind === 'off')
|
|
63
|
+
return undefined;
|
|
64
|
+
if (axes.kind === 'hint' && axes.ignoredKinds?.includes(signal.kind))
|
|
65
|
+
return undefined;
|
|
66
|
+
let until;
|
|
67
|
+
switch (axes.kind) {
|
|
68
|
+
case 'failure-ladder':
|
|
69
|
+
until = history.now + ladderMs(signal, axes, history);
|
|
70
|
+
break;
|
|
71
|
+
case 'hint': {
|
|
72
|
+
const hint = signal.retryAfterMs;
|
|
73
|
+
const clock = axes.hintClock === 'signal' ? signal.observedAt : history.now;
|
|
74
|
+
const usable = hint !== undefined &&
|
|
75
|
+
Number.isFinite(hint) &&
|
|
76
|
+
(hint > 0 || (hint === 0 && axes.zero === 'accept')) &&
|
|
77
|
+
Number.isFinite(clock + Math.max(axes.minimumMs, hint));
|
|
78
|
+
until = usable
|
|
79
|
+
? clock + Math.max(axes.minimumMs, hint)
|
|
80
|
+
: history.now + (axes.defaultMsByKind?.[signal.kind] ?? axes.defaultMs);
|
|
81
|
+
break;
|
|
82
|
+
}
|
|
83
|
+
case 'reset': {
|
|
84
|
+
const resets = signal.windows
|
|
85
|
+
.map((window) => window.resetAt)
|
|
86
|
+
.filter((reset) => reset !== undefined &&
|
|
87
|
+
Number.isFinite(reset) &&
|
|
88
|
+
reset > history.now);
|
|
89
|
+
until = resets.length ? Math.max(...resets) : history.now + axes.defaultMs;
|
|
90
|
+
break;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return Number.isFinite(until)
|
|
94
|
+
? {
|
|
95
|
+
scope: signal.scope,
|
|
96
|
+
until,
|
|
97
|
+
mergeLaw: axes.mergeLaw,
|
|
98
|
+
...(axes.kind === 'hint' &&
|
|
99
|
+
axes.causes?.some((cause) => cause === signal.kind)
|
|
100
|
+
? { cause: signal.kind }
|
|
101
|
+
: {}),
|
|
102
|
+
}
|
|
103
|
+
: undefined;
|
|
104
|
+
}
|
|
105
|
+
export function markIsActive(mark, now) {
|
|
106
|
+
return now < mark.until;
|
|
107
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { MergeLaw } from './marker.js';
|
|
2
|
+
export interface TimedMarkEntry {
|
|
3
|
+
readonly cause?: import('./marker.js').LimitMarkCause;
|
|
4
|
+
readonly until: number;
|
|
5
|
+
readonly evidenceAt: number;
|
|
6
|
+
readonly baseRevision: number;
|
|
7
|
+
readonly committedRevision: number;
|
|
8
|
+
}
|
|
9
|
+
/** Apply supersession before expiry, so a short or zero overwrite removes a long mark. */
|
|
10
|
+
export declare function mergeTimedMarkEntries(law: MergeLaw, entries: readonly TimedMarkEntry[], now: number, clearRevision?: number): readonly TimedMarkEntry[];
|
|
11
|
+
export interface AccessOrder {
|
|
12
|
+
readonly eligibilityStateUpdatedAt: number;
|
|
13
|
+
readonly committedRevision: number;
|
|
14
|
+
}
|
|
15
|
+
export declare function mergeAccessState<T extends AccessOrder>(a: T, b: T): T;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/** Apply supersession before expiry, so a short or zero overwrite removes a long mark. */
|
|
2
|
+
export function mergeTimedMarkEntries(law, entries, now, clearRevision = 0) {
|
|
3
|
+
const candidates = entries.filter((e) => e.baseRevision >= clearRevision);
|
|
4
|
+
if (law !== 'max-until') {
|
|
5
|
+
const winner = candidates.reduce((best, e) => {
|
|
6
|
+
if (!best)
|
|
7
|
+
return e;
|
|
8
|
+
if (law === 'latest-evidence' && e.evidenceAt !== best.evidenceAt) {
|
|
9
|
+
return e.evidenceAt > best.evidenceAt ? e : best;
|
|
10
|
+
}
|
|
11
|
+
return e.committedRevision > best.committedRevision ? e : best;
|
|
12
|
+
}, undefined);
|
|
13
|
+
return winner && now < winner.until ? [winner] : [];
|
|
14
|
+
}
|
|
15
|
+
return candidates
|
|
16
|
+
.filter((e, i) => now < e.until &&
|
|
17
|
+
!candidates.some((other, j) => j !== i &&
|
|
18
|
+
other.until >= e.until &&
|
|
19
|
+
other.baseRevision >= e.baseRevision &&
|
|
20
|
+
(other.until > e.until ||
|
|
21
|
+
other.baseRevision > e.baseRevision ||
|
|
22
|
+
other.committedRevision > e.committedRevision ||
|
|
23
|
+
(other.committedRevision === e.committedRevision && j < i))))
|
|
24
|
+
.sort((a, b) => a.committedRevision - b.committedRevision);
|
|
25
|
+
}
|
|
26
|
+
export function mergeAccessState(a, b) {
|
|
27
|
+
if (a.eligibilityStateUpdatedAt !== b.eligibilityStateUpdatedAt) {
|
|
28
|
+
return a.eligibilityStateUpdatedAt > b.eligibilityStateUpdatedAt ? a : b;
|
|
29
|
+
}
|
|
30
|
+
return a.committedRevision > b.committedRevision ? a : b;
|
|
31
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import type { AuthorizeCredentialEpoch, IdentityBinding } from './identity.js';
|
|
2
|
+
import type { LimitMarkCause, MergeLaw } from './marker.js';
|
|
3
|
+
import type { AccessOrder, TimedMarkEntry } from './merge-laws.js';
|
|
4
|
+
import type { Scope } from './scope.js';
|
|
5
|
+
import type { AccountKey } from './signal.js';
|
|
6
|
+
export declare const LIMITS_HISTORY_BOUND = 1024;
|
|
7
|
+
export interface MarkTarget {
|
|
8
|
+
readonly scope: Scope;
|
|
9
|
+
readonly window: string;
|
|
10
|
+
}
|
|
11
|
+
export interface TimedMarkKey extends MarkTarget {
|
|
12
|
+
readonly account: AccountKey;
|
|
13
|
+
}
|
|
14
|
+
export interface NamespaceMark {
|
|
15
|
+
readonly key: TimedMarkKey;
|
|
16
|
+
readonly mergeLaw: MergeLaw;
|
|
17
|
+
readonly entries: readonly TimedMarkEntry[];
|
|
18
|
+
}
|
|
19
|
+
export interface ClearTombstone {
|
|
20
|
+
readonly key: TimedMarkKey;
|
|
21
|
+
readonly revision: number;
|
|
22
|
+
}
|
|
23
|
+
export interface CommittedOperation {
|
|
24
|
+
readonly producerId: string;
|
|
25
|
+
readonly operationId: string;
|
|
26
|
+
readonly revision: number;
|
|
27
|
+
}
|
|
28
|
+
export interface NamespaceAccess<T = unknown> extends AccessOrder {
|
|
29
|
+
readonly account: AccountKey;
|
|
30
|
+
readonly state: T;
|
|
31
|
+
}
|
|
32
|
+
/** JSON-compatible state; adapters own generation creation, locking and persistence. */
|
|
33
|
+
export interface LimitsNamespace<T = unknown> {
|
|
34
|
+
readonly schemaVersion: 1;
|
|
35
|
+
readonly namespace: string;
|
|
36
|
+
readonly generation: string;
|
|
37
|
+
readonly revision: number;
|
|
38
|
+
readonly lowWatermark: number;
|
|
39
|
+
readonly marks: readonly NamespaceMark[];
|
|
40
|
+
readonly tombstones: readonly ClearTombstone[];
|
|
41
|
+
readonly operationIds: readonly CommittedOperation[];
|
|
42
|
+
readonly access: readonly NamespaceAccess<T>[];
|
|
43
|
+
}
|
|
44
|
+
interface CommandBase {
|
|
45
|
+
readonly producerId: string;
|
|
46
|
+
readonly operationId: string;
|
|
47
|
+
readonly binding: IdentityBinding;
|
|
48
|
+
readonly baseRevision: number;
|
|
49
|
+
}
|
|
50
|
+
export type LimitsCommand<T = unknown> = CommandBase & (({
|
|
51
|
+
readonly type: 'mark';
|
|
52
|
+
readonly until: number;
|
|
53
|
+
readonly evidenceAt: number;
|
|
54
|
+
readonly mergeLaw: MergeLaw;
|
|
55
|
+
readonly cause?: LimitMarkCause;
|
|
56
|
+
} & MarkTarget) | {
|
|
57
|
+
readonly type: 'clear';
|
|
58
|
+
readonly keys: readonly MarkTarget[];
|
|
59
|
+
/** Absent for explicit user clears; automatic clears carry their evidence time. */
|
|
60
|
+
readonly evidenceAt?: number;
|
|
61
|
+
/** A successful probe clears only this cause, but fences absent/expired keys too. */
|
|
62
|
+
readonly cause?: LimitMarkCause;
|
|
63
|
+
} | {
|
|
64
|
+
readonly type: 'access';
|
|
65
|
+
readonly state: T;
|
|
66
|
+
readonly eligibilityStateUpdatedAt: number;
|
|
67
|
+
});
|
|
68
|
+
export interface LimitsMergeContext {
|
|
69
|
+
readonly now: number;
|
|
70
|
+
/** Current identity bindings, loaded under the same lock as this merge. */
|
|
71
|
+
readonly bindings: readonly IdentityBinding[];
|
|
72
|
+
readonly authorizeEpoch: AuthorizeCredentialEpoch;
|
|
73
|
+
}
|
|
74
|
+
export type LimitsRejection = 'below-watermark' | 'future-revision' | 'wrong-namespace' | 'unknown-account' | 'identity-replaced' | 'credential-epoch' | 'cleared' | 'newer-evidence' | 'merge-law-conflict';
|
|
75
|
+
export interface LimitsCommandOutcome {
|
|
76
|
+
readonly producerId: string;
|
|
77
|
+
readonly operationId: string;
|
|
78
|
+
readonly status: 'committed' | 'duplicate' | 'rejected';
|
|
79
|
+
readonly revision?: number;
|
|
80
|
+
readonly reason?: LimitsRejection;
|
|
81
|
+
}
|
|
82
|
+
export interface LimitsMergeResult<T = unknown> {
|
|
83
|
+
readonly snapshot: LimitsNamespace<T>;
|
|
84
|
+
readonly outcomes: readonly LimitsCommandOutcome[];
|
|
85
|
+
}
|
|
86
|
+
export declare function createLimitsNamespace<T = unknown>(namespace: string, generation: string): LimitsNamespace<T>;
|
|
87
|
+
export declare function timedMarkKeyId(key: TimedMarkKey): string;
|
|
88
|
+
/** Apply tombstones before compacting them; the watermark then fences delayed commands. */
|
|
89
|
+
export declare function pruneLimitsNamespace<T>(snapshot: LimitsNamespace<T>, now: number): LimitsNamespace<T>;
|
|
90
|
+
/** Pure transaction body; load namespace state and identity bindings under one lock. */
|
|
91
|
+
export declare function applyLimitsCommands<T>(initial: LimitsNamespace<T>, commands: readonly LimitsCommand<T>[], context: LimitsMergeContext): LimitsMergeResult<T>;
|
|
92
|
+
export {};
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { validateIdentityFence } from './identity.js';
|
|
2
|
+
import { mergeAccessState, mergeTimedMarkEntries } from './merge-laws.js';
|
|
3
|
+
import { sameAccount } from './request-history.js';
|
|
4
|
+
export const LIMITS_HISTORY_BOUND = 1024;
|
|
5
|
+
export function createLimitsNamespace(namespace, generation) {
|
|
6
|
+
return {
|
|
7
|
+
schemaVersion: 1,
|
|
8
|
+
namespace,
|
|
9
|
+
generation,
|
|
10
|
+
revision: 0,
|
|
11
|
+
lowWatermark: 0,
|
|
12
|
+
marks: [],
|
|
13
|
+
tombstones: [],
|
|
14
|
+
operationIds: [],
|
|
15
|
+
access: [],
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
function accountId(account) {
|
|
19
|
+
return JSON.stringify([
|
|
20
|
+
account.namespace,
|
|
21
|
+
account.accountId,
|
|
22
|
+
account.incarnation,
|
|
23
|
+
]);
|
|
24
|
+
}
|
|
25
|
+
export function timedMarkKeyId(key) {
|
|
26
|
+
const scope = key.scope;
|
|
27
|
+
return JSON.stringify([
|
|
28
|
+
accountId(key.account),
|
|
29
|
+
scope.kind,
|
|
30
|
+
scope.kind === 'model'
|
|
31
|
+
? scope.model
|
|
32
|
+
: scope.kind === 'family'
|
|
33
|
+
? scope.family
|
|
34
|
+
: null,
|
|
35
|
+
key.window,
|
|
36
|
+
]);
|
|
37
|
+
}
|
|
38
|
+
function operationId(op) {
|
|
39
|
+
return JSON.stringify([op.producerId, op.operationId]);
|
|
40
|
+
}
|
|
41
|
+
/** Apply tombstones before compacting them; the watermark then fences delayed commands. */
|
|
42
|
+
export function pruneLimitsNamespace(snapshot, now) {
|
|
43
|
+
const clears = new Map(snapshot.tombstones.map((t) => [timedMarkKeyId(t.key), t.revision]));
|
|
44
|
+
const marks = snapshot.marks.flatMap((mark) => {
|
|
45
|
+
const entries = mergeTimedMarkEntries(mark.mergeLaw, mark.entries, now, clears.get(timedMarkKeyId(mark.key)));
|
|
46
|
+
return entries.length ? [{ ...mark, entries }] : [];
|
|
47
|
+
});
|
|
48
|
+
let lowWatermark = snapshot.lowWatermark;
|
|
49
|
+
const compact = (entries) => {
|
|
50
|
+
const ordered = [...entries].sort((a, b) => a.revision - b.revision);
|
|
51
|
+
const count = Math.max(0, ordered.length - LIMITS_HISTORY_BOUND);
|
|
52
|
+
for (const entry of ordered.slice(0, count)) {
|
|
53
|
+
lowWatermark = Math.max(lowWatermark, entry.revision + 1);
|
|
54
|
+
}
|
|
55
|
+
return ordered.slice(count);
|
|
56
|
+
};
|
|
57
|
+
const tombstones = compact(snapshot.tombstones);
|
|
58
|
+
const operationIds = compact(snapshot.operationIds);
|
|
59
|
+
return {
|
|
60
|
+
...snapshot,
|
|
61
|
+
revision: Math.max(snapshot.revision, lowWatermark),
|
|
62
|
+
marks,
|
|
63
|
+
tombstones,
|
|
64
|
+
operationIds,
|
|
65
|
+
lowWatermark,
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
/** Pure transaction body; load namespace state and identity bindings under one lock. */
|
|
69
|
+
export function applyLimitsCommands(initial, commands, context) {
|
|
70
|
+
let snapshot = pruneLimitsNamespace(initial, context.now);
|
|
71
|
+
const outcomes = [];
|
|
72
|
+
for (const command of commands) {
|
|
73
|
+
const reject = (reason) => {
|
|
74
|
+
outcomes.push({
|
|
75
|
+
producerId: command.producerId,
|
|
76
|
+
operationId: command.operationId,
|
|
77
|
+
status: 'rejected',
|
|
78
|
+
reason,
|
|
79
|
+
});
|
|
80
|
+
};
|
|
81
|
+
if (command.binding.account.namespace !== snapshot.namespace) {
|
|
82
|
+
reject('wrong-namespace');
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
if (command.baseRevision < snapshot.lowWatermark) {
|
|
86
|
+
reject('below-watermark');
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
if (command.baseRevision > snapshot.revision) {
|
|
90
|
+
reject('future-revision');
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
const authoritative = context.bindings.find((b) => sameAccount(b.account, command.binding.account));
|
|
94
|
+
if (!authoritative) {
|
|
95
|
+
reject('unknown-account');
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
const fence = validateIdentityFence(command.binding, authoritative, context.authorizeEpoch);
|
|
99
|
+
if (fence) {
|
|
100
|
+
reject(fence);
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
const duplicate = snapshot.operationIds.find((op) => operationId(op) === operationId(command));
|
|
104
|
+
if (duplicate) {
|
|
105
|
+
outcomes.push({ ...duplicate, status: 'duplicate' });
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
const account = authoritative.account;
|
|
109
|
+
const revision = snapshot.revision + 1;
|
|
110
|
+
let marks = [...snapshot.marks];
|
|
111
|
+
let tombstones = [...snapshot.tombstones];
|
|
112
|
+
let access = [...snapshot.access];
|
|
113
|
+
if (command.type === 'mark') {
|
|
114
|
+
const key = { account, scope: command.scope, window: command.window };
|
|
115
|
+
const id = timedMarkKeyId(key);
|
|
116
|
+
const previous = marks.find((m) => timedMarkKeyId(m.key) === id);
|
|
117
|
+
const clear = tombstones.find((t) => timedMarkKeyId(t.key) === id);
|
|
118
|
+
if (clear && command.baseRevision < clear.revision) {
|
|
119
|
+
reject('cleared');
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
if (previous && previous.mergeLaw !== command.mergeLaw) {
|
|
123
|
+
reject('merge-law-conflict');
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
const entries = mergeTimedMarkEntries(command.mergeLaw, [
|
|
127
|
+
...(previous?.entries ?? []),
|
|
128
|
+
{
|
|
129
|
+
until: command.until,
|
|
130
|
+
evidenceAt: command.evidenceAt,
|
|
131
|
+
baseRevision: command.baseRevision,
|
|
132
|
+
committedRevision: revision,
|
|
133
|
+
...(command.cause === 'rate-limit' ||
|
|
134
|
+
command.cause === 'payment-balance'
|
|
135
|
+
? { cause: command.cause }
|
|
136
|
+
: {}),
|
|
137
|
+
},
|
|
138
|
+
], context.now, clear?.revision);
|
|
139
|
+
marks = marks.filter((m) => timedMarkKeyId(m.key) !== id);
|
|
140
|
+
if (entries.length)
|
|
141
|
+
marks.push({ key, mergeLaw: command.mergeLaw, entries });
|
|
142
|
+
}
|
|
143
|
+
else if (command.type === 'clear') {
|
|
144
|
+
const keys = command.keys
|
|
145
|
+
.map((key) => ({ ...key, account }))
|
|
146
|
+
.filter((key) => command.cause === undefined ||
|
|
147
|
+
!marks.some((mark) => timedMarkKeyId(mark.key) === timedMarkKeyId(key) &&
|
|
148
|
+
mark.entries.some((entry) => entry.cause !== command.cause)));
|
|
149
|
+
const ids = new Set(keys.map(timedMarkKeyId));
|
|
150
|
+
const evidenceAt = command.evidenceAt;
|
|
151
|
+
if (evidenceAt !== undefined &&
|
|
152
|
+
marks.some((m) => ids.has(timedMarkKeyId(m.key)) &&
|
|
153
|
+
m.entries.some((e) => e.evidenceAt > evidenceAt))) {
|
|
154
|
+
reject('newer-evidence');
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
marks = marks.filter((m) => !ids.has(timedMarkKeyId(m.key)));
|
|
158
|
+
tombstones = tombstones.filter((t) => !ids.has(timedMarkKeyId(t.key)));
|
|
159
|
+
// A clear enumerates covered keys, not all scopes on the account.
|
|
160
|
+
for (const key of new Map(keys.map((k) => [timedMarkKeyId(k), k])).values()) {
|
|
161
|
+
tombstones.push({ key, revision });
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
else {
|
|
165
|
+
const incoming = {
|
|
166
|
+
account,
|
|
167
|
+
state: command.state,
|
|
168
|
+
eligibilityStateUpdatedAt: command.eligibilityStateUpdatedAt,
|
|
169
|
+
committedRevision: revision,
|
|
170
|
+
};
|
|
171
|
+
const previous = access.find((a) => sameAccount(a.account, account));
|
|
172
|
+
access = access.filter((a) => !sameAccount(a.account, account));
|
|
173
|
+
access.push(previous ? mergeAccessState(previous, incoming) : incoming);
|
|
174
|
+
}
|
|
175
|
+
const op = {
|
|
176
|
+
producerId: command.producerId,
|
|
177
|
+
operationId: command.operationId,
|
|
178
|
+
revision,
|
|
179
|
+
};
|
|
180
|
+
snapshot = pruneLimitsNamespace({
|
|
181
|
+
...snapshot,
|
|
182
|
+
revision,
|
|
183
|
+
marks,
|
|
184
|
+
tombstones,
|
|
185
|
+
access,
|
|
186
|
+
operationIds: [...snapshot.operationIds, op],
|
|
187
|
+
}, context.now);
|
|
188
|
+
outcomes.push({ ...op, status: 'committed' });
|
|
189
|
+
}
|
|
190
|
+
return { snapshot, outcomes };
|
|
191
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { IdentityBinding } from './identity.js';
|
|
2
|
+
import type { LimitsCommand, LimitsCommandOutcome, LimitsNamespace } from './namespace.js';
|
|
3
|
+
/** Bindings and the namespace snapshot must be read from the same authoritative store view. */
|
|
4
|
+
export interface LimitsPersistenceSnapshot {
|
|
5
|
+
readonly snapshot: LimitsNamespace;
|
|
6
|
+
readonly bindings: readonly IdentityBinding[];
|
|
7
|
+
/** False for a cached or unverifiable view; it cannot restore agreement. */
|
|
8
|
+
readonly authoritative: boolean;
|
|
9
|
+
/** An adapter repaired missing or rewritten namespace state; require a later authoritative read without this flag. */
|
|
10
|
+
readonly degradedAgreement?: boolean;
|
|
11
|
+
}
|
|
12
|
+
export type LimitsPersistenceOutcome = Omit<LimitsCommandOutcome, 'reason'> & {
|
|
13
|
+
readonly reason?: LimitsCommandOutcome['reason'] | 'pool-not-ready';
|
|
14
|
+
};
|
|
15
|
+
export interface LimitsPersistenceCommit extends LimitsPersistenceSnapshot {
|
|
16
|
+
readonly outcomes: readonly LimitsPersistenceOutcome[];
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* One canonical namespace. Validate commands against current account identities
|
|
20
|
+
* and credential epochs, then merge under the existing store lock. Never
|
|
21
|
+
* implement commit by saving the caller's memory snapshot.
|
|
22
|
+
*/
|
|
23
|
+
export interface PersistenceAdapter {
|
|
24
|
+
readonly namespace: string;
|
|
25
|
+
read(previous?: LimitsNamespace): Promise<LimitsPersistenceSnapshot>;
|
|
26
|
+
commit(commands: readonly LimitsCommand[], previous?: LimitsNamespace): Promise<LimitsPersistenceCommit>;
|
|
27
|
+
subscribe?(onChange: () => void): () => void;
|
|
28
|
+
}
|
|
29
|
+
/** A definitive refusal settles commands; an ordinary I/O error leaves them queued. */
|
|
30
|
+
export declare class LimitsPersistenceRefusal extends Error {
|
|
31
|
+
readonly code: 'pool-not-ready' | 'limits-unsupported';
|
|
32
|
+
constructor(code: 'pool-not-ready' | 'limits-unsupported');
|
|
33
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export type PiWaitResult = 'elapsed' | 'aborted';
|
|
2
|
+
export interface PiWaitOptions {
|
|
3
|
+
/** Forward the Pi stream's options.signal so cancellation ends the wait. */
|
|
4
|
+
signal?: AbortSignal;
|
|
5
|
+
setWorkingMessage: (text?: string) => void;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Wait in the caller's Pi stream without sending or selecting an account.
|
|
9
|
+
* After 'elapsed', the caller must re-check that the account remains eligible,
|
|
10
|
+
* its identity has not been replaced, and its credentials are still available
|
|
11
|
+
* for use. When waiting to reuse the same account's prompt cache, also check
|
|
12
|
+
* that the session's activity record still belongs to that account incarnation
|
|
13
|
+
* and that the wait target does not exceed its cache expiry. Only then send.
|
|
14
|
+
* After 'aborted', end the stream without a refusal; abort never rejects.
|
|
15
|
+
*/
|
|
16
|
+
export declare function waitForPi(delayMs: number, options: PiWaitOptions): Promise<PiWaitResult>;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { formatDuration } from './duration.js';
|
|
2
|
+
/**
|
|
3
|
+
* Wait in the caller's Pi stream without sending or selecting an account.
|
|
4
|
+
* After 'elapsed', the caller must re-check that the account remains eligible,
|
|
5
|
+
* its identity has not been replaced, and its credentials are still available
|
|
6
|
+
* for use. When waiting to reuse the same account's prompt cache, also check
|
|
7
|
+
* that the session's activity record still belongs to that account incarnation
|
|
8
|
+
* and that the wait target does not exceed its cache expiry. Only then send.
|
|
9
|
+
* After 'aborted', end the stream without a refusal; abort never rejects.
|
|
10
|
+
*/
|
|
11
|
+
export function waitForPi(delayMs, options) {
|
|
12
|
+
if (!Number.isFinite(delayMs) || delayMs < 0) {
|
|
13
|
+
throw new RangeError('Pi wait requires a finite non-negative delay');
|
|
14
|
+
}
|
|
15
|
+
return new Promise((resolve) => {
|
|
16
|
+
const target = Date.now() + delayMs;
|
|
17
|
+
let timer;
|
|
18
|
+
let settled = false;
|
|
19
|
+
const workingMessage = (text) => {
|
|
20
|
+
// A presentation failure must not strand the stream or mask cancellation.
|
|
21
|
+
try {
|
|
22
|
+
options.setWorkingMessage(text);
|
|
23
|
+
}
|
|
24
|
+
catch { }
|
|
25
|
+
};
|
|
26
|
+
const finish = (result) => {
|
|
27
|
+
if (settled)
|
|
28
|
+
return;
|
|
29
|
+
settled = true;
|
|
30
|
+
clearTimeout(timer);
|
|
31
|
+
options.signal?.removeEventListener('abort', abort);
|
|
32
|
+
workingMessage();
|
|
33
|
+
resolve(result);
|
|
34
|
+
};
|
|
35
|
+
const abort = () => finish('aborted');
|
|
36
|
+
const tick = () => {
|
|
37
|
+
const remaining = target - Date.now();
|
|
38
|
+
if (remaining <= 0)
|
|
39
|
+
return finish('elapsed');
|
|
40
|
+
workingMessage(`Waiting for the account limit to reset · ${formatDuration(remaining)} · Esc to cancel`);
|
|
41
|
+
// The callback may itself cancel the stream. Do not arm a timer afterward.
|
|
42
|
+
if (!settled)
|
|
43
|
+
timer = setTimeout(tick, Math.min(1000, remaining));
|
|
44
|
+
};
|
|
45
|
+
options.signal?.addEventListener('abort', abort, { once: true });
|
|
46
|
+
if (options.signal?.aborted)
|
|
47
|
+
abort();
|
|
48
|
+
else
|
|
49
|
+
tick();
|
|
50
|
+
});
|
|
51
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { PoolStore } from '../store/pool.js';
|
|
2
|
+
import { type LimitsRecoveryLogger } from './envelope-loss.js';
|
|
3
|
+
import { type PersistenceAdapter } from './persistence.js';
|
|
4
|
+
export interface PoolLimitsAdapterOptions {
|
|
5
|
+
/** Canonical provider and store namespace, shared by every process using this pool. */
|
|
6
|
+
readonly namespace: string;
|
|
7
|
+
readonly store: PoolStore;
|
|
8
|
+
readonly now?: () => number;
|
|
9
|
+
/** Receives a warning when a detached envelope repair fails. */
|
|
10
|
+
readonly logger?: LimitsRecoveryLogger;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Activate after initialize/load reports ready. Reads never acquire a write
|
|
14
|
+
* lock; recovery is detached and commits merge under the store locks.
|
|
15
|
+
*/
|
|
16
|
+
export declare function createPoolLimitsAdapter(options: PoolLimitsAdapterOptions): Promise<PersistenceAdapter>;
|