Scoop API

scoop:scoop.http.client:0.1.0

src/cache/disk.scoop

Selected production source · src/cache/disk.scoop

1package scoop.http.client
3import scoop.asyncio.*
4import scoop.http.*
5import scoop.platform.fs.Path
6import scoop.text.startsWith
7import scoop.text.endsWith
9/**
10 * A bounded disk cache with atomic entry publication and owned read snapshots. Open it on the
11 * active event loop; pending writes do not appear as completed entries.
12 */
13public class DiskHttpCache private constructor(
14 /**
15 * The cache entry directory.
16 */
17 public val directory: Path,
18 /**
19 * Maximum total accounted storage bytes.
20 */
21 public val maxBytes: Long,
22 /**
23 * Maximum body bytes accepted for one entry.
24 */
25 public val maxEntryBytes: Long,
26 /**
27 * Maximum committed entry count.
28 */
29 public val maxEntries: Long,
30 /**
31 * Maximum metadata bytes accepted for an entry.
32 */
33 public val maxMetadataBytes: Long,
34 /**
35 * Whether completed entry data is synchronized before publication.
36 */
37 public val syncOnCommit: Boolean
38) : HttpCache {
39 private val lock: ClientLock = ClientLock()
40 private val entries: ArrayList<ClientDiskCacheEntry> = ArrayList<ClientDiskCacheEntry>()
41 private val writers: ArrayList<ClientDiskCacheWriter> = ArrayList<ClientDiskCacheWriter>()
42 private var used: Long = 0L
43 init {
44 if (maxBytes <= 0L || maxEntryBytes <= 0L || maxEntries <= 0L || maxMetadataBytes <= 0L)
45 throw IllegalArgumentException(Some("HTTP cache limits must be positive"))
46 }
47 /**
48 * Current accounted committed storage bytes.
49 */
50 public val sizeBytes: Long get() = lock.withLock { used }
51 /**
52 * Current committed entry count.
53 */
54 public val entryCount: Long get() = lock.withLock { entries.size }
56 /**
57 * Opens and loads a disk-cache directory.
58 */
59 public companion object {
60 /**
61 * Creates the directory, loads valid completed entries, and removes abandoned pending or
62 * unusable cache files under the configured limits.
63 */
64 public suspend fun open(directory: Path, maxBytes: Long = 268435456L, maxEntryBytes: Long = 67108864L,
65 maxEntries: Long = 1024L, maxMetadataBytes: Long = 1048576L, syncOnCommit: Boolean = false): DiskHttpCache {
66 val cache = DiskHttpCache(directory, maxBytes, maxEntryBytes, maxEntries, maxMetadataBytes, syncOnCommit)
67 val loop = currentEventLoop()
68 loop.createDirectories(directory)
69 loop.openDirectory(directory).useAsync suspend { listing ->
70 while (true) {
71 val item = listing.next() ?: break
72 val name = String.fromUtf8OrNone(item.name.toByteArray()) ?: continue
73 if (name.startsWith("pending-http-cache-")) { deleteClientCacheFile(item.path); continue }
74 if (!name.startsWith("entry-") || !name.endsWith(".scoop-http-cache")) continue
75 val saved = readClientDiskCacheEntry(item.path, cache.maxMetadataBytes)
76 if (!clientPresent(saved)) { deleteClientCacheFile(item.path); continue }
77 val entry = saved!!
78 if (entry.bodyLength > cache.maxEntryBytes || entry.fileSize > cache.maxBytes) {
79 deleteClientCacheFile(entry.path)
80 continue
81 }
82 cache.accept(entry)
83 }
84 }
85 return cache
86 }
87 }
89 /**
90 * Returns an owned matching representation snapshot, or None. The caller closes a returned
91 * snapshot.
92 */
93 public override suspend fun lookup(request: HttpCacheRequest): HttpCacheSnapshot? {
94 val selected: ClientDiskCacheEntry? = lock.withLock {
95 var index = entries.size
96 while (index > 0L) {
97 index -= 1L
98 val entry = entries[index]
99 if (!entry.record.matches(request)) continue
100 entries.removeAt(index); entries.add(entry); entry.readers += 1L
101 return@withLock Some(entry)
102 }
103 None
104 }
105 val entry = selected ?: return None
106 try { return Some<HttpCacheSnapshot>(ClientDiskCacheSnapshot(this, entry, currentEventLoop().openFile(entry.path))) }
107 catch (error: Throwable) {
108 try { release(entry) }
109 catch (cleanup: Throwable) { throw ResourceUseException(error, cleanup) }
110 throw error
111 }
112 }
114 /**
115 * Starts a tentative body write or returns None when storage declines it; only commit
116 * publishes the entry.
117 */
118 public override suspend fun begin(record: HttpCacheRecord): HttpCacheWriter? {
119 val limit = if (maxEntryBytes < maxBytes) maxEntryBytes else maxBytes
120 val length = parseHttpContentLength(record.head.fields)
121 if (clientPresent(length) && length!! > limit) return None
122 val writer = ClientDiskCacheWriter(this, record, limit)
123 lock.withLock { writers.add(writer) }
124 return Some<HttpCacheWriter>(writer)
125 }
127 /**
128 * Invalidates all identities and Vary variants for the selected partition and URL.
129 */
130 public override suspend fun invalidate(partition: String, url: String) {
131 val retired = lock.withLock {
132 val paths = ArrayList<Path>()
133 var index = entries.size
134 while (index > 0L) {
135 index -= 1L
136 val key = entries[index].record.key
137 if (key.partition == partition && key.url == url) retire(index, paths)
138 }
139 for (writer in writers) if (writer.record.key.partition == partition && writer.record.key.url == url)
140 writer.discard.store(true)
141 paths.toArray()
142 }
143 deleteClientCacheFiles(retired)
144 }
146 /**
147 * Invalidates all entries and prevents existing tentative writes from publishing.
148 */
149 public suspend fun clear() {
150 val retired = lock.withLock {
151 val paths = ArrayList<Path>()
152 while (entries.size > 0L) retire(entries.size - 1L, paths)
153 for (writer in writers) writer.discard.store(true)
154 paths.toArray()
155 }
156 deleteClientCacheFiles(retired)
157 }
159 private suspend fun accept(entry: ClientDiskCacheEntry) { publishEntry(entry, None) }
160 internal suspend fun publish(entry: ClientDiskCacheEntry, writer: ClientDiskCacheWriter) { publishEntry(entry, Some(writer)) }
161 private suspend fun publishEntry(entry: ClientDiskCacheEntry, writer: ClientDiskCacheWriter?) {
162 val retired = lock.withLock {
163 val paths = ArrayList<Path>()
164 if (clientPresent(writer)) {
165 forget(writer!!)
166 if (writer!!.discard.load()) { paths.add(entry.path); return@withLock paths.toArray() }
167 }
168 for (previous in entries) if (replacedClientCacheVariant(previous.record, entry.record) &&
169 previous.record.responseDate > entry.record.responseDate) {
170 paths.add(entry.path); return@withLock paths.toArray()
171 }
172 var index = entries.size
173 while (index > 0L) {
174 index -= 1L
175 if (!replacedClientCacheVariant(entries[index].record, entry.record)) continue
176 retire(index, paths)
177 }
178 while (entries.size >= maxEntries || used > maxBytes - entry.fileSize) retire(0L, paths)
179 entries.add(entry); used += entry.fileSize
180 if (clientPresent(writer)) writer!!.published.store(true)
181 paths.toArray()
182 }
183 deleteClientCacheFiles(retired)
184 }
186 internal fun abandon(writer: ClientDiskCacheWriter) { lock.withLock { forget(writer) } }
187 private fun forget(writer: ClientDiskCacheWriter) {
188 for (index in 0L..<writers.size) if (writers[index] === writer) { writers.removeAt(index); return }
189 }
190 private fun retire(index: Long, paths: MutableList<Path>) {
191 val entry = entries[index]
192 entries.removeAt(index); used -= entry.fileSize; entry.retired = true
193 if (entry.readers == 0L) paths.add(entry.path)
194 }
195 internal suspend fun release(entry: ClientDiskCacheEntry) {
196 val deleting = lock.withLock { entry.readers -= 1L; entry.readers == 0L && entry.retired }
197 if (deleting) deleteClientCacheFiles([entry.path])
198 }