scoop:scoop.http.client:0.1.0
src/cache/api.scoop
Selected production source · src/cache/api.scoop
1
package scoop.http.client3
import scoop.asyncio.*4
import scoop.collections.emptyList5
import scoop.collections.Map6
import scoop.collections.sorted7
import scoop.collections.sortedBy8
import scoop.http.*9
import scoop.platform.time.SystemClock10
import scoop.time.Clock11
import scoop.time.Instant12
import scoop.url.Url14
/**15
* Selects per-call use of configured private response caching.16
*/17
public enum HttpCacheMode {18
/**19
* Uses ordinary freshness, validation, and storage rules.20
*/21
Default,22
/**23
* Bypasses cache use for this call.24
*/25
Bypass,26
/**27
* Requires network refresh rather than serving an ordinary cached hit.28
*/29
Reload,30
/**31
* Requires a usable cached response without making a network request.32
*/33
OnlyIfCached }34
/**35
* Where the response came from in the cache workflow.36
*/37
public enum HttpCacheStatus {38
/**39
* The response was obtained from the network.40
*/41
Network,42
/**43
* A cached representation satisfied the request.44
*/45
Hit,46
/**47
* A cached representation was validated with the origin.48
*/49
Revalidated,50
/**51
* Only-if-cached could not provide a usable representation.52
*/53
Unsatisfied }55
/**56
* Explicit cache storage, identity partition, and clock used for freshness calculations.57
*/58
public class HttpCacheOptions public constructor(59
/**60
* The cache storage implementation.61
*/62
public val storage: HttpCache,63
/**64
* An explicit isolation partition; None selects the client's default partition.65
*/66
public val partition: String? = None,67
/**68
* The wall clock used for response age and freshness.69
*/70
public val clock: Clock = SystemClock71
)73
/**74
* The cache partition, normalized URL, and request identity used to separate representations.75
*/76
public class HttpCacheKey public constructor(77
/**78
* The cache isolation partition.79
*/80
public val partition: String,81
/**82
* The normalized request URL used as the storage key.83
*/84
public val url: String,85
/**86
* The request identity component separating authenticated variants.87
*/88
public val identity: String89
) : Equals<HttpCacheKey>, Hash {90
/**91
* Compares partition, URL, and identity exactly.92
*/93
public override operator fun equals(other: HttpCacheKey): Boolean =94
partition == other.partition && url == other.url && identity == other.identity95
/**96
* Hashes all three components consistently with equality.97
*/98
public override fun hash(): Long = (partition.hash() * 31L + url.hash()) * 31L + identity.hash()99
}101
/**102
* A cache key and copied request fields used for Vary matching.103
*/104
public class HttpCacheRequest public constructor(105
/**106
* The request's storage identity.107
*/108
public val key: HttpCacheKey, fields: List<HttpField>) {109
/**110
* A snapshot of request fields for Vary matching.111
*/112
public val fields: Array<HttpField> = fields.toArray()113
internal val fingerprints: Map<String, String> = clientCacheFingerprints(this.fields)114
internal fun fieldFingerprint(name: String): String = fingerprints[name] ?: clientEmptyCacheFingerprint115
}117
/**118
* One normalized Vary field name and its request-field fingerprint; wildcard names are rejected.119
*/120
public class HttpCacheVary public constructor(name: String,121
/**122
* The normalized request-field fingerprint for this variant.123
*/124
public val fingerprint: String) {125
/**126
* The normalized field name, excluding wildcard.127
*/128
public val name: String = HttpVary([name]).names[0L]129
init { if (this.name == "*") throw IllegalArgumentException(Some("wildcard Vary cannot identify a reusable cache entry")) }130
}132
/**133
* Stored response metadata, request/response times, and sorted unique Vary fingerprints.134
*/135
public class HttpCacheRecord public constructor(136
/**137
* The stored representation identity.138
*/139
public val key: HttpCacheKey,140
/**141
* The stored response head.142
*/143
public val head: HttpResponseHead,144
/**145
* The wall-clock instant when the request was sent.146
*/147
public val sentAt: Instant,148
/**149
* The wall-clock instant when the response was received.150
*/151
public val receivedAt: Instant,152
vary: List<HttpCacheVary> = emptyList<HttpCacheVary>()153
) {154
/**155
* Sorted unique Vary names with their request fingerprints.156
*/157
public val vary: Array<HttpCacheVary> = vary.sortedBy<HttpCacheVary, String> { field -> field.name }.toArray()158
internal val parsedDate: Instant? = clientCacheDate(head.fields, "Date", receivedAt)159
internal val responseDate: Instant = parsedDate ?: receivedAt160
init {161
for (index in 1L..<this.vary.size) if (this.vary[index - 1L].name == this.vary[index].name)162
throw IllegalArgumentException(Some("duplicate cache Vary field"))163
}164
/**165
* Tests key equality and every stored Vary fingerprint against a cache request.166
*/167
public fun matches(request: HttpCacheRequest): Boolean {168
if (key != request.key) return false169
for (field in vary) if (field.fingerprint != request.fieldFingerprint(field.name)) return false170
return true171
}173
/**174
* Construction of normalized metadata from actual responses.175
*/176
public companion object {177
/**178
* Builds stored metadata and Vary fingerprints from a request/response pair, rejecting179
* wildcard Vary.180
*/181
public fun fromResponse(request: HttpCacheRequest, head: HttpResponseHead, sentAt: Instant, receivedAt: Instant): HttpCacheRecord {182
val names = HttpVary.parseFields(head.fields).names.sorted()183
val vary = ArrayList<HttpCacheVary>()184
var previous: String? = None185
for (name in names) {186
if (name == "*") throw IllegalArgumentException(Some("wildcard Vary cannot identify a reusable cache entry"))187
if (previous == Some(name)) continue188
vary.add(HttpCacheVary(name, request.fieldFingerprint(name)))189
previous = Some(name)190
}191
return HttpCacheRecord(request.key, clientStoredCacheHead(clientCacheWithDate(head, receivedAt)), sentAt, receivedAt, vary)192
}193
}194
}196
/**197
* An owned stable cached representation. Close the snapshot after consuming its body so storage198
* can release retained resources.199
*/200
public interface HttpCacheSnapshot : AsyncCloseable {201
/**202
* Metadata belonging to this stable representation snapshot.203
*/204
public val record: HttpCacheRecord205
/**206
* The snapshot's forward-only body source.207
*/208
public val body: AsyncByteSource209
/**210
* The exact stored body byte count.211
*/212
public val bodyLength: Long213
/**214
* The completed stored trailers.215
*/216
public val trailers: Array<HttpField>217
}219
/**220
* A tentative cache-body sink. Commit publishes the complete body and trailers; closing without221
* commit abandons the write.222
*/223
public interface HttpCacheWriter : AsyncByteSink, AsyncCloseable {224
/**225
* Publishes the complete body and trailers after successful writing; callers still close the226
* writer.227
*/228
public suspend fun commit(trailers: List<HttpField>)229
}231
/**232
* Suspendable private-response storage with explicit lookup, tentative writes, and URL233
* invalidation.234
*/235
public interface HttpCache {236
/**237
* Returns an owned matching representation snapshot, or None. The caller closes a returned238
* snapshot.239
*/240
public suspend fun lookup(request: HttpCacheRequest): HttpCacheSnapshot?241
/**242
* Starts a tentative body write or returns None when storage declines it; only commit243
* publishes the entry.244
*/245
public suspend fun begin(record: HttpCacheRecord): HttpCacheWriter?246
/**247
* Invalidates all identities and Vary variants for the selected partition and URL.248
*/249
public suspend fun invalidate(partition: String, url: String)250
}252
internal fun clientCacheUrl(url: Url): String = url.httpOrigin().toString() + url.httpRequestTarget()254
internal fun sameClientCacheVariant(first: HttpCacheRecord, second: HttpCacheRecord): Boolean {255
if (first.key != second.key || first.vary.size != second.vary.size) return false256
for (index in 0L..<first.vary.size) {257
if (first.vary[index].name != second.vary[index].name ||258
first.vary[index].fingerprint != second.vary[index].fingerprint) return false259
}260
return true261
}263
internal fun replacedClientCacheVariant(first: HttpCacheRecord, second: HttpCacheRecord): Boolean {264
if (first.key != second.key) return false265
if (first.vary.size != second.vary.size) return true266
for (index in 0L..<first.vary.size) if (first.vary[index].name != second.vary[index].name) return true267
return sameClientCacheVariant(first, second)268
}