@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,13 +1,7 @@
1
1
  # ProjectName SDK cache feature
2
2
  #
3
- # Response caching for safe (read) requests. Wraps the active transport and
4
- # serves a fresh cached snapshot instead of hitting the network when the same
5
- # method+URL was fetched within `ttl` ms (default 5000). Only successful (2xx)
6
- # responses to cacheable methods (default: GET) are stored, keyed by
7
- # method+URL. The cache is bounded (`max` entries, default 256, oldest evicted
8
- # first) and every hit/miss is recorded on `client._cache` for inspection.
9
- # Response bodies are snapshotted on capture so both the current caller and
10
- # later hits can read the JSON body 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 rules.
11
5
 
12
6
  defmodule ProjectName.Feature.Cache do
13
7
  alias Voxgig.Struct, as: S
@@ -25,6 +19,7 @@ defmodule ProjectName.Feature.Cache do
25
19
 
26
20
  if active do
27
21
  S.setprop(f, "store", S.jm([]))
22
+ S.setprop(f, "secret", :crypto.strong_rand_bytes(32))
28
23
 
29
24
  utility = S.getprop(ctx, "utility")
30
25
  inner = S.getprop(utility, "fetcher")
@@ -47,41 +42,162 @@ defmodule ProjectName.Feature.Cache do
47
42
 
48
43
  methods = opt_list(S.getprop(opts, "methods"), ["GET"])
49
44
 
50
- if method not in methods do
51
- inner.(ctx, url, fetchdef)
45
+ cond do
46
+ method in methods ->
47
+ lookup(f, opts, store, method, ctx, url, fetchdef, inner)
48
+
49
+ method in ["GET", "HEAD"] ->
50
+ inner.(ctx, url, fetchdef)
51
+
52
+ true ->
53
+ try do
54
+ inner.(ctx, url, fetchdef)
55
+ after
56
+ invalidate(f, url)
57
+ end
58
+ end
59
+ end
60
+
61
+ defp lookup(f, opts, store, method, ctx, url, fetchdef, inner) do
62
+ headers = if S.ismap(fetchdef), do: S.getprop(fetchdef, "headers"), else: nil
63
+ key = method <> " " <> url <> " " <> digest(S.getprop(f, "secret"), headers)
64
+ now = F.now(f)
65
+ hit = S.getprop(store, key)
66
+
67
+ if hit != nil and S.getprop(hit, "expiry") > now do
68
+ track(f, "hit")
69
+ {replay(S.getprop(hit, "snapshot")), nil}
52
70
  else
53
- key = method <> " " <> url
54
- now = F.now(f)
55
- hit = S.getprop(store, key)
71
+ {res, err} = inner.(ctx, url, fetchdef)
56
72
 
57
- if hit != nil and S.getprop(hit, "expiry") > now do
58
- track(f, "hit")
59
- {replay(S.getprop(hit, "snapshot")), nil}
60
- else
61
- {res, err} = inner.(ctx, url, fetchdef)
73
+ cond do
74
+ # A body that declares another type than JSON passes by, unread.
75
+ err == nil and cacheable(res) and not json?(res) ->
76
+ track(f, "bypass")
77
+ {res, err}
62
78
 
63
- cond do
64
- # A body that declares another type than JSON passes by, unread.
65
- err == nil and cacheable(res) and not json?(res) ->
66
- track(f, "bypass")
67
- {res, err}
79
+ err == nil and cacheable(res) ->
80
+ snap = snapshot(res)
81
+ ttl = lifetime(S.getprop(snap, "headers"), case S.getprop(opts, "ttl") do nil -> 5000; v -> v end)
68
82
 
69
- err == nil and cacheable(res) ->
70
- snap = snapshot(res)
71
- ttl = case S.getprop(opts, "ttl") do nil -> 5000; v -> v end
83
+ if ttl <= 0 do
84
+ track(f, "bypass")
85
+ {replay(snap), nil}
86
+ else
87
+ S.delprop(store, key)
72
88
  evict(f)
