Skip to content

Commit 4d33cdc

Browse files
committed
♻️ stream the text rebase instead of slurping it
Reading each text body into a string to scan it undid, for text, the one good property the byte-for-byte branch had: memory that does not depend on the size of the document. With the default concurrency of 75 that is 75 whole documents in flight, and css and js bundles are not small. `RebaseTextStream` is a TransformStream that does the substitution as the body arrives, after the shape of `TextLineStream` in effectionx's jsonl-store: the crawl origin is a fixed string, so it holds back the longest partial match at the end of each chunk and lets `flush` emit whatever is left. Nothing else is buffered. Behavior is unchanged, including on failure. A body is only whole once it has all arrived, so it streams into the output root and is moved into place at the end; a body that fails midway leaves neither a truncated file nor an empty directory, exactly as slurping left nothing. Verified on a 12mb document: byte-identical output to the slurping version (same sha256) at half the peak rss, 190mb down to 92mb.
1 parent be302e9 commit 4d33cdc

4 files changed

Lines changed: 208 additions & 23 deletions

File tree

‎downloader.ts‎

Lines changed: 33 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import { fromHtml } from "hast-util-from-html";
1111
import { toHtml } from "hast-util-to-html";
1212
import { selectAll } from "hast-util-select";
1313
import { useTaskBuffer } from "./task-buffer.ts";
14-
import { rebase, rebaseText } from "./rebase.ts";
14+
import { rebase, RebaseTextStream } from "./rebase.ts";
1515
import { createApi } from "@effectionx/context-api";
1616

