scoop:scoop.http.client:0.1.0
src/client.scoop
Selected production source · src/client.scoop
1
package scoop.http.client3
import scoop.asyncio.*4
import scoop.platform.fs.Path5
import scoop.tls.*6
import scoop.tls.asyncio.openTlsClientContext8
/**9
* A reusable structured HTTP/1 and HTTP/2 client bound to one event loop and owner scope. Close it10
* before leaving that scope; responses and streaming sessions have explicit lifetimes.11
*/12
public class HttpClient internal constructor(internal val state: ClientState): AsyncCloseable {13
/**14
* Factories for clients owned by a caller-provided coroutine scope.15
*/16
public companion object {17
/**18
* Creates a client on the current event loop and binds background work to scope; close it19
* before the scope body exits.20
*/21
public suspend fun open(22
scope: CoroutineScope,23
config: HttpClientConfig = httpClientConfig()24
): HttpClient {25
val loop = currentEventLoop()26
val caller = clientJob(loop, true)27
scope.job.ensureActive()28
val cachePartition = clientCachePartition(config)29
val tls = config.tls30
val alpn: Array<Array<Byte>> =31
when (config.versionPolicy) {32
case Auto -> ["h2".toByteArray(), "http/1.1".toByteArray()]33
case Http1Only -> ["http/1.1".toByteArray()]34
case Http2Only -> ["h2".toByteArray()]35
}36
val context =37
openTlsClientContext(38
tls.trust,39
TlsOptions(tls.minimum, tls.maximum, alpn),40
tls.identity41
)42
val state = ClientState(loop, config, context, cachePartition)43
try {44
startClientOwner(state, scope, caller)45
caller.ensureActive()46
state.lock.withLock {47
if (!clientPresent(state.scope) || state.closing)48
throw HttpClientClosedException()49
Unit50
}51
return HttpClient(state)52
} catch (error: Throwable) {53
try {54
if (state.lock.withLock { state.adopted })55
closeClient(state)56
else57
context.close()58
} catch (cleanup: Throwable) {59
throw ResourceUseException(error, cleanup)60
}61
throw error62
}63
}64
}66
/**67
* Whether client shutdown has completed.68
*/69
public val isClosed: Boolean get() = state.lock.withLock { state.closed }70
/** Immutable timeout defaults, available to consumers composing a complete per-call override. */71
public val defaultTimeouts: HttpTimeoutOptions get() = state.config.timeouts72
/**73
* Waits for final response headers and returns an owned response, including non-2xx statuses.74
* The call remains active through body and cleanup.75
*/76
public suspend fun execute(request: HttpRequest): HttpResponse =77
executeClientRequest(state, request)78
/**79
* Runs the block with a response and closes it on every exit; do not retain the response80
* beyond the block.81
*/82
public suspend fun <T> withResponse(83
request: HttpRequest,84
block: suspend (HttpResponse) -> T85
): T = execute(request).useAsync(block)86
/**87
* Streams a successful response into a temporary file and atomically commits it to the88
* explicit destination on completion.89
*/90
public suspend fun download(91
request: HttpRequest,92
destination: Path,93
options: HttpDownloadOptions = httpDownloadOptions()94
): HttpDownloadResult = runClientDownload(state, request, destination, options)95
/**96
* Resumes an explicitly identified partial file using validation metadata, committing the97
* final destination only after a complete response.98
*/99
public suspend fun resumeDownload(100
request: HttpRequest,101
destination: Path,102
resume: HttpResumeOptions,103
options: HttpDownloadOptions = httpDownloadOptions()104
): HttpDownloadResult = runClientDownload(state, request, destination, options, Some(resume))105
/**106
* Opens an owned SSE source with explicit buffering and optional reconnection policy.107
*/108
public suspend fun openSse(109
request: HttpRequest,110
options: HttpSseOptions = httpSseOptions()111
): HttpEventSource = openClientSse(state, request, options)112
/**113
* Runs a block with an SSE source and closes it on every exit.114
*/115
public suspend fun <T> withSse(116
request: HttpRequest,117
options: HttpSseOptions = httpSseOptions(),118
block: suspend (HttpEventSource) -> T119
): T = openSse(request, options).useAsync(block)120
/**121
* Performs an HTTP/1.1 upgrade and returns an owned session or a consumable rejection122
* response.123
*/124
public suspend fun openWebSocket(125
request: HttpWebSocketRequest,126
options: HttpWebSocketOptions = httpWebSocketOptions()127
): HttpWebSocketResult = openClientWebSocket(state, request, options)128
/**129
* Runs a block with the upgrade result and closes the session or rejection response on every130
* exit.131
*/132
public suspend fun <T> withWebSocket(133
request: HttpWebSocketRequest,134
options: HttpWebSocketOptions = httpWebSocketOptions(),135
block: suspend (HttpWebSocketResult) -> T136
): T = openWebSocket(request, options).useAsync(block)137
/**138
* Clears cached authentication state for this provider, so subsequent calls reload credentials139
* or tokens.140
*/141
public fun clearAuthenticationCache(authenticator: HttpAuthenticator) {142
clearClientAuthenticationCache(state, authenticator)143
}144
/**145
* Cancels and awaits active calls, sessions, connections, and cleanup; closing from work that146
* would await itself is rejected.147
*/148
public override suspend fun close() {149
closeClient(state)150
}151
}153
/**154
* Creates a scoped client, runs the block, and closes it on every exit while awaiting active calls155
* and cleanup.156
*/157
public suspend fun <T> withHttpClient(158
config: HttpClientConfig = httpClientConfig(),159
block: suspend (HttpClient) -> T160
): T =161
coroutineScope {162
val scope = this163
HttpClient.open(scope, config).useAsync(block)164
}