@voxgig/sdkgen 4.50.0 → 4.51.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (180) hide show
  1. package/bin/voxgig-sdkgen +1 -1
  2. package/package.json +1 -1
  3. package/project/.sdk/model/feature/cache.aontu +6 -4
  4. package/project/.sdk/model/target/lua.aontu +6 -0
  5. package/project/.sdk/src/cmp/c/Config_c.ts +3 -134
  6. package/project/.sdk/src/cmp/c/TestClean_c.ts +14 -0
  7. package/project/.sdk/src/cmp/clojure/TestClean_clojure.ts +10 -5
  8. package/project/.sdk/src/cmp/cpp/TestClean_cpp.ts +13 -0
  9. package/project/.sdk/src/cmp/csharp/TestClean_csharp.ts +9 -0
  10. package/project/.sdk/src/cmp/elixir/TestClean_elixir.ts +11 -3
  11. package/project/.sdk/src/cmp/go/TestClean_go.ts +39 -3
  12. package/project/.sdk/src/cmp/java/TestClean_java.ts +8 -0
  13. package/project/.sdk/src/cmp/js/TestClean_js.ts +13 -5
  14. package/project/.sdk/src/cmp/kotlin/TestClean_kotlin.ts +22 -0
  15. package/project/.sdk/src/cmp/lua/TestClean_lua.ts +12 -3
  16. package/project/.sdk/src/cmp/ocaml/TestClean_ocaml.ts +18 -4
  17. package/project/.sdk/src/cmp/perl/TestClean_perl.ts +12 -3
  18. package/project/.sdk/src/cmp/php/TestClean_php.ts +10 -3
  19. package/project/.sdk/src/cmp/py/TestClean_py.ts +10 -3
  20. package/project/.sdk/src/cmp/rb/TestClean_rb.ts +10 -3
  21. package/project/.sdk/src/cmp/rust/TestClean_rust.ts +10 -0
  22. package/project/.sdk/src/cmp/scala/TestClean_scala.ts +34 -0
  23. package/project/.sdk/src/cmp/swift/TestClean_swift.ts +20 -10
  24. package/project/.sdk/src/cmp/ts/TestClean_ts.ts +13 -5
  25. package/project/.sdk/src/cmp/zig/TestClean_zig.ts +12 -0
  26. package/project/.sdk/tm/c/core/context.c +1 -0
  27. package/project/.sdk/tm/c/core/sdk.h +7 -4
  28. package/project/.sdk/tm/c/feature/cache.c +243 -13
  29. package/project/.sdk/tm/c/feature/secrets.c +27 -38
  30. package/project/.sdk/tm/c/tests/feature_test.c +104 -0
  31. package/project/.sdk/tm/c/utility/clean.c +26 -33
  32. package/project/.sdk/tm/c/utility/make_options.c +9 -8
  33. package/project/.sdk/tm/clojure/feature/secrets/sdk/feature/secrets.clj +14 -11
  34. package/project/.sdk/tm/clojure/src/sdk/client.clj +3 -1
  35. package/project/.sdk/tm/clojure/src/sdk/core.clj +19 -11
  36. package/project/.sdk/tm/clojure/src/sdk/features.clj +81 -10
  37. package/project/.sdk/tm/clojure/test/sdk/test/feature.clj +33 -0
  38. package/project/.sdk/tm/clojure/test/sdk/test/pipeline.clj +1 -0
  39. package/project/.sdk/tm/cpp/Makefile +5 -0
  40. package/project/.sdk/tm/cpp/core/types.hpp +11 -4
  41. package/project/.sdk/tm/cpp/feature/audit.hpp +6 -7
  42. package/project/.sdk/tm/cpp/feature/cache.hpp +188 -9
  43. package/project/.sdk/tm/cpp/feature/secrets.hpp +12 -0
  44. package/project/.sdk/tm/cpp/test/feature_test.cpp +99 -0
  45. package/project/.sdk/tm/cpp/utility/pipeline.hpp +9 -7
  46. package/project/.sdk/tm/csharp/core/Context.cs +4 -0
  47. package/project/.sdk/tm/csharp/feature/CacheFeature.cs +126 -12
  48. package/project/.sdk/tm/csharp/feature/SecretsFeature.cs +9 -27
  49. package/project/.sdk/tm/csharp/test/FeatureTest.cs +76 -0
  50. package/project/.sdk/tm/csharp/utility/Clean.cs +5 -10
  51. package/project/.sdk/tm/csharp/utility/Fetcher.cs +7 -1
  52. package/project/.sdk/tm/csharp/utility/MakeOptions.cs +5 -12
  53. package/project/.sdk/tm/elixir/lib/projectname/context.ex +2 -0
  54. package/project/.sdk/tm/elixir/lib/projectname/feature/cache.ex +146 -30
  55. package/project/.sdk/tm/elixir/lib/projectname/feature/secrets.ex +10 -56
  56. package/project/.sdk/tm/elixir/lib/projectname/utility.ex +18 -12
  57. package/project/.sdk/tm/elixir/test/feature_test.exs +61 -0
  58. package/project/.sdk/tm/go/core/context.go +6 -0
  59. package/project/.sdk/tm/go/feature/cache_feature.go +131 -4
  60. package/project/.sdk/tm/go/feature/secrets_feature.go +17 -71
  61. package/project/.sdk/tm/go/test/feature_corpus_test.go +150 -2
  62. package/project/.sdk/tm/go/test/feature_test.go +61 -0
  63. package/project/.sdk/tm/go/utility/clean.go +5 -7
  64. package/project/.sdk/tm/go/utility/fetcher.go +11 -0
  65. package/project/.sdk/tm/go/utility/make_options.go +5 -7
  66. package/project/.sdk/tm/java/core/Context.java +9 -0
  67. package/project/.sdk/tm/java/feature/CacheFeature.java +123 -17
  68. package/project/.sdk/tm/java/feature/SecretsFeature.java +9 -92
  69. package/project/.sdk/tm/java/test/FeatureCorpusTest.java +141 -2
  70. package/project/.sdk/tm/java/test/FeatureTest.java +60 -0
  71. package/project/.sdk/tm/java/utility/Clean.java +6 -10
  72. package/project/.sdk/tm/java/utility/Fetcher.java +5 -1
  73. package/project/.sdk/tm/java/utility/MakeOptions.java +3 -1
  74. package/project/.sdk/tm/js/src/Context.js +4 -0
  75. package/project/.sdk/tm/js/src/feature/cache/CacheFeature.js +118 -11
  76. package/project/.sdk/tm/js/src/feature/cost/CostFeature.js +3 -2
  77. package/project/.sdk/tm/js/src/feature/metrics/MetricsFeature.js +1 -1
  78. package/project/.sdk/tm/js/src/feature/paging/PagingFeature.js +4 -4
  79. package/project/.sdk/tm/js/src/feature/rbac/RbacFeature.js +4 -4
  80. package/project/.sdk/tm/js/src/feature/secrets/SecretsFeature.js +16 -6
  81. package/project/.sdk/tm/js/src/feature/validate/ValidateFeature.js +2 -1
  82. package/project/.sdk/tm/js/src/utility/CleanUtility.js +1 -1
  83. package/project/.sdk/tm/js/src/utility/MakeOptionsUtility.js +6 -6
  84. package/project/.sdk/tm/js/test/feature/Corpus.test.js +100 -2
  85. package/project/.sdk/tm/js/test/feature/harness.js +3 -3
  86. package/project/.sdk/tm/js/test/pipeline.test.js +1 -1
  87. package/project/.sdk/tm/kotlin/core/Context.kt +3 -0
  88. package/project/.sdk/tm/kotlin/feature/CacheFeature.kt +102 -7
  89. package/project/.sdk/tm/kotlin/feature/SecretsFeature.kt +10 -20
  90. package/project/.sdk/tm/kotlin/test/FeatureTest.kt +59 -0
  91. package/project/.sdk/tm/kotlin/utility/CoreUtil.kt +5 -5
  92. package/project/.sdk/tm/kotlin/utility/Fetcher.kt +4 -0
  93. package/project/.sdk/tm/kotlin/utility/MakeOptions.kt +3 -1
  94. package/project/.sdk/tm/lua/core/context.lua +6 -0
  95. package/project/.sdk/tm/lua/feature/cache_feature.lua +212 -15
  96. package/project/.sdk/tm/lua/feature/secrets_feature.lua +15 -80
  97. package/project/.sdk/tm/lua/test/feature_test.lua +81 -0
  98. package/project/.sdk/tm/lua/utility/clean.lua +6 -9
  99. package/project/.sdk/tm/lua/utility/fetcher.lua +9 -0
  100. package/project/.sdk/tm/lua/utility/make_options.lua +5 -5
  101. package/project/.sdk/tm/ocaml/feature/secrets_feature.ml +21 -6
  102. package/project/.sdk/tm/ocaml/sdk_features.ml +106 -8
  103. package/project/.sdk/tm/ocaml/sdk_runtime.ml +13 -10
  104. package/project/.sdk/tm/ocaml/sdk_types.ml +2 -0
  105. package/project/.sdk/tm/ocaml/test/t_feature.ml +35 -1
  106. package/project/.sdk/tm/perl/core/context.pm +3 -0
  107. package/project/.sdk/tm/perl/feature/audit_feature.pm +4 -7
  108. package/project/.sdk/tm/perl/feature/cache_feature.pm +111 -15
  109. package/project/.sdk/tm/perl/feature/secrets_feature.pm +13 -18
  110. package/project/.sdk/tm/perl/t/feature.t +66 -0
  111. package/project/.sdk/tm/perl/t/feature_corpus.t +80 -4
  112. package/project/.sdk/tm/perl/utility/clean.pm +6 -8
  113. package/project/.sdk/tm/perl/utility/fetcher.pm +4 -0
  114. package/project/.sdk/tm/perl/utility/make_options.pm +5 -5
  115. package/project/.sdk/tm/php/core/Context.php +4 -0
  116. package/project/.sdk/tm/php/feature/CacheFeature.php +98 -13
  117. package/project/.sdk/tm/php/feature/SecretsFeature.php +18 -15
  118. package/project/.sdk/tm/php/test/FeatureCorpusTest.php +113 -3
  119. package/project/.sdk/tm/php/test/FeatureTest.php +68 -0
  120. package/project/.sdk/tm/php/utility/Clean.php +3 -10
  121. package/project/.sdk/tm/php/utility/Fetcher.php +8 -3
  122. package/project/.sdk/tm/php/utility/MakeOptions.php +5 -7
  123. package/project/.sdk/tm/py/pkg/core/context.py +4 -0
  124. package/project/.sdk/tm/py/pkg/feature/cache_feature.py +79 -13
  125. package/project/.sdk/tm/py/pkg/feature/secrets_feature.py +15 -66
  126. package/project/.sdk/tm/py/pkg/utility/clean.py +4 -10
  127. package/project/.sdk/tm/py/pkg/utility/make_options.py +8 -9
  128. package/project/.sdk/tm/py/test/feature/secrets/test_secrets.py +23 -9
  129. package/project/.sdk/tm/py/test/test_feature.py +50 -0
  130. package/project/.sdk/tm/py/test/test_feature_corpus.py +88 -3
  131. package/project/.sdk/tm/rb/core/context.rb +4 -1
  132. package/project/.sdk/tm/rb/feature/audit_feature.rb +6 -5
  133. package/project/.sdk/tm/rb/feature/cache_feature.rb +75 -11
  134. package/project/.sdk/tm/rb/feature/secrets_feature.rb +9 -64
  135. package/project/.sdk/tm/rb/test/feature_corpus_test.rb +85 -3
  136. package/project/.sdk/tm/rb/test/feature_test.rb +74 -0
  137. package/project/.sdk/tm/rb/utility/clean.rb +6 -7
  138. package/project/.sdk/tm/rb/utility/fetcher.rb +6 -0
  139. package/project/.sdk/tm/rb/utility/make_options.rb +5 -5
  140. package/project/.sdk/tm/rust/core/context.rs +8 -0
  141. package/project/.sdk/tm/rust/feature/cache.rs +120 -3
  142. package/project/.sdk/tm/rust/feature/secrets.rs +36 -98
  143. package/project/.sdk/tm/rust/tests/feature/secrets/main.rs +3 -3
  144. package/project/.sdk/tm/rust/tests/feature_test.rs +100 -0
  145. package/project/.sdk/tm/rust/utility/clean.rs +35 -43
  146. package/project/.sdk/tm/rust/utility/fetcher.rs +6 -0
  147. package/project/.sdk/tm/rust/utility/make_options.rs +8 -11
  148. package/project/.sdk/tm/scala/core/Context.scala +4 -0
  149. package/project/.sdk/tm/scala/feature/CacheFeature.scala +117 -11
  150. package/project/.sdk/tm/scala/feature/SecretsFeature.scala +11 -24
  151. package/project/.sdk/tm/scala/sdktest/SdkTestMain.scala +28 -0
  152. package/project/.sdk/tm/scala/utility/Fetcher.scala +5 -0
  153. package/project/.sdk/tm/scala/utility/Make.scala +3 -1
  154. package/project/.sdk/tm/scala/utility/Misc.scala +5 -8
  155. package/project/.sdk/tm/swift/Sources/ProjectNameSDK/core/Context.swift +3 -0
  156. package/project/.sdk/tm/swift/Sources/ProjectNameSDK/feature/CacheFeature.swift +122 -11
  157. package/project/.sdk/tm/swift/Sources/ProjectNameSDK/feature/SecretsFeature.swift +9 -13
  158. package/project/.sdk/tm/swift/Sources/ProjectNameSDK/utility/Fetcher.swift +4 -0
  159. package/project/.sdk/tm/swift/Sources/ProjectNameSDK/utility/MakeOptions.swift +5 -4
  160. package/project/.sdk/tm/swift/Sources/ProjectNameSDK/utility/ResultUtil.swift +4 -5
  161. package/project/.sdk/tm/swift/Tests/ProjectNameSDKTests/FeatureTest.swift +55 -0
  162. package/project/.sdk/tm/ts/src/Context.ts +4 -0
  163. package/project/.sdk/tm/ts/src/feature/cache/CacheFeature.ts +115 -4
  164. package/project/.sdk/tm/ts/src/feature/cost/CostFeature.ts +3 -2
  165. package/project/.sdk/tm/ts/src/feature/metrics/MetricsFeature.ts +1 -1
  166. package/project/.sdk/tm/ts/src/feature/paging/PagingFeature.ts +4 -4
  167. package/project/.sdk/tm/ts/src/feature/rbac/RbacFeature.ts +4 -4
  168. package/project/.sdk/tm/ts/src/feature/secrets/SecretsFeature.ts +14 -2
  169. package/project/.sdk/tm/ts/src/feature/validate/ValidateFeature.ts +2 -1
  170. package/project/.sdk/tm/ts/src/utility/CleanUtility.ts +1 -1
  171. package/project/.sdk/tm/ts/src/utility/MakeOptionsUtility.ts +6 -6
  172. package/project/.sdk/tm/ts/test/feature/Corpus.test.ts +101 -2
  173. package/project/.sdk/tm/ts/test/feature/harness.ts +3 -3
  174. package/project/.sdk/tm/ts/test/pipeline.test.ts +1 -1
  175. package/project/.sdk/tm/zig/core/context.zig +5 -0
  176. package/project/.sdk/tm/zig/core/utility.zig +11 -9
  177. package/project/.sdk/tm/zig/feature/cache.zig +144 -13
  178. package/project/.sdk/tm/zig/feature/secrets.zig +6 -1
  179. package/project/.sdk/tm/zig/test/feature_test.zig +65 -0
  180. package/project/sdkgen-package.json +1 -1
