@ref0/git 0.27.0 → 0.30.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.
Files changed (79) hide show
  1. package/dist/client/git-http.mjs +29 -12
  2. package/dist/client/push-upload.mjs +13 -12
  3. package/dist/client/remote-helper.mjs +1 -1
  4. package/dist/client/remote.mjs +1 -1
  5. package/dist/client/run-remote-helper.mjs +7 -14
  6. package/dist/client/slice-push.d.mts +13 -9
  7. package/dist/client/slice-push.mjs +16 -5
  8. package/dist/client/slice-report.mjs +6 -8
  9. package/dist/client/transport.mjs +27 -5
  10. package/dist/contracts/git.d.mts +17 -2
  11. package/dist/contracts/store.d.mts +1 -1
  12. package/dist/core/forks.mjs +1 -1
  13. package/dist/core/purge.mjs +1 -1
  14. package/dist/http/push-uploads.mjs +10 -15
  15. package/dist/lfs/copy.d.mts +4 -1
  16. package/dist/lfs/copy.mjs +7 -6
  17. package/dist/lfs/layer.mjs +1 -1
  18. package/dist/lfs/objects.mjs +127 -8
  19. package/dist/lfs/upload-most.mjs +19 -3
  20. package/dist/merges/merges.d.mts +3 -2
  21. package/dist/protocol/bytes/buffers.mjs +5 -5
  22. package/dist/protocol/bytes/crc32.mjs +39 -6
  23. package/dist/protocol/bytes/deflate.d.mts +11 -31
  24. package/dist/protocol/bytes/deflate.mjs +133 -72
  25. package/dist/protocol/bytes/inflate.mjs +2 -2
  26. package/dist/protocol/bytes/sha1-hasher.mjs +12 -12
  27. package/dist/protocol/bytes/zlib-ng/README.md +65 -38
  28. package/dist/protocol/bytes/zlib-ng/compile.d.mts +5 -4
  29. package/dist/protocol/bytes/zlib-ng/compile.mjs +5 -4
  30. package/dist/protocol/bytes/zlib-ng/embedded.mjs +1 -1
  31. package/dist/protocol/bytes/zlib-ng/instance.mjs +14 -8
  32. package/dist/protocol/bytes/zlib-ng/zlib-ng.wasm +0 -0
  33. package/dist/protocol/objects/fsck-names.mjs +27 -7
  34. package/dist/protocol/objects/fsck.mjs +100 -88
  35. package/dist/protocol/objects/object-rules.d.mts +1 -0
  36. package/dist/protocol/objects/tree.d.mts +1 -0
  37. package/dist/protocol/objects/tree.mjs +55 -6
  38. package/dist/protocol/wire/push-uploads.mjs +12 -1
  39. package/dist/server/registry.mjs +12 -0
  40. package/dist/server/server.mjs +7 -1
  41. package/dist/storage/budget.d.mts +2 -1
  42. package/dist/storage/budget.mjs +25 -9
  43. package/dist/storage/calls.d.mts +1 -1
  44. package/dist/storage/calls.mjs +4 -2
  45. package/dist/storage/host-bucket.mjs +15 -5
  46. package/dist/storage/index-bitmaps.d.mts +1 -0
  47. package/dist/storage/index-bitmaps.mjs +15 -14
  48. package/dist/storage/index-build.d.mts +2 -1
  49. package/dist/storage/index-build.mjs +14 -16
  50. package/dist/storage/index-files.mjs +3 -3
  51. package/dist/storage/index-graph.mjs +3 -3
  52. package/dist/storage/index-remap.mjs +6 -7
  53. package/dist/storage/links.mjs +34 -2
  54. package/dist/storage/memory-budget.mjs +12 -3
  55. package/dist/storage/merge-stream.mjs +4 -3
  56. package/dist/storage/merge-write.mjs +2 -2
  57. package/dist/storage/pack-receive.mjs +24 -8
  58. package/dist/storage/packs.d.mts +3 -1
  59. package/dist/storage/packs.mjs +33 -11
  60. package/dist/storage/put-holds.d.mts +1 -0
  61. package/dist/storage/put-holds.mjs +20 -0
  62. package/dist/storage/ready.mjs +4 -2
  63. package/dist/storage/receive-bounds.d.mts +1 -1
  64. package/dist/storage/receive-bounds.mjs +4 -4
  65. package/dist/storage/receive-links.mjs +31 -15
  66. package/dist/storage/receive-steps.mjs +21 -1
  67. package/dist/storage/runs.d.mts +1 -1
  68. package/dist/storage/runs.mjs +7 -5
  69. package/dist/store/door.mjs +9 -1
  70. package/dist/store/job-try.mjs +5 -5
  71. package/dist/store/repo-record.mjs +1 -1
  72. package/dist/sync/step.mjs +3 -4
  73. package/package.json +3 -9
  74. package/dist/http/node.d.mts +0 -62
  75. package/dist/http/node.mjs +0 -212
  76. package/dist/node.d.mts +0 -3
  77. package/dist/node.mjs +0 -1
  78. package/dist/server/edge-node.d.mts +0 -19
  79. package/dist/server/edge-node.mjs +0 -20
