@voxgig/sdkgen 4.37.0 → 4.39.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 (134) hide show
  1. package/bin/voxgig-sdkgen +13 -2
  2. package/dist/action/copies.d.ts +6 -1
  3. package/dist/action/copies.js +43 -1
  4. package/dist/action/copies.js.map +1 -1
  5. package/dist/action/doctor.d.ts +2 -0
  6. package/dist/action/doctor.js +25 -6
  7. package/dist/action/doctor.js.map +1 -1
  8. package/dist/action/edition.js +3 -0
  9. package/dist/action/edition.js.map +1 -1
  10. package/dist/action/feature.js +3 -0
  11. package/dist/action/feature.js.map +1 -1
  12. package/dist/action/package.js +15 -0
  13. package/dist/action/package.js.map +1 -1
  14. package/dist/action/target.js +3 -0
  15. package/dist/action/target.js.map +1 -1
  16. package/dist/helpers/copymerge.d.ts +35 -0
  17. package/dist/helpers/copymerge.js +508 -0
  18. package/dist/helpers/copymerge.js.map +1 -0
  19. package/dist/helpers/flowGuard.js +4 -4
  20. package/dist/helpers/flowGuard.js.map +1 -1
  21. package/dist/helpers/liveDiscovery.d.ts +7 -0
  22. package/dist/helpers/liveDiscovery.js +20 -0
  23. package/dist/helpers/liveDiscovery.js.map +1 -0
  24. package/dist/helpers/opShape.d.ts +2 -1
  25. package/dist/helpers/opShape.js +4 -0
  26. package/dist/helpers/opShape.js.map +1 -1
  27. package/dist/helpers/pointPath.d.ts +2 -1
  28. package/dist/helpers/pointPath.js +6 -0
  29. package/dist/helpers/pointPath.js.map +1 -1
  30. package/dist/helpers/testPolicy.d.ts +14 -4
  31. package/dist/helpers/testPolicy.js +152 -54
  32. package/dist/helpers/testPolicy.js.map +1 -1
  33. package/dist/sdkgen.d.ts +8 -6
  34. package/dist/sdkgen.js +11 -5
  35. package/dist/sdkgen.js.map +1 -1
  36. package/dist/tsconfig.tsbuildinfo +1 -1
  37. package/dist/types.d.ts +1 -0
  38. package/dist/utility.js +7 -3
  39. package/dist/utility.js.map +1 -1
  40. package/model/sdkgen.aontu +4 -0
  41. package/package.json +1 -1
  42. package/project/.sdk/src/cmp/c/TestDirect_c.ts +3 -2
  43. package/project/.sdk/src/cmp/cpp/TestDirect_cpp.ts +3 -2
  44. package/project/.sdk/src/cmp/cpp/TestEntity_cpp.ts +33 -10
  45. package/project/.sdk/src/cmp/csharp/TestDirect_csharp.ts +12 -12
  46. package/project/.sdk/src/cmp/csharp/TestEntity_csharp.ts +73 -28
  47. package/project/.sdk/src/cmp/go/TestDirect_go.ts +12 -10
  48. package/project/.sdk/src/cmp/go/TestEntity_go.ts +67 -23
  49. package/project/.sdk/src/cmp/java/TestDirect_java.ts +12 -11
  50. package/project/.sdk/src/cmp/java/TestEntity_java.ts +71 -23
  51. package/project/.sdk/src/cmp/js/TestDirect_js.ts +13 -12
  52. package/project/.sdk/src/cmp/js/TestEntity_js.ts +41 -17
  53. package/project/.sdk/src/cmp/kotlin/TestDirect_kotlin.ts +12 -10
  54. package/project/.sdk/src/cmp/kotlin/TestEntity_kotlin.ts +64 -23
  55. package/project/.sdk/src/cmp/lua/TestDirect_lua.ts +9 -5
  56. package/project/.sdk/src/cmp/lua/TestEntity_lua.ts +61 -23
  57. package/project/.sdk/src/cmp/perl/TestDirect_perl.ts +9 -5
  58. package/project/.sdk/src/cmp/perl/TestEntity_perl.ts +58 -24
  59. package/project/.sdk/src/cmp/php/TestDirect_php.ts +9 -5
  60. package/project/.sdk/src/cmp/php/TestEntity_php.ts +61 -23
  61. package/project/.sdk/src/cmp/py/TestDirect_py.ts +10 -6
  62. package/project/.sdk/src/cmp/py/TestEntity_py.ts +59 -27
  63. package/project/.sdk/src/cmp/rb/TestDirect_rb.ts +9 -5
  64. package/project/.sdk/src/cmp/rb/TestEntity_rb.ts +59 -23
  65. package/project/.sdk/src/cmp/rust/TestDirect_rust.ts +9 -8
  66. package/project/.sdk/src/cmp/rust/TestEntity_rust.ts +56 -24
  67. package/project/.sdk/src/cmp/scala/TestDirect_scala.ts +3 -2
  68. package/project/.sdk/src/cmp/scala/TestEntity_scala.ts +36 -9
  69. package/project/.sdk/src/cmp/ts/TestDirect_ts.ts +15 -32
  70. package/project/.sdk/src/cmp/ts/TestEntity_ts.ts +41 -17
  71. package/project/.sdk/tm/c/tests/transport_test.c +33 -0
  72. package/project/.sdk/tm/c/utility/fetcher.c +151 -2
  73. package/project/.sdk/tm/c/utility/make_url.c +8 -6
  74. package/project/.sdk/tm/clojure/src/sdk/core.clj +17 -10
  75. package/project/.sdk/tm/clojure/test/sdk/test/pipeline.clj +38 -0
  76. package/project/.sdk/tm/cpp/utility/pipeline.hpp +5 -4
  77. package/project/.sdk/tm/csharp/test/PrimaryUtilityTest.cs +69 -0
  78. package/project/.sdk/tm/csharp/utility/Fetcher.cs +3 -1
  79. package/project/.sdk/tm/csharp/utility/MakeUrl.cs +5 -4
  80. package/project/.sdk/tm/elixir/lib/projectname/utility.ex +10 -6
  81. package/project/.sdk/tm/elixir/test/pipeline_test.exs +61 -0
  82. package/project/.sdk/tm/go/test/primary_utility_test.go +60 -0
  83. package/project/.sdk/tm/go/utility/fetcher.go +15 -4
  84. package/project/.sdk/tm/go/utility/make_url.go +4 -3
  85. package/project/.sdk/tm/java/test/PrimaryUtilityTest.java +47 -0
  86. package/project/.sdk/tm/java/utility/MakeUrl.java +5 -4
  87. package/project/.sdk/tm/js/src/utility/MakeUrlUtility.js +5 -3
  88. package/project/.sdk/tm/js/test/live-runner.js +4 -3
  89. package/project/.sdk/tm/js/test/utility/PrimaryUtility.test.js +40 -0
  90. package/project/.sdk/tm/kotlin/test/PrimaryUtilityTest.kt +41 -0
  91. package/project/.sdk/tm/kotlin/utility/MakeSpecUrl.kt +4 -3
  92. package/project/.sdk/tm/lua/test/primary_utility_test.lua +61 -0
  93. package/project/.sdk/tm/lua/utility/fetcher.lua +54 -6
  94. package/project/.sdk/tm/lua/utility/make_url.lua +5 -4
  95. package/project/.sdk/tm/ocaml/sdk_runtime.ml +5 -5
  96. package/project/.sdk/tm/perl/t/primary_utility.t +54 -0
  97. package/project/.sdk/tm/perl/utility/fetcher.pm +65 -11
  98. package/project/.sdk/tm/perl/utility/make_url.pm +4 -3
  99. package/project/.sdk/tm/php/test/PipelineTest.php +52 -0
  100. package/project/.sdk/tm/php/utility/Fetcher.php +81 -15
  101. package/project/.sdk/tm/php/utility/MakeUrl.php +5 -3
  102. package/project/.sdk/tm/py/pkg/utility/fetcher.py +1 -0
  103. package/project/.sdk/tm/py/pkg/utility/make_url.py +5 -4
  104. package/project/.sdk/tm/py/test/test_primary_utility.py +52 -0
  105. package/project/.sdk/tm/rb/test/primary_utility_test.rb +46 -0
  106. package/project/.sdk/tm/rb/utility/fetcher.rb +41 -5
  107. package/project/.sdk/tm/rb/utility/make_url.rb +5 -3
  108. package/project/.sdk/tm/rust/tests/primary_utility_test.rs +65 -0
  109. package/project/.sdk/tm/rust/utility/make_url.rs +7 -6
  110. package/project/.sdk/tm/scala/sdktest/SdkTestMain.scala +47 -1
  111. package/project/.sdk/tm/scala/utility/Make.scala +8 -6
  112. package/project/.sdk/tm/swift/Sources/ProjectNameSDK/utility/Fetcher.swift +59 -15
  113. package/project/.sdk/tm/swift/Sources/ProjectNameSDK/utility/Make.swift +4 -4
  114. package/project/.sdk/tm/swift/Tests/ProjectNameSDKTests/PrimaryUtilityTest.swift +72 -0
  115. package/project/.sdk/tm/ts/src/utility/MakeUrlUtility.ts +5 -3
  116. package/project/.sdk/tm/ts/test/live-runner.ts +4 -3
  117. package/project/.sdk/tm/ts/test/utility/PrimaryUtility.test.ts +40 -0
  118. package/project/.sdk/tm/zig/core/utility.zig +5 -5
  119. package/project/sdkgen-package.json +1 -1
  120. package/src/action/copies.ts +54 -0
  121. package/src/action/doctor.ts +36 -7
  122. package/src/action/edition.ts +9 -1
  123. package/src/action/feature.ts +7 -1
  124. package/src/action/package.ts +28 -1
  125. package/src/action/target.ts +7 -1
  126. package/src/helpers/copymerge.ts +707 -0
  127. package/src/helpers/flowGuard.ts +4 -4
  128. package/src/helpers/liveDiscovery.ts +31 -0
  129. package/src/helpers/opShape.ts +6 -0
  130. package/src/helpers/pointPath.ts +8 -0
  131. package/src/helpers/testPolicy.ts +193 -55
  132. package/src/sdkgen.ts +13 -3
  133. package/src/types.ts +2 -0
  134. package/src/utility.ts +10 -4
