feat(android): MediaUploader — a phone puts films on a relay, in resumable pieces
MediaOwner signs owner requests and MediaUploader speaks the piece protocol of media put (window, retries, resync after a lost answer). MediaSealer .sealStream seals a film to a file; MediaGrant.encode/capabilityUrl make the link to share. Owner signatures and encoded grants are pinned by new vectors; scripts/media-live-kotlin.ts runs the uploader against a real TS relay with a lost answer and a refused piece injected. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -57,7 +57,9 @@ import { sealWithPinnedKeys } from '../packages/shade-media/src/testing.js';
|
||||
import { LivePublisher, epochKeys, chainStep, linkEpochSeed } from '../packages/shade-media/src/live/channel.js';
|
||||
import { encodeContent, decodeFrame } from '../packages/shade-media/src/live/frame.js';
|
||||
import type { LiveContent } from '../packages/shade-media/src/live/frame.js';
|
||||
import { encodeGrant } from '../packages/shade-media/src/grant.js';
|
||||
import { encodeGrant, toCapabilityUrl } from '../packages/shade-media/src/grant.js';
|
||||
import { OwnerKey, ownerMessage } from '../packages/shade-media/src/owner.js';
|
||||
import type { OwnerOp } from '../packages/shade-media/src/owner.js';
|
||||
import type { MediaGrant } from '../packages/shade-media/src/grant.js';
|
||||
import { albumMeta, encodeAlbum } from '../packages/shade-media/src/album.js';
|
||||
import { withSubtitles } from '../packages/shade-media/src/subtitles.js';
|
||||
@@ -1122,6 +1124,55 @@ async function generateMediaVectors(): Promise<Vector[]> {
|
||||
labels: ['Norsk', null],
|
||||
mediaIds: [hex(new Uint8Array(16).fill(0x55)), hex(new Uint8Array(16).fill(0x66))],
|
||||
});
|
||||
|
||||
// Owner-signed requests: what a relay checks before it takes an upload, a
|
||||
// piece of one, a delete. Ed25519 is deterministic, so the signatures are too.
|
||||
const owner = new OwnerKey(new Uint8Array(32).fill(0x07));
|
||||
const at = 1792360000000;
|
||||
const id = '0123456789abcdef0123456789abcdef';
|
||||
const readTokenHash = 'ab'.repeat(32);
|
||||
const ops: OwnerOp[] = [
|
||||
{ op: 'put', id, size: 4096, readTokenHash },
|
||||
{ op: 'upload', id, size: 50 * 1024 ** 3, readTokenHash },
|
||||
{ op: 'upload', id, size: 4096, readTokenHash: '' },
|
||||
{ op: 'piece', id, offset: 3 * 16 * 1024 * 1024, length: 16 * 1024 * 1024 },
|
||||
{ op: 'piece', id, offset: 50 * 1024 ** 3, length: 0 },
|
||||
{ op: 'abort', id },
|
||||
{ op: 'delete', id },
|
||||
{ op: 'list' },
|
||||
];
|
||||
vectors.push({
|
||||
description: 'owner: signed media requests (x-shade-owner / x-shade-at / x-shade-signature)',
|
||||
seed: hex(new Uint8Array(32).fill(0x07)),
|
||||
owner: owner.id,
|
||||
at,
|
||||
requests: ops.map((o) => ({
|
||||
...o,
|
||||
message: new TextDecoder().decode(ownerMessage(o, at)),
|
||||
headers: owner.headers(o, at),
|
||||
})),
|
||||
});
|
||||
|
||||
// A grant as an uploader hands it on: the wire JSON (field order fixed, the
|
||||
// meta canonical) and the capability link it makes.
|
||||
const shared: MediaGrant = {
|
||||
...film,
|
||||
mediaId: new Uint8Array(16).fill(0x77),
|
||||
readToken: new Uint8Array(32).fill(0x88),
|
||||
meta: { extra: { 'shade.note': 'æøå' }, name: 'Fra telefonen — «Kveld».mp4', mime: 'video/mp4', durationMs: 61500, width: 1080, height: 1920 },
|
||||
};
|
||||
vectors.push({
|
||||
description: 'grant encode: a media grant with url, token and meta, as JSON and as a capability link',
|
||||
mediaId: hex(shared.mediaId),
|
||||
mediaKey: hex(shared.mediaKey),
|
||||
rootDigest: hex(shared.rootDigest),
|
||||
url: shared.url,
|
||||
readToken: hex(shared.readToken!),
|
||||
meta: JSON.stringify(shared.meta),
|
||||
json: encodeGrant(shared),
|
||||
pageUrl: 'https://watch.example/',
|
||||
link: toCapabilityUrl('https://watch.example/', shared),
|
||||
});
|
||||
return vectors;
|
||||
}
|
||||
|
||||
|
||||
117
scripts/media-live-kotlin.ts
Normal file
117
scripts/media-live-kotlin.ts
Normal file
@@ -0,0 +1,117 @@
|
||||
/**
|
||||
* 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) 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 === 1, `Kotlin owner should have 1 file left, 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; photo deleted`,
|
||||
);
|
||||
} finally {
|
||||
server.stop(true);
|
||||
await service.stop();
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
Reference in New Issue
Block a user