@encore.dev/sdk 2.0.0-beta.13 → 2.0.0-beta.15

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 (56) hide show
  1. package/README.md +48 -4
  2. package/config/config.test.ts +47 -13
  3. package/config/secrets.ts +6 -2
  4. package/cron/mod.test.ts +12 -0
  5. package/cron/mod.ts +18 -2
  6. package/dist/config/secrets.d.ts +4 -2
  7. package/dist/config/secrets.d.ts.map +1 -1
  8. package/dist/config/secrets.js +3 -0
  9. package/dist/config/secrets.js.map +1 -1
  10. package/dist/cron/mod.d.ts +17 -2
  11. package/dist/cron/mod.d.ts.map +1 -1
  12. package/dist/cron/mod.js +3 -2
  13. package/dist/cron/mod.js.map +1 -1
  14. package/dist/internal/otel/http.d.ts +4 -2
  15. package/dist/internal/otel/http.d.ts.map +1 -1
  16. package/dist/internal/otel/http.js +32 -5
  17. package/dist/internal/otel/http.js.map +1 -1
  18. package/dist/internal/runtime/napi/napi.cjs +6 -5
  19. package/dist/internal/runtime/napi/napi.d.cts +48 -13
  20. package/dist/redaction/mod.d.ts +62 -0
  21. package/dist/redaction/mod.d.ts.map +1 -0
  22. package/dist/redaction/mod.js +102 -0
  23. package/dist/redaction/mod.js.map +1 -0
  24. package/dist/storage/objects/bucket.d.ts +78 -22
  25. package/dist/storage/objects/bucket.d.ts.map +1 -1
  26. package/dist/storage/objects/bucket.js +95 -42
  27. package/dist/storage/objects/bucket.js.map +1 -1
  28. package/dist/storage/objects/mod.d.ts +1 -1
  29. package/dist/storage/objects/mod.d.ts.map +1 -1
  30. package/dist/storage/objects/mod.js.map +1 -1
  31. package/dist/storage/objects/refs.d.ts +2 -5
  32. package/dist/storage/objects/refs.d.ts.map +1 -1
  33. package/dist/storage/objects/refs.js.map +1 -1
  34. package/dist/tracing/http.d.ts +2 -1
  35. package/dist/tracing/http.d.ts.map +1 -1
  36. package/dist/tracing/http.js +2 -1
  37. package/dist/tracing/http.js.map +1 -1
  38. package/dist/tracing/node.d.ts.map +1 -1
  39. package/dist/tracing/node.js +1 -1
  40. package/dist/tracing/node.js.map +1 -1
  41. package/dist/tsconfig.build.tsbuildinfo +1 -1
  42. package/internal/otel/http.test.ts +50 -0
  43. package/internal/otel/http.ts +40 -5
  44. package/internal/runtime/napi/napi.cjs +6 -5
  45. package/internal/runtime/napi/napi.d.cts +48 -13
  46. package/package.json +6 -1
  47. package/redaction/bridge.test.ts +99 -0
  48. package/redaction/mod.test.ts +188 -0
  49. package/redaction/mod.ts +226 -0
  50. package/storage/objects/bucket.test.ts +168 -16
  51. package/storage/objects/bucket.ts +181 -62
  52. package/storage/objects/mod.ts +1 -0
  53. package/storage/objects/refs.ts +2 -5
  54. package/tracing/http.ts +2 -1
  55. package/tracing/native.test.ts +158 -8
  56. package/tracing/node.ts +1 -0
@@ -214,7 +214,13 @@ export class Bucket
214
214
  if (entry === null) {
215
215
  break;
216
216
  }
217
- yield entry;
217
+ yield {
218
+ name: entry.name,
219
+ size: entry.size,
220
+ etag: entry.etag,
221
+ lastModified: toDate(entry.lastModified),
222
+ isPrefix: entry.isPrefix,
223
+ };
218
224
  }
