Scoop API

scoop:scoop.http.server:0.1.0

src/compression/options.scoop

Selected production source · src/compression/options.scoop

1package scoop.http.server
3import scoop.collections.HashSet
4import scoop.compression.*
5import scoop.http.HttpMediaType
6import scoop.text.endsWith
8/** Response coding preferences and the conditions for dynamic compression. */
9public class ResponseCompressionOptions internal constructor(
10 encodings: List<CompressionOptions> = [CompressionOptions.Gzip(GzipOptions())],
11 /** Known smaller representations prefer identity when it is acceptable. */
12 public val minimumBytes: Long = 1024L,
13 /** The bounded output buffer used by the asynchronous compressor. */
14 public val bufferSize: Long = 8192L,
15 /** Selects compressible media types without reading the body. */
16 public val shouldCompress: (HttpMediaType) -> Boolean =
17 {
18 media -> media.type ==
19 "text" ||
20 (
21 media.type ==
22 "application" &&
23 (media.subtype == "json" || media.subtype == "xml")
24 ) ||
25 media.subtype.endsWith("+json") ||
26 media.subtype.endsWith("+xml")
27 }
28) {
29 /** A snapshot of the configured algorithms in server preference order. */
30 public val encodings: Array<CompressionOptions> = encodings.toArray()
31 internal val choices: Array<ResponseEncoding> = responseEncodings(encodings, bufferSize)
32 init {
33 if (minimumBytes < 0L || bufferSize <= 0L)
34 throw IllegalArgumentException(Some("invalid response compression bounds"))
35 }
38internal class ResponseEncoding(
39 val name: String,
40 val options: CompressionOptions,
41 val bufferSize: Long
44private fun responseEncodings(options: List<CompressionOptions>, bufferSize: Long): Array<
45 ResponseEncoding
46> {
47 val names = HashSet<String>()
48 val choices = ArrayList<ResponseEncoding>()
49 for (option in options) {
50 val name =
51 when (option.format) {
52 case CompressionFormat.Gzip -> "gzip"
53 case CompressionFormat.Zlib -> "deflate"
54 case CompressionFormat.Brotli -> "br"
55 case CompressionFormat.Zstd -> "zstd"
56 case CompressionFormat.RawDeflate -> throw IllegalArgumentException(
57 Some("HTTP deflate requires the zlib wrapper")
58 )
59 }
60 if (!names.add(name))
61 throw IllegalArgumentException(Some("duplicate response content coding"))
62 choices.add(ResponseEncoding(name, option, bufferSize))
63 }
64 return choices.toArray()
67/** Installs compression for the full downstream response, restoring an enclosing policy on exit. */
68public fun responseCompression(
69 options: ResponseCompressionOptions = responseCompressionOptions()
70): HttpMiddleware =
71 suspend {
72 ctx, next ->
73 ctx.requestJob.ensureActive()
74 if (ctx.response.isCommitted || ctx.response.isAborted)
75 throw IllegalStateException(
76 Some("response compression must be installed before commit")
77 )
78 val previous = ctx.compressionOptions
79 ctx.compressionOptions = Some(options)
80 try {
81 next()
82 }
83 finally {
84 ctx.compressionOptions = previous
85 }
86 }