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:
2026-10-19 00:31:06 +02:00
parent 0a706cdb47
commit 7d45be8712
7 changed files with 133 additions and 9 deletions

View File

@@ -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). */
const val DEFAULT_CHUNK_BYTES = 16L * 1024 * 1024
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. */
private const val MAX_TRIES = 8
@@ -166,15 +170,33 @@ class MediaUploader(
private val body: RangeSource,
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) {
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 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
}
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. */
private fun send(method: String, headers: Map<String, String>, body: ByteArray?): Answer =
try {
@@ -257,7 +279,7 @@ class MediaUploader(
return
}
chunk = opened.chunk
val window = opened.window
val window = opened.window.coerceAtMost(MAX_CLIENT_WINDOW)
var acked = 0L
var complete = false
val todo = ArrayDeque<Long>()

View File

@@ -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)
}
}
}
}