Scoop API

scoop:scoop.http.client:0.1.0

src/cache/response.scoop

Selected production source · src/cache/response.scoop

1package scoop.http.client
3import scoop.asyncio.*
4import scoop.crypto.digest
5import scoop.collections.emptyList
6import scoop.http.*
7import scoop.platform.memory.NativeByteBuffer
8import scoop.text.toHexString
10internal suspend fun prepareClientCacheResponse(
11 call: ClientCall,
12 head: HttpResponseHead
13): HttpResponseHead? {
14 invalidateClientResponseCache(call, head)
15 val cache = call.cache ?: return Some(head)
16 val snapshot = cache.snapshot
17 if (head.status != 304U || !clientPresent(snapshot)) {
18 closeClientCacheSnapshot(call)
19 if (clientCacheForbidsStorage(head))
20 cache.options.storage.invalidate(cache.request.key.partition, cache.request.key.url)
21 return Some(head)
22 }
23 val stream = call.exchange!!
24 val complete =
25 NativeByteBuffer.allocate(1L).use suspend { buffer -> stream.readInto(buffer, 1L) == 0L }
26 requireClientCall(call)
27 if (!complete) {
28 cache.options.storage.invalidate(cache.request.key.partition, cache.request.key.url)
29 return None
30 }
31 val origin = call.authentication.digestUse
32 if (clientPresent(origin))
33 finishClientCachedValidation(call, head, origin!!)
34 val proxy = clientForwardProxyDigest(call)
35 if (clientPresent(proxy))
36 finishClientCachedValidation(call, head, proxy!!)
37 if (!clientCacheCompatible(snapshot!!, head)) {
38 cache.options.storage.invalidate(cache.request.key.partition, cache.request.key.url)
39 return None
40 }
41 val merged = clientMergeCachedHead(snapshot!!.record.head, head, cache.receivedAt)
42 if (clientCacheForbidsStorage(merged))
43 cache.options.storage.invalidate(cache.request.key.partition, cache.request.key.url)
44 call.cacheStatus = HttpCacheStatus.Revalidated
45 call.responseStream = Some<ClientResponseStream>(ClientCachedResponseStream(snapshot!!))
46 return Some(merged)
49private fun finishClientCachedValidation(
50 call: ClientCall,
51 head: HttpResponseHead,
52 use: ClientDigestUse
53) {
54 val entity =
55 if (use.nonce.challenge.qop == Some("auth-int"))
56 Some(
57 digest(
58 clientDigestAlgorithm(use.nonce.challenge.algorithm),
59 emptyList<Byte>()
60 ).toHexString()
61 )
62 else
63 None
64 finishClientDigestResponse(call, head, use, entity, call.exchange!!.trailers)
67private fun clientCacheCompatible(snapshot: HttpCacheSnapshot, head: HttpResponseHead): Boolean {
68 try {
69 val length = parseHttpContentLength(head.fields)
70 if (clientPresent(length) && length!! != snapshot.bodyLength)
71 return false
72 if (clientCacheHas(head.fields, "Content-Encoding")) {
73 val original = parseHttpTokenFields(snapshot.record.head.fields, "Content-Encoding")
74 val current = parseHttpTokenFields(head.fields, "Content-Encoding")
75 if (original.size != current.size)
76 return false
77 for (index in 0L ..< original.size)
78 if (original[index] != current[index])
79 return false
80 }
81 val previous = clientCacheField(snapshot.record.head.fields, "ETag")
82 if (clientPresent(previous) && clientCacheHas(head.fields, "ETag")) {
83 val current = clientCacheField(head.fields, "ETag") ?: return false
84 if (
85 !HttpEntityTag.parse(previous!!.value).weaklyMatches(
86 HttpEntityTag.parse(current.value)
87 )
88 )
89 return false
90 }
91 return true
92 } catch (_: HttpFieldParseException) {
93 return false
94 }
97internal suspend fun beginClientCacheResponse(call: ClientCall, head: HttpResponseHead) {
98 val cache = call.cache ?: return
99 if (call.cacheStatus == HttpCacheStatus.Hit || call.cacheStatus == HttpCacheStatus.Unsatisfied)
100 return
101 val record =
102 try {
103 if (!clientMayStoreCache(call.request, head))
104 return
105 HttpCacheRecord.fromResponse(
106 HttpCacheRequest(cache.request.key, clientRequestSnapshotFields(call)),
107 head,
108 cache.sentAt,
109 cache.receivedAt
110 )
111 } catch (_: HttpFieldParseException) {
112 return
113 }
114 val writer = cache.options.storage.begin(record)
115 call.lock.withLock { cache.writer = writer }
116 requireClientCall(call)
119private fun clientCacheForbidsStorage(head: HttpResponseHead): Boolean {
120 try {
121 return HttpCacheControl.parseFields(head.fields).contains("no-store") ||
122 HttpVary.parseFields(head.fields).isWildcard
123 }
124 catch (_: HttpFieldParseException) {
125 return true
126 }
129private suspend fun invalidateClientResponseCache(call: ClientCall, head: HttpResponseHead) {
130 if (
131 call.request.options.cacheMode ==
132 HttpCacheMode.Bypass ||
133 head.status <
134 200U ||
135 head.status >=
136 400U
137 )
138 return
139 val options = call.client.config.cache ?: return
140 val request = call.request
141 if (request.method == "GET" || request.method == "OPTIONS" || request.method == "TRACE")
142 return
143 options.storage.invalidate(call.client.cachePartition!!, clientCacheUrl(request.url))
144 for (name in ["Location", "Content-Location"]) {
145 val field = clientCacheField(head.fields, name) ?: continue
146 val location = HttpLocation.parseOrNone(field.value) ?: continue
147 val url = location.resolve(request.url)
148 if (url.scheme != Some("http") && url.scheme != Some("https"))
149 continue
150 if (url.httpOrigin() == request.origin)
151 options.storage.invalidate(call.client.cachePartition!!, clientCacheUrl(url))
152 }
155internal suspend fun commitClientCache(call: ClientCall) {
156 val cache = call.cache ?: return
157 val writer = call.lock.withLock { cache.writer } ?: return
158 requireClientCall(call)
159 writer.commit(call.responseStream!!.trailers ?: emptyList<HttpField>().toArray())
160 call.lock.withLock { cache.writer = None }
161 writer.close()
162 requireClientCall(call)
165internal suspend fun closeClientCacheSnapshot(call: ClientCall) {
166 val cache = call.cache ?: return
167 val snapshot =
168 call.lock.withLock {
169 val saved = cache.snapshot;
170 cache.snapshot = None;
171 saved
172 }
173 snapshot?.close()
176internal suspend fun cleanupClientCache(call: ClientCall) {
177 val cache = call.cache ?: return
178 val(writer, snapshot) =
179 call.lock.withLock {
180 val saved = (cache.writer, cache.snapshot)
181 cache.writer = None;
182 cache.snapshot = None
183 saved
184 }
185 nonCancellableScope<Unit> {
186 var failure: Throwable? = None
187 try {
188 writer?.close()
189 } catch (error: Throwable) {
190 failure = Some(error)
191 }
192 try {
193 snapshot?.close()
194 } catch (error: Throwable) {
195 failure = Some(clientCombined(failure, error))
196 }
197 if (clientPresent(failure))
198 throw failure!!
199 }