@voxgig/sdkgen 4.37.0 → 4.38.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 (107) hide show
  1. package/bin/voxgig-sdkgen +1 -1
  2. package/dist/helpers/flowGuard.js +4 -4
  3. package/dist/helpers/flowGuard.js.map +1 -1
  4. package/dist/helpers/liveDiscovery.d.ts +7 -0
  5. package/dist/helpers/liveDiscovery.js +20 -0
  6. package/dist/helpers/liveDiscovery.js.map +1 -0
  7. package/dist/helpers/opShape.d.ts +2 -1
  8. package/dist/helpers/opShape.js +4 -0
  9. package/dist/helpers/opShape.js.map +1 -1
  10. package/dist/helpers/pointPath.d.ts +2 -1
  11. package/dist/helpers/pointPath.js +6 -0
  12. package/dist/helpers/pointPath.js.map +1 -1
  13. package/dist/helpers/testPolicy.d.ts +14 -4
  14. package/dist/helpers/testPolicy.js +152 -54
  15. package/dist/helpers/testPolicy.js.map +1 -1
  16. package/dist/sdkgen.d.ts +8 -6
  17. package/dist/sdkgen.js +11 -5
  18. package/dist/sdkgen.js.map +1 -1
  19. package/dist/tsconfig.tsbuildinfo +1 -1
  20. package/dist/utility.js +7 -3
  21. package/dist/utility.js.map +1 -1
  22. package/package.json +1 -1
  23. package/project/.sdk/src/cmp/c/TestDirect_c.ts +3 -2
  24. package/project/.sdk/src/cmp/cpp/TestDirect_cpp.ts +3 -2
  25. package/project/.sdk/src/cmp/cpp/TestEntity_cpp.ts +33 -10
  26. package/project/.sdk/src/cmp/csharp/TestDirect_csharp.ts +12 -12
  27. package/project/.sdk/src/cmp/csharp/TestEntity_csharp.ts +73 -28
  28. package/project/.sdk/src/cmp/go/TestDirect_go.ts +12 -10
  29. package/project/.sdk/src/cmp/go/TestEntity_go.ts +67 -23
  30. package/project/.sdk/src/cmp/java/TestDirect_java.ts +12 -11
  31. package/project/.sdk/src/cmp/java/TestEntity_java.ts +71 -23
  32. package/project/.sdk/src/cmp/js/TestDirect_js.ts +13 -12
  33. package/project/.sdk/src/cmp/js/TestEntity_js.ts +41 -17
  34. package/project/.sdk/src/cmp/kotlin/TestDirect_kotlin.ts +12 -10
  35. package/project/.sdk/src/cmp/kotlin/TestEntity_kotlin.ts +64 -23
  36. package/project/.sdk/src/cmp/lua/TestDirect_lua.ts +9 -5
  37. package/project/.sdk/src/cmp/lua/TestEntity_lua.ts +61 -23
  38. package/project/.sdk/src/cmp/perl/TestDirect_perl.ts +9 -5
  39. package/project/.sdk/src/cmp/perl/TestEntity_perl.ts +58 -24
  40. package/project/.sdk/src/cmp/php/TestDirect_php.ts +9 -5
  41. package/project/.sdk/src/cmp/php/TestEntity_php.ts +61 -23
  42. package/project/.sdk/src/cmp/py/TestDirect_py.ts +10 -6
  43. package/project/.sdk/src/cmp/py/TestEntity_py.ts +59 -27
  44. package/project/.sdk/src/cmp/rb/TestDirect_rb.ts +9 -5
  45. package/project/.sdk/src/cmp/rb/TestEntity_rb.ts +59 -23
  46. package/project/.sdk/src/cmp/rust/TestDirect_rust.ts +9 -8
  47. package/project/.sdk/src/cmp/rust/TestEntity_rust.ts +56 -24
  48. package/project/.sdk/src/cmp/scala/TestDirect_scala.ts +3 -2
  49. package/project/.sdk/src/cmp/scala/TestEntity_scala.ts +36 -9
  50. package/project/.sdk/src/cmp/ts/TestDirect_ts.ts +15 -32
  51. package/project/.sdk/src/cmp/ts/TestEntity_ts.ts +41 -17
  52. package/project/.sdk/tm/c/tests/transport_test.c +33 -0
  53. package/project/.sdk/tm/c/utility/fetcher.c +151 -2
  54. package/project/.sdk/tm/c/utility/make_url.c +8 -6
  55. package/project/.sdk/tm/clojure/src/sdk/core.clj +17 -10
  56. package/project/.sdk/tm/clojure/test/sdk/test/pipeline.clj +38 -0
  57. package/project/.sdk/tm/cpp/utility/pipeline.hpp +5 -4
  58. package/project/.sdk/tm/csharp/test/PrimaryUtilityTest.cs +69 -0
  59. package/project/.sdk/tm/csharp/utility/Fetcher.cs +3 -1
  60. package/project/.sdk/tm/csharp/utility/MakeUrl.cs +5 -4
  61. package/project/.sdk/tm/elixir/lib/projectname/utility.ex +10 -6
  62. package/project/.sdk/tm/elixir/test/pipeline_test.exs +61 -0
  63. package/project/.sdk/tm/go/test/primary_utility_test.go +60 -0
  64. package/project/.sdk/tm/go/utility/fetcher.go +15 -4
  65. package/project/.sdk/tm/go/utility/make_url.go +4 -3
  66. package/project/.sdk/tm/java/test/PrimaryUtilityTest.java +47 -0
  67. package/project/.sdk/tm/java/utility/MakeUrl.java +5 -4
  68. package/project/.sdk/tm/js/src/utility/MakeUrlUtility.js +5 -3
  69. package/project/.sdk/tm/js/test/live-runner.js +4 -3
  70. package/project/.sdk/tm/js/test/utility/PrimaryUtility.test.js +40 -0
  71. package/project/.sdk/tm/kotlin/test/PrimaryUtilityTest.kt +41 -0
  72. package/project/.sdk/tm/kotlin/utility/MakeSpecUrl.kt +4 -3
  73. package/project/.sdk/tm/lua/test/primary_utility_test.lua +61 -0
  74. package/project/.sdk/tm/lua/utility/fetcher.lua +54 -6
  75. package/project/.sdk/tm/lua/utility/make_url.lua +5 -4
  76. package/project/.sdk/tm/ocaml/sdk_runtime.ml +5 -5
  77. package/project/.sdk/tm/perl/t/primary_utility.t +54 -0
  78. package/project/.sdk/tm/perl/utility/fetcher.pm +65 -11
  79. package/project/.sdk/tm/perl/utility/make_url.pm +4 -3
  80. package/project/.sdk/tm/php/test/PipelineTest.php +52 -0
  81. package/project/.sdk/tm/php/utility/Fetcher.php +81 -15
  82. package/project/.sdk/tm/php/utility/MakeUrl.php +5 -3
  83. package/project/.sdk/tm/py/pkg/utility/fetcher.py +1 -0
  84. package/project/.sdk/tm/py/pkg/utility/make_url.py +5 -4
  85. package/project/.sdk/tm/py/test/test_primary_utility.py +52 -0
  86. package/project/.sdk/tm/rb/test/primary_utility_test.rb +46 -0
  87. package/project/.sdk/tm/rb/utility/fetcher.rb +41 -5
  88. package/project/.sdk/tm/rb/utility/make_url.rb +5 -3
  89. package/project/.sdk/tm/rust/tests/primary_utility_test.rs +65 -0
  90. package/project/.sdk/tm/rust/utility/make_url.rs +7 -6
  91. package/project/.sdk/tm/scala/sdktest/SdkTestMain.scala +47 -1
  92. package/project/.sdk/tm/scala/utility/Make.scala +8 -6
  93. package/project/.sdk/tm/swift/Sources/ProjectNameSDK/utility/Fetcher.swift +59 -15
  94. package/project/.sdk/tm/swift/Sources/ProjectNameSDK/utility/Make.swift +4 -4
  95. package/project/.sdk/tm/swift/Tests/ProjectNameSDKTests/PrimaryUtilityTest.swift +72 -0
  96. package/project/.sdk/tm/ts/src/utility/MakeUrlUtility.ts +5 -3
  97. package/project/.sdk/tm/ts/test/live-runner.ts +4 -3
  98. package/project/.sdk/tm/ts/test/utility/PrimaryUtility.test.ts +40 -0
  99. package/project/.sdk/tm/zig/core/utility.zig +5 -5
  100. package/project/sdkgen-package.json +1 -1
  101. package/src/helpers/flowGuard.ts +4 -4
  102. package/src/helpers/liveDiscovery.ts +31 -0
  103. package/src/helpers/opShape.ts +6 -0
  104. package/src/helpers/pointPath.ts +8 -0
  105. package/src/helpers/testPolicy.ts +193 -55
  106. package/src/sdkgen.ts +13 -3
  107. package/src/utility.ts +10 -4