73
- S.setprop(store, key, S.jm(["expiry", now + ttl, "snapshot", snap]))
89
+ S.setprop(store, key, S.jm(["expiry", now + ttl, "scope", scope(url), "snapshot", snap]))
74
90
  track(f, "miss")
75
91
  {replay(snap), nil}
92
+ end
76
93
 
77
- true ->
78
- track(f, "bypass")
79
- {res, err}
94
+ true ->
95
+ track(f, "bypass")
96
+ {res, err}
97
+ end
98
+ end
99
+ end
100
+
101
+ defp header_text(nil), do: nil
102
+ defp header_text(v) when is_binary(v), do: v
103
+ defp header_text(v) when is_float(v) and v == trunc(v), do: Integer.to_string(trunc(v))
104
+ defp header_text(v), do: to_string(v)
105
+
106
+ defp digest(secret, headers) do
107
+ pairs =
108
+ if S.ismap(headers) do
109
+ H.entries(headers)
110
+ |> Enum.flat_map(fn {k, v} ->
111
+ case header_text(v) do
112
+ nil -> []
113
+ text -> [{String.downcase(to_string(k)), text}]
114
+ end
115
+ end)
116
+ |> Enum.sort()
117
+ else
118
+ []
119
+ end
120
+
121
+ text = Enum.map_join(pairs, "", fn {k, v} -> k <> ":" <> v <> "\n" end)
122
+ Base.encode16(:crypto.mac(:hmac, :sha256, secret, text), case: :lower)
123
+ end
124
+
125
+ defp invalidate(f, url) do
126
+ store = S.getprop(f, "store")
127
+ path = scope(url)
128
+ collection = parent(path)
129
+
130
+ H.entries(store)
131
+ |> Enum.filter(fn {_k, e} ->
132
+ entry = S.getprop(e, "scope")
133
+ under?(entry, path) or entry == collection
134
+ end)
135
+ |> Enum.each(fn {k, _e} -> S.delprop(store, k) end)
136
+ end
137
+
138
+ # The configured ttl capped by the response's Cache-Control; zero when the
139
+ # response may not be stored.
140
+ defp lifetime(headers, ttl) do
141
+ control =
142
+ if S.ismap(headers) do
143
+ Enum.find_value(H.entries(headers), "", fn {k, v} ->
144
+ if String.downcase(to_string(k)) == "cache-control", do: String.downcase(header_text(v) || "")
145
+ end)
146
+ else
147
+ ""
148
+ end
149
+
150
+ directives = control |> String.split(",") |> Enum.map(&String.trim/1)
151
+
152
+ if Enum.any?(directives, &(&1 in ["no-store", "private", "no-cache"])) do
153
+ 0
154
+ else
155
+ Enum.reduce(directives, ttl, fn d, life ->
156
+ case Regex.run(~r/^max-age\s*=\s*"?(\d+)"?$/, d) do
157
+ [_, secs] -> min(life, String.to_integer(secs) * 1000)
158
+ _ -> life
80
159
  end
160
+ end)
161
+ end
162
+ end
163
+
164
+ defp scope(url) do
165
+ [base | _] = String.split(to_string(url), ["?", "#"], parts: 2)
166
+ String.replace(base, ~r{/+$}, "")
167
+ end
168
+
169
+ defp parent(scope) do
170
+ root =
171
+ case :binary.match(scope, "://") do
172
+ :nomatch ->
173
+ 0
174
+
175
+ {at, 3} ->
176
+ case :binary.match(scope, "/", scope: {at + 3, byte_size(scope) - at - 3}) do
177
+ :nomatch -> nil
178
+ {slash, 1} -> slash
179
+ end
81
180
  end
181
+
182
+ case root do
183
+ nil ->
184
+ scope
185
+
186
+ root ->
187
+ cut =
188
+ case :binary.matches(scope, "/") do
189
+ [] -> 0
190
+ found -> found |> List.last() |> elem(0)
191
+ end
192
+
193
+ binary_part(scope, 0, max(cut, root))
82
194
  end
83
195
  end
84
196
 