@@ -428,6 +428,75 @@ public class PrimaryUtilityTest
428
428
  Assert.Contains("blocked", err.Message);
429
429
  }
430
430
 
431
+ // A Django route answers its slashless form with a relative Location. The
432
+ // transport follows each hop, and answers a "manual" fetch with the 3xx.
433
+ [Fact]
434
+ public void FetcherRedirect()
435
+ {
436
+ var seen = new System.Collections.Concurrent.ConcurrentQueue<string>();
437
+ var moved = new Dictionary<string, (int Code, string To)>
438
+ {
439
+ ["/redirect/r1"] = (301, "/redirect/r1/"),
440
+ ["/redirect/r1/"] = (308, "done"),
441
+ };
442
+ var listener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0);
443
+ listener.Start();
444
+ System.Threading.Tasks.Task.Run(() =>
445
+ {
446
+ for (var i = 0; i < 4; i++)
447
+ {
448
+ using var conn = listener.AcceptTcpClient();
449
+ using var stream = conn.GetStream();
450
+ var reader = new System.IO.StreamReader(stream);
451
+ var parts = (reader.ReadLine() ?? "").Split(' ');
452
+ var path = 1 < parts.Length ? parts[1] : "";
453
+ while (!string.IsNullOrEmpty(reader.ReadLine())) { }
454
+ seen.Enqueue(path);
455
+ var body = path == "/redirect/r1/done" ? "{\"id\":\"r1\"}" : "";
456
+ var moves = moved.TryGetValue(path, out var hop);
457
+ var head = "HTTP/1.1 " + (moves ? hop.Code : body == "" ? 404 : 200) + " X\r\n" +
458
+ (moves ? "Location: " + hop.To + "\r\n" : "") + "Content-Type: application/json\r\n" +
459
+ "Content-Length: " + body.Length + "\r\nConnection: close\r\n\r\n";
460
+ var bytes = System.Text.Encoding.UTF8.GetBytes(head + body);
461
+ stream.Write(bytes, 0, bytes.Length);
462
+ }
463
+ });
464
+ var bse = "http://127.0.0.1:" + ((System.Net.IPEndPoint)listener.LocalEndpoint).Port;
465
+ try
466
+ {
467
+ var liveClient = new ProjectNameSDK(new Dictionary<string, object?> { ["base"] = bse });
468
+ var liveUtility = liveClient.GetUtility();
469
+ var ctx = liveUtility.MakeContext(new Dictionary<string, object?>
470
+ {
471
+ ["opname"] = "load",
472
+ ["client"] = liveClient,
473
+ ["utility"] = liveUtility,
474
+ }, null);
475
+ Dictionary<string, object?> Def(string? redirect)
476
+ {
477
+ var def = new Dictionary<string, object?>
478
+ {
479
+ ["method"] = "GET",
480
+ ["headers"] = new Dictionary<string, object?>(),
481
+ };
482
+ if (redirect != null) def["redirect"] = redirect;
483
+ return def;
484
+ }
485
+
486
+ var res = (Dictionary<string, object?>)liveUtility.Fetcher(ctx, bse + "/redirect/r1", Def(null))!;
487
+ Assert.Equal(200, res["status"]);
488
+ Assert.Equal("{\"id\":\"r1\"}", res["body"]);
489
+ Assert.Equal(new[] { "/redirect/r1", "/redirect/r1/", "/redirect/r1/done" }, seen.ToArray());
490
+
491
+ var manual = (Dictionary<string, object?>)liveUtility.Fetcher(ctx, bse + "/redirect/r1", Def("manual"))!;
492
+ Assert.Equal(301, manual["status"]);
493
+ }
494
+ finally
495
+ {
496
+ listener.Stop();
497
+ }
498
+ }
499
+
431
500
  // Nothing listens on port 9: a request the guard let through fails there.