@@ -56,6 +56,46 @@ module ProjectNameUtilities
56
56
  ctx.make_error("fetch_getonly_block", "[GET-ONLY GUARD] blocked #{method} #{path}")
57
57
  end
58
58
 
59
+ REDIRECT_STATUS = [301, 302, 303, 307, 308].freeze
60
+ REDIRECT_MAX = 5
61
+ CREDENTIAL_HEADERS = %w[authorization cookie proxy-authorization].freeze
62
+
63
+ def self.redirect_origin(url)
64
+ uri = URI.parse(url)
65
+ [uri.scheme, uri.host, uri.port]
66
+ end
67
+
68
+ # Net::HTTP never follows a redirect. A GET or HEAD follows one, unless the
69
+ # fetch definition says "manual", each hop passing the GET-only guard first;
70
+ # past REDIRECT_MAX hops the last 3xx is the answer. Another origin is not
71
+ # sent the request's credentials.
72
+ def self.follow_redirects(ctx, fullurl, fetchdef)
73
+ method = fetchdef["method"].to_s.upcase
74
+ follow = ["", "GET", "HEAD"].include?(method) && fetchdef["redirect"] != "manual"
75
+ url = fullurl
76
+ hops = 0
77
+ loop do
78
+ refused = getonly_refusal(ctx, url, fetchdef["method"])
79
+ return nil, refused if refused
80
+ res, err = DefaultHttpFetch.call(url, fetchdef)
81
+ location = res.is_a?(Hash) && res["headers"].is_a?(Hash) ? res["headers"]["location"] : nil
82
+ return res, err unless follow && location.is_a?(String) && hops < REDIRECT_MAX &&
83
+ REDIRECT_STATUS.include?(res["status"])
84
+ nxt = begin
85
+ URI.join(url, location.strip).tap { |u| u.fragment = nil }.to_s
86
+ rescue URI::Error
87
+ nil
88
+ end
89
+ return res, err if nxt.nil?
90
+ if redirect_origin(nxt) != redirect_origin(url)
91
+ headers = (fetchdef["headers"] || {}).reject { |k, _| CREDENTIAL_HEADERS.include?(k.to_s.downcase) }
92
+ fetchdef = fetchdef.merge("headers" => headers)
93
+ end
94
+ url = nxt
95
+ hops += 1
96
+ end
97
+ end
98
+
59
99
  DefaultHttpFetch = ->(fullurl, fetchdef) {
60
100
  method_str = fetchdef["method"] || "GET"
61
101
  body_str = fetchdef["body"]
@@ -149,11 +189,7 @@ module ProjectNameUtilities
149
189
 
150
190
  sys_fetch = VoxgigStruct.getpath(options, "system.fetch")
151
191
 
152
- if sys_fetch.nil?
153
- refused = ProjectNameUtilities.getonly_refusal(ctx, fullurl, fetchdef["method"])
154
- return nil, refused if refused
155
- return DefaultHttpFetch.call(fullurl, fetchdef)
156
- end
192
+ return ProjectNameUtilities.follow_redirects(ctx, fullurl, fetchdef) if sys_fetch.nil?
157
193
  return sys_fetch.call(fullurl, fetchdef) if sys_fetch.is_a?(Proc)
158
194
 
159
195
  return nil, ctx.make_error("fetch_invalid", "system.fetch is not a valid function")
@@ -14,10 +14,12 @@ module ProjectNameUtilities
14
14
  # Sent with the request, never recorded as the entity's match.
15
15
  authquery = (spec.respond_to?(:authquery) ? spec.authquery : nil) || []
16
16
 
17
- # A route the definition ends with a slash keeps it, for a Django REST server,
18
- # and a host with no path takes /, or luasocket reads a query as the host.
17
+ # A route ending in a slash keeps it, as defined or as passed to direct(), for
18
+ # Django, and a host with no path takes /, or luasocket reads a query as the host.
19
19
  orig = ctx.point ? VoxgigStruct.getprop(ctx.point, "orig") : nil
20
- if orig.is_a?(String) && orig.end_with?("/") && spec.suffix.to_s.empty? && !url.end_with?("/")
20
+ slashed = (orig.is_a?(String) && orig.end_with?("/")) ||
21
+ (spec.path.is_a?(String) && spec.path.end_with?("/"))
22
+ if slashed && spec.suffix.to_s.empty? && !url.end_with?("/")
21
23
  url += "/"
22
24
  end
23
25
  authority = url.index("://")
@@ -376,6 +376,71 @@ fn primary_fetcher_blocked_test_mode() {
376
376
  );
377
377
  }
