@encore.dev/sdk 2.0.0-beta.14 → 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
@@ -0,0 +1,226 @@
1
+ import {Buffer} from 'node:buffer';
2
+ import type {DescMethod} from '@bufbuild/protobuf';
3
+ import {RT} from '../internal/runtime/mod';
4
+
5
+ /** HTTP headers or gRPC metadata in wire form. gRPC binary values use base64. */
6
+ export type Headers = Iterable<readonly [name: string, value: string]>;
7
+
8
+ export interface RequestUrl {
9
+ readonly route: string | null;
10
+ /** Safe path; never substitute the original if null. */
11
+ readonly path: string | null;
12
+ /** Safe query without the leading question mark. */
13
+ readonly query: string | null;
14
+ }
15
+
16
+ export type Payload =
17
+ | {readonly kind: 'omit'}
18
+ | {
19
+ readonly kind: 'recorded';
20
+ readonly body: Uint8Array;
21
+ readonly truncated: boolean;
22
+ }
23
+ | {readonly kind: 'withheld'; readonly reason: string};
24
+
25
+ export interface HttpExchange {
26
+ readonly headers: Headers;
27
+ readonly body?: Uint8Array;
28
+ }
29
+
30
+ export interface SafeHttpExchange {
31
+ readonly headers: [string, string][];
32
+ readonly body?: Payload;
33
+ }
34
+
35
+ export interface GrpcRequest {
36
+ readonly metadata: Headers;
37
+ readonly message?: Uint8Array;
38
+ }
39
+
40
+ export interface GrpcResponse extends GrpcRequest {
41
+ readonly trailers?: Headers;
42
+ }
43
+
44
+ export interface SafeGrpcRequest {
45
+ readonly metadata: [string, string][];
46
+ readonly message?: Payload;
47
+ }
48
+
49
+ export interface SafeGrpcResponse extends SafeGrpcRequest {
50
+ readonly trailers?: [string, string][];
51
+ }
52
+
53
+ type HttpSpec = {kind: 'http'; method: string; target: string};
54
+ type GrpcSpec = {
55
+ kind: 'grpc';
56
+ service: string;
57
+ method: string;
58
+ client_streaming: boolean;
59
+ server_streaming: boolean;
60
+ };
61
+ type TopicSpec = {kind: 'topic'; name: string} & (
62
+ {operation: 'publish'} | {operation: 'delivery'; subscription: string}
63
+ );
64
+ type HeaderPairs = [string, string][];
65
+ type Spec =
66
+ | (HttpSpec & {operation: 'request_url'})
67
+ | (HttpSpec & {
68
+ operation: 'exchange';
69
+ response: boolean;
70
+ headers: HeaderPairs;
71
+ capture: boolean;
72
+ })
73
+ | (GrpcSpec & {
74
+ operation: 'exchange';
75
+ response: boolean;
76
+ metadata: HeaderPairs;
77
+ trailers: HeaderPairs;
78
+ capture: boolean;
79
+ })
80
+ | TopicSpec;
81
+ type EncodedPayload =
82
+ | Exclude<Payload, {kind: 'recorded'}>
83
+ | {kind: 'recorded'; body: string; truncated: boolean};
84
+ type Result =
85
+ | ({kind: 'request_url'} & RequestUrl)
86
+ | {kind: 'http'; headers: HeaderPairs; body: EncodedPayload | null}
87
+ | {
88
+ kind: 'grpc';
89
+ metadata: HeaderPairs;
90
+ message: EncodedPayload | null;
91
+ trailers: HeaderPairs;
92
+ }
93
+ | EncodedPayload;
94
+
95
+ function apply(spec: Spec, payload: Uint8Array = new Uint8Array()): Result {
96
+ return JSON.parse(
97
+ RT.redact(
98
+ JSON.stringify(spec),
99
+ Buffer.from(payload.buffer, payload.byteOffset, payload.byteLength),
100
+ ),
101
+ ) as Result;
102
+ }
103
+
104
+ function headerPairs(headers: Headers): HeaderPairs {
105
+ return Array.from(headers, ([name, value]) => [name, value]);
106
+ }
107
+
108
+ function payload(result: EncodedPayload): Payload {
109
+ switch (result.kind) {
110
+ case 'omit':
111
+ case 'withheld':
112
+ return result;
113
+ case 'recorded':
114
+ return {...result, body: Buffer.from(result.body, 'base64')};
115
+ default:
116
+ throw new Error('unexpected payload redaction result');
117
+ }
118
+ }
119
+
120
+ /** Applies the service's deployed policy to copies, without emitting telemetry. */
121
+ export class Redactor {
122
+ http(method: string, pathAndQuery: string) {
123
+ const spec = {kind: 'http', method, target: pathAndQuery} as const;
124
+ const exchange = (
125
+ response: boolean,
126
+ original: HttpExchange,
127
+ ): SafeHttpExchange => {
128
+ const result = apply(
129
+ {
130
+ ...spec,
131
+ operation: 'exchange',
132
+ response,
133
+ headers: headerPairs(original.headers),
134
+ capture: original.body !== undefined,
135
+ },
136
+ original.body,
137
+ );
138
+ if (result.kind !== 'http')
139
+ throw new Error('unexpected HTTP redaction result');
140
+ return {
141
+ headers: result.headers,
142
+ ...(result.body === null ? {} : {body: payload(result.body)}),
143
+ };
144
+ };
145
+ return {
146
+ requestUrl: (): RequestUrl => {
147
+ const result = apply({...spec, operation: 'request_url'});
148
+ if (result.kind !== 'request_url')
149
+ throw new Error('unexpected request URL redaction result');
150
+ return {route: result.route, path: result.path, query: result.query};
151
+ },
152
+ request: (original: HttpExchange) => exchange(false, original),
153
+ response: (original: HttpExchange) => exchange(true, original),
154
+ };
155
+ }
156
+
157
+ grpc(descriptor: DescMethod) {
158
+ const spec = {
159
+ kind: 'grpc',
160
+ service: descriptor.parent.typeName,
161
+ method: descriptor.name,
162
+ client_streaming:
163
+ descriptor.methodKind === 'client_streaming' ||
164
+ descriptor.methodKind === 'bidi_streaming',
165
+ server_streaming:
166
+ descriptor.methodKind === 'server_streaming' ||
167
+ descriptor.methodKind === 'bidi_streaming',
168
+ } as const;
169
+ const exchange = (
170
+ response: boolean,
171
+ original: GrpcResponse,
172
+ ): SafeGrpcResponse => {
173
+ const result = apply(
174
+ {
175
+ ...spec,
176
+ operation: 'exchange',
177
+ response,
178
+ metadata: headerPairs(original.metadata),
179
+ trailers: headerPairs(original.trailers ?? []),
180
+ capture: original.message !== undefined,
181
+ },
182
+ original.message,
183
+ );
184
+ if (result.kind !== 'grpc')
185
+ throw new Error('unexpected gRPC redaction result');
186
+ return {
187
+ metadata: result.metadata,
188
+ ...(result.message === null ? {} : {message: payload(result.message)}),
189
+ ...(original.trailers === undefined ? {} : {trailers: result.trailers}),
190
+ };
191
+ };
192
+ return {
193
+ request: (original: GrpcRequest): SafeGrpcRequest =>
194
+ exchange(false, original),
195
+ response: (original: GrpcResponse) => exchange(true, original),
196
+ };
197
+ }
198
+
199
+ topic(name: string) {
200
+ const redact = (spec: TopicSpec, original: Uint8Array): Payload => {
201
+ const result = apply(spec, original);
202
+ if (
203
+ result.kind !== 'omit' &&
204
+ result.kind !== 'withheld' &&
205
+ result.kind !== 'recorded'
206
+ )
207
+ throw new Error('unexpected payload redaction result');
208
+ return payload(result);
209
+ };
210
+ return {
211
+ /** Redact a publish payload using the topic's deployed policy. */
212
+ publish: (original: Uint8Array) =>
213
+ redact({kind: 'topic', name, operation: 'publish'}, original),
214
+ /** Redact a delivery payload using the subscription's deployed policy. */
215
+ delivery: (subscription: string, original: Uint8Array) =>
216
+ redact(
217
+ {kind: 'topic', name, operation: 'delivery', subscription},
218
+ original,
219
+ ),
220
+ };
221
+ }
222
+ }
223
+
224
+ export function redactor(): Redactor {
225
+ return new Redactor();
226
+ }
@@ -49,12 +49,27 @@ const uploadStream = mock((_options: unknown, _source: unknown): unknown => ({
49
49
  abort,
50
50
  }));