432
501
  [Fact]
433
502
  public void FetcherGetOnlyGuard()
@@ -15,11 +15,13 @@ public static partial class SdkUtility
15
15
  // CookieContainer would send one call's Set-Cookie on the next, under a
16
16
  // different credential — and .NET ADDS container cookies to a request
17
17
  // that already carries a Cookie header, which an `apiKey in: cookie`
18
- // scheme does. Pooling is the handler's own and is unaffected.
18
+ // scheme does. Pooling is the handler's own and is unaffected. Past five
19
+ // redirects the last 3xx is the answer, as in every target.
19
20
  private static HttpClientHandler CookielessHandler(bool allowRedirect) =>
20
21
  new HttpClientHandler
21
22
  {
22
23
  AllowAutoRedirect = allowRedirect,
24
+ MaxAutomaticRedirections = 5,
23
25
  UseCookies = false,
24
26
  };
25
27
 
@@ -25,10 +25,11 @@ public static partial class SdkUtility
25
25
  // Sent with the request, never recorded as the entity's match.
26
26
  var authquery = spec.AuthQuery;
27
27
 
28
- // A route the definition ends with a slash keeps it, for a Django REST server,
29
- // and a host with no path takes /, or luasocket reads a query as the host.
30
- if (ctx.Point != null && StructUtils.GetProp(ctx.Point, "orig") is string orig &&
31
- orig.EndsWith("/") && string.IsNullOrEmpty(spec.Suffix) && !url.EndsWith("/"))
28
+ // A route ending in a slash keeps it, as defined or as passed to direct(), for
29
+ // Django, and a host with no path takes /, or luasocket reads a query as the host.
30
+ var slashed = (ctx.Point != null && StructUtils.GetProp(ctx.Point, "orig") is string orig &&
31
+ orig.EndsWith("/")) || (spec.Path?.EndsWith("/") ?? false);
32
+ if (slashed && string.IsNullOrEmpty(spec.Suffix) && !url.EndsWith("/"))
32
33
  {
33
34
  url += "/";
34
35
  }