378
378
 
379
+ // A Django route answers its slashless form with a relative Location. The
380
+ // transport follows each hop, and answers a "manual" fetch with the 3xx.
381
+ #[test]
382
+ fn primary_fetcher_redirect() {
383
+ use std::io::{BufRead, BufReader, Write};
384
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
385
+ let base = format!("http://{}", listener.local_addr().unwrap());
386
+ let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
387
+ let log = seen.clone();
388
+ std::thread::spawn(move || {
389
+ for stream in listener.incoming().take(4) {
390
+ let mut stream = stream.unwrap();
391
+ let mut reader = BufReader::new(stream.try_clone().unwrap());
392
+ let mut line = String::new();
393
+ reader.read_line(&mut line).unwrap();
394
+ let path = line.split(' ').nth(1).unwrap_or("").to_string();
395
+ let mut header = String::from("-");
396
+ while !header.trim().is_empty() {
397
+ header.clear();
398
+ if 0 == reader.read_line(&mut header).unwrap_or(0) {
399
+ break;
400
+ }
401
+ }
402
+ let (status, location) = match path.as_str() {
403
+ "/redirect/r1" => (301, "Location: /redirect/r1/\r\n"),
404
+ "/redirect/r1/" => (308, "Location: done\r\n"),
405
+ "/redirect/r1/done" => (200, ""),
406
+ _ => (404, ""),
407
+ };
408
+ let body = if 200 == status { "{\"id\":\"r1\"}" } else { "" };
409
+ log.lock().unwrap().push(path);
410
+ let _ = write!(stream, "HTTP/1.1 {} X\r\n{}Content-Type: application/json\r\n\
411
+ Content-Length: {}\r\nConnection: close\r\n\r\n{}", status, location, body.len(), body);
412
+ }
413
+ });
414
+
415
+ let live_client = ProjectNameSDK::new(jo(vec![("base", Value::str(&base))]));
416
+ let live_utility = live_client.get_utility();
417
+ let ctx = live_utility.make_context(
418
+ CtxSpec {
419
+ opname: Some("load".to_string()),
420
+ client: Some(live_client.clone()),
421
+ utility: Some(live_utility.clone()),
422
+ ..Default::default()
423
+ },
424
+ None,
425
+ );
426
+ let url = format!("{}/redirect/r1", base);
427
+ let res = live_utility
428
+ .fetch(&ctx, &url, &jo(vec![("method", Value::str("GET")), ("headers", Value::empty_map())]))
429
+ .expect("expected the redirect followed");
430
+ assert!(matches!(getp(&res, "status"), Value::Num(n) if 200.0 == n), "{:?}", getp(&res, "status"));
431
+ assert_eq!(get_str(&res, "body").as_deref(), Some("{\"id\":\"r1\"}"));
432
+ assert_eq!(*seen.lock().unwrap(), vec!["/redirect/r1", "/redirect/r1/", "/redirect/r1/done"]);
433
+
434
+ let manual = live_utility
435
+ .fetch(&ctx, &url, &jo(vec![
436
+ ("method", Value::str("GET")),
437
+ ("headers", Value::empty_map()),
438
+ ("redirect", Value::str("manual")),
439
+ ]))
440
+ .expect("expected the 301");
441
+ assert!(matches!(getp(&manual, "status"), Value::Num(n) if 301.0 == n), "{:?}", getp(&manual, "status"));
442
+ }
443
+
379
444
  // Nothing listens on port 9: a request the guard let through fails there.
380
445
  #[test]
381
446
  fn primary_fetcher_getonly_guard() {
@@ -49,6 +49,7 @@ pub fn make_url_util(ctx: &Rc<Context>) -> Result<String, ProjectNameError> {
49
49
  };
50
50
 
51
51
  let suffixless = suffix.is_empty();
52
+ let path_slash = path.ends_with('/');
52
53
  let mut url = vs::join(
53
54
  &Value::list(vec![
54
55
  Value::str(base.clone()),
@@ -60,12 +61,12 @@ pub fn make_url_util(ctx: &Rc<Context>) -> Result<String, ProjectNameError> {
60
61
  true,
61
62
  );
62
63
 
63
- // A route the definition ends with a slash keeps it, for a Django REST server,
64
- // and a host with no path takes /, or luasocket reads a query as the host.
65
- if let Value::Str(orig) = getp(&ctx.point.borrow().clone(), "orig") {
66
- if orig.ends_with('/') && suffixless && !url.ends_with('/') {
67
- url.push('/');
68
- }
64
+ // A route ending in a slash keeps it, as defined or as passed to direct(), for
65
+ // Django, and a host with no path takes /, or luasocket reads a query as the host.
66
+ let orig_slash = matches!(getp(&ctx.point.borrow().clone(), "orig"),
67
+ Value::Str(orig) if orig.ends_with('/'));
68
+ if (orig_slash || path_slash) && suffixless && !url.ends_with('/') {
69
+ url.push('/');
69
70
  }
70
71
  if let Some(authority) = url.find("://") {
71
72
  if 0 < authority && !url[authority + 3..].contains(|c| matches!(c, '/' | '?' | '#')) {
@@ -706,6 +706,51 @@ object SdkTestMain {
706
706
  // Small identity wrapper so IntConsumer/LongSupplier land in the map as-is.
707
707
  private def f0(o: Object): Object = o
708
708
 
709
+ // A Django route answers its slashless form with a relative Location. The
710
+ // transport follows each hop, and answers a "manual" fetch with the 3xx.
711
+ private def testRedirect(): Unit = {
712
+ val seen = java.util.Collections.synchronizedList(new ArrayList[String]())
713
+ val moved = Map("/redirect/r1" -> (301, "/redirect/r1/"), "/redirect/r1/" -> (308, "done"))
714
+ val server = com.sun.net.httpserver.HttpServer.create(new java.net.InetSocketAddress("127.0.0.1", 0), 0)
715
+ server.createContext("/", (exchange: com.sun.net.httpserver.HttpExchange) => {
716
+ val path = exchange.getRequestURI.getRawPath
717
+ seen.add(path)
718
+ val hop = moved.get(path)
719
+ val body = if (path == "/redirect/r1/done") "{\"id\":\"r1\"}".getBytes("UTF-8") else Array[Byte]()
720
+ hop.foreach(h => exchange.getResponseHeaders.set("Location", h._2))
721
+ exchange.getResponseHeaders.set("Content-Type", "application/json")
722
+ exchange.sendResponseHeaders(hop.map(_._1).getOrElse(if (body.nonEmpty) 200 else 404),
723
+ if (body.nonEmpty) body.length.toLong else -1L)
724
+ exchange.getResponseBody.write(body)
725
+ exchange.close()
726
+ })
727
+ server.start()
728
+ val base = "http://127.0.0.1:" + server.getAddress.getPort
729
+ try {
730
+ val opts = new LinkedHashMap[String, Object]()
731
+ opts.put("base", base)
732
+ val client = new ProjectNameSDK(opts)
733
+ val utility = client.getUtility()
734
+ val cm = new LinkedHashMap[String, Object]()
735
+ cm.put("opname", "load")
736
+ val ctx = utility.makeContext(cm, client.getRootCtx())
737
+ def fetch(redirect: String): JMap[String, Object] = {
738
+ val fetchdef = new LinkedHashMap[String, Object]()
739
+ fetchdef.put("method", "GET")
740
+ fetchdef.put("headers", new LinkedHashMap[String, Object]())
741
+ if (redirect != null) fetchdef.put("redirect", redirect)
742
+ utility.fetcher(ctx, base + "/redirect/r1", fetchdef).asInstanceOf[JMap[String, Object]]
743
+ }
744
+
745
+ val res = fetch(null)
746
+ eq("redirect.status", Integer.valueOf(200), res.get("status"))
747
+ eq("redirect.body", "{\"id\":\"r1\"}", res.get("body"))
748
+ eq("redirect.hops", "[/redirect/r1, /redirect/r1/, /redirect/r1/done]", seen.toString)
749
+ eq("redirect.manual", Integer.valueOf(301), fetch("manual").get("status"))
750
+ }
751
+ finally server.stop(0)
752
+ }
753
+
709
754
  // Nothing listens on port 9: a request the guard let through fails there.
710
755
  // A JVM cannot set its own environment, so the probe runs in a child JVM.
711
756
  private def testGetOnlyGuard(): Unit = {
@@ -736,7 +781,8 @@ object SdkTestMain {
736
781
  "paging" -> testPaging, "streaming" -> testStreaming, "proxy" -> testProxy,
737
782
  "composition" -> testComposition, "featureAdd" -> testFeatureAdd,
738
783
  "featureOrder" -> testFeatureOrder, "entityCrud" -> testEntityCrud,
739
- "entityStream" -> testEntityStream, "getOnlyGuard" -> testGetOnlyGuard)
784
+ "entityStream" -> testEntityStream, "getOnlyGuard" -> testGetOnlyGuard,
785
+ "redirect" -> testRedirect)
740
786
 
741
787
  suites.foreach { case (name, fn) =>
742
788
  try fn()
@@ -678,13 +678,15 @@ object MakeUrl {
678
678
  joinParts.add(spec.suffix)
679
679
  var url = Struct.join(joinParts, "/", true)
680
680
 
681
- // A route the definition ends with a slash keeps it, for a Django REST server,
682
- // and a host with no path takes /, or luasocket reads a query as the host.
681
+ // A route ending in a slash keeps it, as defined or as passed to direct(), for
682
+ // Django, and a host with no path takes /, or luasocket reads a query as the host.
683
683
  val orig = if (ctx.point == null) null else Struct.getprop(ctx.point, "orig", null)
684
- orig match {
685
- case o: String if o.endsWith("/") && (spec.suffix == null || spec.suffix.isEmpty) && !url.endsWith("/") =>
686
- url = url + "/"
687
- case _ =>
684
+ val slashed = (orig match {
685
+ case o: String => o.endsWith("/")
686
+ case _ => false
687
+ }) || (spec.path != null && spec.path.endsWith("/"))
688
+ if (slashed && (spec.suffix == null || spec.suffix.isEmpty) && !url.endsWith("/")) {
689
+ url = url + "/"
688
690
  }
689
691
  val authority = url.indexOf("://")
690
692
  if (0 < authority && !url.substring(authority + 3).exists(c => 0 <= "/?#".indexOf(c))) {
@@ -18,15 +18,7 @@ private func cookielessConfiguration() -> URLSessionConfiguration {
18
18
  return cfg
19
19
  }
20
20
 
21
- private let defaultSession = URLSession(configuration: cookielessConfiguration())
22
-
23
- // Non-following twin of defaultSession. The station feature's
24
- // middleware sets `redirect: manual` on the fetch definition under a
25
- // hosts egress policy: a 3xx must come back as a response like any
26
- // other, because an automatic follow would carry injected credentials
27
- // to a Location no policy approved (the ts donor's fetch honours the
28
- // same key natively; redirect policy is per-delegate in URLSession,
29
- // hence a second session).
21
+ // Every 3xx comes back as a response: defaultHttpFetch follows redirects.
30
22
  private final class ManualRedirectDelegate: NSObject, URLSessionTaskDelegate {
31
23
  func urlSession(
32
24
  _ session: URLSession, task: URLSessionTask,
@@ -61,12 +53,66 @@ func getOnlyRefusal(_ fullurl: String, _ method: String) -> ProjectNameError? {
61
53
  "[GET-ONLY GUARD] blocked \(upper) \(path.isEmpty ? "/" : String(path))", nil)
62
54
  }
63
55
 
56
+ let redirectStatus: Set<Int64> = [301, 302, 303, 307, 308]
57
+ let redirectMax = 5
58
+
59
+ // The Location resolved against the URL that answered with it.
60
+ func resolveLocation(_ base: String, _ location: String) -> String? {
61
+ let trimmed = location.filter { !$0.isWhitespace }
62
+ guard let resolved = URL(string: trimmed, relativeTo: URL(string: base)) else { return nil }
63
+ return String(resolved.absoluteString.prefix { $0 != "#" })
64
+ }
65
+
66
+ private func redirectOrigin(_ url: String) -> String {
67
+ guard let parts = URLComponents(string: url) else { return url }
68
+ let scheme = parts.scheme?.lowercased() ?? ""
69
+ return "\(scheme)://\(parts.host?.lowercased() ?? ""):\(parts.port ?? (scheme == "https" ? 443 : 80))"
70
+ }
71
+
72
+ private func withoutCredentials(_ fetchdef: VMap) -> VMap {
73
+ let copy = VMap(fetchdef.entries)
74
+ if let headers = gp(fetchdef, "headers").asMap {
75
+ var kept = headers.entries
76
+ for key in kept.keys where ["authorization", "cookie", "proxy-authorization"].contains(key.lowercased()) {
77
+ _ = kept.removeValue(forKey: key)
78
+ }
79
+ copy.entries["headers"] = .map(VMap(kept))
80
+ }
81
+ return copy
82
+ }
83
+
84
+ // URLSession on Linux drops the trailing slash of a Location it follows, so
85
+ // redirects are followed here. A GET or HEAD follows one, unless the fetch
86
+ // definition says "manual", each hop passing the GET-only guard first; past
87
+ // redirectMax hops the last 3xx is the answer. Another origin is not sent the
88
+ // request's credentials.
64
89
  func defaultHttpFetch(_ fullurl: String, _ fetchdef: VMap) throws -> Value {
65
- let method = gp(fetchdef, "method").asString ?? "GET"
66
- if let refused = getOnlyRefusal(fullurl, method.isEmpty ? "GET" : method) {
67
- throw refused
90
+ let raw = gp(fetchdef, "method").asString ?? "GET"
91
+ let method = raw.isEmpty ? "GET" : raw.uppercased()
92
+ let follow = (method == "GET" || method == "HEAD") && gp(fetchdef, "redirect").asString != "manual"
93
+ var url = fullurl
94
+ var def = fetchdef
95
+ var hops = 0
96
+ while true {
97
+ if let refused = getOnlyRefusal(url, method) {
98
+ throw refused
99
+ }
100
+ let res = try sendOnce(url, def)
101
+ guard follow, hops < redirectMax, let status = gp(res, "status").asInt,
102
+ redirectStatus.contains(status), let location = gp(gp(res, "headers"), "location").asString,
103
+ let next = resolveLocation(url, location)
104
+ else {
105
+ return res
106
+ }
107
+ if redirectOrigin(next) != redirectOrigin(url) {
108
+ def = withoutCredentials(def)
109
+ }
110
+ url = next
111
+ hops += 1
68
112
  }
113
+ }
69
114
 
115
+ private func sendOnce(_ fullurl: String, _ fetchdef: VMap) throws -> Value {
70
116
  // A request that cannot be sent fails the operation.
71
117
  guard let url = URL(string: fullurl) else {
72
118
  throw ProjectNameError("fetch_transport", "the URL could not be parsed", nil)
@@ -116,9 +162,7 @@ func defaultHttpFetch(_ fullurl: String, _ fetchdef: VMap) throws -> Value {
116
162
  }
117
163
  let box = FetchBox()
118
164
  let sem = DispatchSemaphore(value: 0)
119
- let session = gp(fetchdef, "redirect").asString == "manual"
120
- ? manualRedirectSession : defaultSession
121
- let task = session.dataTask(with: req) { d, r, e in
165
+ let task = manualRedirectSession.dataTask(with: req) { d, r, e in
122
166
  box.data = d; box.resp = r; box.err = e; sem.signal()
123
167
  }
124
168
  task.resume()
@@ -266,10 +266,10 @@ func makeUrlUtil(_ ctx: Context) throws -> String {
266
266
  // Sent with the request, never recorded as the entity's match.
267
267
  let authquery = spec.authquery
268
268
 
269
- // A route the definition ends with a slash keeps it, for a Django REST server,
270
- // and a host with no path takes /, or luasocket reads a query as the host.
271
- if let orig = gp(ctx.point, "orig").asString, orig.hasSuffix("/"), spec.suffix.isEmpty,
272
- !url.hasSuffix("/") {
269
+ // A route ending in a slash keeps it, as defined or as passed to direct(), for
270
+ // Django, and a host with no path takes /, or luasocket reads a query as the host.
271
+ let slashed = (gp(ctx.point, "orig").asString?.hasSuffix("/") ?? false) || spec.path.hasSuffix("/")
272
+ if slashed, spec.suffix.isEmpty, !url.hasSuffix("/") {
273
273
  url += "/"
274
274
  }
275
275
  if let authority = url.range(of: "://"), url.startIndex < authority.lowerBound,
@@ -425,6 +425,78 @@ final class PrimaryUtilityTest: XCTestCase {
425
425
  }
426
426
  }
427
427
 
428
+ // A Django route answers its slashless form with a relative Location. The
429
+ // transport follows each hop, and answers a "manual" fetch with the 3xx.
430
+ func testFetcherRedirect() throws {
431
+ #if os(Linux)
432
+ let fd = socket(AF_INET, Int32(SOCK_STREAM.rawValue), 0)
433
+ #else
434
+ let fd = socket(AF_INET, SOCK_STREAM, 0)
435
+ #endif
436
+ var addr = sockaddr_in()
437
+ addr.sin_family = sa_family_t(AF_INET)
438
+ addr.sin_addr.s_addr = inet_addr("127.0.0.1")
439
+ var len = socklen_t(MemoryLayout<sockaddr_in>.size)
440
+ _ = withUnsafeMutablePointer(to: &addr) {
441
+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { bind(fd, $0, len) }
442
+ }
443
+ listen(fd, 8)
444
+ _ = withUnsafeMutablePointer(to: &addr) {
445
+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { getsockname(fd, $0, &len) }
446
+ }
447
+ let base = "http://127.0.0.1:\(UInt16(bigEndian: addr.sin_port))"
448
+ defer { close(fd) }
449
+
450
+ let lock = NSLock()
451
+ var seen: [String] = []
452
+ let moved = ["/redirect/r1": "301 X\r\nLocation: /redirect/r1/", "/redirect/r1/": "308 X\r\nLocation: done"]
453
+ Thread.detachNewThread {
454
+ for _ in 0..<4 {
455
+ let conn = accept(fd, nil, nil)
456
+ if conn < 0 { return }
457
+ var head = ""
458
+ var buf = [UInt8](repeating: 0, count: 4096)
459
+ while !head.contains("\r\n\r\n") {
460
+ let got = buf.withUnsafeMutableBytes { read(conn, $0.baseAddress, $0.count) }
461
+ if got <= 0 { break }
462
+ head += String(decoding: buf[0..<got], as: UTF8.self)
463
+ }
464
+ let parts = head.split(separator: " ")
465
+ let path = 1 < parts.count ? String(parts[1]) : ""
466
+ lock.lock(); seen.append(path); lock.unlock()
467
+ let body = path == "/redirect/r1/done" ? "{\"id\":\"r1\"}" : ""
468
+ let status = moved[path] ?? (body.isEmpty ? "404 X" : "200 X")
469
+ let reply = Array(("HTTP/1.1 \(status)\r\nContent-Type: application/json\r\n" +
470
+ "Content-Length: \(body.utf8.count)\r\nConnection: close\r\n\r\n\(body)").utf8)
471
+ _ = reply.withUnsafeBytes { write(conn, $0.baseAddress, $0.count) }
472
+ close(conn)
473
+ }
474
+ }
475
+
476
+ let opts = VMap()
477
+ opts.entries["base"] = .string(base)
478
+ let liveClient = ProjectNameSDK(opts)
479
+ let liveUtility = liveClient.getUtility()
480
+ let ctx = liveUtility.makeContext(
481
+ ["opname": "load", "client": liveClient, "utility": liveUtility], nil)
482
+ func def(_ redirect: String?) -> VMap {
483
+ let fetchdef = VMap()
484
+ fetchdef.entries["method"] = .string("GET")
485
+ fetchdef.entries["headers"] = .map(VMap())
486
+ if let redirect = redirect { fetchdef.entries["redirect"] = .string(redirect) }
487
+ return fetchdef
488
+ }
489
+
490
+ let res = try liveUtility.fetcher(ctx, base + "/redirect/r1", def(nil))
491
+ XCTAssertEqual(gp(res, "status").asInt, 200)
492
+ XCTAssertEqual(gp(res, "body").asString, "{\"id\":\"r1\"}")
493
+ lock.lock(); let sent = seen; lock.unlock()
494
+ XCTAssertEqual(sent, ["/redirect/r1", "/redirect/r1/", "/redirect/r1/done"])
495
+
496
+ let manual = try liveUtility.fetcher(ctx, base + "/redirect/r1", def("manual"))
497
+ XCTAssertEqual(gp(manual, "status").asInt, 301)
498
+ }
499
+
428
500
  // Nothing listens on port 9: a request the guard let through fails there.
429
501
  func testFetcherGetOnlyGuard() {
430
502
  let opts = VMap()
@@ -29,10 +29,12 @@ function makeUrl(ctx: Context): Error | string {
29
29
  // Sent with the request, never recorded as the entity's match.
30
30
  const authquery: string[] = spec.authquery || []
31
31
 
32
- // A route the definition ends with a slash keeps it, for a Django REST server,
33
- // and a host with no path takes /, or luasocket reads a query as the host.
32
+ // A route ending in a slash keeps it, as defined or as passed to direct(), for
33
+ // Django, and a host with no path takes /, or luasocket reads a query as the host.
34
34
  const orig = ctx.point?.orig
35
- if ('string' === typeof orig && orig.endsWith('/') && !spec.suffix && !url.endsWith('/')) {
35
+ const slashed = ('string' === typeof orig && orig.endsWith('/')) ||
36
+ ('string' === typeof spec.path && spec.path.endsWith('/'))
37
+ if (slashed && !spec.suffix && !url.endsWith('/')) {
36
38
  url += '/'
37
39
  }
38
40
  const authority = url.indexOf('://')
@@ -179,10 +179,11 @@ function assertLiveReport(report: LiveReport): void {
179
179
  }
180
180
 
181
181
  // An account with no record for a step to read skips in either mode, as
182
- // does a run that leaves out every step.
182
+ // does a run that leaves out every step, or has none to run.
183
183
  function settleLiveReport(report: LiveReport, settle: LiveSettle = {}): void {
184
- if (0 < report.planned && report.excluded === report.planned && null != settle.t) {
185
- return settle.t.skip('Live coverage incomplete: ' + liveSummary(report))
184
+ if (report.excluded === report.planned && null != settle.t) {
185
+ return settle.t.skip('Live coverage incomplete: ' +
186
+ (0 === report.planned ? 'the flow has no step to run' : liveSummary(report)))
186
187
  }
187
188
  if (liveIncomplete(report)) {
188
189
  if (false !== settle.strict || null == settle.t) return assertLiveReport(report)
@@ -2,6 +2,7 @@
2
2
  import { test, describe, before } from 'node:test'
3
3
  import { equal, deepStrictEqual, ok } from 'node:assert'
4
4
  import assert from 'node:assert'
5
+ import Http from 'node:http'
5
6
 
6
7
  import {
7
8
  makeRunner,
@@ -524,6 +525,45 @@ describe('PrimaryUtility', async () => {
524
525
  })
525
526
 
526
527
 
528
+ // A Django route answers its slashless form with a relative Location. The
529
+ // transport follows each hop, and answers a "manual" fetch with the 3xx.
530
+ test('fetcher-redirect', async () => {
531
+ const seen: string[] = []
532
+ const moved: Record<string, [number, string]> = {
533
+ '/redirect/r1': [301, '/redirect/r1/'],
534
+ '/redirect/r1/': [308, 'done'],
535
+ }
536
+ const server = Http.createServer((req: any, res: any) => {
537
+ seen.push(req.url)
538
+ const to = moved[req.url]
539
+ const done = '/redirect/r1/done' === req.url
540
+ res.writeHead(to ? to[0] : done ? 200 : 404, to ? { location: to[1], connection: 'close' } :
541
+ { 'content-type': 'application/json', connection: 'close' })
542
+ res.end(done ? '{"id":"r1"}' : '')
543
+ })
544
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', () => resolve()))
545
+ const base = 'http://127.0.0.1:' + (server.address() as any).port
546
+ try {
547
+ const liveClient = new (SDK as any)({ base })
548
+ const liveUtility = liveClient.utility()
549
+ const ctx = liveUtility.makeContext({ opname: 'load' }, liveClient._rootctx)
550
+ ctx.client = liveClient
551
+
552
+ const res = await liveUtility.fetcher(ctx, base + '/redirect/r1', { method: 'GET', headers: {} })
553
+ equal(res.status, 200)
554
+ deepStrictEqual(await res.json(), { id: 'r1' })
555
+ deepStrictEqual(seen, ['/redirect/r1', '/redirect/r1/', '/redirect/r1/done'])
556
+
557
+ const manual = await liveUtility.fetcher(ctx, base + '/redirect/r1',
558
+ { method: 'GET', headers: {}, redirect: 'manual' })
559
+ equal(manual.status, 301)
560
+ }
561
+ finally {
562
+ server.close()
563
+ }
564
+ })
565
+
566
+
527
567
  test('makeError-no-throw', () => {
528
568
  const ctx = makeFullCtx()
529
569
  ctx.ctrl.throw = false
@@ -1189,12 +1189,12 @@ pub fn make_url_util(ctx: *Context) E![]const u8 {
1189
1189
  h.vstr(spec.suffix),
1190
1190
  }), "/", true) catch "";
1191
1191
 
1192
- // A route the definition ends with a slash keeps it, for a Django REST server,
1193
- // and a host with no path takes /, or luasocket reads a query as the host.
1192
+ // A route ending in a slash keeps it, as defined or as passed to direct(), for
1193
+ // Django, and a host with no path takes /, or luasocket reads a query as the host.
1194
1194
  const orig = h.getp(ctx.point, "orig");
1195
- if (orig == .string and std.mem.endsWith(u8, orig.string, "/") and spec.suffix.len == 0 and
1196
- !std.mem.endsWith(u8, url, "/"))
1197
- {
1195
+ const slashed = (orig == .string and std.mem.endsWith(u8, orig.string, "/")) or
1196
+ std.mem.endsWith(u8, spec.path, "/");
1197
+ if (slashed and spec.suffix.len == 0 and !std.mem.endsWith(u8, url, "/")) {
1198
1198
  url = std.mem.concat(h.A(), u8, &.{ url, "/" }) catch url;
1199
1199
  }
1200
1200
  if (std.mem.indexOf(u8, url, "://")) |authority| {
@@ -3,7 +3,7 @@
3
3
  "package": 1
4
4
  },
5
5
  "name": "@voxgig/sdkgen",
6
- "version": "4.37.0",
6
+ "version": "4.38.0",
7
7
  "provides": {
8
8
  "target": [
9
9
  "c",
@@ -20,8 +20,8 @@ const GENERATED = ['create', 'list', 'load', 'update', 'remove']
20
20
 
21
21
  // A generated flow test calls each step's op with its own match and data,
22
22
  // the record's id where the op acts on one, and what the entity instance
23
- // holds. A step whose call reaches no route is switched off, as the runtime
24
- // would refuse it, and marked unreachable for the live harness to resolve.
23
+ // holds. A step whose op is absent, or whose call reaches no route, is
24
+ // switched off and marked unreachable for the live harness to resolve.
25
25
  function guardFlowSteps(model: any, log?: any): Unreachable[] {
26
26
  const kit = model?.main?.[KIT]
27
27
  const flows = kit?.flow
@@ -76,7 +76,7 @@ function guardFlowSteps(model: any, log?: any): Unreachable[] {
76
76
  ]
77
77
 
78
78
  const op = ent.op?.[step.o]
79
- if (null != op && !opReachable(op, given)) {
79
+ if (null == op || !opReachable(op, given)) {
80
80
  step.a = false
81
81
  step.unreachable = true
82
82
  if ('remove' === step.o && null != step.i?.ref) unremoved.add(step.i.ref)
@@ -103,7 +103,7 @@ function guardFlowSteps(model: any, log?: any): Unreachable[] {
103
103
  point: 'flow-step-unreachable',
104
104
  steps: out.map((s) => s.flow + '.' + s.step + ':' + s.op),
105
105
  note: 'flow step(s) ' + out.map((s) => s.flow + '#' + s.step + ' (' + s.op + ')').join(', ') +
106
- ' switched off: the call they make reaches no route of the operation, ' +
106
+ ' switched off: the entity has no such operation, the call they make reaches no route of it, ' +
107
107
  'or they check a removal such a step was to make. ' +
108
108
  'Every route needs an action, or a path parameter the step does not give.',
109
109
  })
@@ -0,0 +1,31 @@
1
+
2
+ type LiveDiscovery = {
3
+ // the load path parameter the first listed record fills
4
+ param: string
5
+ // the field of that record it reads
6
+ field: string
7
+ }
8
+
9
+
10
+ // What a live direct load lists to find, the same in every target. Only a path
11
+ // parameter the list route does not also take can come from a listed record,
12
+ // `id` first; every other one comes from *_ENTID or its example. A route with no
13
+ // path parameter, or an example for each, loads directly.
14
+ function liveDirectDiscovery(entity: any, loadParams: any[], listPoint: any):
15
+ LiveDiscovery | undefined {
16
+ if (null == listPoint || loadParams.every((p: any) => null != p.ex)) {
17
+ return undefined
18
+ }
19
+ const listed = new Set((listPoint.g?.params || []).map((p: any) => p.n))
20
+ const open = loadParams.filter((p: any) => !listed.has(p.n))
21
+ const param: string | undefined = (open.find((p: any) => 'id' === p.n) ?? open[0])?.n
22
+ if (null == param) {
23
+ return undefined
24
+ }
25
+ return { param, field: 'id' === param ? (entity?.id?.field || 'id') : param }
26
+ }
27
+
28
+
29
+ export type { LiveDiscovery }
30
+
31
+ export { liveDirectDiscovery }