197
+ defp under?(scope, prefix) do
198
+ scope == prefix or String.starts_with?(scope, prefix <> "/")
199
+ end
200
+
85
201
  # A body the transport could not read as JSON passes through, for the operation to report.
86
202
  defp cacheable(res) do
87
203
  if not S.ismap(res) or S.getprop(res, "unreadable") == true do
@@ -714,21 +714,20 @@ defmodule ProjectName.Feature.Secrets do
714
714
  "headers", S.jm(["content-type", "application/json"]),
715
715
  "body", S.jsonify(S.jm([x.request, refresh]), S.jm(["indent", 0])),
716
716
  # Never followed by the client: a redirect would carry the refresh token on.
717
- "redirect", "manual"
717
+ "redirect", "manual",
718
+ # Its own bound, in milliseconds: the timeout feature's wrapper is above it.
719
+ "timeout", 30000
718
720
  ])
719
721
 
720
- sysfetch = S.getpath(options, "system.fetch")
722
+ # The SDK's own transport, beneath every feature's wrapper: it holds
723
+ # the test feature's block and the GET-only guard, and the wrapped one
724
+ # would recurse on the first expiry.
725
+ client = S.getprop(f, "client")
726
+ rootctx = if client != nil, do: S.getprop(client, "_rootctx"), else: nil
721
727
 
722
- # Deliberately NOT the SDK transport. The transport is what this
723
- # feature wraps, and sending the token request back through it would
724
- # recurse on the first expiry - and would route the exchange through
725
- # the test mock, which knows nothing about it. `options.system.fetch`
726
- # is preferred when set, so a test can intercept the purchase.
727
728
  ask = fn at ->
728
729
  try do
729
- if S.isfunc(sysfetch),
730
- do: sysfetch.(at, fetchdef),
731
- else: raw_exchange_fetch(at, fetchdef)
730
+ ProjectName.Utility.fetcher_impl(rootctx, at, fetchdef)
732
731
  rescue
733
732
  e -> {nil, fail(e)}
734
733
  end
@@ -813,52 +812,6 @@ defmodule ProjectName.Feature.Secrets do
813
812
  if S.ismap(body), do: S.getprop(body, name), else: nil
814
813
  end
815
814
 
816
- # The token-exchange transport of last resort: plain :httpc, same result
817
- # shape the system.fetch seam promises. It exists so an exchange works
818
- # with ordinary SDK options - requiring a custom transport for the COMMON
819
- # case would reject every live token purchase before a request was made.
820
- defp raw_exchange_fetch(url, fetchdef) do
821
- Application.ensure_all_started(:inets)
822
- Application.ensure_all_started(:ssl)
823
-
824
- method =
825
- H.or_(S.getprop(fetchdef, "method"), "POST") |> to_string() |> String.downcase() |> String.to_atom()
826
-
827
- body = tostr(S.getprop(fetchdef, "body"))
828
-
829
- hlist =
830
- Enum.map(H.entries(H.or_(S.getprop(fetchdef, "headers"), S.jm([]))), fn {k, v} ->
831
- {String.to_charlist(to_string(k)), String.to_charlist(to_string(v))}
832
- end)
833
-
834
- request =
835
- if method in [:post, :put, :patch, :delete] do
836
- {String.to_charlist(url), hlist, ~c"application/json", body}
837
- else
838
- {String.to_charlist(url), hlist}
839
- end
840
-
841
- case :httpc.request(method, request, [autoredirect: false], body_format: :binary) do
842
- {:ok, {{_v, status, _reason}, rh, resbody}} ->
843
- text = if is_binary(resbody), do: resbody, else: to_string(resbody)
844
-
845
- parsed =
846
- try do
847
- ProjectName.Json.parse(text)
848
- rescue
849
- _ -> nil
850
- end
851
-
852
- headers =
853
- S.jm(Enum.flat_map(rh, fn {k, v} -> [String.downcase(to_string(k)), to_string(v)] end))
854
-
855
- {S.jm(["status", status, "headers", headers, "json", fn -> parsed end, "body", text]), nil}
856
-
857
- {:error, reason} ->
858
- {nil, err("secrets_exchange_failed", "secrets: token exchange transport: " <> inspect(reason))}
859
- end
860
- end
861
-
862
815
  # ---- small helpers -------------------------------------------------------