51
51
 
52
- // The native download stream: hands out `chunks` in turn.
52
+ // The native download: says `nativeInfo` of the object, and hands out
53
+ // `chunks` in turn, or all at once.
54
+ const nativeInfo = {
55
+ etag: 'etag-7',
56
+ version: '7',
57
+ size: 10,
58
+ contentType: 'text/plain',
59
+ lastModified: 1_730_000_000_000,
60
+ };
53
61
  let chunks: unknown[] = [];
54
62
  const next = mock(async () => chunks.shift() ?? null);
55
63
  const close = mock(async () => {});
56
- const downloadStream = mock(
64
+ const bytes = mock(async (): Promise<unknown> => {
65
+ const all = Buffer.concat(chunks as Buffer[]);
66
+ chunks = [];
67
+ return all;
68
+ });
69
+ const download = mock(
57
70
  async (_options: unknown, _source: unknown): Promise<unknown> => ({
71
+ info: nativeInfo,
72
+ bytes,
58
73
  next,
59
74
  close,
60
75
  }),
@@ -79,7 +94,7 @@ function nativeObject(bucket: string, name: string) {
79
94
  bucket,
80
95
  name,
81
96
  uploadStream,
82
- downloadStream,
97
+ download,
83
98
  updateAttrs,
84
99
  extendRetention,
85
100
  delete: remove,
@@ -133,7 +148,8 @@ beforeEach(() => {
133
148
  uploadStream,
134
149
  next,
135
150
  close,
136
- downloadStream,
151
+ bytes,
152
+ download,
137
153
  updateAttrs,
138
154
  extendRetention,
139
155
  remove,
@@ -348,34 +364,125 @@ test('an upload the provider refuses cancels the source stream', async () => {
348
364
  expect(finish).not.toHaveBeenCalled();
349
365
  });
350
366
 
351
- test('downloadStream yields the native chunks and cancelling it closes the native stream', async () => {
367
+ test('download says what the provider said of the object, and reads it whole', async () => {
352
368
  const bucket = new Bucket('uploads');
353
- chunks = [Buffer.from('one'), Buffer.from('two')];
354
- const body = await bucket.downloadStream('a', {
355
- range: {offset: 1, length: 5},
356
- });
357
- expect(downloadStream.mock.lastCall).toEqual([
358
- {version: undefined, range: {offset: 1, length: 5}},
369
+ chunks = [Buffer.from('0123'), Buffer.from('456789')];
370
+ const d = await bucket.download('a.txt', {version: '7'});
371
+ expect(download.mock.lastCall).toEqual([
372
+ {version: '7', range: undefined},
359
373
  undefined,
360
374
  ]);
375
+ expect(d.revision).toEqual({etag: 'etag-7', version: '7'});
376
+ expect(d.size).toBe(10);
377
+ expect(d.contentType).toBe('text/plain');
378
+ expect(d.lastModified).toEqual(new Date(1_730_000_000_000));
379
+ // Nothing of the contents is read before the caller reads.
380
+ expect(bytes).not.toHaveBeenCalled();
381
+ expect(next).not.toHaveBeenCalled();
382
+
383
+ expect((await d.bytes()).toString()).toBe('0123456789');
384
+ // Read once: the bytes are not kept.
385
+ await expect(d.bytes()).rejects.toBeInstanceOf(InvalidArgument);
386
+ expect(() => d.stream()).toThrow(InvalidArgument);
387
+ expect(bytes).toHaveBeenCalledTimes(1);
388
+ });
389
+
390
+ test("a download's revision is what uploadIfMatch and removeIfMatch take, and a stale one is refused", async () => {
391
+ const bucket = new Bucket('uploads');
392
+ chunks = [Buffer.from('{"n":1}')];
393
+ const d = await bucket.download('state.json');
394
+ const state = JSON.parse((await d.bytes()).toString());
395
+
396
+ await bucket.uploadIfMatch(
397
+ 'state.json',
398
+ Buffer.from(JSON.stringify({n: state.n + 1})),
399
+ d.revision,
400
+ );
401
+ expect(uploadStream.mock.lastCall?.[0]).toMatchObject({
402
+ preconditions: {ifMatch: {etag: 'etag-7', version: '7'}},
403
+ });
404
+ expect(Buffer.concat(written).toString()).toBe('{"n":2}');
405
+
406
+ // The object has changed since: the provider refuses the revision.
407
+ finish.mockImplementationOnce(
408
+ async () =>
409
+ new TypedObjectError(ObjectErrorKind.PreconditionFailed, 'changed'),
410
+ );
411
+ await expect(
412
+ bucket.uploadIfMatch('state.json', Buffer.from('late'), d.revision),
413
+ ).rejects.toBeInstanceOf(PreconditionFailed);
414
+
415
+ await bucket.removeIfMatch('state.json', d.revision);
416
+ expect(remove.mock.lastCall?.[0]).toEqual({
417
+ ifMatch: {etag: 'etag-7', version: '7'},
418
+ });
419
+ remove.mockImplementationOnce(
420
+ async () =>
421
+ new TypedObjectError(ObjectErrorKind.PreconditionFailed, 'changed'),
422
+ );
423
+ await expect(
424
+ bucket.removeIfMatch('state.json', d.revision),
425
+ ).rejects.toBeInstanceOf(PreconditionFailed);
426
+ });
427
+
428
+ test("a range is an offset and a length, or the last bytes, and the size is the whole object's", async () => {
429
+ const bucket = new Bucket('uploads');
430
+ const ranges = [
431
+ [
432
+ {offset: 1, length: 5},
433
+ {offset: 1, length: 5},
434
+ ],
435
+ [{offset: 1024}, {offset: 1024, length: undefined}],
436
+ [{last: 4}, {last: 4}],
437
+ ] as const;
438
+ for (const [range, native] of ranges) {
439
+ chunks = [Buffer.from('6789')];
440
+ const d = await bucket.download('a', {range});
441
+ expect(download.mock.lastCall?.[0]).toEqual({
442
+ version: undefined,
443
+ range: native,
444
+ });
445
+ // The contents are the range's; the size is the object's.
446
+ expect((await d.bytes()).length).toBe(4);
447
+ expect(d.size).toBe(10);
448
+ }
449
+
450
+ // Neither, or both, is no range. Plain JavaScript can pass them.
451
+ for (const range of [{}, {length: 4}, {offset: 0, last: 4}]) {
452
+ await expect(
453
+ bucket.download('a', {range: range as never}),
454
+ ).rejects.toBeInstanceOf(InvalidArgument);
455
+ }
456
+ expect(download).toHaveBeenCalledTimes(ranges.length);
457
+ });
458
+
459
+ test('stream yields the native chunks and cancelling it closes the native download', async () => {
460
+ const bucket = new Bucket('uploads');
461
+ chunks = [Buffer.from('one'), Buffer.from('two')];
462
+ const d = await bucket.download('a');
463
+ const body = d.stream();
361
464
  // Nothing is read before the consumer reads.
362
465
  expect(next).not.toHaveBeenCalled();
363
466
  const reader = body.getReader();
364
467
  expect(Buffer.from((await reader.read()).value!).toString()).toBe('one');
365
468
  await reader.cancel();
366
469
  expect(close).toHaveBeenCalledTimes(1);
470
+ // Read once, whichever way.
471
+ expect(() => d.stream()).toThrow(InvalidArgument);
472
+ await expect(d.bytes()).rejects.toBeInstanceOf(InvalidArgument);
367
473
 
368
474
  chunks = [Buffer.from('all')];
369
- const whole = await bucket.downloadStream('b');
475
+ const whole = (await bucket.download('b')).stream();
370
476
  expect(await new Response(whole).text()).toBe('all');
477
+ expect(bytes).not.toHaveBeenCalled();
371
478
  });
372
479
 
373
- test('downloadStream throws for a missing object before any bytes, and errors the stream mid-way', async () => {
480
+ test('download throws for a missing object before any bytes, and its contents error mid-way', async () => {
374
481
  const bucket = new Bucket('uploads');
375
- downloadStream.mockImplementationOnce(
482
+ download.mockImplementationOnce(
376
483
  async () => new TypedObjectError(ObjectErrorKind.NotFound, 'not found'),
377
484
  );
378
- await expect(bucket.downloadStream('missing')).rejects.toBeInstanceOf(
485
+ await expect(bucket.download('missing')).rejects.toBeInstanceOf(
379
486
  ObjectNotFound,
380
487
  );
381
488
 
@@ -383,11 +490,17 @@ test('downloadStream throws for a missing object before any bytes, and errors th
383
490
  Buffer.from('x'),
384
491
  new TypedObjectError(ObjectErrorKind.Other, 'connection reset'),
385
492
  ];
386
- const reader = (await bucket.downloadStream('a')).getReader();
493
+ const reader = (await bucket.download('a')).stream().getReader();
387
494
  await reader.read();
388
495
  const err = await reader.read().catch((e: unknown) => e);
389
496
  expect(err).toBeInstanceOf(ObjectsError);
390
497
  expect((err as Error).message).toBe('connection reset');
498
+
499
+ bytes.mockImplementationOnce(
500
+ async () => new TypedObjectError(ObjectErrorKind.Other, 'connection reset'),
501
+ );
502
+ const whole = await bucket.download('a');
503
+ await expect(whole.bytes()).rejects.toThrow('connection reset');
391
504
  });
392
505
 
393
506
  test('errors unwrap to their classes', async () => {
@@ -470,6 +583,40 @@ test('list passes the delimiter and lets go of the native iterator when the loop
470
583
  expect(markDone).toHaveBeenCalledTimes(1);
471
584
  });
472
585
 
586
+ test('list says when each object was written, and a prefix has no time', async () => {
587
+ const bucket = new Bucket('uploads');
588
+ entries = [
589
+ {name: 'users/1/', size: 0, etag: '', isPrefix: true},
590
+ {
591
+ name: 'users/a.txt',
592
+ size: 1,
593
+ etag: 'e',
594
+ lastModified: 1_730_000_000_000,
595
+ isPrefix: false,
596
+ },
597
+ ];
598
+ const listed = [];
599
+ for await (const entry of bucket.list({prefix: 'users/', delimiter: '/'})) {
600
+ listed.push(entry);
601
+ }
602
+ expect(listed).toEqual([
603
+ {
604
+ name: 'users/1/',
605
+ size: 0,
606
+ etag: '',
607
+ lastModified: undefined,
608
+ isPrefix: true,
609
+ },
610
+ {
611
+ name: 'users/a.txt',
612
+ size: 1,
613
+ etag: 'e',
614
+ lastModified: new Date(1_730_000_000_000),
615
+ isPrefix: false,
616
+ },
617
+ ]);
618
+ });
619
+
473
620
  test('listVersions yields versions with dates', async () => {
474
621
  const bucket = new Bucket('uploads');
475
622
  entries = [
@@ -552,7 +699,12 @@ function _refTyping(bucket: InstanceType<typeof Bucket>) {
552
699
 
553
700
  const rw = bucket.ref<ReadWriter>();
554
701
  void rw.updateAttrs('a', {});
702
+ void rw.download('a').then(d => [d.revision, d.size, d.stream()]);
703
+ // @ts-expect-error a download is read with bytes() or stream(), which downloadStream was
555
704
  void rw.downloadStream('a');
705
+ void rw.download('a', {range: {last: 4}});
706
+ // @ts-expect-error a range is an offset or the last bytes, not both
707
+ void rw.download('a', {range: {offset: 0, last: 4}});
556
708
  void rw.uploadIfMatch('a', new ReadableStream<Uint8Array>(), {etag: 'e'});
557
709
  void rw.removeIfMatch('a', {etag: 'e'});
558
710
  // @ts-expect-error a ReadWriter can't make public URLs