Files
Shade/scripts/media-live-kotlin.ts

119 lines
5.7 KiB
TypeScript
Raw Normal View History

/**
* Live cross-check of the Kotlin media uploader against the real TS relay.
*
* bun run scripts/media-live-kotlin.ts
*
* Serves `createMediaService` (disk store in a temp dir) on a free local
* port, with two faults on the way in: the piece at 16 MiB is stored but its
* answer is lost (a 503 after the store took it), and the piece at 32 MiB is
* refused once before the relay sees it. Uploads a small file with the TS
* client, then runs the gated `MediaLiveTest` in android/ with
* `SHADE_MEDIA_LIVE_SPEC` set. That test opens the TS file from its link,
* seals and uploads a 40 MiB film in pieces and a photo in one PUT, puts the
* film again (the relay already has it), runs an upload job that is "killed"
* after its first piece and resumed, and deletes the photo. This script
* then opens the Kotlin film from its link with the TS reader and checks every
* byte, and that both faults were hit and recovered from.
*
* Vectors pin the signatures byte for byte; this pins the conversation —
* real HTTP, real owner checks, the piece window and the resync after a lost
* answer — which no vector can.
*/
import { createHash, randomBytes } from 'node:crypto';
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { MediaClient, OwnerKey, fromCapabilityUrl, openGrant, toCapabilityUrl } from '../packages/shade-media/src/index.js';
import type { MediaGrant } from '../packages/shade-media/src/index.js';
import { createMediaService, mediaMaxRequestBody } from '../packages/shade-media/src/server.js';
import { OFFSET_HEADER } from '../packages/shade-media/src/upload.js';
const sha256 = (b: Uint8Array) => createHash('sha256').update(b).digest('hex');
function check(cond: unknown, what: string): asserts cond {
if (!cond) throw new Error(`live cross-check failed: ${what}`);
}
const MiB = 1024 * 1024;
const dir = await mkdtemp(join(tmpdir(), 'shade-media-live-'));
const kotlinSeed = new Uint8Array(randomBytes(32));
const kotlinOwner = new OwnerKey(kotlinSeed);
const tsOwner = new OwnerKey(new Uint8Array(randomBytes(32)));
const service = createMediaService({ dir, owners: [kotlinOwner.id, tsOwner.id] });
const faults = { lostAnswer: 0, refused: 0, pieces: 0, starts: 0 };
const server = Bun.serve({
port: 0,
hostname: '127.0.0.1',
maxRequestBodySize: mediaMaxRequestBody(),
async fetch(req) {
const path = new URL(req.url).pathname;
if (path.endsWith('/upload') && req.method === 'POST') faults.starts++;
if (path.endsWith('/upload') && req.method === 'PUT') {
faults.pieces++;
const offset = Number(req.headers.get(OFFSET_HEADER));
if (offset === 32 * MiB && faults.refused === 0) {
faults.refused++;
await req.arrayBuffer();
return new Response('<html><body>502 Bad Gateway</body></html>', { status: 503, headers: { 'content-type': 'text/html' } });
}
if (offset === 16 * MiB && faults.lostAnswer === 0) {
faults.lostAnswer++;
const res = await service.app.fetch(req);
check(res.status === 200 || res.status === 201, `the stored-but-lost piece was refused: ${res.status}`);
return new Response('upstream went away', { status: 503 });
}
}
return service.app.fetch(req);
},
});
const url = `http://127.0.0.1:${server.port}`;
try {
const tsBytes = new TextEncoder().encode('hei fra TS — æøå\n'.repeat(5000));
const tsGrant = await new MediaClient(url, tsOwner).uploadBytes(tsBytes, { meta: { name: 'fra-ts.txt', mime: 'text/plain' } });
const specPath = join(dir, 'spec.json');
const kotlinOut = join(dir, 'kotlin-out.json');
await writeFile(
specPath,
JSON.stringify({
url,
seed: Buffer.from(kotlinSeed).toString('hex'),
tsLink: toCapabilityUrl('https://watch.example/', tsGrant),
tsSha256: sha256(tsBytes),
scratch: dir,
kotlinOut,
}),
);
const androidDir = resolve(import.meta.dir, '../android');
const gradle = Bun.spawn(
['./gradlew', ':shade-android:test', '--tests', 'no.zyon.shade.MediaLiveTest', '--console=plain'],
{ cwd: androidDir, env: { ...process.env, SHADE_MEDIA_LIVE_SPEC: specPath }, stdout: 'inherit', stderr: 'inherit' },
);
check((await gradle.exited) === 0, 'Kotlin MediaLiveTest failed');
const out = JSON.parse(await readFile(kotlinOut, 'utf8')) as {
film: { link: string; sha256: string; size: number };
again: string;
photo: { url: string };
};
const film = fromCapabilityUrl(out.film.link) as MediaGrant;
const reader = await openGrant(film);
check(reader.size === out.film.size, `film is ${reader.size} bytes, Kotlin sealed ${out.film.size}`);
check(sha256(await reader.read(0, reader.size)) === out.film.sha256, 'film bytes differ');
check(reader.meta.name === 'Fra telefonen — «Kveld».mp4', `film name is ${reader.meta.name}`);
check(out.again === out.film.link, 'putting the film again gave another link');
check((await fetch(out.photo.url, { method: 'HEAD' })).status === 404, 'the deleted photo is still served');
check(faults.lostAnswer === 1 && faults.refused === 1, `faults not hit: ${JSON.stringify(faults)}`);
const left = await new MediaClient(url, kotlinOwner).list();
check(left.items.length === 2, `Kotlin owner should have 2 files left (film, re-shared video), has ${left.items.length}`);
console.log(
`LIVE OK — Kotlin read the TS file; Kotlin film ${(out.film.size / MiB).toFixed(1)} MiB in ${faults.pieces} piece requests ` +
`(${faults.starts} starts/resyncs, 1 lost answer, 1 refusal) read back by TS byte for byte; upload job killed and resumed; photo deleted`,
);
} finally {
server.stop(true);
await service.stop();
await rm(dir, { recursive: true, force: true });
}