main
1// Bounds on everything an untrusted server (or a careless caller) can size. Every allocation driven by
2// wire data checks one of these before the buffer exists. A caller's record is parsed once, where it enters
3// (parseLimits: a transport, an operation, a public codec): a key it gives must be a finite non-negative number, a key
4// it leaves out is the default. Past that line the record is a total CheckedLimits and every read is a property read:
5// a missing value compared with `>` is false in JS, so no unchecked record may reach a check.
6import type { ErrorOf } from './errors.js';
7import { plyError } from './errors.js';
8import type { Result } from './result.js';
9import { err, getOrElse, ok } from './result.js';
10import type { Input } from './absent.js';
11import { fromNullish, isMissing, withDefaults } from './absent.js';
13/* oxlint-disable no-magic-numbers -- these are the cap definitions; parsers import the names */
15const KIB = 1024;
16const MIB = KIB * KIB;
18/**
19 * Each side of a line merge. git's MAX_XDIFF_SIZE (xdiff/xdiff.h) is ~1 GiB; a Worker isolate is not.
20 * 8 MiB is large enough for a source file and small enough to reject a blob the merger cannot hold twice.
21 */
22export const LIMIT_MERGE_BLOB: number = 8 * MIB;
23/**
24 * The line merge's work budget: primitive diff steps for one merged file, counted across everything that merge runs
25 * (both histogram diffs, the classic-diff fallbacks, group compaction, conflict refinement). git's histogram diff
26 * rescans the rest of the region on every split (xhistogram.c find_lcs), so a file whose splits peel a line or two at
27 * a time costs O(n²) however short its hash chains are; the byte cap does not bound that. The budget does, whatever
28 * the content: a merge that would pass it is refused as `too large to merge`, never guessed.
29 * A step is ~6-7 ns of CPU on the histogram path and ~12-15 ns on the classic fallback (measured: linemerge.ts,
30 * classicDiff), so the CPU bound is the fallback's rate times the budget.
31 * Sized at 7cfa0b7, on a 16-core machine running about 25 other test processes (process.cpuUsage medians; the cases
32 * are pinned in test/linemerge.test.js, which asserts the counts, not the times):
33 * - Default 2^32: what git itself merges cleanly in about 5 s is merged, on both shapes measured. git merge-file
34 * (2.50) takes 3.4 s on 40,000 lines of swapped pairs (0.75 n² = 1.2e9 steps here) and 7.9 s on 60,000 (2.7e9),
35 * about 2.9 ns a step, so its 5 s is ~1.7e9 steps there; 2^30 refused the first of those. A bulk edit costs git
36 * less per step (about 1.7 ns), so its 5 s is more steps: 130,000 lines with every 10th changed is 4.1 s in git and
37 * 2,451,130,516 steps here, 143,000 lines 5.0 s and 2,965,798,566, so ~3e9; 2^31, sized from the swaps alone,
38 * refused the first of those (measured at 1b9f578). It is also 11.9 times the 361,702,266 steps of the 70,000-line
39 * / 3,500-hunk bulk edit (1.75 s here, 0.76 s in git). A refusal at this budget costs ~25 s of CPU (131,074 lines
40 * of swapped pairs: 24,920 ms, one run, 5.8 ns a step).
41 * - Worker 2^26: the worst inputs found under WORKER_LIMITS.maxMergeBlobBytes are refused in 1.04 s (250,000 swapped
42 * lines, histogram), 1.40 s (1,048,576 random a/b/c lines, classic fallback) and 1.74 s (60 copies each of 8,733
43 * lines, shuffled); at 2^27 the first two took 1.45 s and 1.48 s and the third ran to its end in 2.27 s. The budget
44 * does not cover splitting the three sides into records (0.43 s for 3 x 250,000 lines, 0.89 s for 3 x 1,048,576),
45 * so a budget of 0 still costs 0.55 s and 1.06 s on those inputs: the rest of the second is maxMergeBlobBytes'.
46 */
47export const LIMIT_MERGE_WORK: number = 2 ** 32;
48export const LIMIT_MERGE_WORK_WORKER: number = 2 ** 26;
49/**
50 * Inflated size of any single non-streamed object (trees, commits, tags, metadata blobs).
51 * gitformat-pack does not cap this; 64 MiB is one object a Worker-sized heap can still inflate and hash.
52 */
53export const LIMIT_OBJECT: number = 64 * MIB;
54/** Commits and trees kept from an over-wide blob:none pack. Half an object, so a harvest cannot hide a second full one. */
55export const LIMIT_HARVEST: number = LIMIT_OBJECT / 2;
56/**
57 * Band-1 (pack) bytes one fetch may deliver, buffered or streamed, and band-2 bytes beside them; also one advertisement,
58 * one receive-pack report. Two objects, on the wire. A streamed blob holds none of it, but its ingress has to end
59 * somewhere a caller controls: 128 MiB is above GitHub's 100 MiB file cap, so any blob GitHub stores streams under it.
60 */
61export const LIMIT_PACK_WIRE: number = LIMIT_OBJECT * 2;
62/**
63 * Blob bytes one pushTree may hold before it builds the tree. The same ceiling as the pack on the wire, so one
64 * maximum object still fits and three 48 MiB blobs (144 MiB, which peaked near 440 MB RSS) do not.
65 */
66export const LIMIT_PUSH_BYTES: number = LIMIT_PACK_WIRE;
67/** Result size a delta header may claim (gitformat-pack "Deltified representation"). Same ceiling as one object. */
68export const LIMIT_DELTA_RESULT: number = LIMIT_OBJECT;
69/**
70 * Delta chain depth. pack-objects' default window depth is 50; 64 is past that and still a fixed walk.
71 * resolvePack counts deltas from the full (or external) base, so no resolved object is more than 64 deltas deep in
72 * either pack order (test/delta-bound.test.js).
73 */
74export const LIMIT_DELTA_CHAIN = 64;
75/**
76 * How many maximum-sized objects a buffered pack may inflate at once, including delta results resolvePack
77 * allocates on top of the inflated instructions. Four covers a merge-base triple (base, ours, theirs) plus
78 * the commit that names them. Issue #9's 6 × 64 MiB pack is 384 MiB and must fail before that resident set exists.
79 * Each object also pays LIMIT_OBJECT_OVERHEAD (below), so the four are three maximum objects and a small one.
80 */
81export const LIMIT_INFLATED_OBJECTS = 4;
82export const LIMIT_INFLATED_TOTAL: number = LIMIT_OBJECT * LIMIT_INFLATED_OBJECTS;
83/**
84 * Objects in one buffered pack. gitformat-pack stores the count as a uint32, which is not a memory or CPU bound.
85 * 100_000 is above a blob:none listing of a large repository's trees (the kernel is on the order of 10^4 trees)
86 * and is the ceiling for resolvePack's work: each entry is visited at most three times in any pack order (a delta is
87 * filed under its base and resolved when the base lands), a REF_DELTA base is one Map lookup, never a scan or a pass.
88 */
89export const LIMIT_PACK_OBJECTS = 100_000;
90/**
91 * ls-refs lines, and the rebase chain walked from them. rebaseBranch walks the branch as deep as this chain bound
92 * needs (maxRebaseCommits + 2, or LIMIT_MERGE_DEPTH where that is deeper) and `onto` to LIMIT_MERGE_DEPTH (rebaseBaseOf, src/rebase.ts): each walk has its limit.
93 */
94export const LIMIT_REFS = 10_000;
95export const LIMIT_REBASE_COMMITS: number = LIMIT_REFS;
96/** shallow, ack, and any other v2 section lines per fetch. */
97export const LIMIT_SECTION_LINES = 1000;
98/**
99 * Entries parsed from one tree. A max-sized tree of minimum entries (git's "too-short tree object" floor)
100 * is millions of names; this stops before that array exists.
101 */
102export const LIMIT_TREE_ENTRIES = 200_000;
103/** PATH_MAX for one component, and a depth no real worktree uses. */
104export const LIMIT_PATH_DEPTH = 128;
105export const LIMIT_PATH_COMPONENT = 4096;
106/**
107 * Merge-base doubling search. The walk starts at 8 and doubles; 1024 is eight steps, and the pack byte cap
108 * fires on a wide blob:none window before a deeper search would.
109 */
110export const LIMIT_MERGE_DEPTH = 1024;
111/**
112 * report-status pkt-lines buffered from receive-pack: one unpack line, one status per ref, plus
113 * report-status-v2 option lines. The ref cap is the same order. push reads at least as many lines as git sends for
114 * the commands pushed (1 + N, or 1 + 5N with report-status-v2; push.ts reportLineCap), so a push of N <= maxRefs
115 * commands never trips this cap; a larger value admits a proc-receive hook that reports one command as several refs.
116 */
117export const LIMIT_REPORT_LINES: number = LIMIT_REFS;
118/**
119 * The bytes kept of one report-status reason: the reason of "ng <ref> <reason>", or the status of "unpack <status>".
120 * git's own are under 50 bytes and the longest host reason observed is 86 (Cloudflare Artifacts), so 4 KiB is room for
121 * a host that explains itself. A longer reason is cut here and its ref keeps its status (push.ts cutReportLine): the cap
122 * bounds what is held (one reason a command), never the outcome. Never below git's own longest (push.ts reportReasonCap).
123 */
124export const LIMIT_REPORT_REASON_BYTES = 4096;
125/** The same for a 128 MiB isolate: 10 000 refused refs hold 10 MiB of reasons (and as much again decoded), not 40 MiB. */
126export const LIMIT_REPORT_REASON_BYTES_WORKER = 1024;
127/**
128 * Band-2 bytes (progress, hook output) decoded from one receive-pack answer. A frame past it is dropped unread and the
129 * report is still read (the answer as a whole is held to maxPackBytes). Only a 4 KiB tail is ever kept, so this bounds
130 * the decoding, not the memory: git's progress is a few KiB and a talkative hook some hundreds; 8 MiB is past both.
131 */
132export const LIMIT_REPORT_PROGRESS_BYTES = 8_388_608;
133/**
134 * Parents on one commit. An octopus is a handful; a commit that lists more parents than the ref cap is not
135 * a history bestBases will walk.
136 */
137export const LIMIT_COMMIT_PARENTS: number = LIMIT_REFS;
138/**
139 * Decoded ls-refs payload bytes. maxRefs lines at the pkt-line maximum (gitprotocol-common: 65520) is
140 * hundreds of MiB; the buffered-response cap we already accept for one pack is the ceiling.
141 */
142export const LIMIT_LS_REFS_BYTES: number = LIMIT_PACK_WIRE;
143/**
144 * The whole HTTP exchange, opt-in: 0 (the default) is no total cap, so a long healthy stream is never cut for its
145 * duration alone (#255). A positive value bounds the exchange end to end, body included, as before #255. Stalls are
146 * bounded by the two timers below whatever this is (src/deadline.ts).
147 */
148export const LIMIT_REQUEST_TIMEOUT_MS = 0;
149/** From the request (or the end of a streamed upload) to the response headers. 0 turns it off. */
150export const LIMIT_FIRST_BYTE_TIMEOUT_MS = 60_000;
151/** The longest gap with no progress: no upload chunk pulled, no response body chunk read. 0 turns it off. */
152export const LIMIT_IDLE_TIMEOUT_MS = 60_000;
153/** How many idle limits a consumer may hold one chunk before the exchange is cut (#273). */
154const HELD_PER_IDLE = 4;
155/**
156 * The longest the consumer may hold a chunk (from taking it to asking for the next) before the exchange is cut as
157 * `timeout` naming heldTimeoutMs (#273). Network idle is not charged while the consumer holds; this is the consumer's own
158 * bound, so a stalled consumer does not keep a socket open forever. 4 x the idle default. 0 turns it off.
159 */
160export const LIMIT_HELD_TIMEOUT_MS: number = HELD_PER_IDLE * LIMIT_IDLE_TIMEOUT_MS;
161/**
162 * What one held object costs beyond its bytes, charged against the byte budget that holds it: each parsed pack object
163 * against maxInflatedTotal (parsePack, and resolvePack's room), each local object against it (pushRepo), each file or
164 * change against maxPushBytes (fileEntries, commitChanges), each walked file against maxInflatedTotal (filesFromDir).
165 * Without it 100 000 three-byte blobs (1.4 MB of pack) pass every byte cap and exhaust a 128 MiB heap (#142).
166 * Measured on node 22 (`--expose-gc`, heapUsed after two gc() calls, the result held; scratch scripts in #142):
167 * parsePack + resolvePack of N tiny blobs retains 1.05 KiB per object (0.40 parse, 0.65 resolve), fetchPack with a
168 * tracer 1.15 KiB, and at --max-old-space-size=128 fetchPack survives 90 000 and dies at 99 000 (≥ 1.3 KiB live per
169 * object at the peak); RSS grows 2.0 to 2.3 KiB per object. pushTree of 8-byte files: RSS grows 2.4 KiB per file, and at
170 * 128 MiB it survives 75 000 and dies at 100 000 (≥ 1.3 KiB per file). 3 KiB is above every one of those numbers, so
171 * a byte budget sized for a heap stays inside it however the bytes are split; on DEFAULT_LIMITS that is about 87 000
172 * tiny objects in one pack and 43 000 tiny files in one push. Not a Limits key: it is a property of this code, not a policy.
173 */
174export const LIMIT_OBJECT_OVERHEAD: number = 3 * KIB;
176/**
177 * Inflated bytes a work-budgeted pack scan may produce per pack byte consumed, past the maxInflatedTotal it may always
178 * spend. Not a memory figure (such a scan keeps no object): it bounds the CPU a pack can buy. DEFLATE reaches about
179 * 1032:1; real packs measure far below this (deltas inflate only their instructions).
180 */
181export const LIMIT_WORK_RATIO = 32;
182/**
183 * resolvePackRange's work bound. Resolving a pack honestly costs its floor: every member inflated once and every delta
184 * applied once, which is the sum of sizes the pack itself declares (each capped by maxObjectSize / maxDeltaResult), and
185 * has nothing to do with its compressed size: 80 one-line edits of a 4 MB file are a pack of about 1 MB and a floor of
186 * over 256 MiB. LIMIT_RESOLVE_FACTOR is the work allowed per floor byte: the room for bases made again after a cache
187 * miss. Measured by the test's own RangeSource (test/pack-range-resolve.test.js): that history resolves at about 1x the
188 * sum of its object sizes on the default cache.
189 * The hard ceiling, whatever the pack declares (a pack of maximum-size delta bombs declares a floor as large as it
190 * likes), is the Limits key maxResolveWork, exactly as parsed. parseLimits refuses it below the record's own
191 * maxInflatedTotal (bad_request, #271): such a ceiling would refuse what the retain bound admits.
192 * Left out of a caller's record it is LIMIT_RESOLVE_TOTALS x that record's
193 * maxInflatedTotal, so it follows the preset: 2 GiB on DEFAULT_LIMITS, 512 MiB on WORKER_LIMITS. Measured on a 40 KB
194 * bomb (test/pack-range-resolve-bound.test.js): refused after 512 MiB in about 2 s of CPU and after 2 GiB in about 8 s
195 * (about 4 ns per work byte, most of it hashing each result). An honest pack whose objects sum past the ceiling is
196 * refused too (limit_exceeded, `resolve work bytes`): raise maxResolveWork for it.
197 */
198export const LIMIT_RESOLVE_FACTOR = 4;
199export const LIMIT_RESOLVE_TOTALS = 8;
200export const LIMIT_RESOLVE_WORK: number = LIMIT_INFLATED_TOTAL * LIMIT_RESOLVE_TOTALS;
201/**
202 * What memoryCache() (packcache.ts) retains unless told otherwise: the body bytes and header text of all its entries.
203 * One object's worth: a process that keeps a cache beside its work holds at most one more LIMIT_OBJECT.
204 */
205export const LIMIT_MEMORY_CACHE_BYTES: number = LIMIT_OBJECT;
206/** Entries memoryCache() keeps unless told otherwise, however small: its eviction pass walks them on a put. */
207export const LIMIT_MEMORY_CACHE_ENTRIES = 1024;
208/* oxlint-enable no-magic-numbers */
210export type Limits = {
211 readonly maxMergeBlobBytes: number;
212 readonly maxMergeWork: number;
213 readonly maxObjectSize: number;
214 readonly maxHarvestBytes: number;
215 readonly maxPackBytes: number;
216 readonly maxPushBytes: number;
217 readonly maxDeltaResult: number;
218 readonly maxDeltaChain: number;
219 readonly maxInflatedTotal: number;
220 readonly maxResolveWork: number;
221 readonly maxPackObjects: number;
222 readonly maxRefs: number;
223 readonly maxRebaseCommits: number;
224 readonly maxSectionLines: number;
225 readonly maxTreeEntries: number;
226 readonly maxPathDepth: number;
227 readonly maxPathComponent: number;
228 readonly maxMergeDepth: number;
229 readonly maxReportLines: number;
230 readonly maxReportReasonBytes: number;
231 readonly maxReportProgressBytes: number;
232 readonly maxCommitParents: number;
233 readonly maxLsRefsBytes: number;
234 readonly requestTimeoutMs: number;
235 readonly firstByteTimeoutMs: number;
236 readonly idleTimeoutMs: number;
237 readonly heldTimeoutMs: number;
238};
239export type LimitKey = keyof Limits;
241// A limits record parsed once (#156): every key present, each a finite non-negative number. The brand is a module
242// symbol, written only here (parseLimits, and the presets below); it is not enumerable, so a spread of a checked record
243// is a plain record again and is parsed afresh. Internal code takes CheckedLimits and reads its keys directly.
244const CHECKED_LIMITS: unique symbol = Symbol('checkedLimits');
245export type CheckedLimits = Limits & { readonly [CHECKED_LIMITS]: true };
246// What a caller passes: any subset of the keys (a missing key is the default; maxResolveWork missing is derived from
247// the record's own maxInflatedTotal), or none. null is a value on every key, and refused.
248export type LimitsInput = Input<Limits>;
250// The brand on a record whose every value is a finite non-negative number (each caller's check, or arithmetic on checked
251// values). Frozen: the record is shared by every read past the edge.
252function grant(values: Limits): CheckedLimits {
253 // Stryker disable next-line BooleanLiteral: the brand is its presence (isChecked reads Object.hasOwn); its value is never read
254 const checked: CheckedLimits = { ...values, [CHECKED_LIMITS]: true };
255 Object.defineProperty(checked, CHECKED_LIMITS, { enumerable: false });
256 return Object.freeze(checked);
257}
258const isChecked = (value: LimitsInput): value is CheckedLimits => Object.hasOwn(value, CHECKED_LIMITS);
260export const DEFAULT_LIMITS: CheckedLimits = grant({
261 maxMergeBlobBytes: LIMIT_MERGE_BLOB,
262 maxMergeWork: LIMIT_MERGE_WORK,
263 maxObjectSize: LIMIT_OBJECT,
264 maxHarvestBytes: LIMIT_HARVEST,
265 maxPackBytes: LIMIT_PACK_WIRE,
266 maxPushBytes: LIMIT_PUSH_BYTES,
267 maxDeltaResult: LIMIT_DELTA_RESULT,
268 maxDeltaChain: LIMIT_DELTA_CHAIN,
269 maxInflatedTotal: LIMIT_INFLATED_TOTAL,
270 maxResolveWork: LIMIT_RESOLVE_WORK,
271 maxPackObjects: LIMIT_PACK_OBJECTS,
272 maxRefs: LIMIT_REFS,
273 maxRebaseCommits: LIMIT_REBASE_COMMITS,
274 maxSectionLines: LIMIT_SECTION_LINES,
275 maxTreeEntries: LIMIT_TREE_ENTRIES,
276 maxPathDepth: LIMIT_PATH_DEPTH,
277 maxPathComponent: LIMIT_PATH_COMPONENT,
278 maxMergeDepth: LIMIT_MERGE_DEPTH,
279 maxReportLines: LIMIT_REPORT_LINES,
280 maxReportReasonBytes: LIMIT_REPORT_REASON_BYTES,
281 maxReportProgressBytes: LIMIT_REPORT_PROGRESS_BYTES,
282 maxCommitParents: LIMIT_COMMIT_PARENTS,
283 maxLsRefsBytes: LIMIT_LS_REFS_BYTES,
284 requestTimeoutMs: LIMIT_REQUEST_TIMEOUT_MS,
285 firstByteTimeoutMs: LIMIT_FIRST_BYTE_TIMEOUT_MS,
286 idleTimeoutMs: LIMIT_IDLE_TIMEOUT_MS,
287 heldTimeoutMs: LIMIT_HELD_TIMEOUT_MS,
288});
290/**
291 * Limits for a 128 MiB isolate (a Cloudflare Worker), where DEFAULT_LIMITS are sized for a git client's heap. One object
292 * peaks near twice its size (the inflate output and the buffer the caller holds), so the object and delta caps are
293 * 16 MiB and the inflated total, which also pays LIMIT_OBJECT_OVERHEAD per object, is 64 MiB: half the isolate, about
294 * 21 000 tiny objects. The wire caps (pack, push, ls-refs) are two objects, as in the defaults. maxHarvestBytes is half an
295 * object, maxMergeBlobBytes 2 MiB (the line merger holds each side more than twice), maxMergeWork 2^26 steps per merged
296 * file (LIMIT_MERGE_WORK_WORKER: CPU, not memory), maxTreeEntries 32 768
297 * (a listed entry keeps ~150 B of heap, so the 200 000 default is ~30 MiB of the isolate's 128: #140), and
298 * maxReportReasonBytes 1 KiB (a push of maxRefs refused refs holds one reason each). Every other cap
299 * is the default. The limit sweep runs these at --max-old-space-size=128 (test/sweep/matrix.mjs, `worker.*` cells):
300 * each refuses or succeeds, none runs out of memory.
301 */
302/* oxlint-disable no-magic-numbers -- the preset's cap definitions, as above */
303export const WORKER_LIMITS: CheckedLimits = grant({
304 ...DEFAULT_LIMITS,
305 maxObjectSize: 16 * MIB,
306 maxPackBytes: 32 * MIB,
307 maxPushBytes: 32 * MIB,
308 maxLsRefsBytes: 32 * MIB,
309 maxInflatedTotal: 64 * MIB,
310 maxResolveWork: 64 * MIB * LIMIT_RESOLVE_TOTALS,
311 maxDeltaResult: 16 * MIB,
312 maxHarvestBytes: 8 * MIB,
313 maxMergeBlobBytes: 2 * MIB,
314 maxMergeWork: LIMIT_MERGE_WORK_WORKER,
315 maxTreeEntries: 32_768,
316 // A rebase replays one commit at a time, about one request a commit whatever the depth of the path it changes, and a
317 // Worker request may make 1,000 subrequests (standard plan). 256 commits, each changing one file onto did not touch:
318 // 268 requests with a counting transport, at most 800 asserted (test/rebase.test.js, the WORKER_LIMITS test). A file
319 // that must be line-merged with onto costs about three more requests per commit, and this limit does not bound that
320 // (README, Limits).
321 maxRebaseCommits: 256,
322 maxReportReasonBytes: LIMIT_REPORT_REASON_BYTES_WORKER,
323});
324/* oxlint-enable no-magic-numbers */
326// A caller's overrides on top of the defaults, as a plain record: it is checked where it enters (parseLimits).
327// maxResolveWork left out follows the record's own maxInflatedTotal (resolveWorkOf), as in parseLimits: 8 x it, capped
328// at MAX_SAFE_INTEGER but never below maxInflatedTotal itself, so a derived value always meets parseLimits' bound.
329const resolveWorkOf = (maxInflatedTotal: number): number => Math.max(maxInflatedTotal, Math.min(Number.MAX_SAFE_INTEGER, maxInflatedTotal * LIMIT_RESOLVE_TOTALS));
330export const withLimits = (o: Partial<Limits> = {}): Limits => {
331 // null from an untyped caller is no overrides, as the missing value is: the frozen defaults, not a throw
332 const given = getOrElse<Partial<Limits>>(fromNullish(o), {});
333 const filled = { ...DEFAULT_LIMITS, ...given };
334 return Object.freeze(isMissing(given.maxResolveWork) ? { ...filled, maxResolveWork: resolveWorkOf(filled.maxInflatedTotal) } : filled);
335};
337// A record with maxResolveWork taken out, so it is derived from the record's own maxInflatedTotal where it is parsed:
338// for a spread preset whose maxInflatedTotal is changed (`withDerivedWork({ ...WORKER_LIMITS, maxInflatedTotal: x })`
339// is bounded at 8 x x). Every other key is kept as given.
340export const withDerivedWork = <T extends LimitsInput>(limits: T): Omit<T, 'maxResolveWork'> => {
341 const { maxResolveWork: _derived, ...rest } = limits;
342 return rest;
343};
345// Absent, NaN, Infinity, or negative: the check would not bound anything. Fail before any allocation.
346export const checkLimit = (value: unknown, what: string): Result<number, ErrorOf<'bad_request'>> =>
347 typeof value === 'number' && Number.isFinite(value) && value >= 0
348 ? ok(value)
349 : err(plyError('bad_request', `limits.${what} must be a finite non-negative number`, { what, got: value }));
351// The largest delay a platform timer holds: a signed 32-bit count of ms (24.8 days). The exchange's four timeouts.
352export const MAX_TIMER_MS = 2_147_483_647;
353const TIMER_KEYS: ReadonlySet<string> = new Set(['requestTimeoutMs', 'firstByteTimeoutMs', 'idleTimeoutMs', 'heldTimeoutMs']);
355// The caller's limits record (any subset), or none (null), parsed once where it enters. A key it gives must pass
356// checkLimit (the refusal names the key, `got` is what was passed; keys are checked in DEFAULT_LIMITS order); a key it
357// leaves out, or passes as the missing value, is DEFAULT_LIMITS's (maxResolveWork: 8 x the record's maxInflatedTotal; given, it must be at least the record's maxInflatedTotal). Keys this version does not read are ignored. A
358// record parseLimits already returned is returned as it is; none (null) is DEFAULT_LIMITS.
359// @decoder parseLimits prefix=limits
360export function parseLimits(input: LimitsInput | null): Result<CheckedLimits, ErrorOf<'bad_request'>> {
361 if (input === null) return ok(DEFAULT_LIMITS);
362 if (isChecked(input)) return ok(input);
363 // A spread of DEFAULT_LIMITS: its keys (the brand is not enumerable), in order, each filled from the input where given.
364 const given = withDefaults<Limits>(input, { ...DEFAULT_LIMITS });
365 // the resolve work ceiling a caller leaves out follows the maxInflatedTotal of its own record, not the default's
366 const filled: Limits = isMissing(input.maxResolveWork) ? { ...given, maxResolveWork: resolveWorkOf(given.maxInflatedTotal) } : given;
367 for (const [key, value] of Object.entries(filled)) {
368 const checked = checkLimit(value, key);
369 if (!checked.ok) return checked;
370 // a timer holds at most MAX_TIMER_MS: above it the platform's timer fires at once (Node: 1 ms, with a warning)
371 if (TIMER_KEYS.has(key) && checked.value > MAX_TIMER_MS) return err(plyError('bad_request', `limits.${key} must be at most ${MAX_TIMER_MS} ms (0 turns the timer off)`, { what: key, got: value }));
372 }
373 // #271: the resolver's ceiling is this number as given, so one below the retain bound is refused, never raised
374 if (filled.maxResolveWork < filled.maxInflatedTotal) return err(plyError('bad_request', `limits.maxResolveWork must be at least limits.maxInflatedTotal (${filled.maxInflatedTotal})`, { what: 'maxResolveWork', got: filled.maxResolveWork }));
375 return ok(grant(filled));
376}
378// The limits an entry's options name (`limits`: any subset; left out or null is the defaults), parsed once at the entry.
379export const limitsOf = (options: Input<{ readonly limits: LimitsInput | null }>): Result<CheckedLimits, ErrorOf<'bad_request'>> =>
380 parseLimits(getOrElse<LimitsInput | null>(fromNullish(options.limits), null));
382// A checked record with one bound lowered to `value` (never raised): an operation's room for one step (what is left of
383// a budget, a tighter per-call cap). `value` is arithmetic on checked bounds; below zero is zero.
384export const lowered = (limits: CheckedLimits, key: LimitKey, value: number): CheckedLimits =>
385 grant({ ...limits, [key]: Math.max(0, Math.min(limits[key], value)) });
387// The value for `what` exceeding its bound: `got` against `max`.
388export const limitExceeded = (what: string, got: number, max: number): ErrorOf<'limit_exceeded'> =>
389 plyError('limit_exceeded', `${what} ${got} exceeds limit ${max}`, { what, got, max });
391export { limitExceeded as limitError };
Diagnostics4 git calls · 164 ms
CallStatusSizeTime0164 ms
discover200152 B2 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=2 git.response.bytes=152 git.server.agent=gitty/1.0 git.server.object_format=sha1 git.server.caps=agent ls-refs fetch object-format git.server.fetch=shallow filter sideband-all git.protocol.version=2 git.pkt.frames=8 git.pkt.data=6 git.pkt.flush=2 git.pkt.delim=0 git.pkt.bytes=152 git.pkt.payload.max=34
ls-refs200145 B · hit2 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=2 git.response.bytes=145 git.response.cache=HIT git.response.duration_ms=2 git.protocol.version=2 git.pkt.frames=3 git.pkt.data=2 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=145 git.pkt.payload.max=76 git.ls_refs.count=2 git.ls_refs.head=refs/heads/main
fetchblob:none · deepen 1020038 KiB · hit2 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=2 git.response.bytes=38434 git.response.cache=HIT git.response.duration_ms=2 git.fetch.filter=blob:none git.fetch.filter.requested=tree:0 git.fetch.filter.fallback=blob:none git.fetch.filter.learned=false git.fetch.wants=19912563f540228593df0c489082e5e2508e21e4 git.fetch.haves.count=0 git.fetch.deepen=10 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=6 git.pkt.data=4 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=38434 git.pkt.payload.max=38339 git.sideband.band1.bytes=38338 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=63 git.pack.bytes=38338 git.pack.ofs_delta=0 git.pack.ref_delta=8 git.pack.chain.max=8 git.pack.trailer=0bc36ab7adf82d3109177f11f1ea93f1ce071f77 git.pack.full=55Open pack map
fetch2009.4 KiB160 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=160 git.response.bytes=9639 git.response.cache=MISS git.response.duration_ms=160 git.fetch.wants=4ee94c839b89f27abb9fc7e4fdc56d560f773b1b git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=3 git.pkt.data=2 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=9639 git.pkt.payload.max=9618 git.sideband.band1.bytes=9617 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0
Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.
- Remote
- https://5ad2236b39de4c8bd8f6270ea63f3ea9.artifacts.cloudflare.net/git/public-v0/ply.git
- Ref
- refs/heads/main
- Commit
- 19912563f540228593df0c489082e5e2508e21e4
- cf-ray
- a5e28d9a8c3224d3
- Request
- 8dacc928…
- Protocol
- v2 · sha1
- Agent
- gitty/1.0
- Filter
- advertised
- Fetch
- shallow filter sideband-all
- Capabilities
- agent ls-refs fetch object-format