deepline 0.1.79 → 0.1.81
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/README.md +2 -1
- package/dist/cli/index.js +76 -42
- package/dist/cli/index.mjs +76 -42
- package/dist/index.d.mts +9 -1
- package/dist/index.d.ts +9 -1
- package/dist/index.js +13 -10
- package/dist/index.mjs +13 -10
- package/dist/repo/apps/play-runner-workers/src/child-play-await.ts +192 -0
- package/dist/repo/apps/play-runner-workers/src/coordinator-entry.ts +1103 -1617
- package/dist/repo/apps/play-runner-workers/src/dedup-do.ts +506 -654
- package/dist/repo/apps/play-runner-workers/src/entry.ts +1148 -598
- package/dist/repo/apps/play-runner-workers/src/runtime/tool-http-errors.ts +43 -1
- package/dist/repo/apps/play-runner-workers/src/workflow-retry-state.ts +8 -2
- package/dist/repo/sdk/src/client.ts +15 -8
- package/dist/repo/sdk/src/release.ts +2 -2
- package/dist/repo/sdk/src/types.ts +5 -0
- package/dist/repo/shared_libs/play-runtime/governor/coordinator-rate-state-backend.ts +231 -0
- package/dist/repo/shared_libs/play-runtime/governor/governor.ts +376 -0
- package/dist/repo/shared_libs/play-runtime/governor/policy.ts +179 -0
- package/dist/repo/shared_libs/play-runtime/governor/rate-state-backend.ts +87 -0
- package/dist/repo/shared_libs/play-runtime/run-failure.ts +12 -0
- package/dist/repo/shared_libs/play-runtime/scheduler-backend.ts +24 -0
- package/dist/repo/shared_libs/play-runtime/submit-limits.ts +35 -0
- package/dist/repo/shared_libs/plays/bundling/index.ts +4 -12
- package/dist/repo/shared_libs/plays/bundling/limits.ts +29 -0
- package/dist/repo/shared_libs/plays/static-pipeline.ts +56 -3
- package/dist/repo/shared_libs/temporal/constants.ts +38 -0
- package/package.json +1 -1
- package/dist/repo/shared_libs/play-runtime/tool-batch-executor.ts +0 -149
|
@@ -139,6 +139,43 @@ function formatInsufficientCreditsMessage(input: {
|
|
|
139
139
|
return `Workspace balance ${balance} < required ${required} for ${operation}.${addSuffix}`;
|
|
140
140
|
}
|
|
141
141
|
|
|
142
|
+
function formatPublicToolErrorPayload(input: {
|
|
143
|
+
parsed: Record<string, unknown> | null;
|
|
144
|
+
bodyText: string;
|
|
145
|
+
}): string {
|
|
146
|
+
if (!input.parsed) {
|
|
147
|
+
return input.bodyText.slice(0, 500);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const selected: Record<string, unknown> = {};
|
|
151
|
+
for (const key of [
|
|
152
|
+
'error',
|
|
153
|
+
'message',
|
|
154
|
+
'code',
|
|
155
|
+
'failure_origin',
|
|
156
|
+
'error_category',
|
|
157
|
+
'failure_description',
|
|
158
|
+
'operator_hint',
|
|
159
|
+
'failure_hint',
|
|
160
|
+
'details',
|
|
161
|
+
'provider',
|
|
162
|
+
'operation',
|
|
163
|
+
'request_id',
|
|
164
|
+
'requestId',
|
|
165
|
+
'credential_source',
|
|
166
|
+
'credential_owner',
|
|
167
|
+
]) {
|
|
168
|
+
const value = input.parsed[key];
|
|
169
|
+
if (typeof value === 'string' && value.trim()) {
|
|
170
|
+
selected[key] = value;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
return JSON.stringify(
|
|
175
|
+
Object.keys(selected).length > 0 ? selected : input.parsed,
|
|
176
|
+
).slice(0, 1_500);
|
|
177
|
+
}
|
|
178
|
+
|
|
142
179
|
export function normalizeToolHttpErrorMessage(input: {
|
|
143
180
|
toolId: string;
|
|
144
181
|
status: number;
|
|
@@ -183,7 +220,12 @@ export function normalizeToolHttpErrorMessage(input: {
|
|
|
183
220
|
);
|
|
184
221
|
}
|
|
185
222
|
return new ToolHttpError(
|
|
186
|
-
`tool ${input.toolId} ${input.status} attempt ${input.attempt}/${input.maxAttempts}: ${
|
|
223
|
+
`tool ${input.toolId} ${input.status} attempt ${input.attempt}/${input.maxAttempts}: ${formatPublicToolErrorPayload(
|
|
224
|
+
{
|
|
225
|
+
parsed,
|
|
226
|
+
bodyText: input.bodyText,
|
|
227
|
+
},
|
|
228
|
+
)}`,
|
|
187
229
|
billing,
|
|
188
230
|
);
|
|
189
231
|
}
|
|
@@ -6,10 +6,16 @@ import type {
|
|
|
6
6
|
PlayRuntimeManifestMap,
|
|
7
7
|
} from '../../../shared_libs/plays/compiler-manifest';
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
import {
|
|
10
|
+
PLAY_SUBMIT_INPUT_INLINE_MAX_BYTES,
|
|
11
|
+
PLAY_SUBMIT_INPUT_MAX_BYTES,
|
|
12
|
+
} from '../../../shared_libs/play-runtime/submit-limits';
|
|
13
|
+
|
|
14
|
+
export const WORKFLOW_RETRY_STATE_TARGET_BYTES =
|
|
15
|
+
PLAY_SUBMIT_INPUT_INLINE_MAX_BYTES;
|
|
10
16
|
export const WORKFLOW_RETRY_PARAMS_EXTERNALIZE_AFTER_BYTES =
|
|
11
17
|
WORKFLOW_RETRY_STATE_TARGET_BYTES;
|
|
12
|
-
export const WORKFLOW_RETRY_PARAMS_MAX_BYTES =
|
|
18
|
+
export const WORKFLOW_RETRY_PARAMS_MAX_BYTES = PLAY_SUBMIT_INPUT_MAX_BYTES;
|
|
13
19
|
|
|
14
20
|
export type WorkflowRetryParamsRef = {
|
|
15
21
|
storageKind: 'r2';
|
|
@@ -642,6 +642,7 @@ export class DeeplineClient {
|
|
|
642
642
|
categories?: string;
|
|
643
643
|
grep?: string;
|
|
644
644
|
grepMode?: 'all' | 'any' | 'phrase';
|
|
645
|
+
compact?: boolean;
|
|
645
646
|
}): Promise<ToolDefinition[]> {
|
|
646
647
|
const params = new URLSearchParams();
|
|
647
648
|
if (options?.categories?.trim()) {
|
|
@@ -651,6 +652,7 @@ export class DeeplineClient {
|
|
|
651
652
|
params.set('grep', options.grep.trim());
|
|
652
653
|
params.set('grep_mode', options.grepMode ?? 'all');
|
|
653
654
|
}
|
|
655
|
+
params.set('compact', options?.compact === true ? 'true' : 'false');
|
|
654
656
|
const suffix = params.toString() ? `?${params.toString()}` : '';
|
|
655
657
|
const res = await this.http.get<{ tools: ToolDefinition[] }>(
|
|
656
658
|
`/api/v2/tools${suffix}`,
|
|
@@ -1295,7 +1297,7 @@ export class DeeplineClient {
|
|
|
1295
1297
|
}
|
|
1296
1298
|
const query = params.size > 0 ? `?${params.toString()}` : '';
|
|
1297
1299
|
const response = await this.http.get<Record<string, unknown>>(
|
|
1298
|
-
`/api/v2/
|
|
1300
|
+
`/api/v2/runs/${encodeURIComponent(workflowId)}${query}`,
|
|
1299
1301
|
);
|
|
1300
1302
|
return normalizePlayStatus(response);
|
|
1301
1303
|
}
|
|
@@ -1318,10 +1320,10 @@ export class DeeplineClient {
|
|
|
1318
1320
|
options?.lastEventId && options.lastEventId.trim()
|
|
1319
1321
|
? { 'Last-Event-ID': options.lastEventId.trim() }
|
|
1320
1322
|
: undefined;
|
|
1321
|
-
const params = new URLSearchParams(
|
|
1323
|
+
const params = new URLSearchParams();
|
|
1322
1324
|
params.set('mode', options?.mode ?? 'cli');
|
|
1323
1325
|
for await (const event of this.http.streamSse<PlayLiveEvent>(
|
|
1324
|
-
`/api/v2/
|
|
1326
|
+
`/api/v2/runs/${encodeURIComponent(workflowId)}/tail?${params.toString()}`,
|
|
1325
1327
|
{ signal: options?.signal, headers },
|
|
1326
1328
|
)) {
|
|
1327
1329
|
if (event.scope === 'play') {
|
|
@@ -1344,7 +1346,7 @@ export class DeeplineClient {
|
|
|
1344
1346
|
*/
|
|
1345
1347
|
async cancelPlay(workflowId: string): Promise<void> {
|
|
1346
1348
|
await this.http.request(
|
|
1347
|
-
`/api/v2/
|
|
1349
|
+
`/api/v2/runs/${encodeURIComponent(workflowId)}/stop`,
|
|
1348
1350
|
{ method: 'POST' },
|
|
1349
1351
|
);
|
|
1350
1352
|
}
|
|
@@ -1360,7 +1362,7 @@ export class DeeplineClient {
|
|
|
1360
1362
|
options?: { reason?: string },
|
|
1361
1363
|
): Promise<StopPlayRunResult> {
|
|
1362
1364
|
return this.http.post<StopPlayRunResult>(
|
|
1363
|
-
`/api/v2/
|
|
1365
|
+
`/api/v2/runs/${encodeURIComponent(workflowId)}/stop`,
|
|
1364
1366
|
options?.reason ? { reason: options.reason } : {},
|
|
1365
1367
|
);
|
|
1366
1368
|
}
|
|
@@ -1433,6 +1435,7 @@ export class DeeplineClient {
|
|
|
1433
1435
|
if (status) {
|
|
1434
1436
|
params.set('status', status);
|
|
1435
1437
|
}
|
|
1438
|
+
params.set('compact', 'true');
|
|
1436
1439
|
const response = await this.http.get<{ runs: PlayRunListItem[] }>(
|
|
1437
1440
|
`/api/v2/runs?${params.toString()}`,
|
|
1438
1441
|
);
|
|
@@ -1490,7 +1493,7 @@ export class DeeplineClient {
|
|
|
1490
1493
|
runId: string,
|
|
1491
1494
|
options?: RunsLogsOptions,
|
|
1492
1495
|
): Promise<RunsLogsResult> {
|
|
1493
|
-
const status = await this.getRunStatus(runId);
|
|
1496
|
+
const status = await this.getRunStatus(runId, { full: true });
|
|
1494
1497
|
const logs = status.progress?.logs ?? [];
|
|
1495
1498
|
const limit =
|
|
1496
1499
|
typeof options?.limit === 'number' && Number.isFinite(options.limit)
|
|
@@ -1636,10 +1639,14 @@ export class DeeplineClient {
|
|
|
1636
1639
|
* @param name - Play name
|
|
1637
1640
|
* @returns Version list (newest first)
|
|
1638
1641
|
*/
|
|
1639
|
-
async listPlayVersions(
|
|
1642
|
+
async listPlayVersions(
|
|
1643
|
+
name: string,
|
|
1644
|
+
options?: { full?: boolean },
|
|
1645
|
+
): Promise<PlayRevisionSummary[]> {
|
|
1640
1646
|
const encodedName = encodeURIComponent(name);
|
|
1647
|
+
const suffix = options?.full ? '?full=true' : '';
|
|
1641
1648
|
const response = await this.http.get<{ versions: PlayRevisionSummary[] }>(
|
|
1642
|
-
`/api/v2/plays/${encodedName}/versions`,
|
|
1649
|
+
`/api/v2/plays/${encodedName}/versions${suffix}`,
|
|
1643
1650
|
);
|
|
1644
1651
|
return response.versions ?? [];
|
|
1645
1652
|
}
|
|
@@ -50,10 +50,10 @@ export type SdkRelease = {
|
|
|
50
50
|
};
|
|
51
51
|
|
|
52
52
|
export const SDK_RELEASE = {
|
|
53
|
-
version: '0.1.
|
|
53
|
+
version: '0.1.81',
|
|
54
54
|
apiContract: '2026-06-dataset-column-cell-stale-hard-cutover',
|
|
55
55
|
supportPolicy: {
|
|
56
|
-
latest: '0.1.
|
|
56
|
+
latest: '0.1.81',
|
|
57
57
|
minimumSupported: '0.1.53',
|
|
58
58
|
deprecatedBelow: '0.1.53',
|
|
59
59
|
},
|
|
@@ -131,6 +131,10 @@ export interface ToolDefinition {
|
|
|
131
131
|
operationId?: string;
|
|
132
132
|
/** Alternative names that resolve to this tool. */
|
|
133
133
|
operationAliases?: string[];
|
|
134
|
+
/** Whether detailed input schema is available from `tools describe`. */
|
|
135
|
+
hasInputSchema?: boolean;
|
|
136
|
+
/** Whether detailed output schema is available from `tools describe`. */
|
|
137
|
+
hasOutputSchema?: boolean;
|
|
134
138
|
/** JSON Schema describing the tool's input parameters. */
|
|
135
139
|
inputSchema?: Record<string, unknown>;
|
|
136
140
|
/** JSON Schema describing the tool's output shape. */
|
|
@@ -661,6 +665,7 @@ export interface PlayListItem {
|
|
|
661
665
|
currentPublishedVersion?: number | null;
|
|
662
666
|
tableNamespace?: string | null;
|
|
663
667
|
isDraftDirty?: boolean;
|
|
668
|
+
hasInputSchema?: boolean;
|
|
664
669
|
inputSchema?: Record<string, unknown> | null;
|
|
665
670
|
outputSchema?: Record<string, unknown> | null;
|
|
666
671
|
staticPipeline?: unknown;
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import {
|
|
2
|
+
noopPacingPermit,
|
|
3
|
+
type PacingPermit,
|
|
4
|
+
type PacingRule,
|
|
5
|
+
type RateStateBackend,
|
|
6
|
+
} from './rate-state-backend';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Distributed Rate State Backend for the `esm_workers` substrate.
|
|
10
|
+
*
|
|
11
|
+
* On Cloudflare a single play run fans child plays and map rows across many
|
|
12
|
+
* V8 isolates, so the per-`(org, provider)` request window cannot be
|
|
13
|
+
* process-local — each isolate would otherwise pace against its own private
|
|
14
|
+
* counter and the org could blow past a provider's real limit by the number of
|
|
15
|
+
* isolates. This backend makes the window GLOBAL by RPCing the coordinator
|
|
16
|
+
* Durable Object addressed per bucket (`idFromName('rate:<orgId>:<provider>')`).
|
|
17
|
+
* The DO is single-threaded, so it runs the same sliding-window algorithm as
|
|
18
|
+
* `InMemoryRateStateBackend` correctly for all isolates at once.
|
|
19
|
+
*
|
|
20
|
+
* Latency: a full DO round-trip on every outbound tool call would tax the
|
|
21
|
+
* hello-world latency baseline. Instead the backend LEASES SMALL PERMIT BLOCKS:
|
|
22
|
+
* one `/rate-acquire` round-trip debits up to {@link LEASE_BLOCK_SIZE} permits
|
|
23
|
+
* from the global window, and subsequent acquires draw from the local block
|
|
24
|
+
* until it is exhausted or its short TTL expires. This bounds round-trips to
|
|
25
|
+
* roughly `calls / LEASE_BLOCK_SIZE` while keeping over-issuance bounded by one
|
|
26
|
+
* block per isolate per window.
|
|
27
|
+
*
|
|
28
|
+
* Fail-open: if the coordinator is unreachable the backend logs once and
|
|
29
|
+
* PROCEEDS (grants the permit) rather than stalling the run, matching the
|
|
30
|
+
* semantics of `src/lib/redis/customer-rate-limiter.ts` — a degraded limiter
|
|
31
|
+
* must never become an availability outage. The Governor's global
|
|
32
|
+
* tool-concurrency semaphore remains the unconditional backstop.
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
/** Permits leased per round-trip. Tuned to amortize the DO hop, not to batch. */
|
|
36
|
+
const LEASE_BLOCK_SIZE = 16;
|
|
37
|
+
/**
|
|
38
|
+
* Max age of a leased block. A leased permit debited the global window already,
|
|
39
|
+
* but if it is held past roughly one window it could let an isolate run ahead
|
|
40
|
+
* of a rolled-over window. Discarding stale blocks bounds that to sub-window.
|
|
41
|
+
*/
|
|
42
|
+
const LEASE_BLOCK_TTL_MS = 250;
|
|
43
|
+
/** Cap one coordinator-provided sleep hint; total wait is bounded by run timeout. */
|
|
44
|
+
const MAX_ACQUIRE_SLEEP_MS = 5_000;
|
|
45
|
+
|
|
46
|
+
export interface CoordinatorRatePort {
|
|
47
|
+
/**
|
|
48
|
+
* Lease up to `requested` request-window permits for `bucketId` under all
|
|
49
|
+
* `rules` from the coordinator DO. Returns how many were `granted` (0 when the
|
|
50
|
+
* window is saturated) and a `waitMs` hint before retrying.
|
|
51
|
+
*/
|
|
52
|
+
rateAcquire(input: {
|
|
53
|
+
bucketId: string;
|
|
54
|
+
rules: PacingRule[];
|
|
55
|
+
requested: number;
|
|
56
|
+
}): Promise<{ granted: number; waitMs: number }>;
|
|
57
|
+
/** Feed a Retry-After cooldown back into the global bucket. */
|
|
58
|
+
ratePenalize(input: { bucketId: string; cooldownMs: number }): Promise<void>;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
interface LeasedBlock {
|
|
62
|
+
remaining: number;
|
|
63
|
+
expiresAt: number;
|
|
64
|
+
/** Stable signature of the rules this block was leased under. */
|
|
65
|
+
rulesKey: string;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
interface Options {
|
|
69
|
+
now?: () => number;
|
|
70
|
+
sleep?: (ms: number) => Promise<void>;
|
|
71
|
+
onDegraded?: (info: { bucketId: string; error: string }) => void;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function rulesSignature(rules: readonly PacingRule[]): string {
|
|
75
|
+
return [...rules]
|
|
76
|
+
.map(
|
|
77
|
+
(rule) =>
|
|
78
|
+
`${rule.ruleId}:${rule.requestsPerWindow}:${rule.windowMs}:${rule.maxConcurrency ?? ''}`,
|
|
79
|
+
)
|
|
80
|
+
.sort()
|
|
81
|
+
.join('|');
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export class CoordinatorRateStateBackend implements RateStateBackend {
|
|
85
|
+
private readonly port: CoordinatorRatePort;
|
|
86
|
+
private readonly now: () => number;
|
|
87
|
+
private readonly sleep: (ms: number) => Promise<void>;
|
|
88
|
+
private readonly onDegraded: (info: {
|
|
89
|
+
bucketId: string;
|
|
90
|
+
error: string;
|
|
91
|
+
}) => void;
|
|
92
|
+
private readonly blocks = new Map<string, LeasedBlock>();
|
|
93
|
+
private degradedLogged = false;
|
|
94
|
+
|
|
95
|
+
constructor(port: CoordinatorRatePort, options: Options = {}) {
|
|
96
|
+
this.port = port;
|
|
97
|
+
this.now = options.now ?? (() => Date.now());
|
|
98
|
+
this.sleep =
|
|
99
|
+
options.sleep ??
|
|
100
|
+
((ms: number) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
101
|
+
this.onDegraded =
|
|
102
|
+
options.onDegraded ??
|
|
103
|
+
((info) => {
|
|
104
|
+
if (this.degradedLogged) return;
|
|
105
|
+
this.degradedLogged = true;
|
|
106
|
+
console.warn('[coordinator-rate-state] acquire failed open', info);
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async acquire(input: {
|
|
111
|
+
bucketId: string;
|
|
112
|
+
rules: readonly PacingRule[];
|
|
113
|
+
signal?: AbortSignal;
|
|
114
|
+
}): Promise<PacingPermit> {
|
|
115
|
+
const { bucketId, rules, signal } = input;
|
|
116
|
+
if (rules.length === 0) {
|
|
117
|
+
return noopPacingPermit();
|
|
118
|
+
}
|
|
119
|
+
const rulesKey = rulesSignature(rules);
|
|
120
|
+
|
|
121
|
+
// Draw from a still-valid local block first — no round-trip.
|
|
122
|
+
if (this.drawFromBlock(bucketId, rulesKey)) {
|
|
123
|
+
return noopPacingPermit();
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
while (true) {
|
|
127
|
+
if (signal?.aborted) {
|
|
128
|
+
throw signal.reason instanceof Error
|
|
129
|
+
? signal.reason
|
|
130
|
+
: new Error('Rate-state acquire aborted.');
|
|
131
|
+
}
|
|
132
|
+
let response: { granted: number; waitMs: number };
|
|
133
|
+
try {
|
|
134
|
+
response = await this.port.rateAcquire({
|
|
135
|
+
bucketId,
|
|
136
|
+
rules: [...rules],
|
|
137
|
+
requested: LEASE_BLOCK_SIZE,
|
|
138
|
+
});
|
|
139
|
+
} catch (error) {
|
|
140
|
+
// Fail open: a degraded coordinator must not stall the run.
|
|
141
|
+
this.onDegraded({
|
|
142
|
+
bucketId,
|
|
143
|
+
error: error instanceof Error ? error.message : String(error),
|
|
144
|
+
});
|
|
145
|
+
return noopPacingPermit();
|
|
146
|
+
}
|
|
147
|
+
if (response.granted > 0) {
|
|
148
|
+
// Consume one for this call; cache the rest as a short-lived block.
|
|
149
|
+
const remaining = response.granted - 1;
|
|
150
|
+
if (remaining > 0) {
|
|
151
|
+
this.mergeBlock(bucketId, remaining, rulesKey);
|
|
152
|
+
}
|
|
153
|
+
return noopPacingPermit();
|
|
154
|
+
}
|
|
155
|
+
// Window saturated. Park for the hint, then re-acquire. This is not a
|
|
156
|
+
// degraded coordinator: the limiter answered and said "wait", so granting
|
|
157
|
+
// here would violate the provider request-rate contract. Overall wait is
|
|
158
|
+
// bounded by the play runtime deadline / abort signal.
|
|
159
|
+
const waitMs = Math.max(
|
|
160
|
+
1,
|
|
161
|
+
Math.min(response.waitMs, MAX_ACQUIRE_SLEEP_MS),
|
|
162
|
+
);
|
|
163
|
+
await this.sleep(waitMs);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
penalize(input: { bucketId: string; cooldownMs: number }): void {
|
|
168
|
+
if (input.cooldownMs <= 0) return;
|
|
169
|
+
// Drop any cached block for this bucket so the cooldown takes effect on the
|
|
170
|
+
// very next acquire instead of being masked by already-leased permits.
|
|
171
|
+
this.blocks.delete(input.bucketId);
|
|
172
|
+
void this.port
|
|
173
|
+
.ratePenalize({
|
|
174
|
+
bucketId: input.bucketId,
|
|
175
|
+
cooldownMs: input.cooldownMs,
|
|
176
|
+
})
|
|
177
|
+
.catch((error) => {
|
|
178
|
+
this.onDegraded({
|
|
179
|
+
bucketId: input.bucketId,
|
|
180
|
+
error: error instanceof Error ? error.message : String(error),
|
|
181
|
+
});
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Add freshly-leased permits to the bucket's block instead of overwriting it.
|
|
187
|
+
* Two concurrent acquires can both miss the local block and both round-trip;
|
|
188
|
+
* each debited the global window, so the DO already issued both blocks'
|
|
189
|
+
* permits. Overwriting would drop one set — under-issuance that wastes window
|
|
190
|
+
* capacity and over-throttles. Merging preserves every debited permit:
|
|
191
|
+
* - same rulesKey + still valid → sum remaining, keep the earlier expiry so
|
|
192
|
+
* the merged block never outlives the older lease's sub-window bound.
|
|
193
|
+
* - missing / stale / different rules → start fresh from this lease.
|
|
194
|
+
*/
|
|
195
|
+
private mergeBlock(
|
|
196
|
+
bucketId: string,
|
|
197
|
+
remaining: number,
|
|
198
|
+
rulesKey: string,
|
|
199
|
+
): void {
|
|
200
|
+
const freshExpiresAt = this.now() + LEASE_BLOCK_TTL_MS;
|
|
201
|
+
const existing = this.blocks.get(bucketId);
|
|
202
|
+
if (
|
|
203
|
+
existing &&
|
|
204
|
+
existing.rulesKey === rulesKey &&
|
|
205
|
+
existing.expiresAt > this.now()
|
|
206
|
+
) {
|
|
207
|
+
existing.remaining += remaining;
|
|
208
|
+
existing.expiresAt = Math.min(existing.expiresAt, freshExpiresAt);
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
this.blocks.set(bucketId, {
|
|
212
|
+
remaining,
|
|
213
|
+
expiresAt: freshExpiresAt,
|
|
214
|
+
rulesKey,
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
private drawFromBlock(bucketId: string, rulesKey: string): boolean {
|
|
219
|
+
const block = this.blocks.get(bucketId);
|
|
220
|
+
if (!block) return false;
|
|
221
|
+
if (block.rulesKey !== rulesKey || block.expiresAt <= this.now()) {
|
|
222
|
+
this.blocks.delete(bucketId);
|
|
223
|
+
return false;
|
|
224
|
+
}
|
|
225
|
+
block.remaining -= 1;
|
|
226
|
+
if (block.remaining <= 0) {
|
|
227
|
+
this.blocks.delete(bucketId);
|
|
228
|
+
}
|
|
229
|
+
return true;
|
|
230
|
+
}
|
|
231
|
+
}
|