@@ -1,4 +1,5 @@
1
1
  import { dropBody } from "../protocol/bytes/reader.mjs";
2
+ import { nativeSha256Hasher } from "../protocol/bytes/sha256-hasher.mjs";
2
3
  import { gathered } from "../protocol/bytes/streams.mjs";
3
4
  import { contended, openFor } from "../core/access.mjs";
4
5
  import { ownWriter } from "../core/own-writes.mjs";
@@ -16,14 +17,16 @@ import { isLfsOid, lfsPointerText } from "../protocol/objects/lfs-pointer.mjs";
16
17
  import { ListedRow, UploadRow, largestObject, lfsCollections, linkLife, listedKey, listedRead, objectKey, stagingId, stagingKey, stagingRead, streamMost, uploadGrace, uploadKey, uploadRead } from "./rows.mjs";
17
18
  import { BatchRequest, VerifyRequest, batchMost, bodyOf, lfsAnswer } from "./wire.mjs";
18
19
  import { uploadedRow } from "./uploaded.mjs";
19
- import { pastMost, uploadPieceBytes } from "./upload-most.mjs";
20
+ import { checkedAfterMost, pastMost, uploadPieceBytes } from "./upload-most.mjs";
20
21
  import { fail, gitError, httpStatus } from "../contracts/result.mjs";
21
22
  import { Unavailable } from "@ref0/infra";
22
23
  import * as Effect from "effect/Effect";
23
24
  import * as Stream from "effect/Stream";
24
25
  import * as Option from "effect/Option";
25
26
  import * as Result from "effect/Result";
27
+ import * as Fiber from "effect/Fiber";
26
28
  import * as Clock from "effect/Clock";
29
+ import * as Duration from "effect/Duration";
27
30
  import * as DateTime from "effect/DateTime";
28
31
  // src/lfs/objects.ts