@@ -1,16 +1,17 @@
1
1
  package KOTLINPACKAGE.feature
2
2
 
3
+ import java.security.SecureRandom
3
4
  import java.util.function.Supplier
5
+ import javax.crypto.Mac
6
+ import javax.crypto.spec.SecretKeySpec
4
7
 
5
8
  import KOTLINPACKAGE.core.Context
6
9
  import KOTLINPACKAGE.core.FetcherFn
7
10
  import KOTLINPACKAGE.core.SdkClient
8
11
  import KOTLINPACKAGE.utility.Media
9
12
 
10
- // Response caching for safe (read) requests. Wraps the active transport and
11
- // serves a fresh cached snapshot instead of hitting the network when the same
12
- // method+URL was fetched within `ttl` ms (default: 5000). Only successful
13
- // (2xx) responses to cacheable methods (default: GET) are stored.
13
+ // Response caching for safe (read) requests, per client: see the features
14
+ // reference for the key, the write invalidation and the Cache-Control rules.
14
15
  @Suppress("UNCHECKED_CAST")
15
16
  class CacheFeature : BaseFeature("cache", "0.0.1", true) {
16
17
 
@@ -18,6 +19,7 @@ class CacheFeature : BaseFeature("cache", "0.0.1", true) {
18
19
  private var options: MutableMap<String, Any?>? = null
19
20
  private var store: MutableMap<String, CacheEntry> = linkedMapOf()
20
21
  private var order: MutableList<String> = mutableListOf()
22
+ private var secret: SecretKeySpec? = null
21
23
 
22
24
  // Activity tracking (mirrors the ts client._cache record).
23
25
  var hit = 0
@@ -26,6 +28,7 @@ class CacheFeature : BaseFeature("cache", "0.0.1", true) {
26
28
 
27
29
  private class CacheEntry {
28
30
  var expiry: Long = 0
31
+ var scope: String = ""
29
32
  lateinit var snapshot: CacheSnapshot
30
33
  }
31
34
 
@@ -47,6 +50,9 @@ class CacheFeature : BaseFeature("cache", "0.0.1", true) {
47
50
 
48
51
  this.store = linkedMapOf()
49
52
  this.order = mutableListOf()
53
+ val key = ByteArray(32)
54
+ SecureRandom().nextBytes(key)
55
+ this.secret = SecretKeySpec(key, "HmacSHA256")
50
56
 
51
57
  val inner: FetcherFn = ctx.utility!!.fetcher
52
58
 
@@ -72,10 +78,17 @@ class CacheFeature : BaseFeature("cache", "0.0.1", true) {
72
78
  }
73
79
  }
74
80
  if (!cacheable) {
75
- return inner(ctx, url, fetchdef)
81
+ if (method in SAFE_METHODS) {
82
+ return inner(ctx, url, fetchdef)
83
+ }
84
+ try {
85
+ return inner(ctx, url, fetchdef)
86
+ } finally {
87
+ invalidate(url)
88
+ }
76
89
  }
77
90
 
78
- val key = "$method $url"
91
+ val key = "$method $url " + digest(fetchdef["headers"])
79
92
  val now = FeatureOptions.foptNow(this.options).getAsLong()
80
93
 
81
94
  val hitEntry = this.store[key]
@@ -100,10 +113,16 @@ class CacheFeature : BaseFeature("cache", "0.0.1", true) {
100
113
 
101
114
  if (storable(res)) {
102
115
  val snapshot = snapshot(res)
103
- val ttl = FeatureOptions.foptInt(this.options, "ttl", 5000)
116
+ val ttl = lifetime(snapshot.headers, FeatureOptions.foptInt(this.options, "ttl", 5000).toLong())
117
+ if (ttl <= 0) {
118
+ this.bypass++
119
+ return replay(snapshot)
120
+ }
121
+ drop(key)
104
122
  evict()
105
123
  val entry = CacheEntry()
106
124
  entry.expiry = now + ttl
125
+ entry.scope = scope(url)
107
126
  entry.snapshot = snapshot
108
127
  this.store[key] = entry
109
128
  this.order.add(key)
@@ -115,6 +134,39 @@ class CacheFeature : BaseFeature("cache", "0.0.1", true) {
115
134
  return res
116
135
  }
117
136
 
137
+ private fun digest(headers: Any?): String {
138
+ val pairs = mutableListOf<Pair<String, String>>()
139
+ if (headers is Map<*, *>) {
140
+ for ((name, value) in headers) {
141
+ if (value != null) {
142
+ pairs.add(Pair(name.toString().lowercase(), value.toString()))
143
+ }
144
+ }
145
+ }
146
+ pairs.sortWith(compareBy<Pair<String, String>> { it.first }.thenBy { it.second })
147
+ val mac = Mac.getInstance("HmacSHA256")
148
+ mac.init(this.secret)
149
+ for ((name, value) in pairs) {
150
+ mac.update("$name:$value\n".toByteArray(Charsets.UTF_8))
151
+ }
152
+ return mac.doFinal().joinToString("") { "%02x".format(it) }
153
+ }
154
+
155
+ private fun invalidate(url: String) {
156
+ val path = scope(url)
157
+ val collection = parent(path)
158
+ val dropped = this.store.filterValues { under(it.scope, path) || it.scope == collection }.keys.toList()
159
+ for (key in dropped) {
160
+ drop(key)
161
+ }
162
+ }
163
+
164
+ private fun drop(key: String) {
165
+ if (this.store.remove(key) != null) {
166
+ this.order.remove(key)
167
+ }
168
+ }
169
+
118
170
  // A body the transport could not read as JSON passes through, for the operation to report.
119
171
  private fun storable(res: Any?): Boolean {
120
172
  val status = FeatureOptions.fresStatus(res)
@@ -177,4 +229,47 @@ class CacheFeature : BaseFeature("cache", "0.0.1", true) {
177
229
  this.store.remove(oldest)
178
230
  }
179
231
  }
232
+
233
+ companion object {
234
+ private val SAFE_METHODS = listOf("GET", "HEAD")
235
+ private val UNSTORED = listOf("no-store", "private", "no-cache")
236
+ private val MAX_AGE = Regex("^max-age\\s*=\\s*\"?(\\d+)\"?$")
237
+
238
+ // The configured ttl capped by the response's Cache-Control; zero when
239
+ // the response may not be stored.
240
+ private fun lifetime(headers: Map<String, Any?>, ttl: Long): Long {
241
+ var control = ""
242
+ for ((name, value) in headers) {
243
+ if (name.lowercase() == "cache-control") {
244
+ control = value.toString().lowercase()
245
+ }
246
+ }
247
+ var life = ttl
248
+ for (part in control.split(",")) {
249
+ val directive = part.trim()
250
+ if (directive in UNSTORED) {
251
+ return 0
252
+ }
253
+ val secs = MAX_AGE.matchEntire(directive)?.groupValues?.get(1)?.toLongOrNull()
254
+ if (secs != null) {
255
+ life = minOf(life, secs * 1000)
256
+ }
257
+ }
258
+ return life
259
+ }
260
+
261
+ private fun scope(url: String): String = url.split(Regex("[?#]"), 2)[0].trimEnd('/')
262
+
263
+ private fun parent(scope: String): String {
264
+ val scheme = scope.indexOf("://")
265
+ val root = if (scheme < 0) 0 else scope.indexOf('/', scheme + 3)
266
+ if (root < 0) {
267
+ return scope
268
+ }
269
+ return scope.substring(0, maxOf(scope.lastIndexOf('/'), root))
270
+ }
271
+
272
+ private fun under(scope: String, prefix: String): Boolean =
273
+ scope == prefix || scope.startsWith("$prefix/")
274
+ }
180
275
  }
@@ -21,7 +21,7 @@ import KOTLINPACKAGE.feature.secrets.sekreto.SekretoError
21
21
  import KOTLINPACKAGE.feature.secrets.sekreto.envkey
22
22
  import KOTLINPACKAGE.feature.secrets.sekreto.specof
23
23
  import KOTLINPACKAGE.feature.secrets.sekreto.Json as SekJson
24
- import KOTLINPACKAGE.utility.defaultHttpFetch
24
+ import KOTLINPACKAGE.utility.fetcher
25
25
  import KOTLINPACKAGE.utility.resolveLocation
26
26
  import KOTLINPACKAGE.utility.struct.Struct
27
27
 
@@ -83,6 +83,7 @@ private const val REDIRECT_MAX = 5
83
83
  class SecretsFeature : BaseFeature("secrets", "0.1.0", true) {
84
84
 
85
85
  private var client: SdkClient? = null
86
+ private var rootctx: Context? = null
86
87
 
87
88
  // Every value this feature resolves or buys is a secret the SDK handles,
88
89
  // and none arrives under an option key the intake registration saw.
@@ -170,6 +171,7 @@ class SecretsFeature : BaseFeature("secrets", "0.1.0", true) {
170
171
  // Sync by feature contract: build the chain, never look anything up here.
171
172
  override fun init(ctx: Context, options: MutableMap<String, Any?>) {
172
173
  this.client = ctx.client
174
+ this.rootctx = ctx
173
175
  this.fopts = options
174
176
  this.liveopts = ctx.options ?: linkedMapOf()
175
177
  this.active = FeatureOptions.foptBool(options, "active", false)
@@ -704,27 +706,15 @@ class SecretsFeature : BaseFeature("secrets", "0.1.0", true) {
704
706
  "body" to body,
705
707
  // Never followed by the client: a redirect would carry the refresh token on.
706
708
  "redirect" to "manual",
709
+ // Its own bound, in milliseconds: the timeout feature's wrapper is above it.
710
+ "timeout" to 30000,
707
711
  )
708
712
 
709
- // Deliberately NOT the SDK transport. The transport is what this feature
710
- // wraps, and sending the token request back through it would recurse on
711
- // the first expiry - and would route the exchange through the test mock,
712
- // which knows nothing about it. utility/Fetcher.kt's defaultHttpFetch is
713
- // the SAME raw HTTP path the SDK uses, taken BELOW the mode/test gate,
714
- // so the ordinary case needs no custom transport; a supplied
715
- // system.fetch is honoured so a test can intercept the purchase.
716
- var sysFetch = Struct.getpath(options, listOf("system", "fetch"))
717
- if (sysFetch === Struct.UNDEF) {
718
- sysFetch = null
719
- }
720
-
721
- val ask = { at: String ->
722
- if (sysFetch is BiFunction<*, *, *>) {
723
- (sysFetch as BiFunction<String, MutableMap<String, Any?>, Any?>).apply(at, fetchdef)
724
- } else {
725
- defaultHttpFetch(at, fetchdef)
726
- }
727
- }
713
+ // The SDK's own transport, beneath every feature's wrapper: it holds the
714
+ // test feature's block and the GET-only guard, and the wrapped one would
715
+ // recurse on the first expiry.
716
+ val rctx = this.rootctx!!
717
+ val ask = { at: String -> fetcher(rctx, at, fetchdef) }
728
718
 
729
719
  var res: Any? = ask(url)
730
720
 
@@ -453,6 +453,65 @@ class FeatureTest {
453
453
  assertEquals(3, rec.calls.size, "expected 3 calls")
454
454
  }
455
455
 
456
+ @Test
457
+ fun cache_keysOnRequestHeaders() {
458
+ assumeFeatures("cache")
459
+ val rec = FhRecorder()
460
+ val h = fhMake(rec::fetch, fhF(CacheFeature(), fhMap("ttl", 10000)))
461
+ h.op(fhOp("load").path("/w/1").headers(fhMap("x-tenant", "tenant-a")))
462
+ h.op(fhOp("load").path("/w/1").headers(fhMap("X-Tenant", "tenant-b")))
463
+ assertEquals(2, rec.calls.size, "a second tenant was served the first tenant's entry")
464
+ h.op(fhOp("load").path("/w/1").headers(fhMap("x-tenant", "tenant-b")))
465
+ assertEquals(2, rec.calls.size, "the same headers did not share an entry")
466
+ }
467
+
468
+ @Test
469
+ fun cache_aWriteDropsItsCollection() {
470
+ assumeFeatures("cache")
471
+ val rec = FhRecorder()
472
+ val f = CacheFeature()
473
+ val h = fhMake(rec::fetch, fhF(f, fhMap("ttl", 10000)))
474
+ val paths = listOf("/w/1", "/w", "/w/1/part", "/other/1", "/w/2")
475
+ for (p in paths) {
476
+ h.op(fhOp("load").path(p))
477
+ }
478
+ h.op(fhOp("update").method("PUT").path("/w/1"))
479
+ for (p in paths) {
480
+ h.op(fhOp("load").path(p))
481
+ }
482
+ assertEquals(9, rec.calls.size, "expected the collection refetched and /other cached")
483
+ assertEquals(2, f.hit, "expected /other served from cache")
484
+ }
485
+
486
+ @Test
487
+ fun cache_cacheControlPreventsStoring() {
488
+ assumeFeatures("cache")
489
+ for (control in listOf("no-store", "private", "No-Cache", "max-age=60, private")) {
490
+ val rec = FhRecorder()
491
+ rec.reply = { _, _ -> fhResponse(200, fhMap("ok", true), fhMap("Cache-Control", control)) }
492
+ val h = fhMake(rec::fetch, fhF(CacheFeature(), fhMap("ttl", 10000)))
493
+ h.op(fhOp("load").path("/w"))
494
+ h.op(fhOp("load").path("/w"))
495
+ assertEquals(2, rec.calls.size, "$control was stored")
496
+ }
497
+ }
498
+
499
+ @Test
500
+ fun cache_maxAgeCapsTheTtl() {
501
+ assumeFeatures("cache")
502
+ val clock = FhClock()
503
+ val rec = FhRecorder()
504
+ rec.reply = { _, _ -> fhResponse(200, fhMap("ok", true), fhMap("cache-control", "max-age=1")) }
505
+ val h = fhMake(rec::fetch, fhF(CacheFeature(), fhMap("ttl", 10000, "now", nowFn(clock))))
506
+ h.op(fhOp("load").path("/w"))
507
+ clock.advance(500)
508
+ h.op(fhOp("load").path("/w"))
509
+ assertEquals(1, rec.calls.size, "expected a hit inside max-age")
510
+ clock.advance(600)
511
+ h.op(fhOp("load").path("/w"))
512
+ assertEquals(2, rec.calls.size, "expected max-age=1 to expire the entry before the ttl")
513
+ }
514
+
456
515
  @Test
457
516
  fun cache_inactiveDoesNotWrap() {
458
517
  assumeFeatures("cache")
@@ -40,7 +40,7 @@ private class BinaryBody(val live: List<Any>, val type: String?, val sized: Bool
40
40
  fun holds(v: Any): Boolean = live.any { it === v || (v is String && v == it) }
41
41
  }
42
42
 
43
- // The derived clean block: built by makeOptions from the raw input, grown by
43
+ // The clean registry: built by makeOptions from the raw input, grown by
44
44
  // cleanAdd for as long as the client lives (features register later).
45
45
  class CleanConfig(
46
46
  val active: Boolean,
@@ -95,12 +95,12 @@ fun makeCleanConfig(cleanopts: Any?): CleanConfig {
95
95
  )
96
96
  }
97
97
 
98
- // A context without options (makeError accepts a bare one) still masks by
98
+ // A context without a registry (makeError accepts a bare one) still masks by
99
99
  // the schema defaults.
100
100
  private fun cleanConfig(ctx: Context?): CleanConfig {
101
- val derived = Helpers.toMapAny(ctx?.options?.get("__derived__"))?.get("clean")
102
- if (derived is CleanConfig) {
103
- return derived
101
+ val cfg = ctx?.cleancfg
102
+ if (cfg is CleanConfig) {
103
+ return cfg
104
104
  }
105
105
  return makeCleanConfig(Schema.optspec["clean"])
106
106
  }
@@ -206,6 +206,10 @@ private fun fetchOnce(fullurl: String, fetchdef: MutableMap<String, Any?>): Muta
206
206
  } catch (e: RuntimeException) {
207
207
  throw RuntimeException("fetch: invalid url: $fullurl", e)
208
208
  }
209
+ // A bound in milliseconds, for a caller beneath the timeout feature.
210
+ (fetchdef["timeout"] as? Number)?.toLong()?.takeIf { it > 0 }?.let {
211
+ reqb.timeout(java.time.Duration.ofMillis(it))
212
+ }
209
213
 
210
214
  var hasUA = false
211
215
  val headersRaw = fetchdef["headers"]
@@ -211,10 +211,12 @@ fun makeOptions(ctx: Context): MutableMap<String, Any?> {
211
211
  }
212
212
 
213
213
  val derived = linkedMapOf<String, Any?>()
214
- derived["clean"] = cleancfg
215
214
  derived["featureorder"] = featureorder
216
215
  opts["__derived__"] = derived
217
216
 
217
+ // Beside the options, not in them: optionsMap hands them to callers.
218
+ ctx.cleancfg = cleancfg
219
+
218
220
  // Again over the merged result: the config's own defaults can carry one.
219
221
  registerSensitive(cleancfg, opts - "clean" - "__derived__")
220
222
 
@@ -97,6 +97,12 @@ function Context.new(ctxmap, basectx)
97
97
  self.options = basectx.options
98
98
  end
99
99
 
100
+ -- The clean registry, beside the options rather than in them.
101
+ self.cleancfg = helpers.get_ctx_prop(ctxmap, "cleancfg")
102
+ if self.cleancfg == nil and basectx ~= nil then
103
+ self.cleancfg = basectx.cleancfg
104
+ end
105
+
100
106
  -- Entity
101
107
  local e = helpers.get_ctx_prop(ctxmap, "entity")
102
108
  if e ~= nil then
@@ -1,13 +1,12 @@
1
1
  -- ProjectName SDK cache feature
2
2
  --
3
- -- Response caching for safe (read) requests. Wraps the active transport
4
- -- and serves a fresh cached snapshot instead of hitting the network when
5
- -- the same method+URL was fetched within `ttl` ms (default 5000). Only
6
- -- successful (2xx) responses to cacheable methods (default: GET) are
7
- -- stored, keyed by method+URL. The cache is bounded (`max` entries,
8
- -- default 256, oldest evicted first) and every hit/miss/bypass is counted
9
- -- on `client._cache`. Snapshots are replayed with a re-readable `json()`
10
- -- body so both the original caller and later hits can parse repeatedly.
3
+ -- Response caching for safe (read) requests, per client: see the features
4
+ -- reference for the key, the write invalidation and the Cache-Control
5
+ -- rules.
6
+
7
+ -- Lua has no HMAC: SipHash-2-4 under a random per-client key separates
8
+ -- header sets within one store without holding a header value. It is not a
9
+ -- cryptographic commitment.
11
10
 
12
11
  local BaseFeature = require("feature.base_feature")
13
12
  local media = require("utility.media")
@@ -16,6 +15,138 @@ local CacheFeature = {}
16
15
  CacheFeature.__index = CacheFeature
17
16
  setmetatable(CacheFeature, { __index = BaseFeature })
18
17
 
18
+ local UNSTORED = { ["no-store"] = true, ["private"] = true, ["no-cache"] = true }
19
+
20
+
21
+ local function rotl(x, b)
22
+ return (x << b) | (x >> (64 - b))
23
+ end
24
+
25
+
26
+ local function sipround(v0, v1, v2, v3)
27
+ v0 = v0 + v1; v1 = rotl(v1, 13); v1 = v1 ~ v0; v0 = rotl(v0, 32)
28
+ v2 = v2 + v3; v3 = rotl(v3, 16); v3 = v3 ~ v2
29
+ v0 = v0 + v3; v3 = rotl(v3, 21); v3 = v3 ~ v0
30
+ v2 = v2 + v1; v1 = rotl(v1, 17); v1 = v1 ~ v2; v2 = rotl(v2, 32)
31
+ return v0, v1, v2, v3
32
+ end
33
+
34
+
35
+ local function siphash24(key, data)
36
+ local k0, k1 = string.unpack("<i8<i8", key)
37
+ local v0 = 0x736f6d6570736575 ~ k0
38
+ local v1 = 0x646f72616e646f6d ~ k1
39
+ local v2 = 0x6c7967656e657261 ~ k0
40
+ local v3 = 0x7465646279746573 ~ k1
41
+ local len = #data
42
+ local full = len - (len % 8)
43
+ for i = 1, full, 8 do
44
+ local m = string.unpack("<i8", data, i)
45
+ v3 = v3 ~ m
46
+ v0, v1, v2, v3 = sipround(v0, v1, v2, v3)
47
+ v0, v1, v2, v3 = sipround(v0, v1, v2, v3)
48
+ v0 = v0 ~ m
49
+ end
50
+ local b = len << 56
51
+ for i = 0, (len % 8) - 1 do
52
+ b = b | (string.byte(data, full + i + 1) << (8 * i))
53
+ end
54
+ v3 = v3 ~ b
55
+ v0, v1, v2, v3 = sipround(v0, v1, v2, v3)
56
+ v0, v1, v2, v3 = sipround(v0, v1, v2, v3)
57
+ v0 = v0 ~ b
58
+ v2 = v2 ~ 0xff
59
+ for _ = 1, 4 do
60
+ v0, v1, v2, v3 = sipround(v0, v1, v2, v3)
61
+ end
62
+ return v0 ~ v1 ~ v2 ~ v3
63
+ end
64
+
65
+
66
+ -- The system's random source where it has one; otherwise math.random, which
67
+ -- is not a cryptographic generator.
68
+ CacheFeature._siphash24 = siphash24
69
+
70
+
71
+ local function cache_secret()
72
+ local f = io.open("/dev/urandom", "rb")
73
+ local bytes = f and f:read(16) or ""
74
+ if f then
75
+ f:close()
76
+ end
77
+ while #bytes < 16 do
78
+ bytes = bytes .. string.char(math.random(0, 255))
79
+ end
80
+ return bytes
81
+ end
82
+
83
+
84
+ local function header_text(v)
85
+ if v == nil then
86
+ return nil
87
+ end
88
+ if math.type(v) == "float" and v == math.floor(v) then
89
+ return string.format("%d", math.tointeger(v))
90
+ end
91
+ return tostring(v)
92
+ end
93
+
94
+
95
+ -- The configured ttl capped by the response's Cache-Control; zero when the
96
+ -- response may not be stored.
97
+ local function cache_lifetime(headers, ttl)
98
+ local control = ""
99
+ for k, v in pairs(headers or {}) do
100
+ if type(k) == "string" and string.lower(k) == "cache-control" then
101
+ control = string.lower(header_text(v) or "")
102
+ end
103
+ end
104
+ local life = ttl
105
+ for part in string.gmatch(control .. ",", "([^,]*),") do
106
+ local directive = string.match(part, "^%s*(.-)%s*$")
107
+ if UNSTORED[directive] then
108
+ return 0
109
+ end
110
+ local secs = string.match(directive, '^max%-age%s*=%s*"?(%d+)"?$')
111
+ if secs ~= nil then
112
+ life = math.min(life, tonumber(secs) * 1000)
113
+ end
114
+ end
115
+ return life
116
+ end
117
+
118
+
119
+ local function url_scope(url)
120
+ local base = string.match(url, "^[^?#]*")
121
+ return (string.gsub(base, "/+$", ""))
122
+ end
123
+
124
+
125
+ local function url_parent(scope)
126
+ local root = 0
127
+ local scheme = string.find(scope, "://", 1, true)
128
+ if scheme ~= nil then
129
+ root = string.find(scope, "/", scheme + 3, true)
130
+ if root == nil then
131
+ return scope
132
+ end
133
+ root = root - 1
134
+ end
135
+ local cut = 0
136
+ for i = #scope, 1, -1 do
137
+ if string.sub(scope, i, i) == "/" then
138
+ cut = i - 1
139
+ break
140
+ end
141
+ end
142
+ return string.sub(scope, 1, math.max(cut, root))
143
+ end
144
+
145
+
146
+ local function scope_under(scope, prefix)
147
+ return scope == prefix or string.sub(scope, 1, #prefix + 1) == prefix .. "/"
148
+ end
149
+
19
150
 
20
151
  function CacheFeature.new()
21
152
  local self = setmetatable(BaseFeature.new(), CacheFeature)
@@ -46,6 +177,7 @@ function CacheFeature:init(ctx, options)
46
177
 
47
178
  self.store = {}
48
179
  self.order = {}
180
+ self.secret = cache_secret()
49
181
 
50
182
  local cache_self = self
51
183
  local utility = ctx.utility
@@ -72,10 +204,19 @@ function CacheFeature:_through(ctx, fullurl, fetchdef, inner)
72
204
  end
73
205
  end
74
206
  if not cacheable_method then
75
- return inner(ctx, fullurl, fetchdef)
207
+ if method == "GET" or method == "HEAD" then
208
+ return inner(ctx, fullurl, fetchdef)
209
+ end
210
+ local out = table.pack(pcall(inner, ctx, fullurl, fetchdef))
211
+ self:_invalidate(fullurl)
212
+ if not out[1] then
213
+ error(out[2], 0)
214
+ end
215
+ return table.unpack(out, 2, out.n)
76
216
  end
77
217
 
78
- local key = method .. " " .. fullurl
218
+ local headers = fetchdef ~= nil and fetchdef["headers"] or nil
219
+ local key = method .. " " .. fullurl .. " " .. self:_digest(headers)
79
220
  local now = self:_now()
80
221
  local hit = self.store[key]
81
222
 
@@ -94,12 +235,16 @@ function CacheFeature:_through(ctx, fullurl, fetchdef, inner)
94
235
 
95
236
  if self:_cacheable(res, err) then
96
237
  local snapshot = self:_snapshot(res)
97
- local ttl = self.options["ttl"] == nil and 5000 or self.options["ttl"]
98
- self:_evict()
99
- if self.store[key] == nil then
100
- table.insert(self.order, key)
238
+ local ttl = cache_lifetime(snapshot.headers,
239
+ self.options["ttl"] == nil and 5000 or self.options["ttl"])
240
+ if ttl <= 0 then
241
+ self:_track("bypass")
242
+ return self:_replay(snapshot), nil
101
243
  end
102
- self.store[key] = { expiry = now + ttl, snapshot = snapshot }
244
+ self:_drop(key)
245
+ self:_evict()
246
+ table.insert(self.order, key)
247
+ self.store[key] = { expiry = now + ttl, scope = url_scope(fullurl), snapshot = snapshot }
103
248
  self:_track("miss")
104
249
  return self:_replay(snapshot), nil
105
250
  end
@@ -109,6 +254,58 @@ function CacheFeature:_through(ctx, fullurl, fetchdef, inner)
109
254
  end
110
255
 
111
256
 
257
+ function CacheFeature:_digest(headers)
258
+ local pairs_ = {}
259
+ if type(headers) == "table" then
260
+ for k, v in pairs(headers) do
261
+ local text = type(k) == "string" and header_text(v) or nil
262
+ if text ~= nil then
263
+ table.insert(pairs_, { string.lower(k), text })
264
+ end
265
+ end
266
+ end
267
+ table.sort(pairs_, function(a, b)
268
+ if a[1] ~= b[1] then
269
+ return a[1] < b[1]
270
+ end
271
+ return a[2] < b[2]
272
+ end)
273
+ local parts = {}
274
+ for _, p in ipairs(pairs_) do
275
+ table.insert(parts, p[1] .. ":" .. p[2] .. "\n")
276
+ end
277
+ return string.format("%016x", siphash24(self.secret, table.concat(parts)))
278
+ end
279
+
280
+
281
+ function CacheFeature:_invalidate(url)
282
+ local path = url_scope(url)
283
+ local collection = url_parent(path)
284
+ local dropped = {}
285
+ for key, entry in pairs(self.store) do
286
+ if scope_under(entry.scope, path) or entry.scope == collection then
287
+ table.insert(dropped, key)
288
+ end
289
+ end
290
+ for _, key in ipairs(dropped) do
291
+ self:_drop(key)
292
+ end
293
+ end
294
+
295
+
296
+ function CacheFeature:_drop(key)
297
+ if self.store[key] == nil then
298
+ return
299
+ end
300
+ self.store[key] = nil
301
+ for i = #self.order, 1, -1 do
302
+ if self.order[i] == key then
303
+ table.remove(self.order, i)
304
+ end
305
+ end
306
+ end
307
+
308
+
112
309
  function CacheFeature:_cacheable(res, err)
113
310
  -- A body the transport could not read as JSON passes through, for the operation to report.
114
311
  if err ~= nil or res == nil or res["unreadable"] == true then