1717
export interface Downloader extends Operation<void> {
@@ -116,15 +116,38 @@ export const DownloadApi = createApi("@staticalize/download", {
116116
bytes: new TextEncoder().encode(output).byteLength,
117117
};
118118
} else if (isTextual(response.headers.get("Content-Type"))) {
119-
let content = yield* until(response.text());
120-
let output = rebaseText(content, host, base);
121-
let destdir = dirname(path);
122-
yield* until(ensureDir(destdir));
123-
yield* until(Deno.writeTextFile(path, output));
124-
return {
125-
ok: true,
126-
bytes: new TextEncoder().encode(output).byteLength,
127-
};
119+
let bytes = 0;
120+
let counted = new TransformStream<Uint8Array, Uint8Array>({
121+
transform(chunk, controller) {
122+
bytes += chunk.byteLength;
123+
controller.enqueue(chunk);
124+
},
125+
});
126+
127+
// a body is only whole once it has all arrived, so it streams into the
128+
// output root and is moved into place at the end. a body that fails
129+
// midway leaves neither a truncated file nor an empty directory.
130+
let partial = join(outdir, `.staticalize-${crypto.randomUUID()}.part`);
131+
132+
try {
133+
yield* until(
134+
Deno.writeFile(
135+
partial,
136+
response.body!
137+
.pipeThrough(new TextDecoderStream())
138+
.pipeThrough(new RebaseTextStream(host, base))
139+
.pipeThrough(new TextEncoderStream())
140+
.pipeThrough(counted),
141+
),
142+
);
143+
} catch (cause) {
144+
yield* until(Deno.remove(partial).catch(() => {}));
145+
throw cause;
146+
}
147+
148+
yield* until(ensureDir(dirname(path)));
149+
yield* until(Deno.rename(partial, path));
150+
return { ok: true, bytes };
128151
} else {
129152
let size = Number(response.headers.get("Content-Length") ?? 0);
130153
let destdir = dirname(path);

‎rebase.ts‎

Lines changed: 33 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -22,21 +22,41 @@ export function rebase(source: URL, base: URL): URL {
2222
}
2323

2424
/**
25-
* Replace self-referencing absolute urls in a text body with the public base.
25+
* A TransformStream that replaces self-referencing urls with the public base.
2626
*
2727
* There is no document to walk in a text body, so unlike the html pass this is
2828
* a substitution of the crawl origin rather than a rewrite of known
29-
* url-bearing attributes.
30-
*
31-
* @param body text served by the crawled site
32-
* @param host url of the site being crawled
33-
* @param base public base url of the site, path included
34-
* @returns the body with every url on the crawled site pointing at the base
29+
* url-bearing attributes. It runs over the response as it arrives, so the
30+
* memory it holds is a chunk and change rather than the whole document.
3531
*/
36-
export function rebaseText(body: string, host: URL, base: URL): string {
37-
// the crawl origin stands for the root of the site, so it maps onto the base
38-
// the same way any other url does. the result carries a trailing slash, which
39-
// the urls in the body bring themselves.
40-
let prefix = `${rebase(new URL(host.origin), base)}`.replace(/\/$/, "");
41-
return body.replaceAll(host.origin, prefix);
32+
export class RebaseTextStream extends TransformStream<string, string> {
33+
#carry = "";
34+
35+
constructor(host: URL, base: URL) {
36+
let needle = host.origin;
37+
// the crawl origin stands for the root of the site, so it maps onto the base
38+
// the same way any other url does. the result carries a trailing slash, which
39+
// the urls in the body bring themselves.
40+
let prefix = `${rebase(new URL(needle), base)}`.replace(/\/$/, "");
41+
// a match can straddle a chunk boundary, so hold back the longest partial
42+
// one and let the next chunk complete it
43+
let keep = needle.length - 1;
44+
45+
super({
46+
transform: (chunk, controller) => {
47+
let text = (this.#carry + chunk).replaceAll(needle, prefix);
48+
if (text.length > keep) {
49+
controller.enqueue(text.slice(0, text.length - keep));
50+
this.#carry = text.slice(text.length - keep);
51+
} else {
52+
this.#carry = text;
53+
}
54+
},
55+
flush: (controller) => {
56+
if (this.#carry.length > 0) {
57+
controller.enqueue(this.#carry);
58+
}
59+
},
60+
});
61+
}
4262
}

‎test/rebase.test.ts‎

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
import { expect } from "@std/expect";
2+
import { describe, it } from "@std/testing/bdd";
3+
4+
import { rebase, RebaseTextStream } from "../rebase.ts";
5+
6+
let host = new URL("http://localhost:8321");
7+
8+
async function rebased(
9+
chunks: string[],
10+
base: URL,
11+
from: URL = host,
12+
): Promise<string> {
13+
let stream = ReadableStream.from(chunks)
14+
.pipeThrough(new RebaseTextStream(from, base));
15+
let out = "";
16+
for await (let chunk of stream) {
17+
out += chunk;
18+
}
19+
return out;
20+
}
21+
22+
function cut(text: string, size: number): string[] {
23+
let chunks: string[] = [];
24+
for (let i = 0; i < text.length; i += size) {
25+
chunks.push(text.slice(i, i + size));
26+
}
27+
return chunks;
28+
}
29+
30+
describe("rebase", () => {
31+
it("takes the protocol, host and port of the base", () => {
32+
expect(rebase(new URL(`${host}about`), new URL("https://fs.com")).href)
33+
.toEqual("https://fs.com/about");
34+
});
35+
36+
it("prefixes the path of the base", () => {
37+
expect(
38+
rebase(new URL(`${host}about`), new URL("https://fs.com/effection")).href,
39+
).toEqual("https://fs.com/effection/about");
40+
});
41+
42+
it("treats a trailing slash on the base as no path at all", () => {
43+
expect(rebase(new URL(`${host}about`), new URL("https://fs.com/")).href)
44+
.toEqual("https://fs.com/about");
45+
});
46+
47+
it("keeps the query and fragment of the source", () => {
48+
expect(
49+
rebase(new URL(`${host}search?q=hi#top`), new URL("https://fs.com")).href,
50+
).toEqual("https://fs.com/search?q=hi#top");
51+
});
52+
});
53+
54+
describe("RebaseTextStream", () => {
55+
it("replaces every occurrence in a body", async () => {
56+
await expect(
57+
rebased(
58+
[`[API]: ${host}api.md and ${host}b.md`],
59+
new URL(
60+
"https://fs.com",
61+
),
62+
),
63+
).resolves.toEqual("[API]: https://fs.com/api.md and https://fs.com/b.md");
64+
});
65+
66+
it("leaves urls on other hosts alone", async () => {
67+
await expect(
68+
rebased(
69+
["see https://google.com/a and http://localhost:9999/b"],
70+
new URL(
71+
"https://fs.com",
72+
),
73+
),
74+
).resolves.toEqual("see https://google.com/a and http://localhost:9999/b");
75+
});
76+
77+
it("carries the path of the base", async () => {
78+
await expect(
79+
rebased([`${host}api.md`], new URL("https://fs.com/effection")),
80+
).resolves.toEqual("https://fs.com/effection/api.md");
81+
});
82+
83+
it("matches urls split across chunk boundaries", async () => {
84+
// the interesting cases are a match at the very start, at the very end,
85+
// back to back with another, and bare with no path of its own
86+
let body =
87+
`${host}a.md then ${host}b.md${host}c.md and a bare ${host} to close`;
88+
let want = body.replaceAll(host.origin, "https://fs.com");
89+
90+
for (let size of [1, 2, 3, 7, host.origin.length - 1, host.origin.length]) {
91+
await expect(rebased(cut(body, size), new URL("https://fs.com")))
92+
.resolves.toEqual(want);
93+
}
94+
});
95+
96+
it("emits a body that ends mid-match as it stands", async () => {
97+
// a truncated url is not a url, so it survives rather than disappearing
98+
let partial = host.origin.slice(0, -3);
99+
await expect(rebased(
100+
cut(`ends with ${partial}`, 4),
101+
new URL(
102+
"https://fs.com",
103+
),
104+
)).resolves.toEqual(`ends with ${partial}`);
105+
});
106+
107+
it("passes an empty body through", async () => {
108+
await expect(rebased([], new URL("https://fs.com"))).resolves.toEqual("");
109+
});
110+
});

‎test/staticalize.test.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -435,6 +435,38 @@ describe("staticalize", () => {
435435
);
436436
});
437437

438+
it("leaves nothing behind when a text body fails midway", async () => {
439+
// same bad-gzip fixture as above, but served as text: decoding throws part
440+
// way through, and a half written document is worse than none
441+
app.get(
442+
"/deeply/nested/bad.md",
443+
(c) =>
444+
c.body("this is definitely not gzip", 200, {
445+
"Content-Type": "text/markdown",
446+
"Content-Encoding": "gzip",
447+
}),
448+
)
449+
.get(...sitemap(["/deeply/nested/bad.md"]));
450+
451+
await staticalize({
452+
base: new URL("https://fs.com"),
453+
host,
454+
dir: "test/dist",
455+
});
456+
457+
await expect(exists("test/dist/deeply/nested/bad.md")).resolves.toEqual(
458+
false,
459+
);
460+
// nor is a directory made for a document that never landed
461+
await expect(exists("test/dist/deeply")).resolves.toEqual(false);
462+
// nor is the partial file it streamed into left in the output
463+
let leftovers = [];
464+
for await (let entry of Deno.readDir("test/dist")) {
465+
leftovers.push(entry.name);
466+
}
467+
expect(leftovers).toEqual(["sitemap.xml"]);
468+
});
469+
438470
it("streams bodies that are not text byte for byte", async () => {
439471
// a png that would be corrupted by a decode/encode round trip
440472
let png = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);

0 commit comments

Comments
 (0)