Visual Studio Code, rebuilt in Rust
Rust
#!/usr/bin/env bun
// A local update feed for tests (port/notes.md "Update feed"): serves the files of <dir> on 127.0.0.1 and logs each
// request. A request with `?cut` (put it in the feed entry's url) gets the full Content-Length but only the first half
// of the file, then the connection closes: a download cut midway.
// port/tools/update-feed <dir> [port] prints "update-feed: http://127.0.0.1:<port>/"
import { existsSync, statSync } from 'node:fs';
import { join, normalize } from 'node:path';
const [dir, port = '0'] = process.argv.slice(2);
const server = Bun.serve({
port: Number(port),
hostname: '127.0.0.1',
async fetch(request) {
const url = new URL(request.url);
const path = join(dir, normalize(decodeURIComponent(url.pathname)).replace(/^(\.\.\/)+/, ''));
console.log(`update-feed: ${request.method} ${url.pathname}${url.search}`);
if (!existsSync(path) || !statSync(path).isFile()) {
return new Response('Not Found', { status: 404 });
}
const file = Bun.file(path);
if (!url.searchParams.has('cut')) {
return new Response(file);
}
const half = (await file.arrayBuffer()).slice(0, Math.floor(file.size / 2));
const stream = new ReadableStream({
async start(controller) {
controller.enqueue(new Uint8Array(half));
await Bun.sleep(500);
controller.error(new Error('update-feed: cut midway'));
},
});
return new Response(stream, { headers: { 'Content-Length': String(file.size) } });
},
});
console.log(`update-feed: http://127.0.0.1:${server.port}/`);