@sproutboat/runtime 0.27.0 → 0.27.1
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/CHANGELOG.md +19 -0
- package/package.json +1 -1
- package/src/ingress-utf8.test.js +5 -7
- package/src/native-fetch-prelude.js +198 -5
- package/src/r2-object.test.js +16 -7
- package/src/to-bytes.test.js +1 -1
- package/src/utf8-decode.test.js +4 -2
- package/test/native-byte-text.ts +165 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,24 @@
|
|
|
1
1
|
# @sproutboat/runtime
|
|
2
2
|
|
|
3
|
+
## 0.27.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 0d2d079: Bodies of megabytes no longer take hundreds of megabytes of memory (sproutd #22). Converting bytes to text and text to bytes made one string per character, so reading a 5 MiB R2 object with `text()` peaked at about 400 MiB, and R2 multipart uploads with real (5 MiB) parts ran sproutd's workers out of memory. The conversions now run in one C pass and give exactly the same results. On a standalone build, at 5 MiB:
|
|
8
|
+
|
|
9
|
+
| | before | after |
|
|
10
|
+
|---|---|---|
|
|
11
|
+
| `put()` of a string | 82 MiB | 16 MiB |
|
|
12
|
+
| `put()` then `get()` and `text()` | 400 MiB | 26 MiB |
|
|
13
|
+
| multipart upload, then `get()` and `text()` | 396 MiB | 21 MiB |
|
|
14
|
+
| `request.text()` of the request body | 402 MiB | 24 MiB |
|
|
15
|
+
|
|
16
|
+
Also:
|
|
17
|
+
|
|
18
|
+
- At every date, `uploadPart()` stores an `ArrayBuffer` or a typed array as its bytes. It stored the text `[object ArrayBuffer]`.
|
|
19
|
+
- From `2026-10-26`, `uploadPart()` takes what `put()` takes (a `ReadableStream` or a `Blob` too), and stores text as its UTF-8 bytes, as in workerd. It stored text whose characters all fit in one byte as Latin-1.
|
|
20
|
+
- From `2026-10-26`, an R2 object body's `body` stream is made when first read, and a whole-object `get()` keeps one copy of the bytes, not two.
|
|
21
|
+
|
|
3
22
|
## 0.27.0
|
|
4
23
|
|
|
5
24
|
### Minor Changes
|
package/package.json
CHANGED
package/src/ingress-utf8.test.js
CHANGED
|
@@ -2,17 +2,15 @@ import { expect, test } from "bun:test";
|
|
|
2
2
|
import { readFileSync } from "node:fs";
|
|
3
3
|
const src = readFileSync(new URL("./native-fetch-prelude.js", import.meta.url), "utf8");
|
|
4
4
|
const decoder = src.slice(src.indexOf("function __sbFromUtf8("), src.indexOf("// sproutboat #181"));
|
|
5
|
-
const ingress = src.slice(
|
|
6
|
-
src.indexOf("function __sbDecodeIngress("),
|
|
7
|
-
src.indexOf("globalThis.__sbEntry ="),
|
|
8
|
-
);
|
|
5
|
+
const ingress = src.slice(src.indexOf("function __sbDecodeIngress("), src.indexOf("globalThis.__sbEntry ="));
|
|
9
6
|
const rawBody = src.slice(src.indexOf("function __sbRawBody("), src.indexOf("function __sbHasStreamBody("));
|
|
10
7
|
if (!decoder || !ingress || !rawBody) throw new Error("Ingress decoder source not found");
|
|
11
8
|
// oxlint-disable-next-line no-function-constructor -- Exercise the text-only runtime prelude.
|
|
12
|
-
const load = new Function(
|
|
9
|
+
const load = new Function(
|
|
10
|
+
`// The C fast paths (Porffor.c) cannot run here: the stubs make the JS fallback run.\nfunction __sbFromUtf8Native() { return ""; }\nfunction __sbToBytesNative() { return ""; }\n${decoder}\n${rawBody}\n${ingress}\nreturn __sbDecodeIngress;`,
|
|
11
|
+
);
|
|
13
12
|
const decode = load();
|
|
14
|
-
const raw = (text) =>
|
|
15
|
-
Array.from(new TextEncoder().encode(text), (byte) => String.fromCharCode(byte)).join("");
|
|
13
|
+
const raw = (text) => Array.from(new TextEncoder().encode(text), (byte) => String.fromCharCode(byte)).join("");
|
|
16
14
|
|
|
17
15
|
test("native ingress text and JSON decode Unicode without changing raw bytes", async () => {
|
|
18
16
|
const body = raw('{"id":"caffè-🚤"}');
|
|
@@ -3034,7 +3034,10 @@ if (globalThis.clearInterval == null) globalThis.clearInterval = clearInterval;
|
|
|
3034
3034
|
// these express the same spec-mandated checks and are verified under Porffor
|
|
3035
3035
|
// alpha-10 by examples/kitchen-sink/harness.ts).
|
|
3036
3036
|
function __sbIsStr(v) {
|
|
3037
|
-
|
|
3037
|
+
// sproutd #22: not `Object(v) !== v`, which wraps (copies) a string in Porffor: two such
|
|
3038
|
+
// checks on a 5 MiB part took 20 MiB.
|
|
3039
|
+
// oxlint-disable-next-line anti-slop/no-runtime-typeof -- the one check that does not copy its argument
|
|
3040
|
+
return typeof v === "string";
|
|
3038
3041
|
}
|
|
3039
3042
|
function __sbIsFn(v) {
|
|
3040
3043
|
return v instanceof Function;
|
|
@@ -3936,6 +3939,9 @@ const __SB_BYTES_WINDOW = 512;
|
|
|
3936
3939
|
// TextEncoder); ArrayBuffer / typed-array input is copied byte for byte.
|
|
3937
3940
|
function __sbToBytes(input) {
|
|
3938
3941
|
if (input == null) return "";
|
|
3942
|
+
// sproutd #22: one C pass when the input allows it (see __sbToBytesNative).
|
|
3943
|
+
const native = __sbToBytesNative(input);
|
|
3944
|
+
if (native !== "") return native;
|
|
3939
3945
|
// Windowed accumulation (#180, then #181). Plain `s +=` in a loop is O(n^2)
|
|
3940
3946
|
// here, since Porffor's strings have no rope/cons optimization and every
|
|
3941
3947
|
// append copies the whole accumulated string -- that's #180, a 43KB body
|
|
@@ -4015,6 +4021,9 @@ function __sbBufFrom(latin1) {
|
|
|
4015
4021
|
// regardless of whether it holds real Latin-1 text or raw bytes, so this
|
|
4016
4022
|
// decode is only safe where the caller already knows which one it has.
|
|
4017
4023
|
function __sbFromUtf8(bytes) {
|
|
4024
|
+
// sproutd #22: one C pass for a string of bytes (see __sbFromUtf8Native).
|
|
4025
|
+
const native = __sbFromUtf8Native(bytes);
|
|
4026
|
+
if (native !== "") return native;
|
|
4018
4027
|
// Collected into an array and joined once at the end, not built with
|
|
4019
4028
|
// repeated `out +=` -- Porffor's strings have no rope/cons optimization, so
|
|
4020
4029
|
// `+=` in a loop copies the whole accumulated string on every append,
|
|
@@ -4672,8 +4681,167 @@ static int sb_os_random(unsigned char* buf, size_t n) {
|
|
|
4672
4681
|
return 0;
|
|
4673
4682
|
}
|
|
4674
4683
|
|
|
4684
|
+
// sproutd #22: text and bytes converted in one C pass. The JS loops in
|
|
4685
|
+
// __sbFromUtf8 and __sbToBytes made one string per character, so a 5 MiB R2
|
|
4686
|
+
// object read with text() took about 400 MiB of heap before the next collection.
|
|
4687
|
+
u32 porf_native_fetch_alloc(u32 bytes, u32 type);
|
|
4688
|
+
|
|
4689
|
+
// Lenient UTF-8 decode, exactly as __sbFromUtf8's JS: a lead byte whose
|
|
4690
|
+
// continuation bytes are not all 10xxxxxx passes through as its own unit.
|
|
4691
|
+
// OUT has room for LEN units. Returns the unit count; *WIDE is set when a unit
|
|
4692
|
+
// is above 0xff (the result then needs a UTF-16 string).
|
|
4693
|
+
static size_t sb_utf8_decode_units(const unsigned char* b, size_t len, uint16_t* out, int* wide) {
|
|
4694
|
+
size_t k = 0;
|
|
4695
|
+
*wide = 0;
|
|
4696
|
+
for (size_t i = 0; i < len; i++) {
|
|
4697
|
+
const unsigned b0 = b[i];
|
|
4698
|
+
if (b0 >= 0x80) {
|
|
4699
|
+
if ((b0 & 0xe0) == 0xc0 && i + 1 < len && (b[i + 1] & 0xc0) == 0x80) {
|
|
4700
|
+
out[k] = (uint16_t)(((b0 & 0x1f) << 6) | (b[i + 1] & 0x3f));
|
|
4701
|
+
if (out[k] > 0xff) *wide = 1;
|
|
4702
|
+
k++; i += 1; continue;
|
|
4703
|
+
}
|
|
4704
|
+
if ((b0 & 0xf0) == 0xe0 && i + 2 < len && (b[i + 1] & 0xc0) == 0x80 && (b[i + 2] & 0xc0) == 0x80) {
|
|
4705
|
+
out[k] = (uint16_t)(((b0 & 0x0f) << 12) | ((b[i + 1] & 0x3f) << 6) | (b[i + 2] & 0x3f));
|
|
4706
|
+
if (out[k] > 0xff) *wide = 1;
|
|
4707
|
+
k++; i += 2; continue;
|
|
4708
|
+
}
|
|
4709
|
+
if ((b0 & 0xf8) == 0xf0 && i + 3 < len && (b[i + 1] & 0xc0) == 0x80 && (b[i + 2] & 0xc0) == 0x80 && (b[i + 3] & 0xc0) == 0x80) {
|
|
4710
|
+
int32_t cp = (int32_t)(((b0 & 0x07) << 18) | ((b[i + 1] & 0x3f) << 12) | ((b[i + 2] & 0x3f) << 6) | (b[i + 3] & 0x3f));
|
|
4711
|
+
cp -= 0x10000;
|
|
4712
|
+
out[k++] = (uint16_t)(0xd800 + (cp >> 10));
|
|
4713
|
+
out[k++] = (uint16_t)(0xdc00 + (cp & 0x3ff));
|
|
4714
|
+
*wide = 1;
|
|
4715
|
+
i += 3; continue;
|
|
4716
|
+
}
|
|
4717
|
+
}
|
|
4718
|
+
out[k++] = (uint16_t)b0;
|
|
4719
|
+
}
|
|
4720
|
+
return k;
|
|
4721
|
+
}
|
|
4722
|
+
|
|
4723
|
+
// UTF-8 encode, exactly as __sbToBytes's JS: a high surrogate takes the next
|
|
4724
|
+
// unit as its pair. OUT has room for 3 bytes per unit. Returns the byte count.
|
|
4725
|
+
static size_t sb_utf8_encode_units(const uint16_t* s, size_t len, unsigned char* out) {
|
|
4726
|
+
size_t k = 0;
|
|
4727
|
+
for (size_t i = 0; i < len; i++) {
|
|
4728
|
+
const uint32_t c = s[i];
|
|
4729
|
+
if (c < 0x80) out[k++] = (unsigned char)c;
|
|
4730
|
+
else if (c < 0x800) { out[k++] = (unsigned char)(0xc0 | (c >> 6)); out[k++] = (unsigned char)(0x80 | (c & 0x3f)); }
|
|
4731
|
+
else if (c >= 0xd800 && c < 0xdc00 && i + 1 < len) {
|
|
4732
|
+
const int32_t cp = 0x10000 + (int32_t)((c - 0xd800) << 10) + ((int32_t)s[++i] - 0xdc00);
|
|
4733
|
+
out[k++] = (unsigned char)(0xf0 | ((cp >> 18) & 0xff));
|
|
4734
|
+
out[k++] = (unsigned char)(0x80 | ((cp >> 12) & 0x3f));
|
|
4735
|
+
out[k++] = (unsigned char)(0x80 | ((cp >> 6) & 0x3f));
|
|
4736
|
+
out[k++] = (unsigned char)(0x80 | (cp & 0x3f));
|
|
4737
|
+
} else {
|
|
4738
|
+
out[k++] = (unsigned char)(0xe0 | ((c >> 12) & 0xff));
|
|
4739
|
+
out[k++] = (unsigned char)(0x80 | ((c >> 6) & 0x3f));
|
|
4740
|
+
out[k++] = (unsigned char)(0x80 | (c & 0x3f));
|
|
4741
|
+
}
|
|
4742
|
+
}
|
|
4743
|
+
return k;
|
|
4744
|
+
}
|
|
4745
|
+
|
|
4675
4746
|
`;
|
|
4676
4747
|
|
|
4748
|
+
// sproutd #22: __sbFromUtf8 for a string of bytes (one byte per unit), in C.
|
|
4749
|
+
// Returns "" when it cannot (not a string, or out of memory), so the caller
|
|
4750
|
+
// falls back to the JS loop. All-ASCII byte strings are already their text.
|
|
4751
|
+
// oxlint-disable-next-line no-unused-vars -- `bytes` is read inside the RawC block below, not by JS.
|
|
4752
|
+
function __sbFromUtf8Native(bytes) {
|
|
4753
|
+
let out = "";
|
|
4754
|
+
// oxlint-disable-next-line no-unused-expressions -- Porffor.c`...` is inline C the compiler consumes, not a JS expression.
|
|
4755
|
+
Porffor.c`
|
|
4756
|
+
if (bytes.type == 195 || bytes.type == 67) {
|
|
4757
|
+
const u32 __p = (u32)bytes.val;
|
|
4758
|
+
const size_t __n = (size_t)*(u32*)(MEM + __p);
|
|
4759
|
+
int __ascii = bytes.type == 195;
|
|
4760
|
+
if (__ascii) {
|
|
4761
|
+
const unsigned char* __s = (const unsigned char*)(MEM + __p + 4);
|
|
4762
|
+
for (size_t __i = 0; __i < __n; __i++) if (__s[__i] >= 0x80) { __ascii = 0; break; }
|
|
4763
|
+
}
|
|
4764
|
+
if (__ascii) out = bytes;
|
|
4765
|
+
else {
|
|
4766
|
+
unsigned char* __b = (unsigned char*)malloc(__n + 1);
|
|
4767
|
+
uint16_t* __u = (uint16_t*)malloc(__n * 2 + 2);
|
|
4768
|
+
if (__b && __u) {
|
|
4769
|
+
if (bytes.type == 195) memcpy(__b, MEM + __p + 4, __n);
|
|
4770
|
+
else { const uint16_t* __w = (const uint16_t*)(MEM + __p + 4); for (size_t __i = 0; __i < __n; __i++) __b[__i] = (unsigned char)(__w[__i] & 0xff); }
|
|
4771
|
+
int __wide = 0;
|
|
4772
|
+
const size_t __k = sb_utf8_decode_units(__b, __n, __u, &__wide);
|
|
4773
|
+
if (__wide) {
|
|
4774
|
+
const u32 __s = porf_native_fetch_alloc((u32)(4 + __k * 2), 67);
|
|
4775
|
+
*(u32*)(MEM + __s) = (u32)__k;
|
|
4776
|
+
memcpy(MEM + __s + 4, __u, __k * 2);
|
|
4777
|
+
out = porf_box((f64)__s, 67);
|
|
4778
|
+
} else {
|
|
4779
|
+
for (size_t __i = 0; __i < __k; __i++) __b[__i] = (unsigned char)__u[__i];
|
|
4780
|
+
out = porf_box((f64)porf_native_fetch_alloc_bytestring((const char*)__b, __k), 195);
|
|
4781
|
+
}
|
|
4782
|
+
}
|
|
4783
|
+
free(__b); free(__u);
|
|
4784
|
+
}
|
|
4785
|
+
}
|
|
4786
|
+
`;
|
|
4787
|
+
return out;
|
|
4788
|
+
}
|
|
4789
|
+
|
|
4790
|
+
// sproutd #22: __sbToBytes for a string, a Uint8Array or an ArrayBuffer, in C.
|
|
4791
|
+
// Returns "" when it cannot (another type, a length-tracking view, out of
|
|
4792
|
+
// memory), so the caller falls back to the JS loop.
|
|
4793
|
+
// oxlint-disable-next-line no-unused-vars -- `input` is read inside the RawC block below, not by JS.
|
|
4794
|
+
function __sbToBytesNative(input) {
|
|
4795
|
+
let out = "";
|
|
4796
|
+
// oxlint-disable-next-line no-unused-expressions -- Porffor.c`...` is inline C the compiler consumes, not a JS expression.
|
|
4797
|
+
Porffor.c`
|
|
4798
|
+
const u32 __p = (u32)input.val;
|
|
4799
|
+
if (input.type == 195) {
|
|
4800
|
+
const size_t __n = (size_t)*(u32*)(MEM + __p);
|
|
4801
|
+
const unsigned char* __s = (const unsigned char*)(MEM + __p + 4);
|
|
4802
|
+
size_t __high = 0;
|
|
4803
|
+
for (size_t __i = 0; __i < __n; __i++) if (__s[__i] >= 0x80) __high++;
|
|
4804
|
+
if (!__high) out = input;
|
|
4805
|
+
else {
|
|
4806
|
+
unsigned char* __o = (unsigned char*)malloc(__n + __high + 1);
|
|
4807
|
+
if (__o) {
|
|
4808
|
+
const unsigned char* __src = (const unsigned char*)(MEM + __p + 4);
|
|
4809
|
+
size_t __k = 0;
|
|
4810
|
+
for (size_t __i = 0; __i < __n; __i++) {
|
|
4811
|
+
const unsigned char __c = __src[__i];
|
|
4812
|
+
if (__c < 0x80) __o[__k++] = __c;
|
|
4813
|
+
else { __o[__k++] = (unsigned char)(0xc0 | (__c >> 6)); __o[__k++] = (unsigned char)(0x80 | (__c & 0x3f)); }
|
|
4814
|
+
}
|
|
4815
|
+
out = porf_box((f64)porf_native_fetch_alloc_bytestring((const char*)__o, __k), 195);
|
|
4816
|
+
free(__o);
|
|
4817
|
+
}
|
|
4818
|
+
}
|
|
4819
|
+
} else if (input.type == 67) {
|
|
4820
|
+
const size_t __n = (size_t)*(u32*)(MEM + __p);
|
|
4821
|
+
uint16_t* __w = (uint16_t*)malloc(__n * 2 + 2);
|
|
4822
|
+
unsigned char* __o = (unsigned char*)malloc(__n * 3 + 1);
|
|
4823
|
+
if (__w && __o) {
|
|
4824
|
+
memcpy(__w, MEM + __p + 4, __n * 2);
|
|
4825
|
+
const size_t __k = sb_utf8_encode_units(__w, __n, __o);
|
|
4826
|
+
out = porf_box((f64)porf_native_fetch_alloc_bytestring((const char*)__o, __k), 195);
|
|
4827
|
+
}
|
|
4828
|
+
free(__w); free(__o);
|
|
4829
|
+
} else if (input.type == 13 || input.type == 81) {
|
|
4830
|
+
const int32_t __len = *(int32_t*)(MEM + __p);
|
|
4831
|
+
if (__len > 0) {
|
|
4832
|
+
const u32 __data = input.type == 13 ? __p + 8 : *(u32*)(MEM + __p + 4) + 4;
|
|
4833
|
+
unsigned char* __o = (unsigned char*)malloc((size_t)__len);
|
|
4834
|
+
if (__o) {
|
|
4835
|
+
memcpy(__o, MEM + __data, (size_t)__len);
|
|
4836
|
+
out = porf_box((f64)porf_native_fetch_alloc_bytestring((const char*)__o, (size_t)__len), 195);
|
|
4837
|
+
free(__o);
|
|
4838
|
+
}
|
|
4839
|
+
}
|
|
4840
|
+
}
|
|
4841
|
+
`;
|
|
4842
|
+
return out;
|
|
4843
|
+
}
|
|
4844
|
+
|
|
4677
4845
|
// TRANSPORT: wrap.ts splices one of transport-broker.js / transport-embedded.js here.
|
|
4678
4846
|
|
|
4679
4847
|
// `nStr` is the decimal byte count as a string (same string-param pattern as
|
|
@@ -5218,6 +5386,15 @@ function __sbR2Object(meta, body) {
|
|
|
5218
5386
|
return obj;
|
|
5219
5387
|
}
|
|
5220
5388
|
|
|
5389
|
+
// A part's value for the transport: an ArrayBuffer or a view as its bytes (String() of one
|
|
5390
|
+
// stored "[object ArrayBuffer]", at every date), anything else as text, as before.
|
|
5391
|
+
function __sbR2PartValue(value) {
|
|
5392
|
+
value = __sbUnwrapBody(value);
|
|
5393
|
+
if (value == null) return "";
|
|
5394
|
+
if (!__sbIsStr(value) && value.byteLength !== undefined)
|
|
5395
|
+
return __sbToBytes(value.buffer !== undefined ? new Uint8Array(value.buffer, value.byteOffset, value.byteLength) : new Uint8Array(value));
|
|
5396
|
+
return String(value);
|
|
5397
|
+
}
|
|
5221
5398
|
function __sbR2Multipart(bucket, key, uploadId) {
|
|
5222
5399
|
return {
|
|
5223
5400
|
key,
|
|
@@ -5226,7 +5403,7 @@ function __sbR2Multipart(bucket, key, uploadId) {
|
|
|
5226
5403
|
const number = Number(partNumber);
|
|
5227
5404
|
if (!Number.isInteger(number) || number < 1 || number > 10000)
|
|
5228
5405
|
throw new TypeError("partNumber must be an integer between 1 and 10000");
|
|
5229
|
-
return __sbR2MultipartPut(bucket, key, uploadId, number,
|
|
5406
|
+
return __sbR2MultipartPut(bucket, key, uploadId, number, __sbR2PartValue(value)).part;
|
|
5230
5407
|
},
|
|
5231
5408
|
complete(parts) {
|
|
5232
5409
|
const r = __sbRpc("r2.multipart.complete", { bucket, key, uploadId, parts: parts || [] });
|
|
@@ -5361,7 +5538,16 @@ function __sbR2StrictObject(meta, bytes, range, include) {
|
|
|
5361
5538
|
used = true;
|
|
5362
5539
|
return bytes;
|
|
5363
5540
|
};
|
|
5364
|
-
|
|
5541
|
+
// The stream is made when first asked for: text() and friends read the bytes directly,
|
|
5542
|
+
// so an object read as text never holds a second copy (sproutd #22).
|
|
5543
|
+
let stream = null;
|
|
5544
|
+
Object.defineProperty(obj, "body", {
|
|
5545
|
+
get: () => {
|
|
5546
|
+
if (stream === null) stream = new Response(__sbBufFrom(bytes)).body;
|
|
5547
|
+
return stream;
|
|
5548
|
+
},
|
|
5549
|
+
enumerable: true,
|
|
5550
|
+
});
|
|
5365
5551
|
Object.defineProperty(obj, "bodyUsed", { get: () => used, enumerable: true });
|
|
5366
5552
|
obj.text = async () => __sbFromUtf8(take());
|
|
5367
5553
|
obj.json = async () => JSON.parse(__sbFromUtf8(take()));
|
|
@@ -5392,7 +5578,13 @@ function __sbMakeR2(name) {
|
|
|
5392
5578
|
return {
|
|
5393
5579
|
key,
|
|
5394
5580
|
uploadId,
|
|
5395
|
-
|
|
5581
|
+
// A part is any value put() takes; text is stored as its UTF-8 bytes, as in workerd.
|
|
5582
|
+
uploadPart: async (partNumber, value) => {
|
|
5583
|
+
value = __sbUnwrapBody(value);
|
|
5584
|
+
if (value instanceof Blob) value = await value.arrayBuffer();
|
|
5585
|
+
else if (value != null && __sbIsFn(value.getReader)) value = await new Response(value).arrayBuffer();
|
|
5586
|
+
return inner.uploadPart(partNumber, __sbIsStr(value) ? __sbToBytes(value) : value);
|
|
5587
|
+
},
|
|
5396
5588
|
// ponytail: a multipart object's etag stays the transport's sha256; workerd's is
|
|
5397
5589
|
// MD5-of-part-MD5s-N. Add when an app compares multipart etags.
|
|
5398
5590
|
complete: (parts) => attempt(() => __sbR2StrictObject(__sbRpc("r2.multipart.complete", { bucket: name, key, uploadId, parts: parts || [] }).object, null)),
|
|
@@ -5415,7 +5607,8 @@ function __sbMakeR2(name) {
|
|
|
5415
5607
|
if (!__sbR2OnlyIf(o.onlyIf, meta.md5 || meta.etag, meta.uploaded)) return __sbR2StrictObject(meta, null, { offset: 0, length: meta.size });
|
|
5416
5608
|
const bytes = r.body == null ? "" : r.body;
|
|
5417
5609
|
const range = o.range == null ? { offset: 0, length: meta.size } : __sbR2Range(o.range, meta.size);
|
|
5418
|
-
|
|
5610
|
+
const whole = range.offset === 0 && range.length >= bytes.length;
|
|
5611
|
+
return __sbR2StrictObject(meta, whole ? bytes : bytes.slice(range.offset, range.offset + range.length), range);
|
|
5419
5612
|
});
|
|
5420
5613
|
},
|
|
5421
5614
|
async put(key, value, options) {
|
package/src/r2-object.test.js
CHANGED
|
@@ -18,6 +18,9 @@ const rawStart = src.indexOf("function __sbRawBodyResponse(");
|
|
|
18
18
|
const utf8End = rawStart;
|
|
19
19
|
const rawEnd = src.indexOf("function __sbEqCt(");
|
|
20
20
|
const r2Start = src.indexOf("function __sbR2Object(");
|
|
21
|
+
const isStrStart = src.indexOf("function __sbIsStr(");
|
|
22
|
+
const isStrEnd = src.indexOf("function __sbIsFn(");
|
|
23
|
+
const bytesStart = src.indexOf("const __SB_BYTES_WINDOW");
|
|
21
24
|
const r2End = src.indexOf("// Installed only when the project declares bindings.");
|
|
22
25
|
if (utf8Start === -1 || utf8End === -1) throw new Error("__sbFromUtf8 block not found in prelude");
|
|
23
26
|
if (rawStart === -1 || rawEnd === -1) throw new Error("__sbRawBodyResponse block not found in prelude");
|
|
@@ -27,7 +30,8 @@ if (r2Start === -1 || r2End === -1 || r2End < r2Start) throw new Error("__sbR2Ob
|
|
|
27
30
|
const load = new Function(
|
|
28
31
|
"__sbRpc",
|
|
29
32
|
"__sbR2MultipartPut",
|
|
30
|
-
|
|
33
|
+
// __sbIsStr and __sbToBytes (for uploadPart's values), with the C fast paths stubbed out.
|
|
34
|
+
`function __sbFromUtf8Native() { return ""; }\nfunction __sbToBytesNative() { return ""; }\n${src.slice(isStrStart, isStrEnd)}\n${src.slice(bytesStart, utf8Start)}\n${src.slice(utf8Start, utf8End)}\n${src.slice(rawStart, rawEnd)}\n${src.slice(r2Start, r2End)}\nreturn { __sbR2Object, __sbR2Multipart };`,
|
|
31
35
|
);
|
|
32
36
|
const calls = [];
|
|
33
37
|
const rpc = (op, value) => {
|
|
@@ -70,7 +74,7 @@ test("toResponse() lets caller-supplied headers/status override the defaults", (
|
|
|
70
74
|
expect(resp.headers.get("content-type")).toBe("application/octet-stream");
|
|
71
75
|
});
|
|
72
76
|
|
|
73
|
-
test(
|
|
77
|
+
test('toResponse() on an empty body still returns bytes, not the string ""', async () => {
|
|
74
78
|
const obj = __sbR2Object(meta, "");
|
|
75
79
|
const resp = obj.toResponse();
|
|
76
80
|
const buf = new Uint8Array(await resp.arrayBuffer());
|
|
@@ -84,9 +88,14 @@ test("multipart uploads expose the Cloudflare-shaped uploadPart, complete, and a
|
|
|
84
88
|
expect(upload.uploadPart(1, "first")).toEqual({ partNumber: 1, etag: "part-1" });
|
|
85
89
|
expect(upload.complete([{ partNumber: 1, etag: "part-1" }])).toMatchObject(meta);
|
|
86
90
|
upload.abort();
|
|
87
|
-
expect(calls.map((call) => call.op)).toEqual([
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
91
|
+
expect(calls.map((call) => call.op)).toEqual(["r2.multipart.put", "r2.multipart.complete", "r2.multipart.abort"]);
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
test("uploadPart stores an ArrayBuffer or a view as its bytes, not as [object ArrayBuffer]", () => {
|
|
95
|
+
calls.length = 0;
|
|
96
|
+
const upload = __sbR2Multipart("FILES", "archive.bin", "upload-1");
|
|
97
|
+
upload.uploadPart(1, new Uint8Array([0, 255, 65]).buffer);
|
|
98
|
+
upload.uploadPart(2, new Uint8Array([9, 8, 7, 6]).subarray(1, 3));
|
|
99
|
+
upload.uploadPart(3, "text");
|
|
100
|
+
expect(calls.map((call) => call.value.body)).toEqual(["\u0000ÿA", "\u0008\u0007", "text"]);
|
|
92
101
|
});
|
package/src/to-bytes.test.js
CHANGED
|
@@ -22,7 +22,7 @@ if (hexStart === -1 || hexEnd === -1 || hexEnd < hexStart) throw new Error("__sb
|
|
|
22
22
|
|
|
23
23
|
// oxlint-disable-next-line no-function-constructor -- lifting pure blocks out of the text-only prelude for test
|
|
24
24
|
const load = new Function(
|
|
25
|
-
|
|
25
|
+
`// The C fast paths (Porffor.c) cannot run here: the stubs make the JS fallback run.\nfunction __sbFromUtf8Native() { return ""; }\nfunction __sbToBytesNative() { return ""; }\n${src.slice(isStrStart, isStrEnd)}\n${src.slice(start, end)}\n${src.slice(hexStart, hexEnd)}\nreturn { __sbToBytes, __sbHexOrBytes };`,
|
|
26
26
|
);
|
|
27
27
|
const { __sbToBytes, __sbHexOrBytes } = load();
|
|
28
28
|
|
package/src/utf8-decode.test.js
CHANGED
|
@@ -12,7 +12,9 @@ const end = src.indexOf("// sproutboat #181 — wrap a Response");
|
|
|
12
12
|
if (start === -1 || end === -1 || end < start) throw new Error("__sbFromUtf8 block not found in prelude");
|
|
13
13
|
|
|
14
14
|
// oxlint-disable-next-line no-function-constructor -- lifting a pure block out of the text-only prelude for test
|
|
15
|
-
const load = new Function(
|
|
15
|
+
const load = new Function(
|
|
16
|
+
`// The C fast paths (Porffor.c) cannot run here: the stubs make the JS fallback run.\nfunction __sbFromUtf8Native() { return ""; }\nfunction __sbToBytesNative() { return ""; }\n${src.slice(start, end)}\nreturn { __sbFromUtf8 };`,
|
|
17
|
+
);
|
|
16
18
|
const { __sbFromUtf8 } = load();
|
|
17
19
|
|
|
18
20
|
/** Build a bytestring (one char per raw byte) the way __sbToBytes/porf_native_fetch_alloc_bytestring would, from real UTF-8 bytes. */
|
|
@@ -78,7 +80,7 @@ if (rbrStart === -1 || rbrEnd === -1 || rbrEnd < rbrStart) {
|
|
|
78
80
|
// oxlint-disable-next-line no-function-constructor -- lifting a pure block out of the text-only prelude for test
|
|
79
81
|
const loadRbr = new Function(
|
|
80
82
|
"Response",
|
|
81
|
-
|
|
83
|
+
`// The C fast paths (Porffor.c) cannot run here: the stubs make the JS fallback run.\nfunction __sbFromUtf8Native() { return ""; }\nfunction __sbToBytesNative() { return ""; }\n${src.slice(start, end)}\n${src.slice(rbrStart, rbrEnd)}\nreturn { __sbRawBodyResponse };`,
|
|
82
84
|
);
|
|
83
85
|
// A minimal Response stand-in: only what __sbRawBodyResponse touches (the
|
|
84
86
|
// constructor call and setting .text/.json on the instance), no Porffor
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join, resolve } from "node:path";
|
|
5
|
+
import { ensurePorffor } from "../../toolchain/src/acquire";
|
|
6
|
+
import { preludePath, TRANSPORT_MARKER, transportPath, wrapNativeFetchHandler } from "../src/wrap";
|
|
7
|
+
|
|
8
|
+
// sproutd #22: __sbFromUtf8 and __sbToBytes run in C (__sbFromUtf8Native, __sbToBytesNative).
|
|
9
|
+
// They must give exactly what the JS loops gave, and a body of megabytes must not take
|
|
10
|
+
// hundreds of megabytes of heap (the JS made one string per character: a 5 MiB R2 object
|
|
11
|
+
// read with text() took about 400 MiB).
|
|
12
|
+
const handler = `const bytes = (list) => { let s = ""; for (const b of list) s += String.fromCharCode(b); return s; };
|
|
13
|
+
const codes = (s) => { const out = []; for (let i = 0; i < s.length; i++) out.push(s.charCodeAt(i)); return out; };
|
|
14
|
+
export default {fetch(request) {
|
|
15
|
+
if (new URL(request.url).pathname === "/big") {
|
|
16
|
+
const text = __sbFromUtf8("\\u00c3\\u00a9".repeat(4 * 1024 * 1024));
|
|
17
|
+
const utf8 = __sbToBytes("\\u2713".repeat(1024 * 1024));
|
|
18
|
+
const ascii = __sbToBytes("a".repeat(8 * 1024 * 1024));
|
|
19
|
+
return new Response(JSON.stringify([text.length, text.charCodeAt(0), utf8.length, utf8.charCodeAt(2), ascii.length]));
|
|
20
|
+
}
|
|
21
|
+
const decode = [
|
|
22
|
+
"hello", bytes([0x63, 0x61, 0x66, 0xc3, 0xa9, 0x20, 0xf0, 0x9f, 0x8c, 0xb1, 0x20, 0xe2, 0x9c, 0x93]),
|
|
23
|
+
bytes([0xc2]), bytes([0xe9, 0x41]), bytes([0xf0, 0x9f, 0x8c]), bytes([0xe2, 0x28, 0xa1]), bytes([0xc0, 0x80]),
|
|
24
|
+
bytes([0xf8, 0x88, 0x80, 0x80, 0x80]), bytes([0xed, 0xa0, 0x80]), bytes([0xf4, 0x90, 0x80, 0x80]), bytes([0xff, 0xfe, 0x00]),
|
|
25
|
+
JSON.parse('"caf\\\\u00c3\\\\u00a9 \\\\u0100"'), JSON.parse('"\\\\u00e2\\\\u009c\\\\u0093"'), "",
|
|
26
|
+
];
|
|
27
|
+
const encode = [
|
|
28
|
+
"hello", "caf\\u00e9", "\\u2713 \\ud83c\\udf31", "\\ud800x", "\\udc00", "a\\ud800", "\\u0100\\u07ff\\u0800\\uffff", "",
|
|
29
|
+
new Uint8Array([0, 255, 128]), new Uint8Array([1, 2, 3]).buffer, new Uint8Array(new Uint8Array([9, 8, 7, 6]).buffer, 1, 2), new Uint8Array(0),
|
|
30
|
+
];
|
|
31
|
+
return new Response(JSON.stringify({ decode: decode.map((s) => codes(__sbFromUtf8(s))), encode: encode.map((v) => codes(__sbToBytes(v))) }));
|
|
32
|
+
}};`;
|
|
33
|
+
|
|
34
|
+
// The JS the C replaces, lifted from the prelude with the C stubbed out, as the reference.
|
|
35
|
+
const core = await readFile(preludePath, "utf8");
|
|
36
|
+
const lift = (from: string, to: string) => {
|
|
37
|
+
const start = core.indexOf(from);
|
|
38
|
+
const end = core.indexOf(to, start);
|
|
39
|
+
assert(start >= 0 && end > start, `${from} block not found in prelude`);
|
|
40
|
+
return core.slice(start, end);
|
|
41
|
+
};
|
|
42
|
+
// oxlint-disable-next-line no-function-constructor -- lifting pure blocks out of the text-only prelude for the reference
|
|
43
|
+
const reference = new Function(
|
|
44
|
+
`function __sbFromUtf8Native() { return ""; }\nfunction __sbToBytesNative() { return ""; }\n` +
|
|
45
|
+
lift("function __sbIsStr(", "function __sbIsFn(") +
|
|
46
|
+
lift("const __SB_BYTES_WINDOW", "function __sbBufFrom(") +
|
|
47
|
+
lift("function __sbFromUtf8(", "// sproutboat #181") +
|
|
48
|
+
"return { __sbFromUtf8, __sbToBytes };",
|
|
49
|
+
)();
|
|
50
|
+
const bytes = (list: number[]) => String.fromCharCode(...list);
|
|
51
|
+
const codes = (s: string) => [...s].flatMap((c) => [...Array(c.length).keys()].map((i) => c.charCodeAt(i)));
|
|
52
|
+
const want = {
|
|
53
|
+
decode: [
|
|
54
|
+
"hello",
|
|
55
|
+
bytes([0x63, 0x61, 0x66, 0xc3, 0xa9, 0x20, 0xf0, 0x9f, 0x8c, 0xb1, 0x20, 0xe2, 0x9c, 0x93]),
|
|
56
|
+
bytes([0xc2]),
|
|
57
|
+
bytes([0xe9, 0x41]),
|
|
58
|
+
bytes([0xf0, 0x9f, 0x8c]),
|
|
59
|
+
bytes([0xe2, 0x28, 0xa1]),
|
|
60
|
+
bytes([0xc0, 0x80]),
|
|
61
|
+
bytes([0xf8, 0x88, 0x80, 0x80, 0x80]),
|
|
62
|
+
bytes([0xed, 0xa0, 0x80]),
|
|
63
|
+
bytes([0xf4, 0x90, 0x80, 0x80]),
|
|
64
|
+
bytes([0xff, 0xfe, 0x00]),
|
|
65
|
+
"café Ā",
|
|
66
|
+
"â\u009c\u0093",
|
|
67
|
+
"",
|
|
68
|
+
].map((s) => codes(reference.__sbFromUtf8(s))),
|
|
69
|
+
encode: [
|
|
70
|
+
"hello",
|
|
71
|
+
"café",
|
|
72
|
+
"✓ 🌱",
|
|
73
|
+
"\ud800x",
|
|
74
|
+
"\udc00",
|
|
75
|
+
"a\ud800",
|
|
76
|
+
"Ā߿ࠀ",
|
|
77
|
+
"",
|
|
78
|
+
new Uint8Array([0, 255, 128]),
|
|
79
|
+
new Uint8Array([1, 2, 3]).buffer,
|
|
80
|
+
new Uint8Array(new Uint8Array([9, 8, 7, 6]).buffer, 1, 2),
|
|
81
|
+
new Uint8Array(0),
|
|
82
|
+
].map((v) => codes(reference.__sbToBytes(v))),
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
function freePort(): number {
|
|
86
|
+
const listener = Bun.listen({ hostname: "127.0.0.1", port: 0, socket: { data() {} } });
|
|
87
|
+
const port = listener.port;
|
|
88
|
+
listener.stop(true);
|
|
89
|
+
return port;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const workdir = await mkdtemp(join(tmpdir(), "sb-native-byte-text-"));
|
|
93
|
+
let server: ReturnType<typeof Bun.spawn> | undefined;
|
|
94
|
+
try {
|
|
95
|
+
const porffor = await ensurePorffor();
|
|
96
|
+
const node = Bun.which("node");
|
|
97
|
+
if (!node) throw new Error("native byte-text test needs node on PATH");
|
|
98
|
+
const broker = await readFile(transportPath("broker"), "utf8");
|
|
99
|
+
assert(core.includes(TRANSPORT_MARKER), "runtime prelude is missing its transport marker");
|
|
100
|
+
const generated = join(workdir, "bytes.generated.js");
|
|
101
|
+
const binary = join(workdir, "bytes-native");
|
|
102
|
+
await writeFile(generated, wrapNativeFetchHandler(handler, core.replace(TRANSPORT_MARKER, broker)));
|
|
103
|
+
const compile = Bun.spawn(
|
|
104
|
+
[node, resolve(porffor, "runtime/index.js"), "native", generated, "-o", binary, "-s", "-O0"],
|
|
105
|
+
{
|
|
106
|
+
cwd: workdir,
|
|
107
|
+
stdout: "pipe",
|
|
108
|
+
stderr: "pipe",
|
|
109
|
+
},
|
|
110
|
+
);
|
|
111
|
+
const [exitCode, stdout, stderr] = await Promise.all([
|
|
112
|
+
compile.exited,
|
|
113
|
+
new Response(compile.stdout).text(),
|
|
114
|
+
new Response(compile.stderr).text(),
|
|
115
|
+
]);
|
|
116
|
+
assert.equal(exitCode, 0, `Porffor native compile failed:\n${stderr}\n${stdout}`);
|
|
117
|
+
|
|
118
|
+
const port = freePort();
|
|
119
|
+
// Peak RSS: /proc's high-water mark on Linux, time(1) on macOS.
|
|
120
|
+
const linux = process.platform === "linux";
|
|
121
|
+
server = Bun.spawn(linux ? [binary] : ["/usr/bin/time", "-l", binary], {
|
|
122
|
+
cwd: workdir,
|
|
123
|
+
env: { ...process.env, PORT: String(port) },
|
|
124
|
+
stdout: "ignore",
|
|
125
|
+
stderr: "pipe",
|
|
126
|
+
});
|
|
127
|
+
let ready = false;
|
|
128
|
+
for (let attempt = 0; attempt < 50 && !ready; attempt++) {
|
|
129
|
+
try {
|
|
130
|
+
await fetch(`http://127.0.0.1:${port}/`, { signal: AbortSignal.timeout(500) });
|
|
131
|
+
ready = true;
|
|
132
|
+
} catch {
|
|
133
|
+
if (server.exitCode !== null) break;
|
|
134
|
+
await Bun.sleep(100);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
assert(ready, "compiled handler did not start");
|
|
138
|
+
const got = await (await fetch(`http://127.0.0.1:${port}/`)).json();
|
|
139
|
+
assert.deepEqual(got.decode, want.decode, "__sbFromUtf8 in C decodes as the JS did");
|
|
140
|
+
assert.deepEqual(got.encode, want.encode, "__sbToBytes in C encodes as the JS did");
|
|
141
|
+
console.log("C byte/text conversions match the JS ones");
|
|
142
|
+
|
|
143
|
+
const big = await (await fetch(`http://127.0.0.1:${port}/big`)).json();
|
|
144
|
+
assert.deepEqual(big, [4 * 1024 * 1024, 0xe9, 3 * 1024 * 1024, 0x93, 8 * 1024 * 1024]);
|
|
145
|
+
let peak = 0;
|
|
146
|
+
if (linux) {
|
|
147
|
+
const status = await readFile(`/proc/${server.pid}/status`, "utf8");
|
|
148
|
+
peak = Number(/VmHWM:\s+(\d+) kB/.exec(status)?.[1] ?? 0) * 1024;
|
|
149
|
+
}
|
|
150
|
+
server.kill("SIGINT");
|
|
151
|
+
const timing = linux ? "" : await new Response(server.stderr).text();
|
|
152
|
+
await server.exited;
|
|
153
|
+
server = undefined;
|
|
154
|
+
if (!linux) peak = Number(/(\d+)\s+maximum resident set size/.exec(timing)?.[1] ?? 0);
|
|
155
|
+
assert(peak > 0, "peak RSS was measured");
|
|
156
|
+
// The JS took over 600 MiB for these; the C needs the strings plus one scratch copy.
|
|
157
|
+
assert(peak < 96 * 1024 * 1024, `8 MiB conversions peaked at ${(peak / 1048576).toFixed(1)} MiB`);
|
|
158
|
+
console.log(`8 MiB conversions peak at ${(peak / 1048576).toFixed(1)} MiB RSS`);
|
|
159
|
+
} finally {
|
|
160
|
+
if (server) {
|
|
161
|
+
server.kill(9);
|
|
162
|
+
await server.exited;
|
|
163
|
+
}
|
|
164
|
+
await rm(workdir, { recursive: true, force: true });
|
|
165
|
+
}
|