fix(media): an uploader checks the relay's upload status before trusting it
A chunk of 0 looped forever, a huge chunk held the film in memory and a huge window opened a request (a thread on Kotlin) per piece. statusProblem checks chunk, window, received and landed; the client window is capped at 16. Same in MediaUploader, with tests on both sides. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -132,6 +132,10 @@ New package **`@shade/media`** — see `docs/media.md`.
|
|||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
|
|
||||||
|
- An uploader (TS and Kotlin) trusted the relay's upload status: a `chunk` of
|
||||||
|
0 looped forever, a huge one held the film in memory, a huge `window` opened
|
||||||
|
a request (a thread, on Kotlin) per piece. The status is now checked
|
||||||
|
(`statusProblem`) and the window capped at 16.
|
||||||
- `shade media get` used the sealed file's `meta.name` as the output path,
|
- `shade media get` used the sealed file's `meta.name` as the output path,
|
||||||
so whoever sealed a file chose where it was written (`../../.bashrc`).
|
so whoever sealed a file chose where it was written (`../../.bashrc`).
|
||||||
Names are now reduced to one safe path component.
|
Names are now reduced to one safe path component.
|
||||||
|
|||||||
@@ -16,6 +16,10 @@ import java.util.concurrent.Executors
|
|||||||
/** Files up to this size go up in one PUT; larger ones in pieces (mirror of `@shade/media` upload.ts). */
|
/** Files up to this size go up in one PUT; larger ones in pieces (mirror of `@shade/media` upload.ts). */
|
||||||
const val DEFAULT_CHUNK_BYTES = 16L * 1024 * 1024
|
const val DEFAULT_CHUNK_BYTES = 16L * 1024 * 1024
|
||||||
const val OFFSET_HEADER = "x-shade-offset"
|
const val OFFSET_HEADER = "x-shade-offset"
|
||||||
|
const val MAX_PIECE_BYTES = 64L * 1024 * 1024
|
||||||
|
|
||||||
|
/** Most pieces kept in flight, whatever window a relay offers. */
|
||||||
|
const val MAX_CLIENT_WINDOW = 16
|
||||||
|
|
||||||
/** Failed tries in a row before a resumable upload gives up. */
|
/** Failed tries in a row before a resumable upload gives up. */
|
||||||
private const val MAX_TRIES = 8
|
private const val MAX_TRIES = 8
|
||||||
@@ -166,15 +170,33 @@ class MediaUploader(
|
|||||||
private val body: RangeSource,
|
private val body: RangeSource,
|
||||||
private val onProgress: ((Long, Long) -> Unit)?,
|
private val onProgress: ((Long, Long) -> Unit)?,
|
||||||
) {
|
) {
|
||||||
|
/**
|
||||||
|
* How far the relay got. Checked before it is trusted (mirror of TS
|
||||||
|
* `statusProblem`): a zero chunk would never get through the file, a
|
||||||
|
* huge one would hold it all in memory, a huge window a thread per piece.
|
||||||
|
*/
|
||||||
private inner class Status(json: JSONObject) {
|
private inner class Status(json: JSONObject) {
|
||||||
val chunk = json.getLong("chunk")
|
|
||||||
val window = json.optInt("window", 1).coerceAtLeast(1)
|
|
||||||
val received = json.getLong("received")
|
|
||||||
val landed: Set<Long> = json.optJSONArray("landed")?.let { a -> (0 until a.length()).map { a.getLong(it) }.toSet() } ?: emptySet()
|
|
||||||
val complete = json.optBoolean("complete", false)
|
val complete = json.optBoolean("complete", false)
|
||||||
|
val chunk = if (complete) 0L else json.optLong("chunk", -1)
|
||||||
|
val window = json.optInt("window", 1)
|
||||||
|
val received = if (complete) size else json.optLong("received", -1)
|
||||||
|
val landed: Set<Long> = if (complete) emptySet() else json.optJSONArray("landed")?.let { a ->
|
||||||
|
(0 until a.length()).map { i -> (a.opt(i) as? Number)?.toLong()?.takeIf { it >= 0 } ?: unusable("landed is not a list of piece numbers") }.toSet()
|
||||||
|
} ?: emptySet()
|
||||||
|
|
||||||
|
init {
|
||||||
|
if (!complete) {
|
||||||
|
if (chunk < 1024 * 1024 || chunk > MAX_PIECE_BYTES) unusable("chunk $chunk out of range")
|
||||||
|
if (window < 1) unusable("window $window out of range")
|
||||||
|
if (received < 0 || received > size) unusable("received $received out of range")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fun has(offset: Long) = offset < received || (offset / chunk) in landed
|
fun has(offset: Long) = offset < received || (offset / chunk) in landed
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun unusable(why: String): Nothing = throw MediaUploadException("upload failed: the relay's upload status is unusable: $why")
|
||||||
|
|
||||||
/** A request that got no answer (refused, reset, timed out) is worth repeating. */
|
/** A request that got no answer (refused, reset, timed out) is worth repeating. */
|
||||||
private fun send(method: String, headers: Map<String, String>, body: ByteArray?): Answer =
|
private fun send(method: String, headers: Map<String, String>, body: ByteArray?): Answer =
|
||||||
try {
|
try {
|
||||||
@@ -257,7 +279,7 @@ class MediaUploader(
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
chunk = opened.chunk
|
chunk = opened.chunk
|
||||||
val window = opened.window
|
val window = opened.window.coerceAtMost(MAX_CLIENT_WINDOW)
|
||||||
var acked = 0L
|
var acked = 0L
|
||||||
var complete = false
|
var complete = false
|
||||||
val todo = ArrayDeque<Long>()
|
val todo = ArrayDeque<Long>()
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
package no.zyon.shade
|
||||||
|
|
||||||
|
import com.sun.net.httpserver.HttpServer
|
||||||
|
import no.zyon.shade.media.ByteArraySource
|
||||||
|
import no.zyon.shade.media.DEFAULT_CHUNK_BYTES
|
||||||
|
import no.zyon.shade.media.MediaOwner
|
||||||
|
import no.zyon.shade.media.MediaSealer
|
||||||
|
import no.zyon.shade.media.MediaUploadException
|
||||||
|
import no.zyon.shade.media.MediaUploader
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertThrows
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
import java.net.InetSocketAddress
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger
|
||||||
|
|
||||||
|
/** What the uploader does with a relay that answers nonsense; the real conversation is `MediaLiveTest`. */
|
||||||
|
class MediaUploaderTest {
|
||||||
|
|
||||||
|
private fun relay(answer: String, calls: AtomicInteger): HttpServer =
|
||||||
|
HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply {
|
||||||
|
createContext("/") { ex ->
|
||||||
|
calls.incrementAndGet()
|
||||||
|
ex.requestBody.readBytes()
|
||||||
|
val b = answer.toByteArray()
|
||||||
|
ex.responseHeaders.add("content-type", "application/json")
|
||||||
|
ex.sendResponseHeaders(201, b.size.toLong())
|
||||||
|
ex.responseBody.use { it.write(b) }
|
||||||
|
}
|
||||||
|
start()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun anUnusableUploadStatusIsRefusedAtOnceNotLoopedOn() {
|
||||||
|
val (sealed, result) = MediaSealer.sealBytes(ByteArray(DEFAULT_CHUNK_BYTES.toInt() + 4096))
|
||||||
|
for (bad in listOf(
|
||||||
|
"""{"chunk":0,"received":0}""",
|
||||||
|
"""{"chunk":${64L * 1024 * 1024 * 4},"received":0}""",
|
||||||
|
"""{"chunk":${DEFAULT_CHUNK_BYTES},"received":-1}""",
|
||||||
|
"""{"chunk":${DEFAULT_CHUNK_BYTES},"received":0,"window":0}""",
|
||||||
|
"""{"chunk":${DEFAULT_CHUNK_BYTES},"received":0,"landed":["x"]}""",
|
||||||
|
)) {
|
||||||
|
val calls = AtomicInteger()
|
||||||
|
val server = relay(bad, calls)
|
||||||
|
try {
|
||||||
|
val up = MediaUploader("http://127.0.0.1:${server.address.port}", MediaOwner.generate())
|
||||||
|
val e = assertThrows(MediaUploadException::class.java) { up.putSealed(result, ByteArraySource(sealed)) }
|
||||||
|
assertTrue(bad, e.message!!.contains("unusable"))
|
||||||
|
assertEquals(bad, 1, calls.get())
|
||||||
|
} finally {
|
||||||
|
server.stop(0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,7 +14,7 @@ import type { OwnerKey } from './owner.js';
|
|||||||
import { MediaReader, sealMediaBytes } from './sealed.js';
|
import { MediaReader, sealMediaBytes } from './sealed.js';
|
||||||
import type { MediaMeta, ReaderOptions, SealOptions, SealResult } from './sealed.js';
|
import type { MediaMeta, ReaderOptions, SealOptions, SealResult } from './sealed.js';
|
||||||
import { HttpRangeSource } from './source.js';
|
import { HttpRangeSource } from './source.js';
|
||||||
import { DEFAULT_CHUNK_BYTES, OFFSET_HEADER } from './upload.js';
|
import { DEFAULT_CHUNK_BYTES, MAX_CLIENT_WINDOW, OFFSET_HEADER, statusProblem } from './upload.js';
|
||||||
|
|
||||||
export function mediaUrl(server: string, mediaId: Uint8Array): string {
|
export function mediaUrl(server: string, mediaId: Uint8Array): string {
|
||||||
return `${server.replace(/\/$/, '')}/v1/media/${toHex(mediaId)}`;
|
return `${server.replace(/\/$/, '')}/v1/media/${toHex(mediaId)}`;
|
||||||
@@ -162,7 +162,13 @@ export class MediaClient {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
if (res.status !== 200 && res.status !== 201) return fail(res, 'start');
|
if (res.status !== 200 && res.status !== 201) return fail(res, 'start');
|
||||||
return (await res.json()) as Status;
|
const st = (await res.json().catch(() => {
|
||||||
|
throw new Transient("start: the relay's answer is not JSON");
|
||||||
|
})) as Status;
|
||||||
|
if (st.complete === true) return st;
|
||||||
|
const problem = statusProblem(st, size);
|
||||||
|
if (problem !== null) throw new Error(`upload failed: the relay's upload status is unusable: ${problem}`);
|
||||||
|
return st;
|
||||||
};
|
};
|
||||||
const has = (st: Status, offset: number) => offset < st.received || (st.landed ?? []).includes(offset / st.chunk);
|
const has = (st: Status, offset: number) => offset < st.received || (st.landed ?? []).includes(offset / st.chunk);
|
||||||
|
|
||||||
@@ -172,7 +178,7 @@ export class MediaClient {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const { chunk } = opened;
|
const { chunk } = opened;
|
||||||
const window = Math.max(1, opened.window ?? 1);
|
const window = Math.min(MAX_CLIENT_WINDOW, Math.max(1, opened.window ?? 1));
|
||||||
let acked = 0;
|
let acked = 0;
|
||||||
let complete = false;
|
let complete = false;
|
||||||
const todo: number[] = [];
|
const todo: number[] = [];
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ export { MediaClient, openGrant, openAlbum, readAlbum, mediaUrl } from './client
|
|||||||
export { ALBUM_KIND, ALBUM_MIME, MAX_ALBUM_ITEMS, encodeAlbum, parseAlbum, isAlbum, albumMeta, isMediaGrant } from './album.js';
|
export { ALBUM_KIND, ALBUM_MIME, MAX_ALBUM_ITEMS, encodeAlbum, parseAlbum, isAlbum, albumMeta, isMediaGrant } from './album.js';
|
||||||
export type { Album } from './album.js';
|
export type { Album } from './album.js';
|
||||||
export type { PutOptions } from './client.js';
|
export type { PutOptions } from './client.js';
|
||||||
export { MAX_PIECE_BYTES, DEFAULT_CHUNK_BYTES, MAX_UPLOAD_BYTES, OFFSET_HEADER, UPLOAD_WINDOW, chunkFor } from './upload.js';
|
export { MAX_PIECE_BYTES, DEFAULT_CHUNK_BYTES, MAX_UPLOAD_BYTES, MAX_CLIENT_WINDOW, OFFSET_HEADER, UPLOAD_WINDOW, chunkFor, statusProblem } from './upload.js';
|
||||||
export { LivePublisher, LiveSubscriber, epochKeys, chainStep, MAX_SKIP, MAX_SKIPPED_KEYS } from './live/channel.js';
|
export { LivePublisher, LiveSubscriber, epochKeys, chainStep, MAX_SKIP, MAX_SKIPPED_KEYS } from './live/channel.js';
|
||||||
export type { FrameOptions, PublisherOptions, GrantOptions, ReceivedFrame } from './live/channel.js';
|
export type { FrameOptions, PublisherOptions, GrantOptions, ReceivedFrame } from './live/channel.js';
|
||||||
export { encodeContent, decodeContent, decodeFrame, FLAG_STICKY, FLAG_KEYFRAME, FLAG_END } from './live/frame.js';
|
export { encodeContent, decodeContent, decodeFrame, FLAG_STICKY, FLAG_KEYFRAME, FLAG_END } from './live/frame.js';
|
||||||
|
|||||||
@@ -40,6 +40,23 @@ export const OFFSET_HEADER = 'x-shade-offset';
|
|||||||
/** Pieces past `received` a relay takes at once — what an upload holds in its memory, at most. */
|
/** Pieces past `received` a relay takes at once — what an upload holds in its memory, at most. */
|
||||||
export const UPLOAD_WINDOW = 4;
|
export const UPLOAD_WINDOW = 4;
|
||||||
|
|
||||||
|
/** Most pieces a client keeps in flight, whatever window a relay offers. */
|
||||||
|
export const MAX_CLIENT_WINDOW = 16;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Why a relay's upload status cannot be used, or null. A client checks it
|
||||||
|
* before trusting it: a zero chunk would never get through the file, a huge
|
||||||
|
* one would hold it all in memory, a huge window opens a request per piece.
|
||||||
|
*/
|
||||||
|
export function statusProblem(st: { chunk?: unknown; window?: unknown; received?: unknown; landed?: unknown }, size: number): string | null {
|
||||||
|
const int = (v: unknown) => typeof v === 'number' && Number.isSafeInteger(v);
|
||||||
|
if (!int(st.chunk) || (st.chunk as number) < MiB || (st.chunk as number) > MAX_PIECE_BYTES) return `chunk ${String(st.chunk)} out of range`;
|
||||||
|
if (st.window !== undefined && (!int(st.window) || (st.window as number) < 1)) return `window ${String(st.window)} out of range`;
|
||||||
|
if (!int(st.received) || (st.received as number) < 0 || (st.received as number) > size) return `received ${String(st.received)} out of range`;
|
||||||
|
if (st.landed !== undefined && (!Array.isArray(st.landed) || !st.landed.every((n) => int(n) && n >= 0))) return 'landed is not a list of piece numbers';
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
/** The piece size for a file of `size` bytes: the default, or larger so it fits in 10 000 pieces. */
|
/** The piece size for a file of `size` bytes: the default, or larger so it fits in 10 000 pieces. */
|
||||||
export function chunkFor(size: number): number {
|
export function chunkFor(size: number): number {
|
||||||
const need = Math.ceil(size / MAX_PIECES / MiB) * MiB;
|
const need = Math.ceil(size / MAX_PIECES / MiB) * MiB;
|
||||||
|
|||||||
@@ -202,6 +202,26 @@ describe('pieces', () => {
|
|||||||
expect((await piece(4 * chunk)).status).toBe(404);
|
expect((await piece(4 * chunk)).status).toBe(404);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('a relay whose upload status is unusable is refused at once, not looped on', async () => {
|
||||||
|
const bytes = new Uint8Array(DEFAULT_CHUNK_BYTES + 4096);
|
||||||
|
const { result, bytes: sealed } = await sealMediaBytes(bytes);
|
||||||
|
for (const bad of [
|
||||||
|
{ chunk: 0, received: 0 },
|
||||||
|
{ chunk: MAX_PIECE_BYTES * 4, received: 0 },
|
||||||
|
{ chunk: DEFAULT_CHUNK_BYTES, received: -1 },
|
||||||
|
{ chunk: DEFAULT_CHUNK_BYTES, received: 0, window: 0 },
|
||||||
|
{ chunk: DEFAULT_CHUNK_BYTES, received: 0, landed: ['x'] },
|
||||||
|
]) {
|
||||||
|
let calls = 0;
|
||||||
|
const relay = (async () => {
|
||||||
|
calls++;
|
||||||
|
return Response.json({ id: 'x', size: result.sealedSize, ...bad }, { status: 201 });
|
||||||
|
}) as unknown as typeof fetch;
|
||||||
|
await expect(new MediaClient('http://relay', OwnerKey.generate(), { fetch: relay }).putSealed(result, sealed)).rejects.toThrow(/unusable/);
|
||||||
|
expect(calls).toBe(1);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
test('a single PUT holds one piece at most; bigger files are told to go up in pieces', async () => {
|
test('a single PUT holds one piece at most; bigger files are told to go up in pieces', async () => {
|
||||||
const { app } = serve(new MemoryMediaStore());
|
const { app } = serve(new MemoryMediaStore());
|
||||||
const owner = OwnerKey.generate();
|
const owner = OwnerKey.generate();
|
||||||
|
|||||||
Reference in New Issue
Block a user