219
225
  } finally {
220
226
  iter.markDone();
@@ -315,10 +321,10 @@ export class Bucket
315
321
 
316
322
  /**
317
323
  * Uploads an object only if the bucket still holds the given revision of
318
- * it, as `attrs`, `upload`, `updateAttrs` or a listing returned it, and
319
- * throws `PreconditionFailed` otherwise, also if the object no longer
320
- * exists. This makes read-modify-write safe against concurrent writers.
321
- * A missing revision throws `InvalidArgument`.
324
+ * it, as a download, `attrs`, `upload`, `updateAttrs` or a listing
325
+ * returned it, and throws `PreconditionFailed` otherwise, also if the
326
+ * object no longer exists. This makes read-modify-write safe against
327
+ * concurrent writers. A missing revision throws `InvalidArgument`.
322
328
  *
323
329
  * `data` is bytes or a stream, as `upload` and `uploadStream` take.
324
330
  *
@@ -433,48 +439,24 @@ export class Bucket
433
439
  }
434
440
 
435
441
  /**
436
- * Downloads an object from the bucket and returns its contents.
437
- */
438
- async download(name: string, options?: DownloadOptions): Promise<Buffer> {
439
- const source = activeCtxBytes();
440
- const impl = this.impl.object(name);
441
- const res = await impl.downloadAll(downloadOptions(options), source);
442
- return unwrapErr(res);
443
- }
444
-
445
- /**
446
- * Downloads an object from the bucket as a Web `ReadableStream`, read
447
- * from the provider as the consumer reads it. A missing object throws
448
- * here, before any bytes. Cancelling the stream stops the download.
442
+ * Downloads an object from the bucket. It resolves once the provider has
443
+ * answered, before any of the object's bytes: a missing object, or a
444
+ * range outside it, throws here. The `Download` says what the provider
445
+ * said of the object, and gives its contents whole (`bytes`) or as they
446
+ * arrive (`stream`).
449
447
  *
450
- * In Node.js, `Readable.fromWeb` converts it to a Node.js stream.
448
+ * ```ts
449
+ * const d = await uploads.download("state.json");
450
+ * const state = JSON.parse((await d.bytes()).toString());
451
+ * // Written only if nobody else has since it was read.
452
+ * await uploads.uploadIfMatch("state.json", next(state), d.revision);
453
+ * ```
451
454
  */
452
- async downloadStream(
453
- name: string,
454
- options?: DownloadOptions,
455
- ): Promise<ReadableStream<Uint8Array>> {
455
+ async download(name: string, options?: DownloadOptions): Promise<Download> {
456
456
  const source = activeCtxBytes();
457
457
  const impl = this.impl.object(name);
458
- const stream = unwrapErr(
459
- await impl.downloadStream(downloadOptions(options), source),
460
- );
461
- return new ReadableStream<Uint8Array>(
462
- {
463
- async pull(controller) {
464
- const chunk = unwrapErr(await stream.next());
465
- if (chunk === null) {
466
- controller.close();
467
- } else {
468
- controller.enqueue(chunk);
469
- }
470
- },
471
- async cancel() {
472
- await stream.close();
473
- },
474
- },
475
- // Read ahead of the consumer by nothing.
476
- {highWaterMark: 0},
477
- );
458
+ const res = await impl.download(downloadOptions(options), source);
459
+ return new NativeDownload(unwrapErr(res));
478
460
  }
479
461
 
480
462
  /**
@@ -492,10 +474,10 @@ export class Bucket
492
474
 
493
475
  /**
494
476
  * Removes an object only if the bucket still holds the given revision of
495
- * it, as `attrs`, `upload`, `updateAttrs` or a listing returned it, and
496
- * throws `PreconditionFailed` otherwise, also if the object no longer
497
- * exists. It compares the latest version, so there is no `version` to
498
- * remove. A missing revision throws `InvalidArgument`.
477
+ * it, as a download, `attrs`, `upload`, `updateAttrs` or a listing
478
+ * returned it, and throws `PreconditionFailed` otherwise, also if the
479
+ * object no longer exists. It compares the latest version, so there is no
480
+ * `version` to remove. A missing revision throws `InvalidArgument`.
499
481
  *
500
482
  * The match compares the object's contents, not its attributes:
501
483
  * `updateAttrs` doesn't break it.
@@ -632,7 +614,84 @@ function uploadOptions(
632
614
  function downloadOptions(
633
615
  options: DownloadOptions | undefined,
634
616
  ): runtime.DownloadOptions | undefined {
635
- return options && {version: options.version, range: options.range};
617
+ return options && {version: options.version, range: byteRange(options.range)};
618
+ }
619
+
620
+ function byteRange(
621
+ range: ByteRange | undefined,
622
+ ): runtime.ByteRange | undefined {
623
+ if (range === undefined) {
624
+ return undefined;
625
+ }
626
+ // What the types forbid, plain JavaScript can pass.
627
+ if (range.last !== undefined) {
628
+ if (range.offset !== undefined || range.length !== undefined) {
629
+ throw new InvalidArgument(
630
+ 'a byte range is an offset, with or without a length, or the last bytes: not both',
631
+ );
632
+ }
633
+ return {last: range.last};
634
+ }
635
+ if (typeof range.offset !== 'number') {
636
+ throw new InvalidArgument(
637
+ 'a byte range needs an offset, or `last` for the last bytes',
638
+ );
639
+ }
640
+ return {offset: range.offset, length: range.length};
641
+ }
642
+
643
+ /** The `Download` of the native runtime's download. */
644
+ class NativeDownload implements Download {
645
+ readonly revision: Revision;
646
+ readonly size: number;
647
+ readonly contentType?: string;
648
+ readonly lastModified?: Date;
649
+ private read = false;
650
+
651
+ constructor(private readonly impl: runtime.Download) {
652
+ const info = impl.info;
653
+ this.revision = {etag: info.etag, version: info.version};
654
+ this.size = info.size;
655
+ this.contentType = info.contentType;
656
+ this.lastModified = toDate(info.lastModified);
657
+ }
658
+
659
+ async bytes(): Promise<Buffer> {
660
+ this.take('bytes');
661
+ return unwrapErr(await this.impl.bytes());
662
+ }
663
+
664
+ stream(): ReadableStream<Uint8Array> {
665
+ this.take('stream');
666
+ const impl = this.impl;
667
+ return new ReadableStream<Uint8Array>(
668
+ {
669
+ async pull(controller) {
670
+ const chunk = unwrapErr(await impl.next());
671
+ if (chunk === null) {
672
+ controller.close();
673
+ } else {
674
+ controller.enqueue(chunk);
675
+ }
676
+ },
677
+ async cancel() {
678
+ await impl.close();
679
+ },
680
+ },
681
+ // Read ahead of the consumer by nothing.
682
+ {highWaterMark: 0},
683
+ );
684
+ }
685
+
686
+ /** The contents are read once: the bytes are not kept. */
687
+ private take(method: string): void {
688
+ if (this.read) {
689
+ throw new InvalidArgument(
690
+ `${method}: the download's contents were already read`,
691
+ );
692
+ }
693
+ this.read = true;
694
+ }
636
695
  }
637
696
 
638
697
  function toRevision(rev: Revision | undefined): runtime.Revision | undefined {
@@ -647,7 +706,7 @@ function toRevision(rev: Revision | undefined): runtime.Revision | undefined {
647
706
  function requiredRevision(method: string, rev: Revision): runtime.Revision {
648
707
  if (rev == null || typeof rev.etag !== 'string') {
649
708
  throw new InvalidArgument(
650
- `${method} needs the revision to match: the attributes attrs, upload or updateAttrs returned`,
709
+ `${method} needs the revision to match: a download's revision, or the attributes attrs, upload or updateAttrs returned`,
651
710
  );
652
711
  }
653
712
  return {etag: rev.etag, version: rev.version};
@@ -750,18 +809,33 @@ export interface DeleteOptions {
750
809
  }
751
810
 
752
811
  /**
753
- * A contiguous byte range within an object.
812
+ * A contiguous byte range within an object: `length` bytes from `offset`,
813
+ * or the object's last bytes.
754
814
  */
755
- export interface ByteRange {
756
- /** The zero-based index of the first byte to read. */
757
- offset: number;
758
-
759
- /**
760
- * The number of bytes to read.
761
- * Defaults to reading to the end of the object if unset.
762
- */
763
- length?: number;
764
- }
815
+ export type ByteRange =
816
+ | {
817
+ /** The zero-based index of the first byte to read. */
818
+ offset: number;
819
+
820
+ /**
821
+ * The number of bytes to read.
822
+ * Defaults to reading to the end of the object if unset.
823
+ */
824
+ length?: number;
825
+
826
+ last?: never;
827
+ }
828
+ | {
829
+ /**
830
+ * Read the object's last `last` bytes, however long it is; all of it,
831
+ * if it is shorter. The download's `size` says how long the object
832
+ * is, and so where in it the bytes are.
833
+ */
834
+ last: number;
835
+
836
+ offset?: never;
837
+ length?: never;
838
+ };
765
839
 
766
840
  /**
767
841
  * Options for downloading an object from a bucket.
@@ -777,7 +851,8 @@ export interface DownloadOptions {
777
851
 
778
852
  /**
779
853
  * Download only the given byte range of the object, instead of the whole
780
- * object. The returned Buffer contains just the requested bytes.
854
+ * object. The download's contents are just the requested bytes; its
855
+ * `size` is still the whole object's.
781
856
  *
782
857
  * Throws InvalidArgument if the range is empty or lies beyond the end
783
858
  * of the object.
@@ -785,10 +860,52 @@ export interface DownloadOptions {
785
860
  range?: ByteRange;
786
861
  }
787
862
 
863
+ /**
864
+ * A download under way, as `download` returns it: what the provider said of
865
+ * the object when it answered, and the object's contents, which are read
866
+ * once, whole or as they arrive.
867
+ *
868
+ * What it says is less than `attrs` does: it is what every provider sends
869
+ * with an object's bytes.
870
+ *
871
+ * A download whose contents are never read keeps its connection open until
872
+ * it is garbage collected. To give one up, cancel its stream:
873
+ * `await d.stream().cancel()`.
874
+ */
875
+ export interface Download {
876
+ /**
877
+ * The revision the contents are of. Pass it to `uploadIfMatch` or
878
+ * `removeIfMatch` to write or remove the object only if it is still what
879
+ * was read.
880
+ */
881
+ readonly revision: Revision;
882
+ /** The size of the whole object in bytes, also when a range is read. */
883
+ readonly size: number;
884
+ readonly contentType?: string;
885
+ /** When the object last changed, if the provider said. */
886
+ readonly lastModified?: Date;
887
+
888
+ /**
889
+ * The contents, in one piece. Throws `InvalidArgument` if they were
890
+ * already read.
891
+ */
892
+ bytes(): Promise<Buffer>;
893
+
894
+ /**
895
+ * The contents as a Web `ReadableStream`, read from the provider as the
896
+ * consumer reads it. Cancelling the stream stops the download. Throws
897
+ * `InvalidArgument` if the contents were already read.
898
+ *
899
+ * In Node.js, `Readable.fromWeb` converts it to a Node.js stream.
900
+ */
901
+ stream(): ReadableStream<Uint8Array>;
902
+ }
903
+
788
904
  /**
789
905
  * One revision of an object: what `uploadIfMatch`, `removeIfMatch` and the
790
906
  * `ifMatch` precondition of `updateAttrs` compare. `ObjectAttrs` is one, so
791
- * the attributes an operation returned can be passed as they are.
907
+ * the attributes an operation returned can be passed as they are, and a
908
+ * download's `revision` is one, of the contents it reads.
792
909
  */
793
910
  export interface Revision {
794
911
  etag: string;
@@ -840,6 +957,8 @@ export interface ListEntry {
840
957
  name: string;
841
958
  size: number;
842
959
  etag: string;
960
+ /** When the object was written. Unset for a common prefix. */
961
+ lastModified?: Date;
843
962
  /**
844
963
  * Whether the entry is a common prefix of a listing with a delimiter,
845
964
  * rather than an object. A prefix has size 0 and an empty etag.
@@ -18,6 +18,7 @@ export type {
18
18
  SignedUploadUrl,
19
19
  AttrsOptions,
20
20
  ByteRange,
21
+ Download,
21
22
  DownloadOptions,
22
23
  ExistsOptions,
23
24
  ListOptions,
@@ -1,6 +1,7 @@
1
1
  import type {
2
2
  AttrsOptions,
3
3
  DeleteOptions,
4
+ Download,
4
5
  DownloadOptions,
5
6
  DownloadUrlOptions,
6
7
  ExistsOptions,
@@ -45,11 +46,7 @@ export abstract class SignedUploader extends BucketPerms {
45
46
  }
46
47
 
47
48
  export abstract class Downloader extends BucketPerms {
48
- abstract download(name: string, options?: DownloadOptions): Promise<Buffer>;
49
- abstract downloadStream(
50
- name: string,
51
- options?: DownloadOptions,
52
- ): Promise<ReadableStream<Uint8Array>>;
49
+ abstract download(name: string, options?: DownloadOptions): Promise<Download>;
53
50
  }
54
51
 
55
52
  export abstract class SignedDownloader extends BucketPerms {
package/tracing/http.ts CHANGED
@@ -17,7 +17,8 @@ const headersGetter: TextMapGetter<Headers> = {
17
17
  * No OpenTelemetry globals are registered.
18
18
  *
19
19
  * The span ends when the handler produces a Response, not when its streaming
20
- * body completes. Framework-specific code can add route-based span naming.
20
+ * body completes. Uses the deployed route template when it resolves; does not
21
+ * infer routes from the Request.
21
22
  */
22
23
  export function instrumentHTTP<This, Args extends unknown[]>(
23
24
  handler: (
@@ -35,7 +35,7 @@ test('public spans reach the native OTLP destination with parents, errors, and l
35
35
  return new Response("placed");
36
36
  }))(new Request("http://shop.test:8080/reset/PATH_SECRET?token=QUERY_SECRET", {
37
37
  method: "POST",
38
- headers: {traceparent: "00-0123456789abcdef0123456789abcdef-1234567890abcdef-01"},
38
+ headers: {traceparent: "00-0123456789abcdef0123456789abcdef-1234567890abcdef-01", "user-agent": "AGENT_SECRET"},
39
39
  }));
40
40
  for (const [url, status, method] of [
41
41
  ["https://[::1]:8443/fail?token=private", 500, "GET"],
@@ -75,7 +75,9 @@ test('public spans reach the native OTLP destination with parents, errors, and l
75
75
  stdout += new TextDecoder().decode(value);
76
76
  if (stdout.includes('ready')) break;
77
77
  }
78
- expect(await proc.exited).toBe(0);
78
+ const exitCode = await proc.exited;
79
+ const stderr = await new Response(proc.stderr).text();
80
+ if (exitCode !== 0) throw new Error(stderr);
79
81
  expect(stdout).toContain('ready');
80
82
  const exported = received.flatMap(body =>
81
83
  fields(body, 1).flatMap(rs => fields(rs, 2).flatMap(ss => fields(ss, 2))),
@@ -87,7 +89,7 @@ test('public spans reach the native OTLP destination with parents, errors, and l
87
89
  expect([...named.keys()].sort()).toEqual([
88
90
  'GET',
89
91
  'HTTP',
90
- 'POST',
92
+ 'POST /reset/{id}',
91
93
  'QUERY',
92
94
  'order_request',
93
95
  'rejected_order',
@@ -108,6 +110,10 @@ test('public spans reach the native OTLP destination with parents, errors, and l
108
110
  'url.scheme': 'http',
109
111
  'server.address': 'shop.test',
110
112
  'server.port': 8080,
113
+ 'http.route': '/reset/{id}',
114
+ 'url.path': '/reset/REDACTED',
115
+ 'url.query': 'token=REDACTED',
116
+ 'user_agent.original': '[REDACTED]',
111
117
  });
112
118
  const failure = http.find(
113
119
  span => attributes(span)['http.response.status_code'] === 500,
@@ -147,14 +153,18 @@ test('public spans reach the native OTLP destination with parents, errors, and l
147
153
  });
148
154
  for (const span of http) {
149
155
  const recorded = attributes(span);
150
- expect(recorded['url.path']).toBeUndefined();
156
+ if (span !== request) expect(recorded['url.path']).toBeUndefined();
151
157
  expect(recorded['url.full']).toBeUndefined();
152
- expect(recorded['url.query']).toBeUndefined();
158
+ if (span !== request) {
159
+ expect(recorded['url.query']).toBeUndefined();
160
+ expect(recorded['user_agent.original']).toBeUndefined();
161
+ }
153
162
  expect(JSON.stringify(recorded)).not.toContain('private');
154
163
  }
155
164
  for (const body of received) {
156
165
  expect(body.includes(Buffer.from('PATH_SECRET'))).toBe(false);
157
166
  expect(body.includes(Buffer.from('QUERY_SECRET'))).toBe(false);
167
+ expect(body.includes(Buffer.from('AGENT_SECRET'))).toBe(false);
158
168
  }
159
169
  const outer = named.get('order_request')!;
160
170
  for (const name of ['validate_order', 'rejected_order']) {
@@ -167,7 +177,6 @@ test('public spans reach the native OTLP destination with parents, errors, and l
167
177
  expect(fields(fields(failed, 15)[0]!, 3)[0]).toEqual(Buffer.from([2]));
168
178
  const event = fields(failed, 11)[0]!;
169
179
  expect(fields(event, 2)[0]!.toString()).toBe('exception');
170
- const stderr = await new Response(proc.stderr).text();
171
180
  const record = stderr
172
181
  .split('\n')
173
182
  .filter(line => line.startsWith('{'))
@@ -185,6 +194,127 @@ test('public spans reach the native OTLP destination with parents, errors, and l
185
194
  }
186
195
  }, 15_000);
187
196
 
197
+ const routes: RouteSpec[] = [
198
+ ['/orders/{schema_id}', 'GET', 'schema_id'],
199
+ ['/graphql', 'POST'],
200
+ ['/orders.Orders/Get', 'POST'],
201
+ ];
202
+
203
+ for (const runtime of ['node', 'bun']) {
204
+ for (const schema of [true, false]) {
205
+ test(`${runtime} exports protocol SERVER spans (${schema ? 'with' : 'without'} schema)`, async () => {
206
+ const executable =
207
+ runtime === 'bun' ? process.execPath : Bun.which('node');
208
+ if (!executable)
209
+ throw new Error('Node is required for the SDK protocol matrix');
210
+ const received: Buffer[] = [];
211
+ const receiver = Bun.serve({
212
+ hostname: '127.0.0.1',
213
+ port: 0,
214
+ async fetch(request) {
215
+ expect(new URL(request.url).pathname).toBe('/v1/traces');
216
+ expect(request.method).toBe('POST');
217
+ expect(request.headers.get('content-type')).toBe(
218
+ 'application/x-protobuf',
219
+ );
220
+ received.push(Buffer.from(await request.arrayBuffer()));
221
+ return new Response(new Uint8Array(), {
222
+ headers: {'content-type': 'application/x-protobuf'},
223
+ });
224
+ },
225
+ });
226
+ const proc = Bun.spawn({
227
+ cmd: [executable, join(import.meta.dir, 'protocol.fixture.mjs')],
228
+ cwd: import.meta.dir,
229
+ env: {
230
+ ...process.env,
231
+ NODE_ENV: 'production',
232
+ ENCORE_RUNTIME_CONFIG: runtimeConfig(
233
+ `http://127.0.0.1:${receiver.port}`,
234
+ schema ? routes : [],
235
+ ),
236
+ OTEL_BSP_SCHEDULE_DELAY: '60000',
237
+ },
238
+ stdout: 'pipe',
239
+ stderr: 'pipe',
240
+ });
241
+ const timeout = setTimeout(() => proc.kill('SIGKILL'), 10_000);
242
+ try {
243
+ const [exitCode, stdout, stderr] = await Promise.all([
244
+ proc.exited,
245
+ new Response(proc.stdout).text(),
246
+ new Response(proc.stderr).text(),
247
+ ]);
248
+ if (exitCode !== 0)
249
+ throw new Error(`${runtime} fixture exited ${exitCode}: ${stderr}`);
250
+ const requests: Record<string, {port: number; traceId: string}> =
251
+ JSON.parse(stdout);
252
+ const exported = received.flatMap(body =>
253
+ fields(body, 1).flatMap(rs =>
254
+ fields(rs, 2).flatMap(ss => fields(ss, 2)),
255
+ ),
256
+ );
257
+ const cases = [
258
+ ['Node GET', 'GET', '/orders/{schema_id}', '/orders/REDACTED'],
259
+ ['Node GraphQL', 'POST', '/graphql', '/graphql'],
260
+ ['Node gRPC', 'POST', '/orders.Orders/Get', '/orders.Orders/Get'],
261
+ ];
262
+ if (runtime === 'bun')
263
+ cases.push(
264
+ ['Bun Fetch GET', 'GET', '/orders/{schema_id}', '/orders/REDACTED'],
265
+ ['Bun Fetch GraphQL', 'POST', '/graphql', '/graphql'],
266
+ );
267
+ expect(exported).toHaveLength(cases.length);
268
+ for (const [row, method, template, path] of cases) {
269
+ const {port, traceId} = requests[row]!;
270
+ const matches = exported.filter(
271
+ span => fields(span, 1)[0]?.toString('hex') === traceId,
272
+ );
273
+ expect(matches).toHaveLength(1);
274
+ const [span] = matches;
275
+ expect(fields(span!, 6)[0]?.[0]).toBe(2); // SERVER
276
+ expect(fields(span!, 5)[0]?.toString()).toBe(
277
+ schema ? `${method} ${template}` : method,
278
+ );
279
+ const attrs = attributes(span!);
280
+ expect(attrs['http.route']).toBe(schema ? template : undefined);
281
+ expect(attrs['url.path']).toBe(schema ? path : undefined);
282
+ expect(
283
+ Object.keys(attrs).filter(key =>
284
+ /^(rpc|graphql|encore)\./.test(key),
285
+ ),
286
+ ).toEqual([]);
287
+ expect(attrs).toEqual({
288
+ 'http.request.method': method,
289
+ 'http.response.status_code': 200,
290
+ 'url.scheme': 'http',
291
+ // HTTP/2 supplies :authority, not the Host the node:http adapter reads.
292
+ 'server.address': row === 'Node gRPC' ? 'localhost' : '127.0.0.1',
293
+ 'server.port': row === 'Node gRPC' ? 80 : port,
294
+ ...(schema
295
+ ? {
296
+ 'http.route': template,
297
+ 'url.path': path,
298
+ 'user_agent.original': '[REDACTED]',
299
+ ...(method === 'GET' ? {'url.query': 'token=REDACTED'} : {}),
300
+ }
301
+ : {}),
302
+ });
303
+ }
304
+ for (const body of received) {
305
+ expect(body.toString()).not.toMatch(
306
+ /\/orders\/synthetic|GetOrder|QUERY_SECRET|AGENT_SECRET/,
307
+ );
308
+ }
309
+ } finally {
310
+ clearTimeout(timeout);
311
+ proc.kill();
312
+ receiver.stop(true);
313
+ }
314
+ }, 15_000);
315
+ }
316
+ }
317
+
188
318
  /** Raw values of protobuf field `want`. */
189
319
  function fields(buf: Buffer, want: number): Buffer[] {
190
320
  const out: Buffer[] = [];
@@ -247,8 +377,13 @@ function attributes(span: Buffer): Record<string, string | number> {
247
377
  );
248
378
  }
249
379
 
380
+ type RouteSpec = [template: string, method: string, param?: string];
381
+
250
382
  /** RuntimeConfig hosting shop with an explicit TracingProvider OTLP/HTTP sink. */
251
- function runtimeConfig(endpoint: string): string {
383
+ function runtimeConfig(
384
+ endpoint: string,
385
+ routes: RouteSpec[] = [['/reset/{id}', 'POST', 'id']],
386
+ ): string {
252
387
  const varint = (n: number): number[] => {
253
388
  const bytes: number[] = [];
254
389
  do {
@@ -268,7 +403,22 @@ function runtimeConfig(endpoint: string): string {
268
403
  // RuntimeConfig{environment=1, deployment=3}; Deployment{hosted_services=5,
269
404
  // observability=7}; Observability{tracing=1}; TracingProvider{rid=1, otlp_http=12}.
270
405
  const tracing = [...str(1, 'traces'), ...msg(12, str(1, endpoint))];
271
- const deployment = [...msg(5, str(1, 'shop')), ...msg(7, msg(1, tracing))];
406
+ const hosted = str(1, 'shop');
407
+ for (const [template, method, param] of routes) {
408
+ const policy = [
409
+ ...str(3, 'user-agent'),
410
+ ...str(5, 'token'),
411
+ ...(param ? str(6, param) : []),
412
+ ];
413
+ const endpointPolicy = [...str(1, 'endpoint'), ...msg(3, policy)];
414
+ const route = [
415
+ ...str(1, template),
416
+ ...str(2, method),
417
+ ...msg(3, endpointPolicy),
418
+ ];
419
+ hosted.push(...msg(4, route));
420
+ }
421
+ const deployment = [...msg(5, hosted), ...msg(7, msg(1, tracing))];
272
422
  return Buffer.from([
273
423
  ...msg(1, str(1, 'app')),
274
424
  ...msg(3, deployment),
package/tracing/node.ts CHANGED
@@ -43,6 +43,7 @@ export function instrumentHTTP<This = Server, Result = void>(
43
43
  headersGetter,
44
44
  request.method || '',
45
45
  url,
46
+ request.url ?? '/',
46
47
  );
47
48
  const restoreRequest = bindEmitter(request, context);
48
49
  const restoreResponse = bindEmitter(response, context);