Scoop API

scoop:scoop.http.client:0.1.0

src/cache/disk_writer.scoop

Selected production source · src/cache/disk_writer.scoop

1package scoop.http.client
3import scoop.asyncio.*
4import scoop.bytes.ByteOrder
5import scoop.crypto.secureRandomBytes
6import scoop.http.*
7import scoop.platform.fs.Path
8import scoop.platform.memory.NativeByteBuffer
9import scoop.text.toHexString
11internal class ClientDiskCacheWriter(val owner: DiskHttpCache, val record: HttpCacheRecord, val limit: Long) : HttpCacheWriter {
12 val discard: AtomicBoolean = AtomicBoolean(false)
13 val published: AtomicBoolean = AtomicBoolean(false)
14 private val lock: ClientLock = ClientLock()
15 private val closing: ClientCacheClosure = ClientCacheClosure()
16 private var stopped: Boolean = false
17 private var sealed: Boolean = false
18 private var busy: Boolean = false
19 private var size: Long = 0L
20 private var temporary: TemporaryFile? = None
21 private var destination: Path? = None
22 private val waiters: ArrayList<Continuation<Unit>> = ArrayList<Continuation<Unit>>()
24 private fun enter(commit: Boolean = false) { lock.withLock {
25 if (stopped || sealed) throw IoClosedException()
26 if (busy) throw IllegalStateException(Some("cache writer operation is active"))
27 busy = true
28 if (commit) sealed = true
29 Unit
30 } }
31 private fun leave() {
32 val waiting = lock.withLock { busy = false; val saved = waiters.toArray(); waiters.clear(); saved }
33 for (waiter in waiting) waiter.resume(Unit)
34 }
35 private suspend fun file(): TemporaryFile {
36 val existing = lock.withLock { temporary }
37 if (clientPresent(existing)) return existing!!
38 val created = currentEventLoop().createTempFile(Some(owner.directory), "pending-http-cache-")
39 lock.withLock { temporary = Some(created) }
40 if (lock.withLock { stopped }) throw IoClosedException()
41 return created
42 }
44 public override suspend fun writeFrom(buffer: NativeByteBuffer, count: Long): Long {
45 if (count < 0L) throw IllegalArgumentException(Some("negative cache write count"))
46 if (count > buffer.readableBytes) throw IndexOutOfBoundsException()
47 enter()
48 try {
49 if (count > limit - size) discard.store(true)
50 if (discard.load()) { buffer.skip(count); return count }
51 if (count == 0L) return 0L
52 val output = file().file
53 val before = buffer.readPosition
54 try { return output.writeFrom(buffer, count) }
55 finally { size += buffer.readPosition - before }
56 } finally { leave() }
57 }
59 public override suspend fun flush() {
60 enter()
61 try { lock.withLock { temporary }?.file?.flush() }
62 finally { leave() }
63 }
65 public override suspend fun commit(trailers: List<HttpField>) {
66 enter(true)
67 try {
68 if (discard.load()) return
69 val expected = parseHttpContentLength(record.head.fields)
70 if (clientPresent(expected) && expected!! != size)
71 throw IllegalStateException(Some("cached body length does not match Content-Length"))
72 val metadata = try { encodeClientCacheMetadata(record, trailers, owner.maxMetadataBytes) }
73 catch (_: ClientCacheMetadataLimit) { discard.store(true); return }
74 if (owner.maxBytes < 16L || metadata.size > owner.maxBytes - 16L || size > owner.maxBytes - 16L - metadata.size) {
75 discard.store(true); return
76 }
77 val output = file()
78 NativeByteBuffer.allocate(metadata.size + 16L).use suspend { buffer ->
79 buffer.writeBytes(metadata)
80 buffer.writeUInt64(clientCacheFileMagic, ByteOrder.BigEndian)
81 buffer.writeInt64(metadata.size, ByteOrder.BigEndian)
82 output.file.writeFully(buffer)
83 }
84 if (owner.syncOnCommit) output.file.syncAll()
85 output.close()
86 ensureActive()
87 if (discard.load()) return
88 val path = owner.directory.resolve(Path.fromString("entry-" + secureRandomBytes(16L).toHexString() + ".scoop-http-cache"))
89 lock.withLock { destination = Some(path) }
90 currentEventLoop().moveFile(output.path, path)
91 ensureActive()
92 owner.publish(ClientDiskCacheEntry(path, record, size, size + metadata.size + 16L, trailers.toArray()), this)
93 } finally { leave() }
94 }
96 public override suspend fun close() {
97 closing.close(suspend {
98 val active = lock.withLock { stopped = true; temporary }
99 if (!published.load()) discard.store(true)
100 var failure: Throwable? = None
101 try { active?.close() }
102 catch (error: Throwable) { failure = Some(error) }
103 suspendCoroutine<Unit> { continuation ->
104 val done = lock.withLock { if (busy) { waiters.add(continuation); false } else true }
105 if (done) continuation.resume(Unit)
106 }
107 val (created, target) = lock.withLock { (temporary, destination) }
108 try { if (clientPresent(created) && (!clientPresent(active) || created!!.file !== active!!.file)) created!!.close() }
109 catch (error: Throwable) { failure = Some(clientCombined(failure, error)) }
110 if (!published.load()) {
111 val paths = ArrayList<Path>()
112 if (clientPresent(created)) paths.add(created!!.path)
113 if (clientPresent(target)) paths.add(target!!)
114 try { deleteClientCacheFiles(paths) }
115 catch (error: Throwable) { failure = Some(clientCombined(failure, error)) }
116 }
117 owner.abandon(this)
118 if (clientPresent(failure)) throw failure!!
119 })
120 }