@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
@@ -24,6 +24,7 @@ import {
24
24
  jsOptProp, envName, envToken, liveStrict, liveStrictNote,
25
25
  jsKey,
26
26
  pointParts,
27
+ pointSlash,
27
28
  pointPlaceholders,
28
29
  pointIsGraphql,
29
30
  hasLiveScenarios,
@@ -34,6 +35,7 @@ import {
34
35
  liveEntity,
35
36
  liveGetOnlyReason, LIVE_GETONLY_ENV,
36
37
  liveDirectGetOnly, liveExcludedLines, liveExcludedSummary,
38
+ liveDirectDiscovery, liveIdKey,
37
39
  } from '@voxgig/sdkgen'
38
40
 
39
41
 
@@ -300,7 +302,7 @@ function generateDirectLoad(model: Model, entity: ModelEntity) {
300
302
  }
301
303
 
302
304
  const allLoadParams = loadPoint.g?.params || []
303
- const loadPath = normalizePathParams(pointParts(loadPoint), allLoadParams, loadPoint.r?.param)
305
+ const loadPath = normalizePathParams(pointParts(loadPoint), allLoadParams, loadPoint.r?.param) + pointSlash(loadPoint)
304
306
 
305
307
  // Some upstream OpenAPI specs declare a parameter as `in: path` even when
306
308
  // that path has no `{name}` placeholder for it. Only path params that
@@ -331,25 +333,13 @@ function generateDirectLoad(model: Model, entity: ModelEntity) {
331
333
  const listPoint = null == listOp?.points ? undefined :
332
334
  primaryPoint(listOp.points, entity.name, 'list')
333
335
  const listParams = listPoint?.g?.params || []
334
- const listPath = listPoint ? normalizePathParams(pointParts(listPoint), listParams, listPoint.r?.param) : ''
335
- const hasList = null != listPoint
336
-
337
- const ancestorParams = loadParams.filter((p: any) => p.n !== 'id')
336
+ const listPath = listPoint ? normalizePathParams(pointParts(listPoint), listParams, listPoint.r?.param) + pointSlash(listPoint) : ''
337
+ const discovery = liveDirectDiscovery(entity, loadParams, listPoint)
338
338
 
339
339
  const paramAsserts = loadParams.map((p: any, i: number) =>
340
340
  ' assert(calls[0].url.includes(\'direct0' + (i + 1) + '\'))\n').join('')
341
341
 
342
- const liveListParams = listParams.map((p: any) => {
343
- const key = p.n === 'id'
344
- ? entity.name + '01'
345
- : p.n.replace(/_id$/, '') + '01'
346
- return { name: p.n, key }
347
- })
348
-
349
- const liveAncestorParams = ancestorParams.map((p: any) => {
350
- const key = p.n.replace(/_id$/, '') + '01'
351
- return { name: p.n, key }
352
- })
342
+ const liveListParams = listParams.map((p: any) => ({ name: p.n, key: liveIdKey(entity.name, p.n) }))
353
343
 
354
344
  const liveQueryPrefix = liveQueryLines ? liveQueryLines + '\n' : ''
355
345
 
@@ -377,19 +367,14 @@ ${liveQueryPrefix}${exampleLines}
377
367
  ${loadParams.map((p: any, i: number) => ` ${jsProp('params', p.n)} = 'direct0${i + 1}'`).join('\n')}
378
368
  }`
379
369
  }
380
- else if (hasList) {
381
- // List-bootstrap pattern picks the load id from a list call's response,
382
- // so the test can succeed without ENTID env var. Ancestor params, if
383
- // any, still need ENTID overrides because the list call itself can need
384
- // them embedded.
370
+ else if (null != discovery) {
371
+ const liveAncestorParams = loadParams.filter((p: any) => p.n !== discovery.param)
372
+ .map((p: any) => ({ name: p.n, key: liveIdKey(entity.name, p.n) }))
385
373
  liveIdKeys = [...new Set([...liveListParams, ...liveAncestorParams].map((lp: any) => lp.key))]
386
374
  const listParamLines = liveListParams.map((lp: any) =>
387
375
  ` ${lp.name}: setup.idmap['${lp.key}'],`).join('\n')
388
376
  const ancestorParamLines = liveAncestorParams.map((lp: any) =>
389
377
  ` ${jsProp('params', lp.name)} = setup.idmap['${lp.key}']`).join('\n')
390
- const idParamName = loadParams.find((p: any) => p.n === 'id')
391
- ? 'id'
392
- : (loadParams[0]?.n ?? 'id')
393
378
 
394
379
  liveParamsBlock = ` if (setup.live) {
395
380
  ${liveQueryPrefix} const listResult: any = await client.direct({
@@ -409,21 +394,19 @@ ${listParamLines}
409
394
  if (0 === listArr.length) {
410
395
  return void liveEmpty(t, 'The account has no ${entity.name} record to load')
411
396
  }
412
- const candidateId = ${jsOptProp('listArr[0]', idParamName)} ?? listArr[0]?.id
397
+ const candidateId = ${jsOptProp('listArr[0]', discovery.field)}
413
398
  if (null == candidateId) {
414
399
  return void liveMiss(t, LIVE_STRICT, 'Live load blocked: discovery returned no usable identity')
415
400
  }
416
- ${jsProp('params', idParamName)} = candidateId
401
+ ${jsProp('params', discovery.param)} = candidateId
417
402
  ${ancestorParamLines}
418
403
  } else {
419
404
  ${loadParams.map((p: any, i: number) => ` ${jsProp('params', p.n)} = 'direct0${i + 1}'`).join('\n')}
420
405
  }`
421
406
  } else if (hasLiveQuery || loadParams.length > 0) {
422
- // With no examples and no list to discover from, the ids come from the
423
- // *_ENTID variable; without them the test is blocked.
424
- const liveLoadParams = loadParams.map((p: any) => ({
425
- name: p.n, key: p.n === 'id' ? entity.name + '01' : p.n.replace(/_id$/, '') + '01',
426
- }))
407
+ // A path parameter no listed record gives comes from *_ENTID and the
408
+ // examples merged into it; without them the test is blocked.
409
+ const liveLoadParams = loadParams.map((p: any) => ({ name: p.n, key: liveIdKey(entity.name, p.n) }))
427
410
  liveIdKeys = liveLoadParams.map((lp: any) => lp.key)
428
411
  liveParamsBlock = ` if (setup.live) {
429
412
  ${liveQueryPrefix}${liveLoadParams.map((lp: any) =>
@@ -488,7 +471,7 @@ function generateDirectList(model: Model, entity: ModelEntity) {
488
471
  }
489
472
 
490
473
  const listParams = listPoint.g?.params || []
491
- const listPath = normalizePathParams(pointParts(listPoint), listParams, listPoint.r?.param)
474
+ const listPath = normalizePathParams(pointParts(listPoint), listParams, listPoint.r?.param) + pointSlash(listPoint)
492
475
 
493
476
  const liveQueryLines = liveQueryLinesTs(listPoint)
494
477
 
@@ -36,19 +36,20 @@ import {
36
36
  serverVarEnv,
37
37
  serverVariables,
38
38
  isHttpBasicAuth,
39
- entityDataIdField, envName, envToken,
39
+ entityDataIdField, entityRecordIdField, envName, envToken,
40
40
  jsKey,
41
41
  jsProp,
42
42
  hasLiveScenarios,
43
43
  liveStrict,
44
44
  liveStrictNote,
45
45
  liveEntity,
46
- liveGetOnly,
46
+ liveGates,
47
47
  liveFlowRoutes,
48
48
  flowLoadRoute,
49
49
  flowLoadReadsRecord,
50
50
  LIVE_GETONLY_ENV,
51
51
  } from '@voxgig/sdkgen'
52
+ import type { LiveGate } from '@voxgig/sdkgen'
52
53
 
53
54
 
54
55
  import {
@@ -56,11 +57,16 @@ import {
56
57
  } from './utility_ts'
57
58
 
58
59
 
59
- // The steps a GET-only live run leaves out, for the live harness.
60
- function getOnlyArg(entity: any, flow: any): string {
61
- const plan = liveGetOnly(entity, flow)
62
- return null == plan ? '' : `, 'TRUE' === process.env.${LIVE_GETONLY_ENV} ? ${JSON.stringify(
63
- Object.fromEntries(plan.excluded.map(({ id, reason }) => [id, reason])))} : {}`
60
+ // The steps a live run leaves out, for the live harness: a GET-only run's
61
+ // when the guard is set, else those any live run leaves out.
62
+ function excludedArg(entity: any, flow: any): string {
63
+ const gates = liveGates(entity, flow)
64
+ const getOnly = gates.find((gate) => gate.getOnly)
65
+ const any = gates.find((gate) => !gate.getOnly)
66
+ const map = (gate?: LiveGate) => JSON.stringify(
67
+ Object.fromEntries((gate?.plan.excluded || []).map(({ id, reason }) => [id, reason])))
68
+ return null != getOnly ? `, 'TRUE' === process.env.${LIVE_GETONLY_ENV} ? ${map(getOnly)} : ${map(any)}` :
69
+ 0 < (any?.plan.excluded.length || 0) ? ', ' + map(any) : ''
64
70
  }
65
71
 
66
72
 
@@ -161,7 +167,7 @@ function basicSetup(extra?: any) {
161
167
 
162
168
  // TODO: need a xlang JSON parse utility in voxgig/struct with better error msgs
163
169
  const entityData = JSON.parse(entityDataSource)
164
-
170
+ ${fixtureIdentity(entity)}
165
171
  options.entity = entityData.existing
166
172
 
167
173
  let client = ${model.Name}SDK.test(options, extra)
@@ -254,7 +260,7 @@ function basicSetup(extra?: any) {
254
260
  ${hasLiveScenarios(model) ? `if (live) { t.skip('Covered by live operation scenarios'); return }` : ''}
255
261
  const setup = basicSetup()
256
262
  if (setup.live) {
257
- return runLiveEntity(setup, ${JSON.stringify(liveEntity(ctx$, entity))}, ${JSON.stringify(liveFlowRoutes(entity, basicflow))}, '${nom(entity, 'Name')}', ${JSON.stringify(liveFacts)}, { strict: LIVE_STRICT, t }${getOnlyArg(entity, basicflow)})
263
+ return runLiveEntity(setup, ${JSON.stringify(liveEntity(ctx$, entity))}, ${JSON.stringify(liveFlowRoutes(entity, basicflow))}, '${nom(entity, 'Name')}', ${JSON.stringify(liveFacts)}, { strict: LIVE_STRICT, t }${excludedArg(entity, basicflow)})
258
264
  }
259
265
  const client = setup.client
260
266
  const struct = setup.struct
@@ -343,7 +349,7 @@ const generateCreate: OpGen = (ctx, step, index) => {
343
349
  ${datavar} = (await ${entvar}.create(${datavar})).data()
344
350
  `)
345
351
  if (hasEntIdC) {
346
- Content(` assert(null != ${datavar}.id)
352
+ Content(` assert(null != ${rid(entity, datavar)})
347
353
  `)
348
354
  }
349
355
  else {
@@ -392,12 +398,12 @@ const generateList: OpGen = (ctx, step, index) => {
392
398
 
393
399
  if ('ItemExists' === validator.apply && hasRefData && hasDataId) {
394
400
  Content(`
395
- assert(!isempty(select(${listvar}, { id: ${validRef}_data.id })))
401
+ assert(!isempty(select(${listvar}, { ${jsKey(entityRecordIdField(entity))}: ${rid(entity, validRef + '_data')} })))
396
402
  `)
397
403
  }
398
404
  else if ('ItemNotExists' === validator.apply && hasRefData && hasDataId) {
399
405
  Content(`
400
- assert(isempty(select(${listvar}, { id: ${validRef}_data.id })))
406
+ assert(isempty(select(${listvar}, { ${jsKey(entityRecordIdField(entity))}: ${rid(entity, validRef + '_data')} })))
401
407
  `)
402
408
  }
403
409
  }
@@ -429,7 +435,7 @@ const generateUpdate: OpGen = (ctx, step, index) => {
429
435
  Content(` const ${datavar}: any = {}
430
436
  `)
431
437
  if (hasEntIdU) {
432
- Content(` ${datavar}.id = ${srcdatavar}.id
438
+ Content(` ${datavar}.id = ${rid(entity, srcdatavar)}
433
439
  `)
434
440
  }
435
441
 
@@ -459,7 +465,7 @@ const generateUpdate: OpGen = (ctx, step, index) => {
459
465
  const ${resdatavar} = (await ${entvar}.update(${datavar})).data()
460
466
  `)
461
467
  if (hasEntIdU) {
462
- Content(` assert(${resdatavar}.id === ${datavar}.id)
468
+ Content(` assert(${rid(entity, resdatavar)} === ${datavar}.id)
463
469
  `)
464
470
  }
465
471
  else {
@@ -536,7 +542,7 @@ const generateLoad: OpGen = (ctx, step, index) => {
536
542
  Content(` const ${matchvar}: any = {}
537
543
  `)
538
544
  if (hasEntId) {
539
- Content(` ${matchvar}.id = ${srcdatavar}.id
545
+ Content(` ${matchvar}.id = ${rid(entity, srcdatavar)}
540
546
  `)
541
547
  loadMatch(entity, step, matchvar, srcdatavar)
542
548
  }
@@ -545,7 +551,7 @@ const generateLoad: OpGen = (ctx, step, index) => {
545
551
  }
546
552
  if (hasEntId) {
547
553
  Content(` const ${datavar} = (await ${entvar}.load(${matchvar})).data()
548
- assert(${datavar}.id === ${srcdatavar}.id)
554
+ assert(${rid(entity, datavar)} === ${rid(entity, srcdatavar)})
549
555
  `)
550
556
  }
551
557
  else {
@@ -585,7 +591,7 @@ const generateRemove: OpGen = (ctx, step, index) => {
585
591
  // Always match the prior-created entity by id. The mock test feature
586
592
  // removes the first match in entmap, so without a specific id the
587
593
  // result depends on hash-sort order and flakes (see cheapshark).
588
- Content(` const ${matchvar}: any = { id: ${srcdatavar}.id }
594
+ Content(` const ${matchvar}: any = { id: ${rid(entity, srcdatavar)} }
589
595
  `)
590
596
  parentMatch(step, matchvar)
591
597
  Content(` await ${entvar}.remove(${matchvar})
@@ -593,6 +599,24 @@ const generateRemove: OpGen = (ctx, step, index) => {
593
599
  }
594
600
 
595
601
 
602
+ // The record field the entity's identity is read from, on a record.
603
+ function rid(entity: any, record: string): string {
604
+ return jsProp(record, entityRecordIdField(entity))
605
+ }
606
+
607
+
608
+ // The fixture keeps each record's key in `id`; an entity keeping its identity
609
+ // in another field reads the key from there too.
610
+ function fixtureIdentity(entity: any): string {
611
+ const field = entityRecordIdField(entity)
612
+ return 'id' === field ? '' : `
613
+ for (const rec of Object.values(entityData.existing?.[${JSON.stringify(entity.name)}] ?? {}) as any[]) {
614
+ if (null != rec?.id) ${jsProp('rec', field)} = rec.id
615
+ }
616
+ `
617
+ }
618
+
619
+
596
620
  // A child's route names its parents, and an entity no earlier step has
597
621
  // filled knows none of them, so the call itself gives each parent id.
598
622
  function parentMatch(step: any, matchvar: string) {
@@ -122,6 +122,20 @@ static void answer(int c) {
122
122
  return;
123
123
  }
124
124
 
125
+ // A Django route answers its slashless form with a relative Location.
126
+ if (0 == strcmp(target, "/redirect/r1")) {
127
+ say(c, "HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect/r1/\r\nContent-Length: 0\r\n\r\n");
128
+ return;
129
+ }
130
+ if (0 == strcmp(target, "/redirect/r1/")) {
131
+ say(c, "HTTP/1.1 308 Permanent Redirect\r\nLocation: done\r\nContent-Length: 0\r\n\r\n");
132
+ return;
133
+ }
134
+ if (0 == strcmp(target, "/redirect/r1/done")) {
135
+ reply(c, "200 OK", "application/json", "{\"id\":\"r1\"}");
136
+ return;
137
+ }
138
+
125
139
  // The last segment names the case, whatever prefix the API's config adds.
126
140
  char path[256];
127
141
  size_t plen = strcspn(target, "?");
@@ -390,6 +404,25 @@ int main(void) {
390
404
  CHECK(NULL == err && v_eq(getp(direct, "ok"), v_bool(true)), "a direct request goes live");
391
405
  CHECK_STR_EQ(get_str(getp(direct, "data"), "framing"), "length", "and reads the response");
392
406
 
407
+ // The fetcher follows each hop, relative Location and all, and answers a
408
+ // "manual" fetch with the 3xx.
409
+ Utility* util = sdk_get_utility(sdk);
410
+ CtxSpec cs;
411
+ memset(&cs, 0, sizeof(cs));
412
+ cs.opname = "load";
413
+ cs.client = sdk;
414
+ cs.utility = util;
415
+ Context* ctx = make_context_util(cs, NULL);
416
+ snprintf(url, sizeof(url), "%s/redirect/r1", base);
417
+ err = NULL;
418
+ res = utility_fetch(util, ctx, url, cmap(2, "method", v_str("GET"), "headers", v_map()), &err);
419
+ CHECK(NULL == err && 200 == to_int(getp(res, "status")), "a redirect is followed, hop by hop");
420
+ CHECK_STR_EQ(get_str(json_of(res), "id"), "r1", "to the route its Location names");
421
+ err = NULL;
422
+ res = utility_fetch(util, ctx, url, cmap(3, "method", v_str("GET"), "headers", v_map(),
423
+ "redirect", v_str("manual")), &err);
424
+ CHECK(NULL == err && 301 == to_int(getp(res, "status")), "a manual fetch is answered by the 301");
425
+
393
426
  kill(server, SIGKILL);
394
427
  waitpid(server, NULL, 0);
395
428
  TEST_SUMMARY("transport");
@@ -36,6 +36,156 @@ static PNError* getonly_refusal(Context* ctx, const char* fullurl, voxgig_value*
36
36
  return context_make_error(ctx, "fetch_getonly_block", buf);
37
37
  }
38
38
 
39
+ #define REDIRECT_MAX 5
40
+
41
+ static int same_text(const char* a, const char* b) {
42
+ for (; '\0' != *a && tolower((unsigned char)*a) == tolower((unsigned char)*b); a++, b++) {}
43
+ return tolower((unsigned char)*a) == tolower((unsigned char)*b);
44
+ }
45
+
46
+ // The Location resolved against the URL that answered with it (RFC 3986
47
+ // 5.2), or NULL when the base has no scheme. The caller frees it.
48
+ static char* resolve_location(const char* base, const char* raw) {
49
+ size_t n = 0, rlen = strlen(raw);
50
+ char* loc = (char*)malloc(rlen + 1);
51
+ for (size_t i = 0; i < rlen && '#' != raw[i]; i++) {
52
+ if (!isspace((unsigned char)raw[i])) loc[n++] = raw[i];
53
+ }
54
+ loc[n] = '\0';
55
+ size_t s = 0;
56
+ while (isalnum((unsigned char)loc[s]) || (0 < s && '\0' != loc[s] && NULL != strchr("+-.", loc[s]))) {
57
+ s++;
58
+ }
59
+ if (0 < s && isalpha((unsigned char)loc[0]) && ':' == loc[s]) return loc;
60
+
61
+ const char* sep = strstr(base, "://");
62
+ if (NULL == sep) {
63
+ free(loc);
64
+ return NULL;
65
+ }
66
+ const char* auth = sep + 3;
67
+ const char* path = auth + strcspn(auth, "/?#");
68
+ size_t plen = strcspn(path, "?#");
69
+ const char* query = '?' == path[plen] ? path + plen : "";
70
+ size_t qlen = strcspn(query, "#");
71
+ size_t cap = strlen(base) + n + 4;
72
+ char* out = (char*)malloc(cap);
73
+ if ('/' == loc[0] && '/' == loc[1]) {
74
+ snprintf(out, cap, "%.*s:%s", (int)(sep - base), base, loc);
75
+ free(loc);
76
+ return out;
77
+ }
78
+
79
+ const char* lq = strchr(loc, '?');
80
+ size_t lplen = NULL == lq ? n : (size_t)(lq - loc);
81
+ char* merged = (char*)malloc(cap);
82
+ if (0 == lplen) {
83
+ snprintf(merged, cap, "%.*s", 0 == plen ? 1 : (int)plen, 0 == plen ? "/" : path);
84
+ if (NULL == lq) lq = query;
85
+ } else if ('/' == loc[0]) {
86
+ snprintf(merged, cap, "%.*s", (int)lplen, loc);
87
+ } else {
88
+ size_t dir = plen;
89
+ while (0 < dir && '/' != path[dir - 1]) dir--;
90
+ snprintf(merged, cap, "%.*s%.*s", 0 == dir ? 1 : (int)dir, 0 == dir ? "/" : path,
91
+ (int)lplen, loc);
92
+ }
93
+ if (NULL == lq) lq = "";
94
+
95
+ size_t mlen = strlen(merged), count = 0;
96
+ const char** segs = (const char**)malloc(sizeof(char*) * (mlen + 2));
97
+ size_t* lens = (size_t*)malloc(sizeof(size_t) * (mlen + 2));
98
+ for (const char* p = merged;; ) {
99
+ size_t len = strcspn(p, "/");
100
+ if (2 == len && 0 == strncmp(p, "..", 2)) {
101
+ if (1 < count) count--;
102
+ } else if (!(1 == len && '.' == p[0])) {
103
+ segs[count] = p;
104
+ lens[count++] = len;
105
+ }
106
+ if ('\0' == p[len]) {
107
+ if ((1 == len && '.' == p[0]) || (2 == len && 0 == strncmp(p, "..", 2))) {
108
+ segs[count] = p + len;
109
+ lens[count++] = 0;
110
+ }
111
+ break;
112
+ }
113
+ p += len + 1;
114
+ }
115
+ size_t o = (size_t)snprintf(out, cap, "%.*s", (int)(path - base), base);
116
+ for (size_t i = 0; i < count; i++) {
117
+ o += (size_t)snprintf(out + o, cap - o, "%s%.*s", 0 == i ? "" : "/", (int)lens[i], segs[i]);
118
+ }
119
+ snprintf(out + o, cap - o, "%.*s", (int)(lq == query ? qlen : strlen(lq)), lq);
120
+ free(segs);
121
+ free(lens);
122
+ free(merged);
123
+ free(loc);
124
+ return out;
125
+ }
126
+
127
+ static int same_origin(const char* a, const char* b) {
128
+ const char* as = strstr(a, "://");
129
+ const char* bs = strstr(b, "://");
130
+ if (NULL == as || NULL == bs) return 0;
131
+ size_t alen = (size_t)(as - a) + 3 + strcspn(as + 3, "/?#");
132
+ size_t blen = (size_t)(bs - b) + 3 + strcspn(bs + 3, "/?#");
133
+ if (alen != blen) return 0;
134
+ for (size_t i = 0; i < alen; i++) {
135
+ if (tolower((unsigned char)a[i]) != tolower((unsigned char)b[i])) return 0;
136
+ }
137
+ return 1;
138
+ }
139
+
140
+ // The request as another origin may see it: without its credentials.
141
+ static voxgig_value* without_credentials(voxgig_value* fetchdef) {
142
+ voxgig_value* copy = voxgig_clone(fetchdef);
143
+ voxgig_value* headers = getp(copy, "headers");
144
+ if (voxgig_is_map(headers)) {
145
+ voxgig_map* hm = voxgig_as_map(headers);
146
+ voxgig_value* kept = cmap(0);
147
+ for (size_t i = 0; i < hm->len; i++) {
148
+ const char* name = hm->entries[i].key;
149
+ if (!same_text(name, "authorization") && !same_text(name, "cookie") &&
150
+ !same_text(name, "proxy-authorization")) {
151
+ setp(kept, name, hm->entries[i].value);
152
+ }
153
+ }
154
+ setp(copy, "headers", kept);
155
+ }
156
+ return copy;
157
+ }
158
+
159
+ // The default transport follows no redirect. A GET or HEAD follows one here,
160
+ // unless the fetch definition says "manual", each hop passing the GET-only
161
+ // guard first; past REDIRECT_MAX hops the last 3xx is the answer. Another
162
+ // origin is not sent the request's credentials.
163
+ static voxgig_value* follow_redirects(Context* ctx, const char* fullurl,
164
+ voxgig_value* fetchdef, PNError** err) {
165
+ const char* method = get_str(fetchdef, "method");
166
+ const char* redirect = get_str(fetchdef, "redirect");
167
+ int follow = (NULL == method || '\0' == method[0] || same_text(method, "GET") ||
168
+ same_text(method, "HEAD")) && !(NULL != redirect && 0 == strcmp(redirect, "manual"));
169
+ char* url = (char*)malloc(strlen(fullurl) + 1);
170
+ strcpy(url, fullurl);
171
+ for (int hops = 0;; hops++) {
172
+ *err = getonly_refusal(ctx, url, fetchdef);
173
+ voxgig_value* res = NULL != *err ? NULL : http_fetch(ctx, url, fetchdef, err);
174
+ const char* location = NULL == res ? NULL : get_str(getp(res, "headers"), "location");
175
+ int64_t status = NULL == res ? -1 : to_int(getp(res, "status"));
176
+ int moved = 301 == status || 302 == status || 303 == status || 307 == status || 308 == status;
177
+ char* next = follow && moved && NULL != location && hops < REDIRECT_MAX
178
+ ? resolve_location(url, location) : NULL;
179
+ if (NULL == next) {
180
+ free(url);
181
+ return res;
182
+ }
183
+ if (!same_origin(url, next)) fetchdef = without_credentials(fetchdef);
184
+ free(url);
185
+ url = next;
186
+ }
187
+ }
188
+
39
189
  voxgig_value* fetcher_util(Fetcher* self, Context* ctx, const char* fullurl,
40
190
  voxgig_value* fetchdef, PNError** err) {
41
191
  (void)self;
@@ -73,8 +223,7 @@ voxgig_value* fetcher_util(Fetcher* self, Context* ctx, const char* fullurl,
73
223
  voxgig_value* sys_fetch = getpath2(options, "system", "fetch");
74
224
 
75
225
  if (v_is_noval(sys_fetch) || v_is_null(sys_fetch)) {
76
- *err = getonly_refusal(ctx, fullurl, fetchdef);
77
- return NULL != *err ? NULL : http_fetch(ctx, fullurl, fetchdef, err);
226
+ return follow_redirects(ctx, fullurl, fetchdef, err);
78
227
  }
79
228
 
80
229
  if (voxgig_is_func(sys_fetch)) {
@@ -58,13 +58,15 @@ char* make_url_util(Context* ctx, PNError** err) {
58
58
  char* url = str_append(NULL, joined ? joined : "");
59
59
  free(joined);
60
60
 
61
- // A route the definition ends with a slash keeps it, for a Django REST server,
62
- // and a host with no path takes /, or luasocket reads a query as the host.
61
+ // A route ending in a slash keeps it, as defined or as passed to direct(), for
62
+ // Django, and a host with no path takes /, or luasocket reads a query as the host.
63
63
  voxgig_value* orig = getp(ctx->point, "orig");
64
- if (voxgig_is_string(orig) && (NULL == spec->suffix || '\0' == spec->suffix[0])) {
65
- const char* o = voxgig_as_string(orig);
66
- size_t olen = strlen(o), ulen = strlen(url);
67
- if (0 < olen && '/' == o[olen - 1] && (0 == ulen || '/' != url[ulen - 1])) {
64
+ if (NULL == spec->suffix || '\0' == spec->suffix[0]) {
65
+ const char* o = voxgig_is_string(orig) ? voxgig_as_string(orig) : "";
66
+ const char* p = NULL == spec->path ? "" : spec->path;
67
+ size_t olen = strlen(o), plen = strlen(p), ulen = strlen(url);
68
+ if (((0 < olen && '/' == o[olen - 1]) || (0 < plen && '/' == p[plen - 1])) &&
69
+ (0 == ulen || '/' != url[ulen - 1])) {
68
70
  url = str_append(url, "/");
69
71
  }
70
72
  }
@@ -1359,9 +1359,11 @@
1359
1359
  authquery (set (oget spec :authquery []))
1360
1360
  point (oget ctx :point)
1361
1361
  orig (when point (vs/getprop point "orig"))]
1362
- ;; A route the definition ends with a slash keeps it, for a Django REST server,
1363
- ;; and a host with no path takes /, or luasocket reads a query as the host.
1364
- (when (and (string? orig) (str/ends-with? orig "/") (empty? (str (oget spec :suffix)))
1362
+ ;; A route ending in a slash keeps it, as defined or as passed to direct(), for
1363
+ ;; Django, and a host with no path takes /, or luasocket reads a query as the host.
1364
+ (when (and (or (and (string? orig) (str/ends-with? orig "/"))
1365
+ (str/ends-with? (str (oget spec :path)) "/"))
1366
+ (empty? (str (oget spec :suffix)))
1365
1367
  (not (str/ends-with? @url "/")))
1366
1368
  (swap! url str "/"))
1367
1369
  (let [authority (str/index-of @url "://")]
@@ -1797,12 +1799,16 @@
1797
1799
 
1798
1800
  ;; java.net.http rather than HttpURLConnection, which refuses PATCH. HTTP/1.1,
1799
1801
  ;; as the vendored sekreto client: over cleartext, HTTP/2 opens with an h2c
1800
- ;; upgrade that holds the body back, and some servers refuse that request.
1801
- (def ^:private http-client
1802
- (delay (-> (HttpClient/newBuilder)
1803
- (.version HttpClient$Version/HTTP_1_1)
1804
- (.followRedirects HttpClient$Redirect/NORMAL)
1805
- (.build))))
1802
+ ;; upgrade that holds the body back, and some servers refuse that request. A
1803
+ ;; fetch definition whose redirect is "manual" gets every 3xx as its answer.
1804
+ (defn- http-client-for [redirect]
1805
+ (-> (HttpClient/newBuilder)
1806
+ (.version HttpClient$Version/HTTP_1_1)
1807
+ (.followRedirects redirect)
1808
+ (.build)))
1809
+
1810
+ (def ^:private http-client (delay (http-client-for HttpClient$Redirect/NORMAL)))
1811
+ (def ^:private manual-http-client (delay (http-client-for HttpClient$Redirect/NEVER)))
1806
1812
 
1807
1813
  (defn- body-publisher [body]
1808
1814
  (cond
@@ -1842,7 +1848,8 @@
1842
1848
  (let [ua (str "Mozilla/5.0 (compatible; " SDK-NAME "SDK/1.0)")]
1843
1849
  (.setHeader builder "User-Agent" ua)
1844
1850
  (vs/setprop headers "user-agent" ua)))
1845
- (let [resp (.send ^HttpClient @http-client (.build builder) (HttpResponse$BodyHandlers/ofByteArray))
1851
+ (let [client (if (= "manual" (vs/getprop fetchdef "redirect")) @manual-http-client @http-client)
1852
+ resp (.send ^HttpClient client (.build builder) (HttpResponse$BodyHandlers/ofByteArray))
1846
1853
  body (String. ^bytes (.body resp) "UTF-8")
1847
1854
  resp-headers (vs/jm)]
1848
1855
  (doseq [[k vlist] (.map (.headers resp))]
@@ -42,6 +42,42 @@
42
42
  (str (:code err) " " (:msg err) "\n")
43
43
  "sent\n"))))))
44
44
 
45
+ ;; A Django route answers its slashless form with a relative Location. The
46
+ ;; transport follows each hop, and answers a "manual" fetch with the 3xx.
47
+ (defn- redirect-check []
48
+ (let [seen (java.util.Collections/synchronizedList (java.util.ArrayList.))
49
+ moved {"/redirect/r1" [301 "/redirect/r1/"] "/redirect/r1/" [308 "done"]}
50
+ server (com.sun.net.httpserver.HttpServer/create (java.net.InetSocketAddress. "127.0.0.1" 0) 0)]
51
+ (.createContext server "/"
52
+ (reify com.sun.net.httpserver.HttpHandler
53
+ (handle [_ ex]
54
+ (let [path (.getRawPath (.getRequestURI ex))
55
+ [code to] (get moved path)
56
+ body (.getBytes (if (= path "/redirect/r1/done") "{\"id\":\"r1\"}" "") "UTF-8")
57
+ size (alength ^bytes body)]
58
+ (.add seen path)
59
+ (when to (.set (.getResponseHeaders ex) "Location" to))
60
+ (.set (.getResponseHeaders ex) "Content-Type" "application/json")
61
+ (.sendResponseHeaders ex (int (or code (if (pos? size) 200 404))) (long (if (pos? size) size -1)))
62
+ (.write (.getResponseBody ex) body)
63
+ (.close ex)))))
64
+ (.start server)
65
+ (try
66
+ (let [base (str "http://127.0.0.1:" (.getPort (.getAddress server)))
67
+ sdk (client/make-sdk (vs/jm "base" base))
68
+ ctx (make-ctx sdk "load")
69
+ fetch (fn [& kvs] ((core/uget ctx :fetcher) ctx (str base "/redirect/r1")
70
+ (apply vs/jm "method" "GET" "headers" (vs/jm) kvs)))
71
+ [res err] (fetch)
72
+ [manual merr] (fetch "redirect" "manual")]
73
+ (t/is-eq err nil "error")
74
+ (t/is-eq (mget res "status") 200 "status")
75
+ (t/is-eq (mget res "body") "{\"id\":\"r1\"}" "body")
76
+ (t/is-eq (vec seen) ["/redirect/r1" "/redirect/r1/" "/redirect/r1/done" "/redirect/r1"] "hops")
77
+ (t/is-eq merr nil "manual error")
78
+ (t/is-eq (mget manual "status") 301 "manual status"))
79
+ (finally (.stop server 0)))))
80
+
45
81
  ;; A JVM cannot set its own environment, so the probe runs in a child JVM.
46
82
  (defn- getonly-child []
47
83
  (let [pb (ProcessBuilder. ^java.util.List
@@ -69,6 +105,8 @@
69
105
  (t/is-true (clojure.string/ends-with? (clojure.string/trim out) "\nsent") out)
70
106
  (t/is-true (not (clojure.string/includes? out "GUARDKEY01")) out))))
71
107
 
108
+ (chk "fetcher-redirect" redirect-check)
109
+
72
110
  ;; ---- make-point ----
73
111
  (chk "point-rejects-disallowed-op"
74
112
  (fn [] (let [ctx (make-ctx sdk "nope")
@@ -664,11 +664,12 @@ inline std::string makeUrl(CtxPtr ctx) {
664
664
  Value joinParts = vlist({Value(spec->base), Value(spec->prefix), Value(spec->path), Value(spec->suffix)});
665
665
  std::string url = Struct::join(joinParts, "/", true);
666
666
 
667
- // A route the definition ends with a slash keeps it, for a Django REST server,
668
- // and a host with no path takes /, or luasocket reads a query as the host.
667
+ // A route ending in a slash keeps it, as defined or as passed to direct(), for
668
+ // Django, and a host with no path takes /, or luasocket reads a query as the host.
669
669
  Value orig = ctx->point.is_map() ? getp(ctx->point, "orig") : Value::undef();
670
- if (orig.is_string() && !orig.as_string().empty() && '/' == orig.as_string().back() &&
671
- spec->suffix.empty() && (url.empty() || '/' != url.back())) {
670
+ const bool slashed = (orig.is_string() && !orig.as_string().empty() && '/' == orig.as_string().back()) ||
671
+ (!spec->path.empty() && '/' == spec->path.back());
672
+ if (slashed && spec->suffix.empty() && (url.empty() || '/' != url.back())) {
672
673
  url += "/";
673
674
  }
674
675
  const size_t authority = url.find("://");