29
32
  /**
@@ -157,7 +160,7 @@ const batch = /* @__PURE__ */ Effect.fnUntraced(function* (parts, call) {
157
160
  if (body.objects.length > 1e3) return yield* fail("RESOURCE_EXHAUSTED", `A batch names at most ${batchMost} objects`);
158
161
  const upload = body.operation === "upload";
159
162
  const repo = yield* openFor(call.caller, call.repo, upload, void 0, "first-read");
160
- const most = upload && parts.signed === void 0 ? parts.uploadMost : void 0;
163
+ const most = !upload ? void 0 : parts.signed === void 0 ? parts.uploadMost : parts.signed.puts === "unchecked" ? checkedAfterMost : void 0;
161
164
  const refusalOf = (oid, size) => {
162
165
  if (!isLfsOid(oid)) return "An oid is a SHA-256, as 64 lowercase hex digits";
163
166
  if (!validSize(size)) return `A size is 0 to ${largestObject} bytes`;
@@ -270,7 +273,10 @@ const uploads = /* @__PURE__ */ Effect.fnUntraced(function* (parts, call, repo,
270
273
  for (const { oid, size } of objects) {
271
274
  const generation = generations.get(oid);
272
275
  const key = generation === void 0 ? void 0 : objectKey(repo.internalId, oid, generation);
273
- const actions = key === void 0 ? void 0 : yield* uploadActions(parts, call, oid, key, expiresAt);
276
+ const actions = key === void 0 ? void 0 : yield* uploadActions(parts, call, {
277
+ oid,
278
+ size
279
+ }, key, expiresAt);
274
280
  answers.set(oid, actions === void 0 ? {
275
281
  oid,
276
282
  size
@@ -286,12 +292,13 @@ const uploads = /* @__PURE__ */ Effect.fnUntraced(function* (parts, call, repo,
286
292
  return yield* contended();
287
293
  });
288
294
  /** A link to upload the object, to the Worker or to `key` in a signed bucket. */
289
- const uploadActions = /* @__PURE__ */ Effect.fnUntraced(function* (parts, call, oid, key, expiresAt) {
295
+ const uploadActions = /* @__PURE__ */ Effect.fnUntraced(function* (parts, call, { oid, size }, key, expiresAt) {
290
296
  const signed = parts.signed;
291
297
  if (signed === void 0) return { upload: ownAction(call, `objects/${oid}`, expiresAt) };
292
298
  return {
293
299
  upload: yield* bucketCall(signed.putUrl(key, {
294
300
  sha256: oid,
301
+ size,
295
302
  expiresAt
296
303
  })),
297
304
  verify: ownAction(call, "objects/verify", expiresAt)
@@ -301,13 +308,18 @@ const uploadActions = /* @__PURE__ */ Effect.fnUntraced(function* (parts, call,
301
308
  * `POST objects/verify`, after a signed upload: lists the object once the bucket holds bytes at
302
309
  * the caller's own upload row's key that it checked against its oid, which only the caller's links
303
310
  * wrote. The rows are read before the bucket, so upkeep's commit that drops the upload row to
304
- * delete the bytes moves the version this commit expects.
311
+ * delete the bytes moves the version this commit expects. Over links that check nothing, it hashes
312
+ * the bytes itself, as `checkedAfter` does.
305
313
  */
306
314
  const verify = /* @__PURE__ */ Effect.fnUntraced(function* (parts, call) {
307
315
  const { oid, size } = yield* bodyOf(call.request, VerifyRequest);
308
316
  if (!isLfsOid(oid)) return yield* fail("INVALID_ARGUMENT", "An oid is a SHA-256, as 64 lowercase hex digits");
309
317
  const { rows: registered, signed } = parts;
310
318
  const repo = yield* openFor(call.caller, call.repo, true, void 0, "first-read");
319
+ if (signed?.puts === "unchecked") return yield* checkedAfter(parts, signed, call, repo, {
320
+ oid,
321
+ size
322
+ });
311
323
  const writer = yield* ownWriter(call.caller);
312
324
  for (let tries = 0; tries < 5; tries += 1) {
313
325
  const at = yield* Clock.currentTimeMillis;
@@ -318,7 +330,7 @@ const verify = /* @__PURE__ */ Effect.fnUntraced(function* (parts, call) {
318
330
  if (rows?.listed !== void 0 && !unseen) return lfsAnswer(200, { message: "Verified" });
319
331
  const key = rows?.upload === void 0 ? void 0 : objectKey(repo.internalId, oid, rows.upload.generation);
320
332
  const stored = signed === void 0 || key === void 0 ? void 0 : yield* bucketCall(Effect.map(signed.head(key), Option.getOrUndefined));
321
- if (stored?.sha256 !== oid) return yield* fail("FAILED_PRECONDITION", "The bucket holds no bytes for this object", { hint: "Upload it again" });
333
+ if (stored?.sha256 !== oid) return yield* noBytes();
322
334
  if (stored.size !== size) return yield* fail("INVALID_ARGUMENT", `This object is ${stored.size} bytes, not ${size}`);
323
335
  const own = writer === void 0 ? [] : [uploadedRow(writer, oid, at)];
324
336
  const writes = unseen ? { put: own } : {
@@ -339,6 +351,110 @@ const verify = /* @__PURE__ */ Effect.fnUntraced(function* (parts, call) {
339
351
  }
340
352
  return yield* contended();
341
353
  });
354
+ /** Verify's answer where the bucket holds no checked bytes for the object. */
355
+ const noBytes = () => fail("FAILED_PRECONDITION", "The bucket holds no bytes for this object", { hint: "Upload it again" });
356
+ /**
357
+ * Verify over links that check nothing: the caller's own upload row's key, its holding key, holds
358
+ * whatever its links' PUTs sent, and any PUT may replace it. So the bucket copies it to a staging
359
+ * key of its own, which no link names, and verify reads and hashes the copy there: bytes it reads
360
+ * stay what it listed, whatever a PUT to the holding key does after the copy. A copy of the oid's
361
+ * bytes, at its size, is listed at the staging key; any other is deleted, and its staging row
362
+ * dropped. The holding key is deleted after, matched or not; the upload row stays, so a PUT landing
363
+ * late is upkeep's to delete, at the row's `removeAt`, as every upload's is. The copy lands whole,
364
+ * so upkeep's delete of the holding key comes before it, or after: a check reads only its own key,
365
+ * whose staging row lasts a day past its start, and stops at its deadline, `streamMost` past it.
366
+ */
367
+ const checkedAfter = /* @__PURE__ */ Effect.fnUntraced(function* (parts, links, call, repo, { oid, size }) {
368
+ const { rows: registered, bucket } = parts;
369
+ const started = yield* Clock.currentTimeMillis;
370
+ const read = yield* objectRows(registered, call.caller, repo, [oid], { asked: repo });
371
+ const rows = read.rows.get(oid);
372
+ const unseen = (yield* unseenRows(call.caller, repo, [oid], read.rows)).has(oid);
373
+ if (rows?.listed !== void 0 && !unseen) return lfsAnswer(200, { message: "Verified" });
374
+ const upload = rows?.upload;
375
+ const deadline = started + streamMost;
376
+ if (upload === void 0) return yield* noBytes();
377
+ if (upload.size !== size) return yield* fail("INVALID_ARGUMENT", `This object is ${upload.size} bytes, not ${size}`);
378
+ const holding = objectKey(repo.internalId, oid, upload.generation);
379
+ const [staging] = yield* stagedKeys(registered, repo.internalId, started + uploadGrace, 1);
380
+ if (staging === void 0) return yield* Effect.die(/* @__PURE__ */ new Error("One staging key asked, none made"));
381
+ const copying = yield* Effect.timeoutOption(bucketCall(Effect.catchTag(Effect.as(links.copy(holding, staging.key), true), "NotFound", () => Effect.succeed(false))), Duration.millis(Math.max(0, deadline - (yield* Clock.currentTimeMillis))));
382
+ if (Option.isNone(copying)) return yield* checkTooLong();
383
+ if (!copying.value) {
384
+ yield* dropStaged(parts, repo.internalId, staging.row.id);
385
+ return yield* noBytes();
386
+ }
387
+ const checked = (yield* Clock.currentTimeMillis) > deadline ? "past" : yield* hashedAt(bucket, staging.key, {
388
+ size,
389
+ deadline
390
+ });
391
+ if (checked === "past") {
392
+ yield* bucketDo(bucket.remove(staging.key));
393
+ yield* dropStaged(parts, repo.internalId, staging.row.id);
394
+ return yield* checkTooLong();
395
+ }
396
+ if (checked !== oid) {
397
+ yield* bucketDo(bucket.remove(staging.key));
398
+ yield* dropStaged(parts, repo.internalId, staging.row.id);
399
+ yield* bestEffort(bucketDo(bucket.remove(holding)));
400
+ return yield* fail("FAILED_PRECONDITION", "The bytes uploaded aren't this object's", { hint: "Upload it again" });
401
+ }
402
+ const answer = yield* listStaged(registered, call.caller, repo, {
403
+ oid,
404
+ size,
405
+ key: staging.key,
406
+ staged: staging.row.id,
407
+ deadline,
408
+ unseen,
409
+ keepUpload: true
410
+ });
411
+ yield* bestEffort(bucketDo(bucket.remove(holding)));
412
+ return answer;
413
+ });
414
+ /** A check that ran past its deadline: git-lfs uploads again. */
415
+ const checkTooLong = () => fail("DEADLINE_EXCEEDED", "The check of the upload ran too long", { hint: "Upload it again" });
416
+ /** Why a check's read stopped: its deadline passed. */
417
+ const pastDeadline = () => /* @__PURE__ */ new Error("The check's deadline passed");
418
+ /**
419
+ * The SHA-256 of the bytes at `key`, as lowercase hex, read until `deadline`: `'past'` when the
420
+ * deadline stopped the read, and `'other'` when the key holds no bytes or other than `size` of
421
+ * them, its read stopped as soon as it passes `size`.
422
+ */
423
+ const hashedAt = /* @__PURE__ */ Effect.fnUntraced(function* (bucket, key, { size, deadline }) {
424
+ const stop = new AbortController();
425
+ const left = Math.max(0, deadline - (yield* Clock.currentTimeMillis));
426
+ const timer = yield* Effect.forkChild(Effect.andThen(Effect.sleep(left), Effect.sync(() => stop.abort())));
427
+ const opened = yield* Effect.timeoutOption(bucketStream(bucket, key), Duration.millis(left));
428
+ if (Option.isNone(opened)) {
429
+ yield* Fiber.interrupt(timer);
430
+ return "past";
431
+ }
432
+ const body = opened.value;
433
+ if (body === void 0) {
434
+ yield* Fiber.interrupt(timer);
435
+ return stop.signal.aborted ? "past" : "other";
436
+ }
437
+ const hasher = nativeSha256Hasher();
438
+ let bytes = 0;
439
+ const hashed = yield* Effect.result(Stream.fromReadableStream({
440
+ evaluate: () => bodyUntilAborted(body, stop.signal, pastDeadline),
441
+ onError: (cause) => new Unavailable({
442
+ message: bucketFailed,
443
+ cause
444
+ })
445
+ }).pipe(Stream.takeUntil((chunk) => {
446
+ bytes += chunk.length;
447
+ return bytes > size;
448
+ }), Stream.runForEach((chunk) => hasher.write(chunk))));
449
+ yield* Fiber.interrupt(timer);
450
+ if (stop.signal.aborted) return "past";
451
+ if (Result.isFailure(hashed)) return yield* bucketDo(Effect.fail(hashed.failure));
452
+ if (bytes !== size) {
453
+ yield* dropBody(body);
454
+ return "other";
455
+ }
456
+ return yield* hasher.hex;
457
+ });
342
458
  /**
343
459
  * `PUT objects/<oid>`, a Worker upload: streams the body to a staging key of its own, put with its
344
460
  * oid as the SHA-256 the bucket checks, so the Worker never hashes it, and lists the object at that
@@ -471,7 +587,10 @@ const counted = (body, most) => {
471
587
  size: () => size
472
588
  };
473
589
  };
474
- /** Lists a Worker upload's bytes at their staging key, in the commit that drops its staging row. */
590
+ /**
591
+ * Lists an upload's bytes at their staging key, a Worker upload's or a checked one's, in the
592
+ * commit that drops its staging row, and its upload row unless `keepUpload`.
593
+ */
475
594
  const listStaged = /* @__PURE__ */ Effect.fnUntraced(function* (registered, caller, repo, staged) {
476
595
  const writer = yield* ownWriter(caller);
477
596
  for (let tries = 0; tries < 5; tries += 1) {
@@ -496,7 +615,7 @@ const listStaged = /* @__PURE__ */ Effect.fnUntraced(function* (registered, call
496
615
  key: staged.key
497
616
  }
498
617
  }, ...own],
499
- delete: [uploadKey(staged.oid, read.uploader), {
618
+ delete: [...staged.keepUpload === true ? [] : [uploadKey(staged.oid, read.uploader)], {
500
619
  collection: lfsCollections.staging,
501
620
  id: staged.staged
502
621
  }],
@@ -14,6 +14,21 @@ const cpuShare = .8;
14
14
  * 4,096 B, each paid for once over (run 46342279485, #2296): one piece an upload, held as it streams.
15
15
  */
16
16
  const uploadPieceBytes = 1024 ** 2;
17
+ /**
18
+ * git-lfs 3.7.1 waits 30 s for an answer with no byte on its connection, `lfs.activitytimeout`'s
19
+ * default, and verify sends none until it's done, so the check ends inside it.
20
+ */
21
+ const verifyWaitMs = 3e4;
22
+ /** The share of git-lfs's wait a check may spend: the rest is the verify's rows' and the runtime's. */
23
+ const checkShare = .8;
24
+ /**
25
+ * The largest upload over links that check nothing: what verify checks at `checkedMiBPerSecond`
26
+ * within `checkShare` of git-lfs's `verifyWaitMs`, 480 MiB.
27
+ */
28
+ const checkedAfterMost = {
29
+ bytes: Math.floor(checkShare * verifyWaitMs / 1e3 * 20) * 1024 ** 2,
30
+ by: "check"
31
+ };
17
32
  /** The bytes `cpuMs` of CPU streams to a checked put, at `uploadMsPerMiB` within `cpuShare` of it. */
18
33
  const cpuBytes = (cpuMs) => Math.floor(cpuShare * cpuMs / 22 * 1024 ** 2);
19
34
  /** The largest upload `caps` let finish: `largestObject` where neither binds below it. */
@@ -40,8 +55,9 @@ const capsRefusal = (caps) => {
40
55
  const setBy = {
41
56
  body: "the largest body its platform passes on",
42
57
  cpu: "what its CPU cap lets it stream to the bucket",
43
- object: "R2's largest single put"
58
+ object: "R2's largest single put",
59
+ check: "what it checks within the 30 s git-lfs waits for a verify"
44
60
  };
45
61
  /** Why an upload of more than `most` is refused, and what takes it. */
46
- const pastMost = (most) => `An upload through this server is at most ${most.bytes} bytes, ${setBy[most.by]}: a bucket that signs its links takes a larger one straight`;
47
- export { capsRefusal, cpuShare, pastMost, uploadMostOf, uploadPieceBytes };
62
+ const pastMost = (most) => most.by === "check" ? `An upload to this server is at most ${most.bytes} bytes, ${setBy[most.by]}` : `An upload through this server is at most ${most.bytes} bytes, ${setBy[most.by]}: a bucket that signs its links takes a larger one straight`;
63
+ export { capsRefusal, checkShare, checkedAfterMost, cpuShare, pastMost, uploadMostOf, uploadPieceBytes, verifyWaitMs };
@@ -9,8 +9,9 @@ import "effect/Context";
9
9
  import * as Layer from "effect/Layer";
10
10
  export interface MergesOptions {
11
11
  /**
12
- * `xdiff.wasm` compiled: a Worker imports `@ref0/xdiff-wasm/xdiff.wasm`, which its bundler compiles, and
13
- * a host on Node passes `await xdiff()` from `@ref0/xdiff-wasm/node`.
12
+ * `xdiff.wasm` compiled: every host imports `@ref0/xdiff-wasm/xdiff.wasm`, which a Worker's bundler
13
+ * compiles, and which Node's export condition, a Vercel function's and Next.js's on Vercel, answers
14
+ * with the module compiled from its embedded bytes.
14
15
  */
15
16
  readonly xdiff: WebAssembly.Module;
16
17
  }
@@ -93,9 +93,9 @@ const wasmPageBytes = 65536;
93
93
  /**
94
94
  * The most zlib-ng's memory grows to in an isolate, set by the host side, never zlib-ng's: what a
95
95
  * 128 MB isolate's operations are allotted, in whole pages, 103,284,736 bytes. Each inflater is
96
- * charged to its read's meter as `inflaterBytes`; this holds them all together within the
97
- * isolate. An inflater that would take it past fails to open, as `InflateError`, and those open
98
- * go on.
96
+ * charged to its read's meter as `inflaterBytes`, and the deflater a write runs as
97
+ * `deflaterBytes`; this holds them all together within the isolate. One that would take it past
98
+ * fails to open, as `InflateError` or `DeflateError`, and those open go on.
99
99
  */
100
- const inflaterMemoryBytes = Math.floor(allottableOf(defaultMemory) / wasmPageBytes) * wasmPageBytes;
101
- export { BufferError, BufferMeter, allotNow, allotOrFail, allotScoped, allottableOf, capacityOf, defaultMemory, headroomBytes, idleHeapBytes, inflaterMemoryBytes };
100
+ const zlibNgMemoryBytes = Math.floor(allottableOf(defaultMemory) / wasmPageBytes) * wasmPageBytes;
101
+ export { BufferError, BufferMeter, allotNow, allotOrFail, allotScoped, allottableOf, capacityOf, defaultMemory, headroomBytes, idleHeapBytes, zlibNgMemoryBytes };
@@ -1,14 +1,47 @@
1
- import untyped from "pako/lib/zlib/crc32.js";
1
+ import { call, instance } from "./zlib-ng/instance.mjs";
2
+ import * as Result from "effect/Result";
2
3
  // src/protocol/bytes/crc32.ts
3
4
  /**
4
5
  * CRC-32 as zlib's `crc32()` computes it, the polynomial 0xEDB88320 reflected, which a version 2
5
- * pack index keeps for each entry's bytes in the pack: pako 2.1.0's port of zlib's own, the
6
- * library this package already inflates and deflates with. Written a piece at a time: start from
7
- * `crc32Start`, fold each piece in with `crc32Update`, and the last value is the CRC.
6
+ * pack index keeps for each entry's bytes in the pack: zlib-ng 2.3.3's, in the instance
7
+ * `zlib-ng/` makes, its input copied into a buffer in the module's own data a piece at a time.
8
+ * Every entry of push-90mib's pack, its header and its member folded in as the pack reader does,
9
+ * took it 44 ms of CPU in local workerd and 33 ms on Node, where pako 2.1.0's port of zlib's,
10
+ * which it replaced, took 141 and 135 ms. The buffer is placed with
11
+ * the module, so a CRC never allocates and never fails for memory; an instance that can't start is
12
+ * a defect, thrown, since no pack is read or written without one. Written a piece at a time: start
13
+ * from `crc32Start`, fold each piece in with `crc32Update`, and the last value is the CRC.
8
14
  */
9
- const zlibCrc32 = untyped;
15
+ /** The most bytes one `zn_crc32` call reads: its buffer, `ZN_CRC_INPUT` in `adapter.c`. */
16
+ const crcInputBytes = 32768;
17
+ /** The CRC buffer's address in the instance it's in, asked once an instance. */
18
+ let input;
19
+ /** `run`'s answer, or a throw: zlib-ng's instance didn't start or trapped. */
20
+ const answer = (result) => {
21
+ if (Result.isFailure(result)) throw new Error(result.failure.message);
22
+ return result.success;
23
+ };
24
+ /** The isolate's instance and its CRC buffer. */
25
+ const crcInput = () => {
26
+ const on = answer(instance());
27
+ if (input?.on !== on) input = {
28
+ on,
29
+ at: answer(call(on, (exports) => exports.zn_crc32_input()))
30
+ };
31
+ return input;
32
+ };
10
33
  /** The CRC of no bytes. */
11
34
  const crc32Start = 0;
12
35
  /** `crc` with `bytes` folded in after the bytes it already covers. */
13
- const crc32Update = (crc, bytes) => zlibCrc32(crc, bytes, bytes.byteLength, 0) >>> 0;
36
+ const crc32Update = (crc, bytes) => {
37
+ if (bytes.byteLength === 0) return crc >>> 0;
38
+ const { on, at } = crcInput();
39
+ let running = crc;
40
+ for (let from = 0; from < bytes.byteLength; from += crcInputBytes) {
41
+ const piece = bytes.subarray(from, from + crcInputBytes);
42
+ on.view.set(piece, at);
43
+ running = answer(call(on, (exports) => exports.zn_crc32(running, piece.byteLength)));
44
+ }
45
+ return running >>> 0;
46
+ };
14
47
  export { crc32Start, crc32Update };
@@ -1,36 +1,15 @@
1
1
  import { BufferError, BufferMeter } from "./buffers.mjs";
2
+ import "./zlib-ng/instance.mjs";
2
3
  import * as Schema from "effect/Schema";
3
4
  import * as Effect from "effect/Effect";
5
+ import "effect/Result";
4
6
  import * as Scope from "effect/Scope";
5
7
  /**
6
- * One zlib member deflated at a time, as a pack holds one per entry, at zlib's defaults: level 6,
7
- * method 8, window 15, memory level 8, strategy 0, and no flush but the last. Two ways, by size:
8
- *
9
- * - An object up to `wholeObjectBytes` is deflated whole by `deflateWhole`, through pako 2.1.0's
10
- * low-level deflater into one buffer of `deflatedMost` its length, in one synchronous call, on
11
- * one deflate state kept and reset between calls. A `CompressionStream` costs about 27 ms of
12
- * waiting in workerd for each one made, written and read, whatever its size, which a pack of
13
- * small objects paid an object (ref0 #3222). A fresh pako state for each one cost a 200-byte
14
- * object about 69 µs of CPU in Node and 53 µs in workerd; the kept one, reset, 18 and 20 µs.
15
- * - A larger one is streamed by `memberDeflater`, through the runtime's
16
- * `CompressionStream('deflate')`, so what the writer holds never grows with an object's size.
17
- *
18
- * pako is a port of plain zlib, and Node and workerd build Chromium's, so the two can write other
19
- * bytes for one object. Both are zlib members any inflater reads; nothing compares compressed
20
- * bytes, only what they inflate to.
21
- *
22
- * The stream's pieces are each awaited with a read always pending, so a stream that accepts input
23
- * only as its output is read never stalls, and output the compressor hasn't given yet when a write
24
- * settles is taken by the next write or the finish: the stream's own backpressure limits what it
25
- * queues, which `deflaterBytes` counts. No timer is waited on, since a timer's turn costs
26
- * milliseconds in workerd. Each output piece's whole buffer is held by the meter until the sink
27
- * it's handed to returns.
28
- */
29
- /**
30
- * The bytes one compressor keeps in the runtime's native memory, which no buffer here shows: zlib's
31
- * deflate state at window 15 and memory level 8, as `deflate.c` sizes it: a 64 KiB window, a
32
- * 64 KiB `prev` and a 64 KiB `head` table, and a 64 KiB pending buffer, with its state struct.
33
- * An estimate, held on the meter under `deflater` while a compressor lives.
8
+ * The bytes one compressor keeps outside any buffer here, held on the meter under `deflater` while
9
+ * it lives: the kept deflater's stream and state in zlib-ng's memory, 350,304 bytes with zlib-ng
10
+ * 2.3.3 at window 15 and memory level 8, and its two buffers, `deflateWindow` each, which
11
+ * `zlib-ng/instance.test.ts` measures. It covers a `CompressionStream`'s too, zlib's state in the
12
+ * runtime's native memory, which `deflate.c` sizes at about 256 KiB.
34
13
  */
35
14
  export declare const deflaterBytes: number;
36
15
  /**
@@ -41,7 +20,7 @@ export declare const deflaterBytes: number;
41
20
  export declare const deflatedMost: (size: number) => number;
42
21
  /**
43
22
  * The largest object deflated whole: its body and one output buffer of `deflatedMost` its length,
44
- * beside pako's state, about 768 KiB at most. Deflating 256 KiB at level 6 costs a few
23
+ * beside the deflater, about 1 MiB at most. Deflating 256 KiB at level 6 costs a few
45
24
  * milliseconds of CPU, well under the stream's wait it replaces, and a call that size keeps a cut
46
25
  * by the writer's turn or time bound within milliseconds.
47
26
  */
@@ -73,8 +52,9 @@ export interface MemberDeflater<E, R> {
73
52
  export declare const memberDeflater: <E, R>(meter: BufferMeter, emit: (bytes: Uint8Array) => Effect.Effect<void, E, R>) => Effect.Effect<MemberDeflater<E, R>, BufferError, Scope.Scope>;
74
53
  /**
75
54
  * One member of `bytes`, deflated whole into one buffer of `deflatedMost` their length and given
76
- * as a view of what it wrote: a call that can't finish in it fails as `compressor`. Its caller
77
- * holds `deflaterBytes` and `deflatedMost` of their length on its meter while it runs.
55
+ * as a view of what it wrote: a call that can't finish in it, or a deflater that can't be placed,
56
+ * fails as `compressor`. Its caller holds `deflaterBytes` and `deflatedMost` of their length on
57
+ * its meter while it runs.
78
58
  */
79
59
  export declare const deflateWhole: (bytes: Uint8Array) => Effect.Effect<Uint8Array, DeflateError>;
80
60
  export {};