@@ -1525,16 +1525,20 @@ defmodule ProjectName.Utility do
1525
1525
  true
1526
1526
  )
1527
1527
 
1528
- # A route the definition ends with a slash keeps it, for a Django REST server,
1529
- # and a host with no path takes /, or luasocket reads a query as the host.
1528
+ # A route ending in a slash keeps it, as defined or as passed to direct(), for
1529
+ # Django, and a host with no path takes /, or luasocket reads a query as the host.
1530
1530
  orig = S.getprop(S.getprop(ctx, "point"), "orig")
1531
+ path = S.getprop(spec, "path")
1531
1532
  suffix = S.getprop(spec, "suffix")
1532
1533
 
1534
+ slashed =
1535
+ (is_binary(orig) and String.ends_with?(orig, "/")) or
1536
+ (is_binary(path) and String.ends_with?(path, "/"))
1537
+
1533
1538
  url0 =
1534
- if is_binary(orig) and String.ends_with?(orig, "/") and (suffix == nil or suffix == "") and
1535
- not String.ends_with?(joined, "/"),
1536
- do: joined <> "/",
1537
- else: joined
1539
+ if slashed and (suffix == nil or suffix == "") and not String.ends_with?(joined, "/"),
1540
+ do: joined <> "/",
1541
+ else: joined
1538
1542
  url0 =
1539
1543
  case :binary.match(url0, "://") do
1540
1544
  {authority, 3} when 0 < authority ->
@@ -296,6 +296,67 @@ defmodule ProjectName.PipelineTest do
296
296
  assert err.code == "request_no_spec"
297
297
  end
298
298
 
299
+ # A Django route answers its slashless form with a relative Location. The
300
+ # transport follows each hop, and answers a "manual" fetch with the 3xx.
301
+ test "fetcher follows a relative redirect" do
302
+ {:ok, listen} =
303
+ :gen_tcp.listen(0, [:binary, active: false, reuseaddr: true, ip: {127, 0, 0, 1}])
304
+
305
+ {:ok, port} = :inet.port(listen)
306
+ parent = self()
307
+ moved = %{"/redirect/r1" => {301, "/redirect/r1/"}, "/redirect/r1/" => {308, "done"}}
308
+
309
+ read_head = fn read_head, sock, acc ->
310
+ if String.contains?(acc, "\r\n\r\n") do
311
+ acc
312
+ else
313
+ case :gen_tcp.recv(sock, 0, 5000) do
314
+ {:ok, data} -> read_head.(read_head, sock, acc <> data)
315
+ _ -> acc
316
+ end
317
+ end
318
+ end
319
+
320
+ serve = fn serve, n ->
321
+ with true <- n > 0, {:ok, sock} <- :gen_tcp.accept(listen) do
322
+ path = Enum.at(String.split(read_head.(read_head, sock, ""), " "), 1, "")
323
+ send(parent, {:seen, path})
324
+ body = if path == "/redirect/r1/done", do: ~s({"id":"r1"}), else: ""
325
+
326
+ {status, location} =
327
+ case Map.get(moved, path) do
328
+ {code, to} -> {code, "Location: #{to}\r\n"}
329
+ nil -> {if(body == "", do: 404, else: 200), ""}
330
+ end
331
+
332
+ :gen_tcp.send(sock, "HTTP/1.1 #{status} X\r\n#{location}Content-Type: application/json\r\n" <>
333
+ "Content-Length: #{byte_size(body)}\r\nConnection: close\r\n\r\n#{body}")
334
+ :gen_tcp.close(sock)
335
+ serve.(serve, n - 1)
336
+ end
337
+ end
338
+
339
+ spawn(fn -> serve.(serve, 4) end)
340
+ base = "http://127.0.0.1:#{port}"
341
+ ctx = make_ctx(ProjectName.new(S.jm(["base", base])), "load")
342
+ fetchdef = fn extra -> S.jm(["method", "GET", "headers", S.jm([])] ++ extra) end
343
+
344
+ try do
345
+ {res, err} = Utility.fetcher(ctx, base <> "/redirect/r1", fetchdef.([]))
346
+ assert err == nil
347
+ assert S.getprop(res, "status") == 200
348
+ assert S.getprop(res, "body") == ~s({"id":"r1"})
349
+ seen = for _ <- 1..3, do: (receive do {:seen, p} -> p after 5000 -> nil end)
350
+ assert seen == ["/redirect/r1", "/redirect/r1/", "/redirect/r1/done"]
351
+
352
+ {manual, merr} = Utility.fetcher(ctx, base <> "/redirect/r1", fetchdef.(["redirect", "manual"]))
353
+ assert merr == nil
354
+ assert S.getprop(manual, "status") == 301
355
+ after
356
+ :gen_tcp.close(listen)
357
+ end
358
+ end
359
+
299
360
  # Nothing listens on port 9: a request the guard let through fails there.
300
361
  test "fetcher refuses a non-GET under the GET-only guard" do
301
362
  c = ProjectName.new(S.jm(["base", "http://127.0.0.1:9"]))
@@ -3,7 +3,10 @@ package sdktest
3
3
  import (
4
4
  "errors"
5
5
  "fmt"
6
+ "net/http"
7
+ "net/http/httptest"
6
8
  "strings"
9
+ "sync"
7
10
  "testing"
8
11
 
9
12
  sdk "GOMODULE"
@@ -332,6 +335,63 @@ func TestPrimaryUtility(t *testing.T) {
332
335
  })