863
816
 
864
817
  defp statuses(v) do
@@ -908,6 +861,7 @@ defmodule ProjectName.Feature.Secrets do
908
861
  # an exception, or a plain string from the default HTTP path.
909
862
  defp aserr(e, code) do
910
863
  cond do
864
+ match?(%ProjectName.Error{}, e) -> e
911
865
  is_exception(e) -> fail(e)
912
866
  is_binary(e) -> err(code, e)
913
867
  true -> err(code, inspect(e))
@@ -170,8 +170,8 @@ defmodule ProjectName.Utility do
170
170
  end
171
171
  end
172
172
 
173
- # The derived clean block: a struct node so it lives in options.__derived__
174
- # and its `values` stays MUTABLE after make_options - features register
173
+ # The clean registry: a struct node held on the context as `cleancfg`, whose
174
+ # `values` stays MUTABLE after make_options - features register
175
175
  # what they resolve later.
176
176
  def make_clean_config(cleanopts) do
177
177
  o = fn k -> if S.ismap(cleanopts), do: S.getprop(cleanopts, k), else: nil end
@@ -187,14 +187,13 @@ defmodule ProjectName.Utility do
187
187
  ])
188
188
  end
189
189
 
190
- # A context without options (make_error accepts a bare one) still masks by
191
- # the schema defaults.
190
+ # A context without a registry (make_error accepts a bare one) still masks
191
+ # by the schema defaults.
192
192
  defp clean_config(ctx) do
193
- options = if S.ismap(ctx), do: S.getprop(ctx, "options"), else: nil
194
- derived = if S.ismap(options), do: S.getpath(options, "__derived__.clean"), else: nil
193
+ cfg = if S.ismap(ctx), do: S.getprop(ctx, "cleancfg"), else: nil
195
194
 
196
- if S.ismap(derived) do
197
- derived
195
+ if S.ismap(cfg) do
196
+ cfg
198
197
  else
199
198
  make_clean_config(S.getprop(ProjectName.Schema.optspec(), "clean"))
200
199
  end
@@ -781,7 +780,7 @@ defmodule ProjectName.Utility do
781
780
  end)
782
781
 
783
782
  cleancfg = make_clean_config(cleanraw)
784
- cleanctx = S.jm(["options", S.jm(["__derived__", S.jm(["clean", cleancfg])])])
783
+ cleanctx = S.jm(["cleancfg", cleancfg])
785
784
 
786
785
  clean_add_sensitive(cleanctx, secret_scan(opts0, ["clean"]))
787
786
 
@@ -907,11 +906,14 @@ defmodule ProjectName.Utility do
907
906
  list
908
907
  end
909
908
 
910
- derived = S.jm(["clean", cleancfg, "featureorder", S.jt(feature_order)])
909
+ derived = S.jm(["featureorder", S.jt(feature_order)])
911
910
  S.setprop(opts, "__derived__", derived)
912
911
 
912
+ # Beside the options, not in them: options_map hands them to callers.
913
+ S.setprop(ctx, "cleancfg", cleancfg)
914
+
913
915
  # Again over the merged result: the config's own defaults can carry one.
914
- clean_add_sensitive(S.jm(["options", opts]), secret_scan(opts, ["clean", "__derived__"]))
916
+ clean_add_sensitive(cleanctx, secret_scan(opts, ["clean", "__derived__"]))
915
917
 
916
918
  opts
917
919
  end
@@ -2780,7 +2782,11 @@ defmodule ProjectName.Utility do
2780
2782
  # A 3xx rides back as a normal response: follow_redirects decides the
2781
2783
  # next request, and a `redirect: "manual"` annotation (set by the station
2782
2784
  # feature when a hosts egress policy is active) makes the 3xx the answer.
