scoop:scoop.http.client:0.1.0
src/cache/response.scoop
Selected production source · src/cache/response.scoop
1
package scoop.http.client3
import scoop.asyncio.*4
import scoop.crypto.digest5
import scoop.collections.emptyList6
import scoop.http.*7
import scoop.platform.memory.NativeByteBuffer8
import scoop.text.toHexString10
internal suspend fun prepareClientCacheResponse(11
call: ClientCall,12
head: HttpResponseHead13
): HttpResponseHead? {14
invalidateClientResponseCache(call, head)15
val cache = call.cache ?: return Some(head)16
val snapshot = cache.snapshot17
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 None30
}31
val origin = call.authentication.digestUse32
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 None40
}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.Revalidated45
call.responseStream = Some<ClientResponseStream>(ClientCachedResponseStream(snapshot!!))46
return Some(merged)47
}49
private fun finishClientCachedValidation(50
call: ClientCall,51
head: HttpResponseHead,52
use: ClientDigestUse53
) {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
else63
None64
finishClientDigestResponse(call, head, use, entity, call.exchange!!.trailers)65
}67
private fun clientCacheCompatible(snapshot: HttpCacheSnapshot, head: HttpResponseHead): Boolean {68
try {69
val length = parseHttpContentLength(head.fields)70
if (clientPresent(length) && length!! != snapshot.bodyLength)71
return false72
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 false77
for (index in 0L ..< original.size)78
if (original[index] != current[index])79
return false80
}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 false84
if (85
!HttpEntityTag.parse(previous!!.value).weaklyMatches(86
HttpEntityTag.parse(current.value)87
)88
)89
return false90
}91
return true92
} catch (_: HttpFieldParseException) {93
return false94
}95
}97
internal suspend fun beginClientCacheResponse(call: ClientCall, head: HttpResponseHead) {98
val cache = call.cache ?: return99
if (call.cacheStatus == HttpCacheStatus.Hit || call.cacheStatus == HttpCacheStatus.Unsatisfied)100
return101
val record =102
try {103
if (!clientMayStoreCache(call.request, head))104
return105
HttpCacheRecord.fromResponse(106
HttpCacheRequest(cache.request.key, clientRequestSnapshotFields(call)),107
head,108
cache.sentAt,109
cache.receivedAt110
)111
} catch (_: HttpFieldParseException) {112
return113
}114
val writer = cache.options.storage.begin(record)115
call.lock.withLock { cache.writer = writer }116
requireClientCall(call)117
}119
private fun clientCacheForbidsStorage(head: HttpResponseHead): Boolean {120
try {121
return HttpCacheControl.parseFields(head.fields).contains("no-store") ||122
HttpVary.parseFields(head.fields).isWildcard123
}124
catch (_: HttpFieldParseException) {125
return true126
}127
}129
private 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
400U137
)138
return139
val options = call.client.config.cache ?: return140
val request = call.request141
if (request.method == "GET" || request.method == "OPTIONS" || request.method == "TRACE")142
return143
options.storage.invalidate(call.client.cachePartition!!, clientCacheUrl(request.url))144
for (name in ["Location", "Content-Location"]) {145
val field = clientCacheField(head.fields, name) ?: continue146
val location = HttpLocation.parseOrNone(field.value) ?: continue147
val url = location.resolve(request.url)148
if (url.scheme != Some("http") && url.scheme != Some("https"))149
continue150
if (url.httpOrigin() == request.origin)151
options.storage.invalidate(call.client.cachePartition!!, clientCacheUrl(url))152
}153
}155
internal suspend fun commitClientCache(call: ClientCall) {156
val cache = call.cache ?: return157
val writer = call.lock.withLock { cache.writer } ?: return158
requireClientCall(call)159
writer.commit(call.responseStream!!.trailers ?: emptyList<HttpField>().toArray())160
call.lock.withLock { cache.writer = None }161
writer.close()162
requireClientCall(call)163
}165
internal suspend fun closeClientCacheSnapshot(call: ClientCall) {166
val cache = call.cache ?: return167
val snapshot =168
call.lock.withLock {169
val saved = cache.snapshot;170
cache.snapshot = None;171
saved172
}173
snapshot?.close()174
}176
internal suspend fun cleanupClientCache(call: ClientCall) {177
val cache = call.cache ?: return178
val(writer, snapshot) =179
call.lock.withLock {180
val saved = (cache.writer, cache.snapshot)181
cache.writer = None;182
cache.snapshot = None183
saved184
}185
nonCancellableScope<Unit> {186
var failure: Throwable? = None187
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
}200
}