333
336
 
334
337
  // Nothing listens on port 9: a request the guard let through fails there.
338
+ // A Django route answers its slashless form with a relative Location. The
339
+ // transport follows each hop, and answers a "manual" fetch with the 3xx.
340
+ t.Run("fetcher-redirect", func(t *testing.T) {
341
+ var mu sync.Mutex
342
+ seen := []string{}
343
+ moved := map[string]struct {
344
+ code int
345
+ to string
346
+ }{"/redirect/r1": {301, "/redirect/r1/"}, "/redirect/r1/": {308, "done"}}
347
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
348
+ mu.Lock()
349
+ seen = append(seen, r.URL.Path)
350
+ mu.Unlock()
351
+ if hop, ok := moved[r.URL.Path]; ok {
352
+ w.Header().Set("Location", hop.to)
353
+ w.WriteHeader(hop.code)
354
+ return
355
+ }
356
+ if r.URL.Path != "/redirect/r1/done" {
357
+ w.WriteHeader(404)
358
+ return
359
+ }
360
+ w.Header().Set("Content-Type", "application/json")
361
+ fmt.Fprint(w, `{"id":"r1"}`)
362
+ }))
363
+ defer server.Close()
364
+
365
+ liveClient := sdk.NewProjectNameSDK(map[string]any{"base": server.URL})
366
+ liveUtility := liveClient.GetUtility()
367
+ ctx := liveUtility.MakeContext(map[string]any{
368
+ "opname": "load",
369
+ "client": liveClient,
370
+ "utility": liveUtility,
371
+ }, nil)
372
+
373
+ res, err := liveUtility.Fetcher(ctx, server.URL+"/redirect/r1", map[string]any{"method": "GET", "headers": map[string]any{}})
374
+ resmap, _ := res.(map[string]any)
375
+ if err != nil || resmap["status"] != 200 {
376
+ t.Fatalf("expected the redirect followed to a 200, got: %v %v", res, err)
377
+ }
378
+ if body := resmap["json"].(func() any)(); vs.GetProp(body, "id") != "r1" {
379
+ t.Errorf("unexpected body: %v", body)
380
+ }
381
+ mu.Lock()
382
+ sent := strings.Join(seen, " ")
383
+ mu.Unlock()
384
+ if sent != "/redirect/r1 /redirect/r1/ /redirect/r1/done" {
385
+ t.Errorf("unexpected requests: %v", sent)
386
+ }
387
+
388
+ res, err = liveUtility.Fetcher(ctx, server.URL+"/redirect/r1",
389
+ map[string]any{"method": "GET", "headers": map[string]any{}, "redirect": "manual"})
390
+ if resmap, _ = res.(map[string]any); err != nil || resmap["status"] != 301 {
391
+ t.Errorf("expected a manual redirect answered by its 301, got: %v %v", res, err)
392
+ }
393
+ })
394
+
335
395
  t.Run("fetcher-getonly-guard", func(t *testing.T) {
336
396
  liveClient := sdk.NewProjectNameSDK(map[string]any{"base": "http://127.0.0.1:9"})
337
397
  liveUtility := liveClient.GetUtility()
@@ -43,15 +43,26 @@ func clientFor(fetchdef map[string]any) *http.Client {
43
43
  }
44
44
 
45
45
  // A shallow copy shares the pooled Transport; only CheckRedirect differs.
46
+ policy := *client
47
+ policy.CheckRedirect = followRedirect
46
48
  if redirect, ok := fetchdef["redirect"].(string); ok && redirect == "manual" {
47
- manual := *client
48
- manual.CheckRedirect = func(req *http.Request, via []*http.Request) error {
49
+ policy.CheckRedirect = func(req *http.Request, via []*http.Request) error {
49
50
  return http.ErrUseLastResponse
50
51
  }
51
- client = &manual
52
52
  }
53
53
 
54
- return client
54
+ return &policy
55
+ }
56
+
57
+ const maxRedirects = 5
58
+
59
+ // Each redirect passes the GET-only guard before it is sent; past
60
+ // maxRedirects hops the last 3xx is the answer.
61
+ func followRedirect(req *http.Request, via []*http.Request) error {
62
+ if len(via) > maxRedirects {
63
+ return http.ErrUseLastResponse
64
+ }
65
+ return getOnlyRefusal(req.URL.String(), req.Method)
55
66
  }
56
67
 
57
68
  const getOnlyEnv = "VOXGIG_GETONLY_GUARD"
@@ -27,9 +27,10 @@ func makeUrlUtil(ctx *core.Context) (string, error) {
27
27
  url := vs.Join([]any{spec.Base, spec.Prefix, spec.Path, spec.Suffix}, "/", true)
28
28
  resmatch := map[string]any{}
29
29
 
30
- // A route the definition ends with a slash keeps it, for a Django REST server,
31
- // and a host with no path takes /, or luasocket reads a query as the host.
32
- if orig, _ := vs.GetProp(ctx.Point, "orig").(string); strings.HasSuffix(orig, "/") &&
30
+ // A route ending in a slash keeps it, as defined or as passed to direct(), for
31
+ // Django, and a host with no path takes /, or luasocket reads a query as the host.
32
+ orig, _ := vs.GetProp(ctx.Point, "orig").(string)
33
+ if (strings.HasSuffix(orig, "/") || strings.HasSuffix(spec.Path, "/")) &&
33
34
  spec.Suffix == "" && !strings.HasSuffix(url, "/") {
34
35
  url += "/"
35
36
  }
@@ -414,6 +414,53 @@ public class PrimaryUtilityTest {
414
414
  }
415
415
  }
416
416
 
417
+ // A Django route answers its slashless form with a relative Location. The
418
+ // transport follows each hop, and answers a "manual" fetch with the 3xx.
419
+ @Test
420
+ @SuppressWarnings("unchecked")
421
+ public void fetcherRedirect() throws Exception {
422
+ List<String> seen = java.util.Collections.synchronizedList(new ArrayList<>());
423
+ Map<String, Object[]> moved = Map.of(
424
+ "/redirect/r1", new Object[] {301, "/redirect/r1/"}, "/redirect/r1/", new Object[] {308, "done"});
425
+ com.sun.net.httpserver.HttpServer server = com.sun.net.httpserver.HttpServer.create(
426
+ new java.net.InetSocketAddress("127.0.0.1", 0), 0);
427
+ server.createContext("/", (exchange) -> {
428
+ String path = exchange.getRequestURI().getRawPath();
429
+ seen.add(path);
430
+ Object[] hop = moved.get(path);
431
+ byte[] body = "/redirect/r1/done".equals(path) ? "{\"id\":\"r1\"}".getBytes() : new byte[0];
432
+ if (hop != null) {
433
+ exchange.getResponseHeaders().set("Location", (String) hop[1]);
434
+ }
435
+ exchange.getResponseHeaders().set("Content-Type", "application/json");
436
+ exchange.sendResponseHeaders(hop != null ? (int) hop[0] : 0 < body.length ? 200 : 404,
437
+ 0 < body.length ? body.length : -1);
438
+ exchange.getResponseBody().write(body);
439
+ exchange.close();
440
+ });
441
+ server.start();
442
+ String base = "http://127.0.0.1:" + server.getAddress().getPort();
443
+ try {
444
+ ProjectNameSDK liveClient = new ProjectNameSDK(fhMap("base", base));
445
+ Utility liveUtility = liveClient.getUtility();
446
+ Context ctx = liveUtility.makeContext.apply(fhMap(
447
+ "opname", "load", "client", liveClient, "utility", liveUtility), null);
448
+
449
+ Map<String, Object> res = (Map<String, Object>) liveUtility.fetcher.fetch(ctx, base + "/redirect/r1",
450
+ fhMap("method", "GET", "headers", new LinkedHashMap<>()));
451
+ assertEquals(200, res.get("status"));
452
+ assertEquals("{\"id\":\"r1\"}", res.get("body"));
453
+ assertEquals(List.of("/redirect/r1", "/redirect/r1/", "/redirect/r1/done"), seen);
454
+
455
+ Map<String, Object> manual = (Map<String, Object>) liveUtility.fetcher.fetch(ctx,
456
+ base + "/redirect/r1", fhMap("method", "GET", "headers", new LinkedHashMap<>(), "redirect", "manual"));
457
+ assertEquals(301, manual.get("status"));
458
+ }
459
+ finally {
460
+ server.stop(0);
461
+ }
462
+ }
463
+
417
464
  // Nothing listens on port 9: a request the guard let through fails there.
418
465
  // A JVM cannot set its own environment, so the probe runs in a child JVM.
419
466
  @Test
@@ -37,11 +37,12 @@ final class MakeUrl {
37
37
  joinParts.add(spec.suffix);
38
38
  String url = Struct.join(joinParts, "/", true);
39
39
 
40
- // A route the definition ends with a slash keeps it, for a Django REST server,
41
- // and a host with no path takes /, or luasocket reads a query as the host.
40
+ // A route ending in a slash keeps it, as defined or as passed to direct(), for
41
+ // Django, and a host with no path takes /, or luasocket reads a query as the host.
42
42
  Object orig = ctx.point == null ? null : Struct.getprop(ctx.point, "orig", null);
43
- if (orig instanceof String && ((String) orig).endsWith("/") &&
44
- (spec.suffix == null || spec.suffix.isEmpty()) && !url.endsWith("/")) {
43
+ boolean slashed = (orig instanceof String && ((String) orig).endsWith("/")) ||
44
+ (spec.path != null && spec.path.endsWith("/"));
45
+ if (slashed && (spec.suffix == null || spec.suffix.isEmpty()) && !url.endsWith("/")) {
45
46
  url = url + "/";
46
47
  }
47
48
  int authority = url.indexOf("://");
@@ -20,10 +20,12 @@ function makeUrl(ctx) {
20
20
 
21
21
  let url = join([spec.base, spec.prefix, spec.path, spec.suffix], '/', true)
22
22
 
23
- // A route the definition ends with a slash keeps it, for a Django REST server,
24
- // and a host with no path takes /, or luasocket reads a query as the host.
23
+ // A route ending in a slash keeps it, as defined or as passed to direct(), for
24
+ // Django, and a host with no path takes /, or luasocket reads a query as the host.
25
25
  const orig = ctx.point && ctx.point.orig
26
- if ('string' === typeof orig && orig.endsWith('/') && !spec.suffix && !url.endsWith('/')) {
26
+ const slashed = ('string' === typeof orig && orig.endsWith('/')) ||
27
+ ('string' === typeof spec.path && spec.path.endsWith('/'))
28
+ if (slashed && !spec.suffix && !url.endsWith('/')) {
27
29
  url += '/'
28
30
  }
29
31
  const authority = url.indexOf('://')
@@ -127,10 +127,11 @@ function assertLiveReport(report) {
127
127
  }
128
128
  }
129
129
  // An account with no record for a step to read skips in either mode, as
130
- // does a run that leaves out every step.
130
+ // does a run that leaves out every step, or has none to run.
131
131
  function settleLiveReport(report, settle = {}) {
132
- if (0 < report.planned && report.excluded === report.planned && null != settle.t) {
133
- return settle.t.skip('Live coverage incomplete: ' + liveSummary(report));
132
+ if (report.excluded === report.planned && null != settle.t) {
133
+ return settle.t.skip('Live coverage incomplete: ' +
134
+ (0 === report.planned ? 'the flow has no step to run' : liveSummary(report)));
134
135
  }
135
136
  if (liveIncomplete(report)) {
136
137
  if (false !== settle.strict || null == settle.t)
@@ -2,6 +2,7 @@
2
2
  const { test, describe, before } = require('node:test')
3
3
  const { equal, deepStrictEqual, ok } = require('node:assert')
4
4
  const assert = require('node:assert')
5
+ const Http = require('node:http')
5
6
 
6
7
  const {
7
8
  makeRunner,
@@ -527,6 +528,45 @@ describe('PrimaryUtility', async () => {
527
528
  })
528
529
 
529
530
 
531
+ // A Django route answers its slashless form with a relative Location. The
532
+ // transport follows each hop, and answers a "manual" fetch with the 3xx.
533
+ test('fetcher-redirect', async () => {
534
+ const seen = []
535
+ const moved = {
536
+ '/redirect/r1': [301, '/redirect/r1/'],
537
+ '/redirect/r1/': [308, 'done'],
538
+ }
539
+ const server = Http.createServer((req, res) => {
540
+ seen.push(req.url)
541
+ const to = moved[req.url]
542
+ const done = '/redirect/r1/done' === req.url
543
+ res.writeHead(to ? to[0] : done ? 200 : 404, to ? { location: to[1], connection: 'close' } :
544
+ { 'content-type': 'application/json', connection: 'close' })
545
+ res.end(done ? '{"id":"r1"}' : '')
546
+ })
547
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve()))
548
+ const base = 'http://127.0.0.1:' + server.address().port
549
+ try {
550
+ const liveClient = new SDK({ base })
551
+ const liveUtility = liveClient.utility()
552
+ const ctx = liveUtility.makeContext({ opname: 'load' }, liveClient._rootctx)
553
+ ctx.client = liveClient
554
+
555
+ const res = await liveUtility.fetcher(ctx, base + '/redirect/r1', { method: 'GET', headers: {} })
556
+ equal(res.status, 200)
557
+ deepStrictEqual(await res.json(), { id: 'r1' })
558
+ deepStrictEqual(seen, ['/redirect/r1', '/redirect/r1/', '/redirect/r1/done'])
559
+
560
+ const manual = await liveUtility.fetcher(ctx, base + '/redirect/r1',
561
+ { method: 'GET', headers: {}, redirect: 'manual' })
562
+ equal(manual.status, 301)
563
+ }
564
+ finally {
565
+ server.close()
566
+ }
567
+ })
568
+
569
+
530
570
  test('makeError-no-throw', () => {
531
571
  const ctx = makeFullCtx()
532
572
  ctx.ctrl.throw = false
@@ -407,6 +407,47 @@ class PrimaryUtilityTest {
407
407
  }
408
408
  }
409
409
 
410
+ // A Django route answers its slashless form with a relative Location. The
411
+ // transport follows each hop, and answers a "manual" fetch with the 3xx.
412
+ @Test
413
+ fun fetcherRedirect() {
414
+ val seen = java.util.Collections.synchronizedList(mutableListOf<String>())
415
+ val moved = mapOf("/redirect/r1" to (301 to "/redirect/r1/"), "/redirect/r1/" to (308 to "done"))
416
+ val server = com.sun.net.httpserver.HttpServer.create(java.net.InetSocketAddress("127.0.0.1", 0), 0)
417
+ server.createContext("/") { exchange ->
418
+ val path = exchange.requestURI.rawPath
419
+ seen.add(path)
420
+ val hop = moved[path]
421
+ val body = if (path == "/redirect/r1/done") "{\"id\":\"r1\"}".toByteArray() else ByteArray(0)
422
+ if (hop != null) exchange.responseHeaders.set("Location", hop.second)
423
+ exchange.responseHeaders.set("Content-Type", "application/json")
424
+ exchange.sendResponseHeaders(hop?.first ?: if (body.isNotEmpty()) 200 else 404,
425
+ if (body.isNotEmpty()) body.size.toLong() else -1L)
426
+ exchange.responseBody.write(body)
427
+ exchange.close()
428
+ }
429
+ server.start()
430
+ val base = "http://127.0.0.1:" + server.address.port
431
+ try {
432
+ val liveClient = ProjectNameSDK(fhMap("base", base))
433
+ val liveUtility = liveClient.getUtility()
434
+ val ctx = liveUtility.makeContext(
435
+ fhMap("opname", "load", "client", liveClient, "utility", liveUtility), null)
436
+
437
+ val res = liveUtility.fetcher(ctx, "$base/redirect/r1",
438
+ fhMap("method", "GET", "headers", linkedMapOf<String, Any?>())) as Map<*, *>
439
+ assertEquals(200, res["status"])
440
+ assertEquals("{\"id\":\"r1\"}", res["body"])
441
+ assertEquals(listOf("/redirect/r1", "/redirect/r1/", "/redirect/r1/done"), seen.toList())
442
+
443
+ val manual = liveUtility.fetcher(ctx, "$base/redirect/r1",
444
+ fhMap("method", "GET", "headers", linkedMapOf<String, Any?>(), "redirect", "manual")) as Map<*, *>
445
+ assertEquals(301, manual["status"])
446
+ } finally {
447
+ server.stop(0)
448
+ }
449
+ }
450
+
410
451
  // Nothing listens on port 9: a request the guard let through fails there.
411
452
  // A JVM cannot set its own environment, so the probe runs in a child JVM.
412
453
  @Test
@@ -114,11 +114,12 @@ fun makeUrl(ctx: Context): String {
114
114
  joinParts.add(spec.suffix)
115
115
  var url = Struct.join(joinParts, "/", true)
116
116
 
117
- // A route the definition ends with a slash keeps it, for a Django REST server,
118
- // and a host with no path takes /, or luasocket reads a query as the host.
117
+ // A route ending in a slash keeps it, as defined or as passed to direct(), for
118
+ // Django, and a host with no path takes /, or luasocket reads a query as the host.
119
119
  val point = ctx.point
120
120
  val orig = if (point == null) null else Struct.getprop(point, "orig", null)
121
- if (orig is String && orig.endsWith("/") && spec.suffix.isEmpty() && !url.endsWith("/")) {
121
+ val slashed = (orig is String && orig.endsWith("/")) || spec.path.endsWith("/")
122
+ if (slashed && spec.suffix.isEmpty() && !url.endsWith("/")) {
122
123
  url += "/"
123
124
  }
124
125
  val authority = url.indexOf("://")
@@ -504,6 +504,67 @@ describe("PrimaryUtility", function()
504
504
  end)
505
505
 
506
506
 
507
+ -- A Django route answers its slashless form with a relative Location. The
508
+ -- transport follows each hop, and answers a "manual" fetch with the 3xx.
509
+ -- Lua has no threads, so the server is a second interpreter.
510
+ local redirect_server = [[
511
+ local socket = require("socket")
512
+ local server = assert(socket.bind("127.0.0.1", 0))
513
+ server:settimeout(20)
514
+ io.stdout:write(select(2, server:getsockname()), "\n")
515
+ io.stdout:flush()
516
+ local moved = { ["/redirect/r1"] = { 301, "/redirect/r1/" }, ["/redirect/r1/"] = { 308, "done" } }
517
+ for _ = 1, 4 do
518
+ local sock = server:accept()
519
+ if not sock then break end
520
+ sock:settimeout(20)
521
+ local path = string.match(sock:receive("*l") or "", "^%S+ (%S+)") or ""
522
+ repeat local line = sock:receive("*l") until line == nil or line == ""
523
+ io.stdout:write(path, "\n")
524
+ local hop = moved[path]
525
+ local body = path == "/redirect/r1/done" and '{"id":"r1"}' or ""
526
+ sock:send("HTTP/1.1 " .. (hop and hop[1] or (body == "" and 404 or 200)) .. " X\r\n" ..
527
+ (hop and ("Location: " .. hop[2] .. "\r\n") or "") .. "Content-Type: application/json\r\n" ..
528
+ "Content-Length: " .. #body .. "\r\nConnection: close\r\n\r\n" .. body)
529
+ sock:close()
530
+ end
531
+ ]]
532
+
533
+ local has_socket = pcall(require, "socket.http")
534
+ ;(has_socket and it or pending)("fetcher-redirect", function()
535
+ local first = 0
536
+ while arg and arg[first - 1] ~= nil do first = first - 1 end
537
+ local lua = arg and first < 0 and arg[first] or "lua"
538
+ local script = os.tmpname()
539
+ local f = assert(io.open(script, "w"))
540
+ f:write(string.format("package.path = %q\npackage.cpath = %q\n", package.path, package.cpath), redirect_server)
541
+ f:close()
542
+ local child = assert(io.popen(string.format("%q %q", lua, script)))
543
+ local base = "http://127.0.0.1:" .. assert(child:read("*l"))
544
+
545
+ local live_client = sdk.new({ base = base })
546
+ local live_utility = live_client:get_utility()
547
+ local ctx = live_utility.make_context({
548
+ opname = "load",
549
+ client = live_client,
550
+ utility = live_utility,
551
+ }, nil)
552
+ local res, err = live_utility.fetcher(ctx, base .. "/redirect/r1", { method = "GET", headers = {} })
553
+ local manual, merr = live_utility.fetcher(ctx, base .. "/redirect/r1",
554
+ { method = "GET", headers = {}, redirect = "manual" })
555
+ local seen = child:read("*a")
556
+ child:close()
557
+ os.remove(script)
558
+
559
+ assert.is_nil(err)
560
+ assert.are.equal(200, res.status)
561
+ assert.are.same({ id = "r1" }, res.json())
562
+ assert.are.equal("/redirect/r1\n/redirect/r1/\n/redirect/r1/done\n/redirect/r1\n", seen)
563
+ assert.is_nil(merr)
564
+ assert.are.equal(301, manual.status)
565
+ end)
566
+
567
+
507
568
  -- Nothing listens on port 9: a request the guard let through fails there.
508
569
  -- Lua cannot set its own environment, so the test answers for os.getenv.
509
570
  it("fetcher-getonly-guard", function()