2783
- case :httpc.request(method, request, [autoredirect: false], body_format: :binary) do
2785
+ # A bound in milliseconds, for a caller beneath the timeout feature.
2786
+ bound = S.getprop(fetchdef, "timeout")
2787
+ httpopts = [autoredirect: false] ++ if is_number(bound) and bound > 0, do: [timeout: trunc(bound)], else: []
2788
+
2789
+ case :httpc.request(method, request, httpopts, body_format: :binary) do
2784
2790
  {:ok, {{_v, status, _reason}, resp_headers, resp_body}} ->
2785
2791
  rh =
2786
2792
  Enum.reduce(resp_headers, S.jm([]), fn {k, v}, acc ->
@@ -458,6 +458,67 @@ defmodule ProjectName.FeatureTest do
458
458
  end
459
459
  end
460
460
 
461
+ test "cache keys on the request headers" do
462
+ if has?("cache") do
463
+ {server, calls} = FH.recording_server()
464
+ h = harness([fspec("cache", %{"ttl" => 10000})], %{server: server})
465
+ FH.op(h, %{path: "/w/1", headers: S.jm(["x-tenant", "tenant-a"])})
466
+ FH.op(h, %{path: "/w/1", headers: S.jm(["X-Tenant", "tenant-b"])})
467
+ assert S.size(calls) == 2
468
+ FH.op(h, %{path: "/w/1", headers: S.jm(["x-tenant", "tenant-b"])})
469
+ assert S.size(calls) == 2
470
+ end
471
+ end
472
+
473
+ test "cache drops a write's collection" do
474
+ if has?("cache") do
475
+ {server, calls} = FH.recording_server()
476
+ h = harness([fspec("cache", %{"ttl" => 10000})], %{server: server})
477
+ paths = ["/w/1", "/w", "/w/1/part", "/other/1", "/w/2"]
478
+ Enum.each(paths, fn p -> FH.op(h, %{path: p}) end)
479
+ FH.op(h, %{op: "update", method: "PUT", path: "/w/1"})
480
+ Enum.each(paths, fn p -> FH.op(h, %{path: p}) end)
481
+ assert S.size(calls) == 9
482
+ assert S.getprop(track(h, "_cache"), "hit") == 2
483
+ end
484
+ end
485
+
486
+ test "cache does not store what Cache-Control forbids" do
487
+ if has?("cache") do
488
+ for control <- ["no-store", "private", "No-Cache", "max-age=60, private"] do
489
+ {server, calls} =
490
+ FH.recording_server(fn _n, _fd ->
491
+ {FH.make_response(200, S.jm(["ok", true]), S.jm(["Cache-Control", control])), nil}
492
+ end)
493
+
494
+ h = harness([fspec("cache", %{"ttl" => 10000})], %{server: server})
495
+ FH.op(h, %{path: "/w"})
496
+ FH.op(h, %{path: "/w"})
497
+ assert S.size(calls) == 2, control
498
+ end
499
+ end
500
+ end
501
+
502
+ test "cache caps the ttl by max-age" do
503
+ if has?("cache") do
504
+ clock = FH.make_clock()
505
+
506
+ {server, calls} =
507
+ FH.recording_server(fn _n, _fd ->
508
+ {FH.make_response(200, S.jm(["ok", true]), S.jm(["cache-control", "max-age=1"])), nil}
509
+ end)
510
+
511
+ h = harness([fspec("cache", %{"ttl" => 10000, "now" => FH.clock_now(clock)})], %{server: server})
512
+ FH.op(h, %{path: "/w"})
513
+ FH.clock_advance(clock, 500)
514
+ FH.op(h, %{path: "/w"})
515
+ assert S.size(calls) == 1
516
+ FH.clock_advance(clock, 600)
517
+ FH.op(h, %{path: "/w"})
518
+ assert S.size(calls) == 2
519
+ end
520
+ end
521
+
461
522
  # === idempotency ===
462
523
 
463
524
  test "idempotency adds a key to mutating ops" do
@@ -22,6 +22,7 @@ type Context struct {
22
22
  Config map[string]any
23
23
  Entopts map[string]any
24
24
  Options map[string]any
25
+ CleanCfg any // the clean registry, beside the options rather than in them
25
26
  Opmap map[string]*Operation
26
27
  Opmu *sync.Mutex
27
28
  Response *Response
@@ -131,6 +132,11 @@ func NewContext(ctxmap map[string]any, basectx *Context) *Context {
131
132
  if ctx.Options == nil && basectx != nil {
132
133
  ctx.Options = basectx.Options
133
134
  }
135
+ if cc := getCtxProp(ctxmap, "cleancfg"); cc != nil {
136
+ ctx.CleanCfg = cc
137
+ } else if basectx != nil {
138
+ ctx.CleanCfg = basectx.CleanCfg
139
+ }
134
140
 
135
141
  // Entity
136
142
  if e := getCtxProp(ctxmap, "entity"); e != nil {
@@ -1,6 +1,13 @@
1
1
  package feature
2
2
 
3
3
  import (
4
+ "crypto/hmac"
5
+ "crypto/rand"
6
+ "crypto/sha256"
7
+ "encoding/hex"
8
+ "fmt"
9
+ "sort"
10
+ "strconv"
4
11
  "strings"
5
12
 
6
13
  "GOMODULE/core"
@@ -13,6 +20,7 @@ type CacheFeature struct {
13
20
  options map[string]any
14
21
  store map[string]*cacheEntry
15
22
  order []string
23
+ secret []byte
16
24
 
17
25
  // Activity tracking (mirrors the ts client._cache record).
18
26
  Hit int
@@ -22,6 +30,7 @@ type CacheFeature struct {
22
30
 
23
31
  type cacheEntry struct {
24
32
  expiry int64
33
+ scope string
25
34
  snapshot *cacheSnapshot
26
35
  }
27
36
 
@@ -53,6 +62,10 @@ func (f *CacheFeature) Init(ctx *core.Context, options map[string]any) {
53
62
 
54
63
  f.store = map[string]*cacheEntry{}
55
64
  f.order = []string{}
65
+ f.secret = make([]byte, 32)
66
+ if _, err := rand.Read(f.secret); err != nil {
67
+ panic(err)
68
+ }
56
69
 
57
70
  inner := ctx.Utility.Fetcher
58
71
 
@@ -81,10 +94,14 @@ func (f *CacheFeature) through(ctx *core.Context, url string, fetchdef map[strin
81
94
  }
82
95
  }
83
96
  if !cacheable {
84
- return inner(ctx, url, fetchdef)
97
+ res, err := inner(ctx, url, fetchdef)
98
+ if method != "GET" && method != "HEAD" {
99
+ f.invalidate(url)
100
+ }
101
+ return res, err
85
102
  }
86
103
 
87
- key := method + " " + url
104
+ key := method + " " + url + " " + f.digest(fetchdef["headers"])
88
105
  now := foptNow(f.options)()
89
106
 
90
107
  if hit, ok := f.store[key]; ok && hit.expiry > now {
@@ -96,9 +113,14 @@ func (f *CacheFeature) through(ctx *core.Context, url string, fetchdef map[strin
96
113
 
97
114
  if err == nil && f.storable(res) {
98
115
  snapshot := f.snapshot(res)
99
- ttl := foptInt(f.options, "ttl", 5000)
116
+ ttl := cacheLifetime(snapshot.headers, int64(foptInt(f.options, "ttl", 5000)))
117
+ if ttl <= 0 {
118
+ f.Bypass++
119
+ return f.replay(snapshot), nil
120
+ }
121
+ f.drop(key)
100
122
  f.evict()
101
- f.store[key] = &cacheEntry{expiry: now + int64(ttl), snapshot: snapshot}
123
+ f.store[key] = &cacheEntry{expiry: now + ttl, scope: cacheScope(url), snapshot: snapshot}
102
124
  f.order = append(f.order, key)
103
125
  f.Miss++
104
126
  return f.replay(snapshot), nil
@@ -108,6 +130,111 @@ func (f *CacheFeature) through(ctx *core.Context, url string, fetchdef map[strin
108
130
  return res, err
109
131
  }
110
132
 
133
+ func (f *CacheFeature) digest(headers any) string {
134
+ pairs := [][2]string{}
135
+ if hm, ok := headers.(map[string]any); ok {
136
+ for k, v := range hm {
137
+ if v != nil {
138
+ pairs = append(pairs, [2]string{strings.ToLower(k), fmt.Sprint(v)})
139
+ }
140
+ }
141
+ } else if hm, ok := headers.(map[string]string); ok {
142
+ for k, v := range hm {
143
+ pairs = append(pairs, [2]string{strings.ToLower(k), v})
144
+ }
145
+ }
146
+ sort.Slice(pairs, func(i, j int) bool {
147
+ if pairs[i][0] != pairs[j][0] {
148
+ return pairs[i][0] < pairs[j][0]
149
+ }
150
+ return pairs[i][1] < pairs[j][1]
151
+ })
152
+ mac := hmac.New(sha256.New, f.secret)
153
+ for _, p := range pairs {
154
+ mac.Write([]byte(p[0] + ":" + p[1] + "\n"))
155
+ }
156
+ return hex.EncodeToString(mac.Sum(nil))
157
+ }
158
+
159
+ func (f *CacheFeature) invalidate(url string) {
160
+ path := cacheScope(url)
161
+ collection := cacheParent(path)
162
+ for key, entry := range f.store {
163
+ if cacheUnder(entry.scope, path) || entry.scope == collection {
164
+ f.drop(key)
165
+ }
166
+ }
167
+ }
168
+
169
+ func (f *CacheFeature) drop(key string) {
170
+ if _, ok := f.store[key]; !ok {
171
+ return
172
+ }
173
+ delete(f.store, key)
174
+ for i, k := range f.order {
175
+ if k == key {
176
+ f.order = append(f.order[:i], f.order[i+1:]...)
177
+ break
178
+ }
179
+ }
180
+ }
181
+
182
+ // The configured ttl capped by the response's Cache-Control; zero when the
183
+ // response may not be stored.
184
+ func cacheLifetime(headers map[string]any, ttl int64) int64 {
185
+ control := ""
186
+ for k, v := range headers {
187
+ if strings.ToLower(k) == "cache-control" {
188
+ control = strings.ToLower(fmt.Sprint(v))
189
+ }
190
+ }
191
+ life := ttl
192
+ for _, part := range strings.Split(control, ",") {
193
+ directive := strings.TrimSpace(part)
194
+ switch directive {
195
+ case "no-store", "private", "no-cache":
196
+ return 0
197
+ }
198
+ if strings.HasPrefix(directive, "max-age") {
199
+ value := strings.TrimSpace(strings.TrimPrefix(directive, "max-age"))
200
+ if strings.HasPrefix(value, "=") {
201
+ value = strings.Trim(strings.TrimSpace(value[1:]), "\"")
202
+ if secs, err := strconv.ParseInt(value, 10, 64); err == nil && secs >= 0 && secs*1000 < life {
203
+ life = secs * 1000
204
+ }
205
+ }
206
+ }
207
+ }
208
+ return life
209
+ }
210
+
211
+ func cacheScope(url string) string {
212
+ if i := strings.IndexAny(url, "?#"); i >= 0 {
213
+ url = url[:i]
214
+ }
215
+ return strings.TrimRight(url, "/")
216
+ }
217
+
218
+ func cacheParent(scope string) string {
219
+ root := 0
220
+ if scheme := strings.Index(scope, "://"); scheme >= 0 {
221
+ root = strings.Index(scope[scheme+3:], "/")
222
+ if root < 0 {
223
+ return scope
224
+ }
225
+ root += scheme + 3
226
+ }
227
+ cut := strings.LastIndex(scope, "/")
228
+ if cut < root {
229
+ cut = root
230
+ }
231
+ return scope[:cut]
232
+ }
233
+
234
+ func cacheUnder(scope string, prefix string) bool {
235
+ return scope == prefix || strings.HasPrefix(scope, prefix+"/")
236
+ }
237
+
111
238
  // A body the transport could not read as JSON passes through, for the operation to report.
112
239
  // A body that declares another type than JSON passes by, unread.
113
240
  func (f *CacheFeature) storable(res any) bool {