@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
@@ -63,8 +63,8 @@ local json = require("dkjson")
63
63
  local helpers = require("core.helpers")
64
64
  local BaseFeature = require("feature.base_feature")
65
65
  local sekreto = require("feature.secrets.sekreto")
66
- local tls = require("utility.tls")
67
66
  local base64 = require("utility.clean").base64
67
+ local fetcher_util = require("utility.fetcher")
68
68
 
69
69
 
70
70
  local SecretsFeature = {}
@@ -469,6 +469,9 @@ function SecretsFeature:_transport(ctx, fullurl, fetchdef, inner)
469
469
  -- settled success is free, and with `cache = false` the chain is asked
470
470
  -- once per REQUEST, which is that option's meaning.
471
471
  local refused = self:_resolve()
472
+ if type(refused) == "table" and refused.is_sdk_error then
473
+ return nil, refused
474
+ end
472
475
  if refused ~= nil then
473
476
  return nil, ctx:make_error("secrets_refused", sekreto.errmessage(refused))
474
477
  end
@@ -637,77 +640,6 @@ function SecretsFeature:_buy()
637
640
  end
638
641
 
639
642
 
640
- -- The token-exchange transport of last resort: LuaSocket's http, answering
641
- -- the same shape the system.fetch seam promises (status + json). It exists
642
- -- so an exchange works with ordinary SDK options - requiring a custom
643
- -- transport for the COMMON case would reject every live token purchase
644
- -- before a request was made. Mirrors utility/fetcher.lua's own default
645
- -- (which is a local there, not exported); like it, this is HTTP through
646
- -- socket.http, and an https token endpoint needs luasec on the package path,
647
- -- which the rockspec does not require, and is verified as utility/tls says.
648
- local function raw_exchange_fetch(fullurl, fetchdef)
649
- local http_ok, http = pcall(require, "socket.http")
650
- local ltn12_ok, ltn12 = pcall(require, "ltn12")
651
- if not http_ok or not ltn12_ok then
652
- return nil, "HTTP library not available (install luasocket)"
653
- end
654
-
655
- local headers = {}
656
- for k, v in pairs(fetchdef["headers"] or {}) do
657
- if type(v) == "string" then
658
- headers[k] = v
659
- end
660
- end
661
-
662
- local body = fetchdef["body"]
663
- if type(body) ~= "string" then
664
- body = nil
665
- end
666
- if body ~= nil then
667
- headers["content-length"] = tostring(#body)
668
- end
669
-
670
- local create, refused = tls.create(fullurl)
671
- if refused ~= nil then
672
- return nil, refused
673
- end
674
-
675
- local chunks = {}
676
- local res, code, rawheaders = http.request({
677
- url = fullurl,
678
- method = fetchdef["method"] or "POST",
679
- headers = headers,
680
- source = body and ltn12.source.string(body) or nil,
681
- sink = ltn12.sink.table(chunks),
682
- create = create,
683
- redirect = false,
684
- })
685
-
686
- if not res then
687
- return nil, code
688
- end
689
-
690
- local raw = table.concat(chunks)
691
- local resheaders = {}
692
- for k, v in pairs(type(rawheaders) == "table" and rawheaders or {}) do
693
- resheaders[string.lower(k)] = v
694
- end
695
-
696
- return {
697
- status = code,
698
- headers = resheaders,
699
- json = function()
700
- if #raw == 0 then
701
- return nil
702
- end
703
- local decoded = json.decode(raw)
704
- return decoded
705
- end,
706
- body = raw,
707
- }, nil
708
- end
709
-
710
-
711
643
  function SecretsFeature:_buy_once()
712
644
  local x = self._exchange
713
645
 
@@ -728,14 +660,12 @@ function SecretsFeature:_buy_once()
728
660
  base = base:gsub("/+$", "")
729
661
  local url = base .. "/" .. (x.path:gsub("^/+", ""))
730
662
 
731
- -- Deliberately NOT the SDK transport. The transport is what this feature
732
- -- wraps, and sending the token request back through it would recurse on
733
- -- the first expiry - and would route the exchange through the test mock,
734
- -- which knows nothing about it. system.fetch, when the caller supplied
735
- -- one, is the raw seam beneath the transport and is honoured.
736
- local fetch = vs.getpath(options, "system.fetch")
737
- if type(fetch) ~= "function" then
738
- fetch = raw_exchange_fetch
663
+ -- The SDK's own transport, beneath every feature's wrapper: it holds the
664
+ -- test feature's block and the GET-only guard, and the wrapped one would
665
+ -- recurse on the first expiry.
666
+ local rootctx = self._rootctx
667
+ local fetch = function(at, fd)
668
+ return fetcher_util(rootctx, at, fd)
739
669
  end
740
670
 
741
671
  -- The body is ENCODED, never concatenated: a refresh token (or a
@@ -747,6 +677,8 @@ function SecretsFeature:_buy_once()
747
677
  body = json.encode({ [x.request] = self._refresh }),
748
678
  -- Never followed by the client: a redirect would carry the refresh token on.
749
679
  redirect = "manual",
680
+ -- Its own bound, in milliseconds: the timeout feature's wrapper is above it.
681
+ timeout = 30000,
750
682
  }
751
683
  local res, err = fetch(url, fetchdef)
752
684
 
@@ -761,6 +693,9 @@ function SecretsFeature:_buy_once()
761
693
  res, err = fetch(at, fetchdef)
762
694
  end
763
695
 
696
+ if type(err) == "table" and err.is_sdk_error then
697
+ return nil, err
698
+ end
764
699
  if err ~= nil then
765
700
  return nil, sekreto.SekretoError(
766
701
  "secrets: token exchange failed: " .. tostring(err) .. " from " .. url)
@@ -718,6 +718,87 @@ describe("feature", function()
718
718
  h.op({ op = "load", path = "/x" })
719
719
  assert.are.equal(2, #rec.calls)
720
720
  end)
721
+
722
+ -- The reference vectors of the SipHash paper: key 00..0f, message 00..len-1.
723
+ it("matches the SipHash reference vectors", function()
724
+ local CacheFeature = require("feature.cache_feature")
725
+ local bytes = {}
726
+ for i = 0, 63 do bytes[#bytes + 1] = string.char(i) end
727
+ local msg = table.concat(bytes)
728
+ local key = string.sub(msg, 1, 16)
729
+ for _, v in ipairs({
730
+ { 0, "726fdb47dd0e0e31" },
731
+ { 1, "74f839c593dc67fd" },
732
+ { 2, "0d6c8009d9a94f5a" },
733
+ { 3, "85676696d7fb7e2d" },
734
+ { 4, "cf2794e0277187b7" },
735
+ { 5, "18765564cd99a68d" },
736
+ { 6, "cbc9466e58fee3ce" },
737
+ { 7, "ab0200f58b01d137" },
738
+ { 8, "93f5f5799a932462" },
739
+ { 15, "a129ca6149be45e5" },
740
+ { 16, "3f2acc7f57c29bdb" },
741
+ { 63, "958a324ceb064572" },
742
+ }) do
743
+ assert.are.equal(v[2], string.format("%016x", CacheFeature._siphash24(key, string.sub(msg, 1, v[1]))))
744
+ end
745
+ end)
746
+
747
+ it("keys on the request headers", function()
748
+ local rec = recording_server()
749
+ local h = make_client({ features = {
750
+ { name = "cache", options = { ttl = 10000 } },
751
+ }, server = rec.server })
752
+ h.op({ op = "load", path = "/w/1", headers = { ["x-tenant"] = "tenant-a" } })
753
+ h.op({ op = "load", path = "/w/1", headers = { ["X-Tenant"] = "tenant-b" } })
754
+ assert.are.equal(2, #rec.calls)
755
+ h.op({ op = "load", path = "/w/1", headers = { ["x-tenant"] = "tenant-b" } })
756
+ assert.are.equal(2, #rec.calls)
757
+ end)
758
+
759
+ it("drops a write's collection", function()
760
+ local rec = recording_server()
761
+ local h = make_client({ features = {
762
+ { name = "cache", options = { ttl = 10000 } },
763
+ }, server = rec.server })
764
+ local paths = { "/w/1", "/w", "/w/1/part", "/other/1", "/w/2" }
765
+ for _, p in ipairs(paths) do h.op({ op = "load", path = p }) end
766
+ h.op({ op = "update", method = "PUT", path = "/w/1" })
767
+ for _, p in ipairs(paths) do h.op({ op = "load", path = p }) end
768
+ assert.are.equal(9, #rec.calls)
769
+ assert.are.equal(2, h.client._cache.hit)
770
+ end)
771
+
772
+ it("does not store what Cache-Control forbids", function()
773
+ for _, control in ipairs({ "no-store", "private", "No-Cache", "max-age=60, private" }) do
774
+ local rec = recording_server(function()
775
+ return make_response(200, { ok = true }, { ["Cache-Control"] = control })
776
+ end)
777
+ local h = make_client({ features = {
778
+ { name = "cache", options = { ttl = 10000 } },
779
+ }, server = rec.server })
780
+ h.op({ op = "load", path = "/w" })
781
+ h.op({ op = "load", path = "/w" })
782
+ assert.are.equal(2, #rec.calls, control)
783
+ end
784
+ end)
785
+
786
+ it("caps the ttl by max-age", function()
787
+ local clock = make_clock()
788
+ local rec = recording_server(function()
789
+ return make_response(200, { ok = true }, { ["cache-control"] = "max-age=1" })
790
+ end)
791
+ local h = make_client({ features = {
792
+ { name = "cache", options = { ttl = 10000, now = clock.now } },
793
+ }, server = rec.server })
794
+ h.op({ op = "load", path = "/w" })
795
+ clock.advance(500)
796
+ h.op({ op = "load", path = "/w" })
797
+ assert.are.equal(1, #rec.calls)
798
+ clock.advance(600)
799
+ h.op({ op = "load", path = "/w" })
800
+ assert.are.equal(2, #rec.calls)
801
+ end)
721
802
  end) end
722
803
 
723
804
 
@@ -141,16 +141,13 @@ local function make_clean_config(cleanopts)
141
141
  end
142
142
 
143
143
 
144
- -- A context without options (make_error accepts a bare one) still masks by
145
- -- the schema defaults.
144
+ -- A context without a registry (make_error accepts a bare one) still masks
145
+ -- by the schema defaults.
146
146
  local function clean_config(ctx)
147
- if type(ctx) == "table" and type(ctx.options) == "table" then
148
- local derived = ctx.options["__derived__"]
149
- if type(derived) == "table" and type(derived.clean) == "table"
150
- and type(derived.clean.values) == "table"
151
- then
152
- return derived.clean
153
- end
147
+ if type(ctx) == "table" and type(ctx.cleancfg) == "table"
148
+ and type(ctx.cleancfg.values) == "table"
149
+ then
150
+ return ctx.cleancfg
154
151
  end
155
152
 
156
153
  local ok, schema = pcall(require, "schema")
@@ -267,6 +267,14 @@ local function send_once(fullurl, fetchdef)
267
267
  return nil, refused
268
268
  end
269
269
 
270
+ -- A bound in milliseconds, for a caller beneath the timeout feature;
271
+ -- luasocket reads its timeout from the module, so it is restored after.
272
+ local bound = fetchdef["timeout"]
273
+ local was = http.TIMEOUT
274
+ if type(bound) == "number" and bound > 0 then
275
+ http.TIMEOUT = bound / 1000
276
+ end
277
+
270
278
  local response_body = {}
271
279
  local res, code, response_headers = http.request({
272
280
  url = fullurl,
@@ -277,6 +285,7 @@ local function send_once(fullurl, fetchdef)
277
285
  redirect = false,
278
286
  create = create,
279
287
  })
288
+ http.TIMEOUT = was
280
289
 
281
290
  if not res then
282
291
  return nil, code
@@ -180,7 +180,7 @@ local function make_options_util(ctx)
180
180
  vs.clone(cfgclean),
181
181
  vs.clone(rawclean),
182
182
  }))
183
- local cleanctx = { options = { __derived__ = { clean = cleancfg } } }
183
+ local cleanctx = { cleancfg = cleancfg }
184
184
  cleanmod.clean_add_sensitive(cleanctx, secret_scan(opts, { clean = true, extend = true }))
185
185
  for _, block in ipairs({ cfgclean, rawclean }) do
186
186
  for _, raw in ipairs(cleanmod.splitvalues(block.values)) do
@@ -405,10 +405,10 @@ local function make_options_util(ctx)
405
405
  cleanmod.clean_add_sensitive(cleanctx,
406
406
  secret_scan(opts, { clean = true, extend = true, __derived__ = true }))
407
407
 
408
- opts["__derived__"] = {
409
- clean = cleancfg,
410
- featureorder = featureorder,
411
- }
408
+ opts["__derived__"] = { featureorder = featureorder }
409
+
410
+ -- Beside the options, not in them: options_map hands them to callers.
411
+ ctx.cleancfg = cleancfg
412
412
 
413
413
  return opts
414
414
  end
@@ -227,6 +227,9 @@ let make ?(plugins : Defs.definition list = [])
227
227
  * where it places a credential, and Basic only where it composes one. *)
228
228
  let declared = ref false in
229
229
  let basic = ref false in
230
+ (* The transport's refusal of the last purchase, which the gate answers in
231
+ * place of a resolution error. *)
232
+ let refused : sdk_error option ref = ref None in
230
233
 
231
234
  let refuse (msg : string) =
232
235
  (match !initerr with None -> initerr := Some msg | Some _ -> ()) in
@@ -310,17 +313,25 @@ let make ?(plugins : Defs.definition list = [])
310
313
  ("body", Str (jsonify (jo [(x.xrequest, Str !refresh)])));
311
314
  (* Never followed by the client: a redirect would carry the refresh token on. *)
312
315
  ("redirect", Str "manual")] in
316
+ let sysfetch = getpath_s opts "system.fetch" in
313
317
  let fetch =
314
- match getpath_s opts "system.fetch" with
318
+ match sysfetch with
315
319
  | Func _ as sf -> Some (fun url fd -> call_vfn sf (ja [Str url; fd]))
316
320
  | _ -> transport in
317
- match fetch with
318
- | None ->
321
+ (* Not fetcher_util, as every other target does: the core bundles no
322
+ * client, so only its GET-only guard precedes the vendored one. *)
323
+ refused := (match sysfetch, !client with
324
+ | Func _, _ -> None
325
+ | _, Some { cl_rootctx = Some rctx; _ } -> Sdk_runtime.getonly_refusal rctx url fetchdef
326
+ | _ -> None);
327
+ match !refused, fetch with
328
+ | Some e, _ -> Error e.err_msg
329
+ | None, None ->
319
330
  Error ("secrets: the token exchange has no HTTP transport: this SDK's core bundles "
320
331
  ^ "none and no secrets plugin group needing one is active, so the vendored "
321
332
  ^ "HTTP client is not compiled; supply options.system.fetch or activate a "
322
333
  ^ "plugin group")
323
- | Some fetch ->
334
+ | None, Some fetch ->
324
335
  (* By option alone, and only while the exchange stays on its own origin. *)
325
336
  let rec ask at hops =
326
337
  let res = fetch at fetchdef in
@@ -426,7 +437,7 @@ let make ?(plugins : Defs.definition list = [])
426
437
  let current = !cred in
427
438
  let token =
428
439
  if "" <> current && current <> used then Some current
429
- else (match buy x with Ok t -> Some t | Error _ -> None) in
440
+ else (match buy x with Ok t -> Some t | Error _ -> refused := None; None) in
430
441
  match token with
431
442
  (* The purchase failed: answer with the API's own refusal rather
432
443
  * than this one - the refusal is the more useful of the two. *)
@@ -451,7 +462,11 @@ let make ?(plugins : Defs.definition list = [])
451
462
  (match resolve () with
452
463
  | Error msg ->
453
464
  bump_num (bucket ()) "refusals" 1.;
454
- (Noval, Some (ctx_make_error fctx "secrets_provider" msg))
465
+ let blocked = !refused in
466
+ refused := None;
467
+ (Noval, Some (match blocked with
468
+ | Some e -> e
469
+ | None -> ctx_make_error fctx "secrets_provider" msg))
455
470
  | Ok () ->
456
471
  if "" <> !cred then reauth fetchdef !cred;
457
472
  (match !exchange with
@@ -262,9 +262,93 @@ let ratelimit_feature () : feature =
262
262
  (* cache *)
263
263
  (* ------------------------------------------------------------------ *)
264
264
 
265
+ (* No HMAC in the stdlib: HMAC-MD5 over Digest separates header sets within
266
+ one client's store without holding a header value. It is not a
267
+ cryptographic commitment. *)
268
+ let cache_hmac (key : string) (msg : string) : string =
269
+ let key = if String.length key > 64 then Digest.string key else key in
270
+ let key = key ^ String.make (64 - String.length key) '\000' in
271
+ let pad c = String.map (fun ch -> Char.chr (Char.code ch lxor c)) key in
272
+ Digest.to_hex (Digest.string (pad 0x5c ^ Digest.string (pad 0x36 ^ msg)))
273
+
274
+ let cache_secret () : string =
275
+ let from_os =
276
+ try
277
+ let ic = open_in_bin "/dev/urandom" in
278
+ Fun.protect ~finally:(fun () -> close_in_noerr ic) (fun () -> Some (really_input_string ic 32))
279
+ with _ -> None in
280
+ match from_os with
281
+ | Some s -> s
282
+ | None ->
283
+ let st = Random.State.make_self_init () in
284
+ String.init 32 (fun _ -> Char.chr (Random.State.int st 256))
285
+
286
+ let cache_header_text (v : value) : string option =
287
+ match v with Noval | Null -> None | Str s -> Some s | _ -> Some (vstr_of v)
288
+
289
+ let cache_digest (secret : string) (headers : value) : string =
290
+ let pairs = match headers with
291
+ | Map _ ->
292
+ List.filter_map (fun k ->
293
+ Option.map (fun t -> (string_lower k, t)) (cache_header_text (getp headers k))) (keysof headers)
294
+ | _ -> [] in
295
+ let text = String.concat "" (List.map (fun (k, v) -> k ^ ":" ^ v ^ "\n") (List.sort compare pairs)) in
296
+ cache_hmac secret text
297
+
298
+ (* The configured ttl capped by the response's Cache-Control; zero when the
299
+ response may not be stored. *)
300
+ let cache_lifetime (headers : value) (ttl : float) : float =
301
+ let control = match headers with
302
+ | Map _ ->
303
+ List.fold_left (fun acc k ->
304
+ if string_lower k = "cache-control" then
305
+ (match cache_header_text (getp headers k) with Some t -> string_lower t | None -> acc)
306
+ else acc) "" (keysof headers)
307
+ | _ -> "" in
308
+ let directives = List.map String.trim (String.split_on_char ',' control) in
309
+ if List.exists (fun d -> List.mem d ["no-store"; "private"; "no-cache"]) directives then 0.
310
+ else
311
+ List.fold_left (fun life d ->
312
+ let n = String.length d in
313
+ if n > 7 && String.sub d 0 7 = "max-age" then begin
314
+ let rest = String.trim (String.sub d 7 (n - 7)) in
315
+ if String.length rest > 0 && rest.[0] = '=' then begin
316
+ let v = String.trim (String.sub rest 1 (String.length rest - 1)) in
317
+ let lv = String.length v in
318
+ let v = if lv >= 2 && v.[0] = '"' && v.[lv - 1] = '"' then String.sub v 1 (lv - 2) else v in
319
+ let rec digits i = i >= String.length v || (v.[i] >= '0' && v.[i] <= '9' && digits (i + 1)) in
320
+ if v <> "" && digits 0 then
321
+ (match float_of_string_opt v with Some secs -> Float.min life (secs *. 1000.) | None -> life)
322
+ else life
323
+ end else life
324
+ end else life) ttl directives
325
+
326
+ let cache_scope (url : string) : string =
327
+ let n = String.length url in
328
+ let rec cut i = if i >= n then n else (match url.[i] with '?' | '#' -> i | _ -> cut (i + 1)) in
329
+ let rec trim e = if e > 0 && url.[e - 1] = '/' then trim (e - 1) else e in
330
+ String.sub url 0 (trim (cut 0))
331
+
332
+ let cache_parent (scope : string) : string =
333
+ let n = String.length scope in
334
+ let rec find_scheme i = if i + 3 > n then None else if String.sub scope i 3 = "://" then Some i else find_scheme (i + 1) in
335
+ let root = match find_scheme 0 with
336
+ | None -> Some 0
337
+ | Some at -> String.index_from_opt scope (at + 3) '/' in
338
+ match root with
339
+ | None -> scope
340
+ | Some root ->
341
+ let cut = match String.rindex_opt scope '/' with Some c -> c | None -> 0 in
342
+ String.sub scope 0 (max cut root)
343
+
344
+ let cache_under (scope : string) (prefix : string) : bool =
345
+ let lp = String.length prefix in
346
+ scope = prefix || (String.length scope > lp && String.sub scope 0 lp = prefix && scope.[lp] = '/')
347
+
265
348
  let cache_feature () : feature =
266
349
  let options = ref (empty_map ()) in
267
350
  let store = ref [] in
351
+ let secret = ref "" in
268
352
  let f = { f_name = "cache"; f_version = "0.0.1"; f_active = true; f_options = Noval;
269
353
  f_init = (fun _ _ -> ()); f_hook = (fun _ _ -> ()) } in
270
354
  let track ctx kind =
@@ -293,12 +377,20 @@ let cache_feature () : feature =
293
377
  let evict () =
294
378
  let mx = opt_int !options "max" ~default:256 in
295
379
  while List.length !store >= mx do (match !store with _ :: tl -> store := tl | [] -> ()) done in
380
+ let invalidate url =
381
+ let path = cache_scope url in
382
+ let collection = cache_parent path in
383
+ store := List.filter (fun (_, e) ->
384
+ let scope = vstr_of (getp e "scope") in
385
+ not (cache_under scope path || scope = collection)) !store in
296
386
  let through ctx url fetchdef inner =
297
387
  let meth = match getp fetchdef "method" with Str s -> string_upper s | _ -> "GET" in
298
388
  let methods = List.map string_upper (opt_str_list !options "methods" ~default:["GET"]) in
299
- if not (List.mem meth methods) then inner ctx url fetchdef
300
- else begin
301
- let key = meth ^ " " ^ url in
389
+ if not (List.mem meth methods) then begin
390
+ if meth = "GET" || meth = "HEAD" then inner ctx url fetchdef
391
+ else Fun.protect ~finally:(fun () -> invalidate url) (fun () -> inner ctx url fetchdef)
392
+ end else begin
393
+ let key = meth ^ " " ^ url ^ " " ^ cache_digest !secret (getp fetchdef "headers") in
302
394
  let now = now_of !options in
303
395
  match List.assoc_opt key !store with
304
396
  | Some hit when (match getp hit "expiry" with Num e -> e > now | _ -> false) ->
@@ -309,11 +401,16 @@ let cache_feature () : feature =
309
401
  if err = None && cacheable res && not (json res) then (track ctx "bypass"; (res, err))
310
402
  else if err = None && cacheable res then begin
311
403
  let snap = snapshot res in
312
- let ttl = opt_num !options "ttl" ~default:5000. in
313
- evict ();
314
- store := (List.remove_assoc key !store) @ [(key, jo [("expiry", Num (now +. ttl)); ("snapshot", snap)])];
315
- track ctx "miss";
316
- (replay snap, None)
404
+ let ttl = cache_lifetime (getp snap "headers") (opt_num !options "ttl" ~default:5000.) in
405
+ if ttl <= 0. then (track ctx "bypass"; (replay snap, None))
406
+ else begin
407
+ store := List.remove_assoc key !store;
408
+ evict ();
409
+ store := !store @ [(key, jo [("expiry", Num (now +. ttl)); ("scope", Str (cache_scope url));
410
+ ("snapshot", snap)])];
411
+ track ctx "miss";
412
+ (replay snap, None)
413
+ end
317
414
  end else (track ctx "bypass"; (res, err))
318
415
  end in
319
416
  f.f_init <- (fun ctx opts ->
@@ -321,6 +418,7 @@ let cache_feature () : feature =
321
418
  f.f_active <- opt_active opts;
322
419
  if f.f_active then begin
323
420
  store := [];
421
+ secret := cache_secret ();
324
422
  let u = cu ctx in
325
423
  let inner = u.u_fetcher in
326
424
  u.u_fetcher <- (fun fctx url fd -> through fctx url fd inner)
@@ -226,6 +226,7 @@ let make_context_impl (cs : ctxspec) (basectx : ctx option) : ctx =
226
226
  let options =
227
227
  match cs.cs_options with Some (Map _ as m) -> m
228
228
  | _ -> (match basectx with Some b -> b.c_options | None -> Noval) in
229
+ let cleancfg = match basectx with Some b -> b.c_cleancfg | None -> Noval in
229
230
  let entity =
230
231
  match cs.cs_entity with Some _ as e -> e
231
232
  | None -> (match basectx with Some b -> b.c_entity | None -> None) in
@@ -248,6 +249,7 @@ let make_context_impl (cs : ctxspec) (basectx : ctx option) : ctx =
248
249
  c_id = id; c_out = Hashtbl.create 8; c_ctrl = ctrl; c_meta = meta;
249
250
  c_client = client; c_utility = utility; c_op = new_operation (empty_map ());
250
251
  c_point = point; c_config = config; c_entopts = entopts; c_options = options;
252
+ c_cleancfg = cleancfg;
251
253
  c_opmap = opmap; c_response = response; c_result = result; c_spec = spec;
252
254
  c_data = data; c_reqdata = reqdata; c_match = mtch; c_reqmatch = reqmatch;
253
255
  c_entity = entity; c_shared = shared; c_scratch = Hashtbl.create 8;
@@ -302,9 +304,9 @@ let count_opt (v : value) (dflt : int) : int =
302
304
  | _ -> None in
303
305
  match n with Some n when n >= 0. -> int_of_float (Float.floor n) | _ -> dflt
304
306
 
305
- (* The derived clean block: a struct map so it lives in options.__derived__
306
- * and its `values` list stays MUTABLE after make_options - features
307
- * register what they resolve later. *)
307
+ (* The clean registry: a struct map held on the context as c_cleancfg, whose
308
+ * `values` list stays MUTABLE after make_options - features register what
309
+ * they resolve later. *)
308
310
  let make_clean_config (cleanopts : value) : value =
309
311
  jo [("active", Bool (getp cleanopts "active" <> Bool false));
310
312
  ("keys", ja (List.map (fun s -> Str s) (splitkeys (getp cleanopts "keys"))));
@@ -313,10 +315,10 @@ let make_clean_config (cleanopts : value) : value =
313
315
  ("hint", vint_of (count_opt (getp cleanopts "hint") 0));
314
316
  ("min", vint_of (max 1 (count_opt (getp cleanopts "min") 4)))]
315
317
 
316
- (* A context without options (make_error accepts a bare one) still masks by
317
- * the schema defaults. *)
318
+ (* A context without a registry (make_error accepts a bare one) still masks
319
+ * by the schema defaults. *)
318
320
  let clean_config (ctx : ctx) : value =
319
- match getpath_s ctx.c_options "__derived__.clean" with
321
+ match ctx.c_cleancfg with
320
322
  | Map _ as m -> m
321
323
  | _ -> make_clean_config (getp (Sdk_schema.opt_spec_value ()) "clean")
322
324
 
@@ -1776,7 +1778,7 @@ let make_options_util (ctx : ctx) : value =
1776
1778
  | Map _ -> List.iter (fun k -> setp cleanraw k (getp src k)) (keysof src)
1777
1779
  | _ -> ()) [getp optspec "clean"; getp cfgopts "clean"; getp opts "clean"];
1778
1780
  let cleancfg = make_clean_config cleanraw in
1779
- let cleanctx = { ctx with c_options = jo [("__derived__", jo [("clean", cleancfg)])] } in
1781
+ let cleanctx = { ctx with c_cleancfg = cleancfg } in
1780
1782
  clean_add_sensitive cleanctx (secret_scan opts ["clean"]);
1781
1783
  List.iter (fun src -> List.iter (clean_add_util cleanctx) (splitvalues (getpath_s src "clean.values")))
1782
1784
  [cfgopts; opts];
@@ -1857,11 +1859,12 @@ let make_options_util (ctx : ctx) : value =
1857
1859
  if List.mem "test" names
1858
1860
  then "test" :: List.filter (fun n -> n <> "test") names
1859
1861
  else names in
1860
- let derived = jo [("clean", cleancfg);
1861
- ("featureorder", ja (List.map (fun s -> Str s) feature_order))] in
1862
+ let derived = jo [("featureorder", ja (List.map (fun s -> Str s) feature_order))] in
1862
1863
  setp opts "__derived__" derived;
1864
+ (* Beside the options, not in them: options_map hands them to callers. *)
1865
+ ctx.c_cleancfg <- cleancfg;
1863
1866
  (* Again over the merged result: the config's own defaults can carry one. *)
1864
- clean_add_sensitive { ctx with c_options = opts } (secret_scan opts ["clean"; "__derived__"]);
1867
+ clean_add_sensitive cleanctx (secret_scan opts ["clean"; "__derived__"]);
1865
1868
  opts
1866
1869
 
1867
1870
  (* ------------------------------------------------------------------ *)
@@ -263,6 +263,8 @@ and ctx = {
263
263
  mutable c_config : value;
264
264
  mutable c_entopts : value;
265
265
  mutable c_options : value;
266
+ (* The clean registry, beside the options rather than in them. *)
267
+ mutable c_cleancfg : value;
266
268
  (* Shared by every context of one client, so by requests on other domains:
267
269
  * a map replaced whole, never changed in place. *)
268
270
  mutable c_opmap : operation OpMap.t Atomic.t;
@@ -215,7 +215,41 @@ let () =
215
215
  let (srv, calls) = recording_server () in
216
216
  let h = make_client ~server:srv [("cache", jo [("active", Bool false)])] in
217
217
  ignore (op h ~op:"load" ~path:"/x" ()); ignore (op h ~op:"load" ~path:"/x" ());
218
- check_int "calls" (List.length !calls) 2)
218
+ check_int "calls" (List.length !calls) 2);
219
+ test "cache.keys_on_request_headers" (fun () ->
220
+ let (srv, calls) = recording_server () in
221
+ let h = make_client ~server:srv [("cache", jo [("ttl", Num 10000.)])] in
222
+ ignore (op h ~op:"load" ~path:"/w/1" ~headers:[("x-tenant", Str "tenant-a")] ());
223
+ ignore (op h ~op:"load" ~path:"/w/1" ~headers:[("X-Tenant", Str "tenant-b")] ());
224
+ check_int "tenant calls" (List.length !calls) 2;
225
+ ignore (op h ~op:"load" ~path:"/w/1" ~headers:[("x-tenant", Str "tenant-b")] ());
226
+ check_int "same headers calls" (List.length !calls) 2);
227
+ test "cache.write_drops_collection" (fun () ->
228
+ let (srv, calls) = recording_server () in
229
+ let h = make_client ~server:srv [("cache", jo [("ttl", Num 10000.)])] in
230
+ let paths = ["/w/1"; "/w"; "/w/1/part"; "/other/1"; "/w/2"] in
231
+ List.iter (fun p -> ignore (op h ~op:"load" ~path:p ())) paths;
232
+ ignore (op h ~op:"update" ~method_:"PUT" ~path:"/w/1" ());
233
+ List.iter (fun p -> ignore (op h ~op:"load" ~path:p ())) paths;
234
+ check_int "calls" (List.length !calls) 9;
235
+ check_vnum "hit" (getp (track h "cache") "hit") 2.);
236
+ test "cache.control_prevents_storing" (fun () ->
237
+ List.iter (fun control ->
238
+ let (srv, calls) = recording_server
239
+ ~reply:(fun _ _ -> (make_response ~headers:[("Cache-Control", Str control)] 200 (jo [("ok", Bool true)]), None)) () in
240
+ let h = make_client ~server:srv [("cache", jo [("ttl", Num 10000.)])] in
241
+ ignore (op h ~op:"load" ~path:"/w" ()); ignore (op h ~op:"load" ~path:"/w" ());
242
+ check_int control (List.length !calls) 2)
243
+ ["no-store"; "private"; "No-Cache"; "max-age=60, private"]);
244
+ test "cache.max_age_caps_ttl" (fun () ->
245
+ let c = make_clock () in
246
+ let (srv, calls) = recording_server
247
+ ~reply:(fun _ _ -> (make_response ~headers:[("cache-control", Str "max-age=1")] 200 (jo [("ok", Bool true)]), None)) () in
248
+ let h = make_client ~server:srv [("cache", jo [("ttl", Num 10000.); ("now", clock_now_fn c)])] in
249
+ ignore (op h ~op:"load" ~path:"/w" ()); clock_advance c 500.; ignore (op h ~op:"load" ~path:"/w" ());
250
+ check_int "inside max-age" (List.length !calls) 1;
251
+ clock_advance c 600.; ignore (op h ~op:"load" ~path:"/w" ());
252
+ check_int "after max-age" (List.length !calls) 2)
219
253
  end;
220
254
 
221
255
  (* ---------------- idempotency ---------------- *)
@@ -65,6 +65,9 @@ sub new {
65
65
  my $o = $gcp->($ctxmap, 'options');
66
66
  $self->{options} = Voxgig::Struct::ismap($o) ? $o : ($basectx ? $basectx->{options} : undef);
67
67
 
68
+ # The clean registry, beside the options rather than in them.
69
+ $self->{cleancfg} = $gcp->($ctxmap, 'cleancfg') // ($basectx ? $basectx->{cleancfg} : undef);
70
+
68
71
  my $e = $gcp->($ctxmap, 'entity');
69
72
  $self->{entity} = defined $e ? $e : ($basectx ? $basectx->{entity} : undef);
70
73