@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,11 +1,8 @@
1
- // Response caching for safe (read) requests. Wraps the active transport and
2
- // serves a fresh cached snapshot instead of hitting the network when the same
3
- // method+URL was fetched within `ttl` ms (default: 5000). Only successful
4
- // (2xx) responses to cacheable methods (default: GET) are stored, keyed by
5
- // method+URL. The cache is bounded (`max` entries, default 256, oldest evicted
6
- // first) and every hit/miss/bypass is counted. Bodies are snapshotted on
7
- // capture so both the current caller and later hits can re-read the JSON body
8
- // repeatedly.
1
+ // Response caching for safe (read) requests, per client: see the features
2
+ // reference for the key, the write invalidation and the Cache-Control rules.
3
+ // Foundation on Linux has no HMAC: the seeded Hasher over a random per-client
4
+ // salt separates header sets within one store without holding a header value.
5
+ // It is not a cryptographic commitment.
9
6
 
10
7
  import Foundation
11
8
 
@@ -14,6 +11,10 @@ public final class CacheFeature: BaseFeature {
14
11
  private var options: VMap?
15
12
  private var store: [String: CacheEntry] = [:]
16
13
  private var order: [String] = []
14
+ private var salt: [UInt8] = []
15
+
16
+ private static let safeMethods: Set<String> = ["GET", "HEAD"]
17
+ private static let unstored: Set<String> = ["no-store", "private", "no-cache"]
17
18
 
18
19
  // Activity tracking (mirrors the ts client._cache record).
19
20
  public var hit = 0
@@ -22,6 +23,7 @@ public final class CacheFeature: BaseFeature {
22
23
 
23
24
  private final class CacheEntry {
24
25
  var expiry: Int64 = 0
26
+ var scope: String = ""
25
27
  var snapshot: CacheSnapshot = CacheSnapshot()
26
28
  }
27
29
 
@@ -50,6 +52,8 @@ public final class CacheFeature: BaseFeature {
50
52
 
51
53
  store = [:]
52
54
  order = []
55
+ var rng = SystemRandomNumberGenerator()
56
+ salt = (0..<32).map { _ in UInt8.random(in: 0...255, using: &rng) }
53
57
 
54
58
  let inner = ctx.utility!.fetcher!
55
59
 
@@ -68,10 +72,14 @@ public final class CacheFeature: BaseFeature {
68
72
  let methods = foptStrList(options, "methods") ?? ["GET"]
69
73
  let cacheable = methods.contains { $0.uppercased() == method }
70
74
  if !cacheable {
75
+ if CacheFeature.safeMethods.contains(method) {
76
+ return try inner(ctx, url, fetchdef)
77
+ }
78
+ defer { invalidate(url) }
71
79
  return try inner(ctx, url, fetchdef)
72
80
  }
73
81
 
74
- let key = method + " " + url
82
+ let key = method + " " + url + " " + digest(fetchdef.entries["headers"])
75
83
  let now = foptNow(options)()
76
84
 
77
85
  if let entry = store[key], entry.expiry > now {
@@ -95,10 +103,16 @@ public final class CacheFeature: BaseFeature {
95
103
 
96
104
  if err == nil && CacheFeature.storable(res) {
97
105
  let snap = CacheFeature.snapshot(res)
98
- let ttl = foptInt(options, "ttl", 5000)
106
+ let ttl = CacheFeature.lifetime(snap.headers, Int64(foptInt(options, "ttl", 5000)))
107
+ if ttl <= 0 {
108
+ bypass += 1
109
+ return CacheFeature.replay(snap)
110
+ }
111
+ drop(key)
99
112
  evict()
100
113
  let entry = CacheEntry()
101
- entry.expiry = now + Int64(ttl)
114
+ entry.expiry = now + ttl
115
+ entry.scope = CacheFeature.scope(url)
102
116
  entry.snapshot = snap
103
117
  store[key] = entry
104
118
  order.append(key)
@@ -113,6 +127,103 @@ public final class CacheFeature: BaseFeature {
113
127
  return res
114
128
  }
115
129
 
130
+ private func digest(_ headers: Value?) -> String {
131
+ var pairs: [(String, String)] = []
132
+ if let hm = headers?.asMap {
133
+ for (k, v) in hm.entries {
134
+ if let text = CacheFeature.headerText(v) {
135
+ pairs.append((k.lowercased(), text))
136
+ }
137
+ }
138
+ }
139
+ pairs.sort { $0.0 != $1.0 ? $0.0 < $1.0 : $0.1 < $1.1 }
140
+ var hasher = Hasher()
141
+ hasher.combine(salt)
142
+ for (k, v) in pairs {
143
+ hasher.combine(k + ":" + v + "\n")
144
+ }
145
+ return String(UInt64(bitPattern: Int64(hasher.finalize())), radix: 16)
146
+ }
147
+
148
+ private static func headerText(_ v: Value) -> String? {
149
+ switch v {
150
+ case .noval, .null: return nil
151
+ case .string(let s): return s
152
+ case .int(let n): return String(n)
153
+ case .bool(let b): return String(b)
154
+ default: return "\(v)"
155
+ }
156
+ }
157
+
158
+ private func invalidate(_ url: String) {
159
+ let path = CacheFeature.scope(url)
160
+ let collection = CacheFeature.parent(path)
161
+ for (key, entry) in store
162
+ where CacheFeature.under(entry.scope, path) || entry.scope == collection {
163
+ drop(key)
164
+ }
165
+ }
166
+
167
+ private func drop(_ key: String) {
168
+ if store.removeValue(forKey: key) != nil {
169
+ order.removeAll { $0 == key }
170
+ }
171
+ }
172
+
173
+ // The configured ttl capped by the response's Cache-Control; zero when the
174
+ // response may not be stored.
175
+ private static func lifetime(_ headers: VMap, _ ttl: Int64) -> Int64 {
176
+ var control = ""
177
+ for (k, v) in headers.entries where k.lowercased() == "cache-control" {
178
+ control = (headerText(v) ?? "").lowercased()
179
+ }
180
+ var life = ttl
181
+ for part in control.split(separator: ",", omittingEmptySubsequences: false) {
182
+ let directive = part.trimmingCharacters(in: .whitespaces)
183
+ if unstored.contains(directive) {
184
+ return 0
185
+ }
186
+ if directive.hasPrefix("max-age") {
187
+ var value = directive.dropFirst("max-age".count).trimmingCharacters(in: .whitespaces)
188
+ if value.hasPrefix("=") {
189
+ value = value.dropFirst().trimmingCharacters(in: .whitespaces)
190
+ .trimmingCharacters(in: CharacterSet(charactersIn: "\""))
191
+ if !value.isEmpty, value.count < 16, value.allSatisfy({ $0.isASCII && $0.isNumber }),
192
+ let secs = Int64(value) {
193
+ life = min(life, secs * 1000)
194
+ }
195
+ }
196
+ }
197
+ }
198
+ return life
199
+ }
200
+
201
+ private static func scope(_ url: String) -> String {
202
+ var out = String(url.split(maxSplits: 1, omittingEmptySubsequences: false) { $0 == "?" || $0 == "#" }[0])
203
+ while out.hasSuffix("/") {
204
+ out.removeLast()
205
+ }
206
+ return out
207
+ }
208
+
209
+ private static func parent(_ scope: String) -> String {
210
+ let chars = Array(scope)
211
+ var root = 0
212
+ if let scheme = scope.range(of: "://") {
213
+ let after = scope.distance(from: scope.startIndex, to: scheme.upperBound)
214
+ guard let slash = chars[after...].firstIndex(of: "/") else {
215
+ return scope
216
+ }
217
+ root = slash
218
+ }
219
+ let cut = chars.lastIndex(of: "/") ?? 0
220
+ return String(chars[0..<Swift.max(cut, root)])
221
+ }
222
+
223
+ private static func under(_ scope: String, _ prefix: String) -> Bool {
224
+ return scope == prefix || scope.hasPrefix(prefix + "/")
225
+ }
226
+
116
227
  // A body the transport could not read as JSON passes through, for the operation to report.
117
228
  private static func storable(_ res: Value) -> Bool {
118
229
  let (status, has) = fresStatus(res)
@@ -72,6 +72,7 @@ import VoxgigPlugin
72
72
 
73
73
  public final class SecretsFeature: BaseFeature {
74
74
  private var client: ProjectNameSDK?
75
+ private var rootctx: Context?
75
76
  private var fopts: VMap?
76
77
 
77
78
  // The LIVE options map (the root context's options - the same instance
@@ -175,6 +176,7 @@ public final class SecretsFeature: BaseFeature {
175
176
  // Sync by feature contract: build the chain, never look anything up here.
176
177
  public override func initFeature(_ ctx: Context, _ options: VMap) {
177
178
  client = ctx.client
179
+ rootctx = ctx
178
180
  fopts = options
179
181
  liveopts = ctx.options ?? VMap()
180
182
  active = foptBool(options, "active", false)
@@ -652,21 +654,15 @@ public final class SecretsFeature: BaseFeature {
652
654
  fetchdef.entries["body"] = .string(body)
653
655
  // Never followed by the client: a redirect would carry the refresh token on.
654
656
  fetchdef.entries["redirect"] = .string("manual")
657
+ // Its own bound, in milliseconds: the timeout feature's wrapper is above it.
658
+ fetchdef.entries["timeout"] = .int(30000)
655
659
 
656
- // Deliberately NOT the SDK transport. The transport is what this feature
657
- // wraps, and sending the token request back through it would recurse on
658
- // the first expiry - and would route the exchange through the test mock,
659
- // which knows nothing about it. utility/Fetcher.swift's defaultHttpFetch
660
- // is the SAME raw HTTP path the SDK uses, taken BELOW the mode/test
661
- // gate, so the ordinary case needs no custom transport (and no
662
- // rawExchangeFetch twin, unlike go); a supplied system.fetch is honoured
663
- // so a test can intercept the purchase.
664
- let sysFetch = gpath(options, "system", "fetch")
660
+ // The SDK's own transport, beneath every feature's wrapper: it holds the
661
+ // test feature's block and the GET-only guard, and the wrapped one would
662
+ // recurse on the first expiry.
663
+ let rootctx = self.rootctx!
665
664
  func fetch(_ at: String) throws -> Value {
666
- if let fn = sysFetch.asNative as? SystemFetch {
667
- return fn(at, fetchdef)
668
- }
669
- return try defaultHttpFetch(at, fetchdef)
665
+ return try fetcherUtil(rootctx, at, fetchdef)
670
666
  }
671
667
 
672
668
  var res = try fetch(url)
@@ -135,6 +135,10 @@ private func sendOnce(_ fullurl: String, _ fetchdef: VMap) throws -> Value {
135
135
 
136
136
  var req = URLRequest(url: url)
137
137
  req.httpMethod = gp(fetchdef, "method").asString ?? "GET"
138
+ // A bound in milliseconds, for a caller beneath the timeout feature.
139
+ if let ms = gp(fetchdef, "timeout").asDouble, ms > 0 {
140
+ req.timeoutInterval = ms / 1000
141
+ }
138
142
 
139
143
  let body = gp(fetchdef, "body")
140
144
  if let text = body.asString, text != "" {
@@ -69,8 +69,7 @@ func makeOptionsUtil(_ ctx: Context) -> VMap {
69
69
  }
70
70
  }
71
71
  let cleancfg = makeCleanConfig(merge(.list(cleanlayers)))
72
- let cleanctx = Context(
73
- ["options": vm(("__derived__", .map(vm(("clean", .nat(cleancfg))))))], nil)
72
+ let cleanctx = Context(["cleancfg": cleancfg], nil)
74
73
  cleanAddOptions(cleanctx, cleanOmit(opts, ["clean"]))
75
74
  let cleanvalues = cleanSplitValues(gpath(cfgopts, "clean", "values"))
76
75
  + cleanSplitValues(gpath(opts, "clean", "values"))
@@ -176,12 +175,14 @@ func makeOptionsUtil(_ ctx: Context) -> VMap {
176
175
  }
177
176
 
178
177
  let derived = VMap()
179
- derived.entries["clean"] = .nat(cleancfg)
180
178
  derived.entries["featureorder"] = .list(VList(featureorder))
181
179
  result.entries["__derived__"] = .map(derived)
182
180
 
181
+ // Beside the options, not in them: optionsMap hands them to callers.
182
+ ctx.cleancfg = cleancfg
183
+
183
184
  // Again over the merged result: the config's own defaults can carry one.
184
- cleanAddOptions(Context(["options": result], nil), cleanOmit(result, ["clean", "__derived__"]))
185
+ cleanAddOptions(cleanctx, cleanOmit(result, ["clean", "__derived__"]))
185
186
 
186
187
  return result
187
188
  }
@@ -134,9 +134,8 @@ func transformResponseUtil(_ ctx: Context) -> Value {
134
134
  // stays raw, so a hook can still read the header it must add to. See
135
135
  // docs/explanation/secret-redaction.md.
136
136
 
137
- // The derived clean block, MUTABLE after makeOptions since features register
138
- // values later. Carried as a native object under options.__derived__.clean,
139
- // which JSON.stringify prints as "<function>" rather than as the registry.
137
+ // The clean registry, MUTABLE after makeOptions since features register
138
+ // values later. Held on the context beside the options, never in them.
140
139
  // Nested in Utility, whose registry it is, so no entity type can collide
141
140
  // with it.
142
141
  extension Utility {
@@ -247,10 +246,10 @@ func makeCleanConfig(_ cleanopts: Value) -> Utility.CleanConfig {
247
246
  return cfg
248
247
  }
249
248
 
250
- // A context without options (makeError accepts a bare one) still masks by
249
+ // A context without a registry (makeError accepts a bare one) still masks by
251
250
  // the schema defaults.
252
251
  func cleanConfigOf(_ ctx: Context) -> Utility.CleanConfig {
253
- if let cfg = gpath(ctx.options, "__derived__", "clean").asNative as? Utility.CleanConfig {
252
+ if let cfg = ctx.cleancfg {
254
253
  return cfg
255
254
  }
256
255
  return makeCleanConfig(gp(SdkSchema.optspec, "clean"))
@@ -602,6 +602,61 @@ final class FeatureCacheTest: XCTestCase {
602
602
  _ = h.op(FhOpSpec(op: "load", path: "/x"))
603
603
  XCTAssertEqual(rec.calls.count, 2)
604
604
  }
605
+
606
+ func testKeysOnRequestHeaders() {
607
+ if Fh.skipWithout("cache") { return }
608
+ let rec = FhRecorder()
609
+ let h = Fh.make(rec.fetch, (CacheFeature(), vm(("ttl", .int(10000)))))
610
+ _ = h.op(FhOpSpec(op: "load", path: "/w/1", headers: vm(("x-tenant", .string("tenant-a")))))
611
+ _ = h.op(FhOpSpec(op: "load", path: "/w/1", headers: vm(("X-Tenant", .string("tenant-b")))))
612
+ XCTAssertEqual(rec.calls.count, 2, "a second tenant was served the first tenant's entry")
613
+ _ = h.op(FhOpSpec(op: "load", path: "/w/1", headers: vm(("x-tenant", .string("tenant-b")))))
614
+ XCTAssertEqual(rec.calls.count, 2, "the same headers did not share an entry")
615
+ }
616
+
617
+ func testAWriteDropsItsCollection() {
618
+ if Fh.skipWithout("cache") { return }
619
+ let rec = FhRecorder()
620
+ let f = CacheFeature()
621
+ let h = Fh.make(rec.fetch, (f, vm(("ttl", .int(10000)))))
622
+ let paths = ["/w/1", "/w", "/w/1/part", "/other/1", "/w/2"]
623
+ for p in paths { _ = h.op(FhOpSpec(op: "load", path: p)) }
624
+ _ = h.op(FhOpSpec(op: "update", method: "PUT", path: "/w/1"))
625
+ for p in paths { _ = h.op(FhOpSpec(op: "load", path: p)) }
626
+ XCTAssertEqual(rec.calls.count, 9)
627
+ XCTAssertEqual(f.hit, 2)
628
+ }
629
+
630
+ func testCacheControlPreventsStoring() {
631
+ if Fh.skipWithout("cache") { return }
632
+ for control in ["no-store", "private", "No-Cache", "max-age=60, private"] {
633
+ let rec = FhRecorder()
634
+ rec.reply = { _, _ in
635
+ Fh.response(200, mapv(("ok", .bool(true))), vm(("Cache-Control", .string(control))))
636
+ }
637
+ let h = Fh.make(rec.fetch, (CacheFeature(), vm(("ttl", .int(10000)))))
638
+ _ = h.op(FhOpSpec(op: "load", path: "/w"))
639
+ _ = h.op(FhOpSpec(op: "load", path: "/w"))
640
+ XCTAssertEqual(rec.calls.count, 2, control + " was stored")
641
+ }
642
+ }
643
+
644
+ func testMaxAgeCapsTheTtl() {
645
+ if Fh.skipWithout("cache") { return }
646
+ let clock = FhClock()
647
+ let rec = FhRecorder()
648
+ rec.reply = { _, _ in
649
+ Fh.response(200, mapv(("ok", .bool(true))), vm(("cache-control", .string("max-age=1"))))
650
+ }
651
+ let h = Fh.make(rec.fetch, (CacheFeature(), vm(("ttl", .int(10000)), ("now", .nat(clock.now)))))
652
+ _ = h.op(FhOpSpec(op: "load", path: "/w"))
653
+ clock.advance(500)
654
+ _ = h.op(FhOpSpec(op: "load", path: "/w"))
655
+ XCTAssertEqual(rec.calls.count, 1, "expected a hit inside max-age")
656
+ clock.advance(600)
657
+ _ = h.op(FhOpSpec(op: "load", path: "/w"))
658
+ XCTAssertEqual(rec.calls.count, 2, "expected max-age=1 to expire the entry before the ttl")
659
+ }
605
660
  }
606
661
 
607
662
  // --- idempotency -------------------------------------------------------------
@@ -40,6 +40,9 @@ class Context {
40
40
  entopts: Record<string, any>
41
41
  options: Record<string, any>
42
42
 
43
+ // The clean registry, which holds every registered credential in plain form.
44
+ cleancfg?: any
45
+
43
46
  opmap: Record<string, Operation>
44
47
 
45
48
  response?: Response
@@ -73,6 +76,7 @@ class Context {
73
76
  this.config = getprop(ctxmap, 'config', getprop(basectx, 'config'))
74
77
  this.entopts = getprop(ctxmap, 'entopts', getprop(basectx, 'entopts'))
75
78
  this.options = getprop(ctxmap, 'options', getprop(basectx, 'options'))
79
+ this.cleancfg = getprop(ctxmap, 'cleancfg', getprop(basectx, 'cleancfg'))
76
80
 
77
81
  this.entity = getprop(ctxmap, 'entity', getprop(basectx, 'entity'))
78
82
  this.shared = getprop(ctxmap, 'shared', getprop(basectx, 'shared'))
@@ -14,6 +14,7 @@ class CacheFeature extends BaseFeature {
14
14
  _client?: ProjectNameSDK
15
15
  _options: any = {}
16
16
  _store: Map<string, any> = new Map()
17
+ _key?: Promise<any>
17
18
 
18
19
 
19
20
  init(ctx: Context, options: FeatureOptions): void | Promise<any> {
@@ -26,6 +27,7 @@ class CacheFeature extends BaseFeature {
26
27
  }
27
28
 
28
29
  this._store = new Map()
30
+ this._key = cacheKey()
29
31
 
30
32
  const self = this
31
33
  const utility = ctx.utility
@@ -42,10 +44,18 @@ class CacheFeature extends BaseFeature {
42
44
  const methods = this._options.methods || ['GET']
43
45
 
44
46
  if (methods.indexOf(method) < 0) {
45
- return inner(ctx, url, fetchdef)
47
+ if (SAFE_METHODS.indexOf(method) >= 0) {
48
+ return inner(ctx, url, fetchdef)
49
+ }
50
+ try {
51
+ return await inner(ctx, url, fetchdef)
52
+ }
53
+ finally {
54
+ this._invalidate(url)
55
+ }
46
56
  }
47
57
 
48
- const key = method + ' ' + url
58
+ const key = method + ' ' + url + ' ' + await this._digest(fetchdef && fetchdef.headers)
49
59
  const now = this._now()
50
60
  const hit = this._store.get(key)
51
61
 
@@ -72,9 +82,16 @@ class CacheFeature extends BaseFeature {
72
82
  return this._replay(snapshot)
73
83
  }
74
84
 
75
- const ttl = null == this._options.ttl ? 5000 : this._options.ttl
85
+ const ttl = cacheLifetime(snapshot.headers,
86
+ null == this._options.ttl ? 5000 : this._options.ttl)
87
+ if (ttl <= 0) {
88
+ this._track('bypass')
89
+ return this._replay(snapshot)
90
+ }
91
+
92
+ this._store.delete(key)
76
93
  this._evict()
77
- this._store.set(key, { expiry: now + ttl, snapshot })
94
+ this._store.set(key, { expiry: now + ttl, scope: urlScope(url), snapshot })
78
95
  this._track('miss')
79
96
  return this._replay(snapshot)
80
97
  }
@@ -84,6 +101,25 @@ class CacheFeature extends BaseFeature {
84
101
  }
85
102
 
86
103
 
104
+ async _digest(this: any, headers: any): Promise<string> {
105
+ const subtle = globalThis.crypto.subtle
106
+ const mac = await subtle.sign('HMAC', await this._key,
107
+ new TextEncoder().encode(headerText(headers)))
108
+ return Array.from(new Uint8Array(mac), (b: number) => b.toString(16).padStart(2, '0')).join('')
109
+ }
110
+
111
+
112
+ _invalidate(this: any, url: string) {
113
+ const path = urlScope(url)
114
+ const collection = urlParent(path)
115
+ for (const [key, entry] of this._store) {
116
+ if (scopeUnder(entry.scope, path) || entry.scope === collection) {
117
+ this._store.delete(key)
118
+ }
119
+ }
120
+ }
121
+
122
+
87
123
  _cacheable(this: any, res: any): boolean {
88
124
  if (null == res || res instanceof Error) {
89
125
  return false
@@ -182,6 +218,81 @@ class CacheFeature extends BaseFeature {
182
218
  }
183
219
 
184
220
 
221
+ const SAFE_METHODS = ['GET', 'HEAD']
222
+
223
+ const UNSTORED = ['no-store', 'private', 'no-cache']
224
+
225
+
226
+ // A fresh random secret per client: the key holds a digest of the headers,
227
+ // never a header value.
228
+ function cacheKey(): Promise<any> {
229
+ const crypto = globalThis.crypto
230
+ return crypto.subtle.importKey('raw', crypto.getRandomValues(new Uint8Array(32)),
231
+ { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])
232
+ }
233
+
234
+
235
+ function headerText(headers: any): string {
236
+ const pairs: string[][] = []
237
+ for (const name of Object.keys(headers || {})) {
238
+ if (null != headers[name]) {
239
+ pairs.push([name.toLowerCase(), String(headers[name])])
240
+ }
241
+ }
242
+ pairs.sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0)
243
+ return pairs.map((p) => p[0] + ':' + p[1] + '\n').join('')
244
+ }
245
+
246
+
247
+ // The configured ttl, capped by the response's Cache-Control; zero when the
248
+ // response may not be stored.
249
+ function cacheLifetime(headers: Record<string, any>, ttl: number): number {
250
+ let control = ''
251
+ for (const name of Object.keys(headers || {})) {
252
+ if ('cache-control' === name.toLowerCase()) {
253
+ control = String(headers[name])
254
+ }
255
+ }
256
+ let life = ttl
257
+ for (const part of control.toLowerCase().split(',')) {
258
+ const directive = part.trim()
259
+ if (UNSTORED.indexOf(directive) >= 0) {
260
+ return 0
261
+ }
262
+ const age = directive.match(/^max-age\s*=\s*"?(\d+)"?$/)
263
+ if (null != age) {
264
+ life = Math.min(life, Number(age[1]) * 1000)
265
+ }
266
+ }
267
+ return life
268
+ }
269
+
270
+
271
+ function urlScope(url: string): string {
272
+ let scope = String(url).split(/[?#]/)[0]
273
+ while (scope.endsWith('/')) {
274
+ scope = scope.slice(0, -1)
275
+ }
276
+ return scope
277
+ }
278
+
279
+
280
+ function urlParent(scope: string): string {
281
+ const scheme = scope.indexOf('://')
282
+ const root = scheme < 0 ? 0 : scope.indexOf('/', scheme + 3)
283
+ if (root < 0) {
284
+ return scope
285
+ }
286
+ const cut = scope.lastIndexOf('/')
287
+ return scope.slice(0, cut < root ? root : cut)
288
+ }
289
+
290
+
291
+ function scopeUnder(scope: string, prefix: string): boolean {
292
+ return scope === prefix || scope.startsWith(prefix + '/')
293
+ }
294
+
295
+
185
296
  export {
186
297
  CacheFeature
187
298
  }
@@ -29,8 +29,9 @@ class CostFeature extends BaseFeature {
29
29
  client._cost = {
30
30
  currency: this._options.currency || 'USD',
31
31
  total: { calls: 0, attempts: 0, amount: 0, reported: 0, estimated: 0 },
32
- ops: {},
33
- actors: {},
32
+ // Keyed by a caller's string, so no prototype to collide with.
33
+ ops: Object.create(null),
34
+ actors: Object.create(null),
34
35
  budget: { limit, spent: 0, remaining: limit, exceeded: false },
35
36
  last: undefined,
36
37
  }
@@ -25,7 +25,7 @@ class MetricsFeature extends BaseFeature {
25
25
  if (null == client._metrics) {
26
26
  client._metrics = {
27
27
  total: { count: 0, ok: 0, err: 0, totalMs: 0, maxMs: 0 },
28
- ops: {},
28
+ ops: Object.create(null),
29
29
  }
30
30
  }
31
31
  }
@@ -176,17 +176,17 @@ class PagingFeature extends BaseFeature {
176
176
  const afterVar = this._options.afterVar || 'after'
177
177
  const firstVar = this._options.firstVar || 'first'
178
178
 
179
- const declared: Record<string, boolean> = {}
179
+ const declared = new Set<string>()
180
180
  for (const v of ((point.graphql && point.graphql.vars) || [])) {
181
- declared[v.name] = true
181
+ declared.add(v.name)
182
182
  }
183
183
 
184
- if (null != paging.cursor && declared[afterVar]) {
184
+ if (null != paging.cursor && declared.has(afterVar)) {
185
185
  vars[afterVar] = paging.cursor
186
186
  }
187
187
 
188
188
  if (null != this._options.limit && null == vars[firstVar] &&
189
- declared[firstVar]) {
189
+ declared.has(firstVar)) {
190
190
  vars[firstVar] = this._options.limit
191
191
  }
192
192
  }
@@ -12,7 +12,7 @@ class RbacFeature extends BaseFeature {
12
12
 
13
13
  _client?: ProjectNameSDK
14
14
  _options: any = {}
15
- _granted: Record<string, boolean> = {}
15
+ _granted: Set<string> = new Set()
16
16
 
17
17
 
18
18
  init(ctx: Context, options: FeatureOptions): void | Promise<any> {
@@ -20,10 +20,10 @@ class RbacFeature extends BaseFeature {
20
20
  this._options = options || {}
21
21
  this.active = (options as any).active
22
22
 
23
- this._granted = {}
23
+ this._granted = new Set()
24
24
  const perms = this._options.permissions || []
25
25
  for (const p of perms) {
26
- this._granted[p] = true
26
+ this._granted.add(p)
27
27
  }
28
28
  }
29
29
 
@@ -41,7 +41,7 @@ class RbacFeature extends BaseFeature {
41
41
  return
42
42
  }
43
43
 
44
- if (this._granted['*'] || this._granted[required]) {
44
+ if (this._granted.has('*') || this._granted.has(required)) {
45
45
  this._track(ctx, required, true)
46
46
  return
47
47
  }
@@ -1,6 +1,7 @@
1
1
  import type { Context, FeatureOptions } from '../../types'
2
2
 
3
3
  import { BaseFeature } from '../base/BaseFeature'
4
+ import { fetcher } from '../../utility/FetcherUtility'
4
5
  import { Sekreto, envkey } from './sekreto'
5
6
  // The plugin DEFINITIONS the model selected for this feature, emitted by
6
7
  // Config generically from the catalogue's active `plugin.def` entries.
@@ -261,9 +262,20 @@ class SecretsFeature extends BaseFeature {
261
262
  body: JSON.stringify({ [x.request]: this._refresh }),
262
263
  // Never followed by the client: a redirect would carry the refresh token on.
263
264
  redirect: 'manual',
265
+ // Its own bound: the timeout feature's wrapper is above it.
266
+ signal: AbortSignal.timeout(30000),
264
267
  }
265
268
 
266
- let res = await fetch(url, fetchdef)
269
+ // The SDK transport beneath every wrapper; its GET-only refusal fails the op.
270
+ const send = async (at: string) => {
271
+ const sent: any = await fetcher(this._client._rootctx, at, fetchdef)
272
+ if (sent instanceof Error) {
273
+ throw sent
274
+ }
275
+ return sent
276
+ }
277
+
278
+ let res = await send(url)
267
279
 
268
280
  // By option alone, and only while the exchange stays on its own origin.
269
281
  let at = url
@@ -273,7 +285,7 @@ class SecretsFeature extends BaseFeature {
273
285
  break
274
286
  }
275
287
  at = next
276
- res = await fetch(at, fetchdef)
288
+ res = await send(at)
277
289
  }
278
290
 
279
291
  const status = null == res ? 0 : res.status
@@ -131,7 +131,8 @@ class ValidateFeature extends BaseFeature {
131
131
 
132
132
 
133
133
  _entitySpec(this: any, ctx: any): any {
134
- return this._spec[entname(ctx)]
134
+ const name = entname(ctx)
135
+ return Object.prototype.hasOwnProperty.call(this._spec, name) ? this._spec[name] : undefined
135
136
  }
136
137
 
137
138
 
@@ -67,7 +67,7 @@ function count(val: any, dflt: number): number {
67
67
  // A context without options (makeError accepts a bare one) still masks by
68
68
  // the schema defaults.
69
69
  function cleanConfig(ctx: any): CleanConfig {
70
- const derived = ctx?.options?.__derived__?.clean
70
+ const derived = ctx?.cleancfg
71
71
  if (null != derived) {
72
72
  return derived
73
73
  }