feat(android): UploadJobs — an upload from a phone survives the app being killed
MediaUploader.upload(jobs, key, …) seals once into an app-private job directory and resumes with the same media id; a job already done gives its grant again unless the relay says the file is gone. OS file locks keep one upload per job. The live cross-check now kills a job after its first piece and resumes it. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -104,6 +104,52 @@ class MediaUploader(
|
||||
return FileRangeSource(sealedFile).use { putSealed(result, it, readToken, meta, onProgress) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload `source` as the job `key` in `jobs`, so that a run cut short (the
|
||||
* app killed, the phone out of signal for an hour) is resumed by calling
|
||||
* this again: sealed once, into the job's directory, then put with the
|
||||
* same media id. A job already done gives its grant again while the relay
|
||||
* still serves it — sharing the same video twice is one upload, one link.
|
||||
* `open` is only called when the file must be sealed.
|
||||
*/
|
||||
fun upload(
|
||||
jobs: UploadJobs,
|
||||
key: String,
|
||||
source: String,
|
||||
meta: MediaMeta,
|
||||
open: () -> java.io.InputStream,
|
||||
readToken: ByteArray? = newReadToken(),
|
||||
onProgress: ((Long, Long) -> Unit)? = null,
|
||||
): MediaGrant = jobs.claim(key).use {
|
||||
var job = jobs.load(key)
|
||||
job?.grant?.let { g ->
|
||||
if (!gone(g)) return@use g
|
||||
jobs.reset(key) // deleted from the relay since: a new upload
|
||||
job = null
|
||||
}
|
||||
val j = job ?: run {
|
||||
val sealed = jobs.sealedFile(key)
|
||||
val result = open().use { input -> sealed.outputStream().buffered().use { MediaSealer.sealStream(input, it, meta) } }
|
||||
UploadJobs.Job(result, readToken, meta, source).also { jobs.save(key, it) }
|
||||
}
|
||||
val grant = FileRangeSource(jobs.sealedFile(key)).use { putSealed(j.result, it, j.readToken, j.meta, onProgress) }
|
||||
jobs.done(key, j, grant)
|
||||
grant
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the relay says the file a grant opens is gone (deleted since).
|
||||
* A relay that cannot be reached has not said so: its link still stands.
|
||||
*/
|
||||
fun gone(grant: MediaGrant): Boolean {
|
||||
val u = grant.url ?: return true
|
||||
return try {
|
||||
request("HEAD", u, grant.readToken?.let { mapOf(MediaOwner.READ_TOKEN_HEADER to b64u(it)) } ?: emptyMap(), null).status in setOf(404, 410)
|
||||
} catch (e: IOException) {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/** Remove one of your files from the relay; false if it was not there. */
|
||||
fun delete(mediaId: ByteArray): Boolean {
|
||||
val res = request("DELETE", mediaUrl(mediaId), owner.headers(OwnerOp.Delete(hex(mediaId))), null)
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
package no.zyon.shade.media
|
||||
|
||||
import org.json.JSONException
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.nio.channels.FileChannel
|
||||
import java.nio.channels.FileLock
|
||||
import java.nio.channels.OverlappingFileLockException
|
||||
import java.nio.file.StandardOpenOption
|
||||
import java.security.MessageDigest
|
||||
|
||||
/**
|
||||
* Uploads that outlive the app — mirror of `@shade/media` put-jobs.ts. A
|
||||
* phone kills an app that uploads for long (a film over mobile data); this is
|
||||
* what lets the next start send the same file again, with the same media id,
|
||||
* so the relay already has most of it. Each upload has a directory:
|
||||
*
|
||||
* sealed.smf the sealed copy, kept until the relay has all of it
|
||||
* job.json the seal result (with the file key), the read token, the
|
||||
* meta, and the grant once the relay stored it. Keep the
|
||||
* directory app-private (`filesDir`): it holds keys.
|
||||
* lock held (an OS file lock) by whoever is uploading it
|
||||
*
|
||||
* A job is keyed by what identifies the source (the relay, a content URI,
|
||||
* its size and name, …), so sharing the same video twice is one upload and
|
||||
* gives the same link. Jobs untouched for 30 days are removed.
|
||||
*/
|
||||
class UploadJobs(private val dir: File) {
|
||||
|
||||
class Job(
|
||||
val result: SealResult,
|
||||
/** Null for public ciphertext. */
|
||||
val readToken: ByteArray?,
|
||||
val meta: MediaMeta,
|
||||
/** What the job is of, for listing (a file name, a URI). */
|
||||
val source: String,
|
||||
/** Set once the relay stored the file. */
|
||||
val grant: MediaGrant? = null,
|
||||
)
|
||||
|
||||
class BusyException(message: String) : Exception(message)
|
||||
|
||||
/** The job for a source identified by `parts` (the relay URL first). */
|
||||
fun key(vararg parts: String): String {
|
||||
val md = MessageDigest.getInstance("SHA-256")
|
||||
for (p in parts) {
|
||||
val b = p.toByteArray(Charsets.UTF_8)
|
||||
md.update(byteArrayOf((b.size ushr 24).toByte(), (b.size ushr 16).toByte(), (b.size ushr 8).toByte(), b.size.toByte()))
|
||||
md.update(b)
|
||||
}
|
||||
return md.digest().copyOf(16).joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
|
||||
private fun jobDir(key: String): File {
|
||||
require(KEY_RE.matches(key)) { "not a job key: $key" }
|
||||
return File(dir, key)
|
||||
}
|
||||
|
||||
fun sealedFile(key: String): File = File(jobDir(key), "sealed.smf")
|
||||
|
||||
/**
|
||||
* Take the job for this upload; release with `close()`. Throws
|
||||
* [BusyException] while another thread or process has it. A lock left by a
|
||||
* process that died is released by the OS, so it never needs clearing.
|
||||
*/
|
||||
fun claim(key: String): AutoCloseable {
|
||||
val d = jobDir(key).also { it.mkdirs() }
|
||||
val ch = FileChannel.open(File(d, "lock").toPath(), StandardOpenOption.CREATE, StandardOpenOption.WRITE)
|
||||
val lock: FileLock? = try {
|
||||
ch.tryLock()
|
||||
} catch (e: OverlappingFileLockException) {
|
||||
null
|
||||
}
|
||||
if (lock == null) {
|
||||
ch.close()
|
||||
throw BusyException("this file is already being uploaded")
|
||||
}
|
||||
return AutoCloseable {
|
||||
lock.release()
|
||||
ch.close()
|
||||
}
|
||||
}
|
||||
|
||||
/** The job, if an earlier run got as far as sealing — and its sealed copy is whole, unless it is done. */
|
||||
fun load(key: String): Job? {
|
||||
val o = try {
|
||||
JSONObject(File(jobDir(key), "job.json").readText())
|
||||
} catch (e: java.io.IOException) {
|
||||
return null
|
||||
} catch (e: JSONException) {
|
||||
return null
|
||||
}
|
||||
if (o.optInt("v") != 1) return null
|
||||
val job = try {
|
||||
val r = o.getJSONObject("result")
|
||||
Job(
|
||||
SealResult(
|
||||
fromB64u(r.getString("mediaId"), MEDIA_ID_BYTES),
|
||||
fromB64u(r.getString("mediaKey"), MEDIA_KEY_BYTES),
|
||||
fromB64u(r.getString("rootDigest"), DIGEST_BYTES),
|
||||
r.getLong("plaintextSize"),
|
||||
r.getLong("sealedSize"),
|
||||
r.getInt("segmentSize"),
|
||||
r.getLong("segmentCount"),
|
||||
),
|
||||
if (o.isNull("readToken")) null else fromB64u(o.getString("readToken")),
|
||||
MediaMeta.fromJson(o.getString("meta")),
|
||||
o.optString("source"),
|
||||
if (o.has("grant")) Grants.parse(o.getString("grant")) as? MediaGrant else null,
|
||||
)
|
||||
} catch (e: JSONException) {
|
||||
return null
|
||||
} catch (e: MediaFormatException) {
|
||||
return null
|
||||
}
|
||||
if (job.grant != null) return job
|
||||
return if (sealedFile(key).length() == job.result.sealedSize) job else null
|
||||
}
|
||||
|
||||
fun save(key: String, job: Job) {
|
||||
val r = job.result
|
||||
val o = JSONObject()
|
||||
.put("v", 1)
|
||||
.put("source", job.source)
|
||||
.put(
|
||||
"result",
|
||||
JSONObject()
|
||||
.put("mediaId", b64u(r.mediaId))
|
||||
.put("mediaKey", b64u(r.mediaKey))
|
||||
.put("rootDigest", b64u(r.rootDigest))
|
||||
.put("plaintextSize", r.plaintextSize)
|
||||
.put("sealedSize", r.sealedSize)
|
||||
.put("segmentSize", r.segmentSize)
|
||||
.put("segmentCount", r.segmentCount),
|
||||
)
|
||||
.put("readToken", job.readToken?.let { b64u(it) } ?: JSONObject.NULL)
|
||||
.put("meta", job.meta.toJson())
|
||||
job.grant?.let { o.put("grant", it.encode()) }
|
||||
val d = jobDir(key).also { it.mkdirs() }
|
||||
val tmp = File(d, "job.json.tmp")
|
||||
tmp.writeText(o.toString())
|
||||
if (!tmp.renameTo(File(d, "job.json"))) throw java.io.IOException("cannot write the job for $key")
|
||||
}
|
||||
|
||||
/** The relay has it: keep the grant, drop the sealed copy. */
|
||||
fun done(key: String, job: Job, grant: MediaGrant): Job {
|
||||
val finished = Job(job.result, job.readToken, job.meta, job.source, grant)
|
||||
save(key, finished)
|
||||
sealedFile(key).delete()
|
||||
return finished
|
||||
}
|
||||
|
||||
/** Start the job over (its file was deleted from the relay), keeping the claim. */
|
||||
fun reset(key: String) {
|
||||
File(jobDir(key), "job.json").delete()
|
||||
sealedFile(key).delete()
|
||||
}
|
||||
|
||||
fun forget(key: String) {
|
||||
jobDir(key).deleteRecursively()
|
||||
}
|
||||
|
||||
/** Jobs not yet done whose sealed copy is whole: what to resume after a restart. */
|
||||
fun unfinished(): List<Pair<String, Job>> =
|
||||
(dir.list() ?: emptyArray()).filter { KEY_RE.matches(it) }
|
||||
.mapNotNull { k -> load(k)?.takeIf { it.grant == null }?.let { k to it } }
|
||||
|
||||
/** Remove jobs nobody touched for 30 days, and half-sealed leftovers after an hour. */
|
||||
fun prune(now: Long = System.currentTimeMillis()): Int {
|
||||
var n = 0
|
||||
for (k in dir.list() ?: emptyArray()) {
|
||||
if (!KEY_RE.matches(k)) continue
|
||||
val jobFile = File(jobDir(k), "job.json")
|
||||
val touched = if (jobFile.exists()) jobFile.lastModified() else jobDir(k).lastModified()
|
||||
val stale = now - touched > MAX_AGE_MS || (!jobFile.exists() && now - touched > 3_600_000L)
|
||||
if (!stale) continue
|
||||
val held = try {
|
||||
claim(k)
|
||||
} catch (e: BusyException) {
|
||||
continue
|
||||
}
|
||||
held.close()
|
||||
forget(k)
|
||||
n++
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
private companion object {
|
||||
val KEY_RE = Regex("^[0-9a-f]{32}$")
|
||||
const val MAX_AGE_MS = 30L * 24 * 3600 * 1000
|
||||
}
|
||||
}
|
||||
@@ -7,9 +7,11 @@ import no.zyon.shade.media.MediaMeta
|
||||
import no.zyon.shade.media.MediaOwner
|
||||
import no.zyon.shade.media.MediaSealer
|
||||
import no.zyon.shade.media.MediaUploader
|
||||
import no.zyon.shade.media.UploadJobs
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assume.assumeTrue
|
||||
import org.junit.Test
|
||||
@@ -69,6 +71,38 @@ class MediaLiveTest {
|
||||
val again = FileRangeSource(sealedFile).use { uploader.putSealed(result, it, token, meta) }
|
||||
assertEquals(film.capabilityUrl("https://watch.example/"), again.capabilityUrl("https://watch.example/"))
|
||||
|
||||
// A shared video as an upload job: the app is killed after the first
|
||||
// piece; the next start resumes past it, and sharing it a third time
|
||||
// sends nothing and gives the same link.
|
||||
val jobs = UploadJobs(File(spec.getString("scratch"), "jobs"))
|
||||
val video = ByteArray(36 * 1024 * 1024).also { SecureRandom().nextBytes(it) }
|
||||
val key = jobs.key(spec.getString("url"), "content://media/external/video/42", video.size.toString())
|
||||
val videoMeta = MediaMeta(name = "VID_0042.mp4", mime = "video/mp4")
|
||||
var opened = 0
|
||||
val open = { opened++; video.inputStream() }
|
||||
class Killed : RuntimeException()
|
||||
try {
|
||||
uploader.upload(jobs, key, "VID_0042.mp4", videoMeta, open) { acked, _ -> if (acked > 0) throw Killed() }
|
||||
error("the upload should have been cut short")
|
||||
} catch (e: Killed) {
|
||||
// as if the app was killed mid-upload
|
||||
}
|
||||
assertEquals(1, jobs.unfinished().size)
|
||||
var firstSeen = -1L
|
||||
val resumed = uploader.upload(jobs, key, "VID_0042.mp4", videoMeta, open) { acked, _ -> if (firstSeen < 0) firstSeen = acked }
|
||||
assertTrue("resumed from $firstSeen", firstSeen > 0)
|
||||
assertEquals("sealed once", 1, opened)
|
||||
resumed.open().use { r -> assertEquals(sha256(video), sha256(r.read(0, r.size.toInt()))) }
|
||||
val third = uploader.upload(jobs, key, "VID_0042.mp4", videoMeta, open)
|
||||
assertEquals(resumed.encode(), third.encode())
|
||||
assertEquals(1, opened)
|
||||
assertTrue(jobs.unfinished().isEmpty())
|
||||
// Deleted from the relay since: the next share is a new upload with a new link.
|
||||
assertTrue(uploader.delete(resumed.mediaId))
|
||||
val fresh = uploader.upload(jobs, key, "VID_0042.mp4", videoMeta, open)
|
||||
assertNotEquals(resumed.encode(), fresh.encode())
|
||||
assertEquals(2, opened)
|
||||
|
||||
// A photo: one PUT; then deleted.
|
||||
val photo = uploader.uploadBytes(ByteArray(300_000).also { SecureRandom().nextBytes(it) }, MediaMeta(name = "IMG_0001.jpg", mime = "image/jpeg"))
|
||||
photo.open().use { assertEquals("IMG_0001.jpg", it.meta.name) }
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
package no.zyon.shade
|
||||
|
||||
import no.zyon.shade.media.MediaGrant
|
||||
import no.zyon.shade.media.MediaMeta
|
||||
import no.zyon.shade.media.MediaSealer
|
||||
import no.zyon.shade.media.UploadJobs
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
|
||||
class UploadJobsTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
private fun sealed(jobs: UploadJobs, key: String, meta: MediaMeta = MediaMeta(name = "Kveld.mp4")): UploadJobs.Job {
|
||||
val result = jobs.sealedFile(key).also { it.parentFile.mkdirs() }.outputStream().use {
|
||||
MediaSealer.sealStream(ByteArray(200_000) { i -> i.toByte() }.inputStream(), it, meta)
|
||||
}
|
||||
return UploadJobs.Job(result, ByteArray(32) { 9 }, meta, "content://media/1")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun keysAreTheSourceAndTheRelay() {
|
||||
val jobs = UploadJobs(tmp.root)
|
||||
val k = jobs.key("https://relay", "content://media/1", "1234", "Kveld.mp4")
|
||||
assertEquals(k, jobs.key("https://relay", "content://media/1", "1234", "Kveld.mp4"))
|
||||
assertNotEquals(k, jobs.key("https://other", "content://media/1", "1234", "Kveld.mp4"))
|
||||
// Parts are length-prefixed: moving a separator is another job.
|
||||
assertNotEquals(jobs.key("ab", "c"), jobs.key("a", "bc"))
|
||||
assertTrue(Regex("^[0-9a-f]{32}$").matches(k))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resumableOnlyWithAWholeSealedCopyAndDoneKeepsTheGrant() {
|
||||
val jobs = UploadJobs(tmp.root)
|
||||
val key = jobs.key("r", "s")
|
||||
jobs.claim(key).use {
|
||||
val job = sealed(jobs, key)
|
||||
jobs.save(key, job)
|
||||
val back = jobs.load(key)!!
|
||||
assertArrayEquals(job.result.mediaKey, back.result.mediaKey)
|
||||
assertArrayEquals(job.readToken, back.readToken)
|
||||
assertEquals("Kveld.mp4", back.meta.name)
|
||||
assertEquals(listOf(key), jobs.unfinished().map { it.first })
|
||||
|
||||
// Cut short: not resumable.
|
||||
val f = jobs.sealedFile(key)
|
||||
val whole = f.readBytes()
|
||||
f.writeBytes(whole.copyOf(whole.size - 1))
|
||||
assertNull(jobs.load(key))
|
||||
f.writeBytes(whole)
|
||||
|
||||
val grant = MediaGrant.of(job.result, "http://relay/v1/media/x", job.readToken, job.meta)
|
||||
jobs.done(key, job, grant)
|
||||
assertFalse(f.exists())
|
||||
assertEquals(grant.encode(), jobs.load(key)!!.grant!!.encode())
|
||||
assertTrue(jobs.unfinished().isEmpty())
|
||||
|
||||
jobs.reset(key)
|
||||
assertNull(jobs.load(key))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun oneUploadPerJobAndTheLockGoesWithItsHolder() {
|
||||
val jobs = UploadJobs(tmp.root)
|
||||
val key = jobs.key("r", "busy")
|
||||
val held = jobs.claim(key)
|
||||
assertThrows(UploadJobs.BusyException::class.java) { jobs.claim(key) }
|
||||
held.close()
|
||||
jobs.claim(key).close()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun pruneOldJobsAndHalfSealedLeftoversButNotOnesInUse() {
|
||||
val jobs = UploadJobs(tmp.root)
|
||||
val now = System.currentTimeMillis()
|
||||
val old = jobs.key("old")
|
||||
val fresh = jobs.key("fresh")
|
||||
val half = jobs.key("half")
|
||||
val busy = jobs.key("busy")
|
||||
for (k in listOf(old, fresh, busy)) jobs.claim(k).use { jobs.save(k, sealed(jobs, k)) }
|
||||
jobs.claim(half).close()
|
||||
java.io.File(tmp.root, "$old/job.json").setLastModified(now - 31L * 86_400_000)
|
||||
java.io.File(tmp.root, "$busy/job.json").setLastModified(now - 31L * 86_400_000)
|
||||
java.io.File(tmp.root, half).setLastModified(now - 7_200_000)
|
||||
jobs.claim(busy).use { assertEquals(2, jobs.prune(now)) }
|
||||
assertNotNull(jobs.load(fresh))
|
||||
assertNotNull(jobs.load(busy))
|
||||
assertFalse(java.io.File(tmp.root, old).exists())
|
||||
assertFalse(java.io.File(tmp.root, half).exists())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user