@encore.dev/sdk 2.0.0-beta.8 → 2.0.0-beta.9

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 (186) hide show
  1. package/README.md +54 -0
  2. package/app_meta.test.ts +25 -5
  3. package/app_meta.ts +43 -12
  4. package/config/config.test.ts +8 -12
  5. package/config/config.ts +16 -12
  6. package/config/secrets.ts +19 -10
  7. package/config/value.ts +13 -17
  8. package/cron/mod.test.ts +52 -0
  9. package/cron/mod.ts +9 -2
  10. package/dist/app_meta.d.ts +37 -12
  11. package/dist/app_meta.d.ts.map +1 -1
  12. package/dist/app_meta.js +1 -0
  13. package/dist/app_meta.js.map +1 -1
  14. package/dist/config/config.d.ts +16 -12
  15. package/dist/config/config.d.ts.map +1 -1
  16. package/dist/config/config.js +5 -2
  17. package/dist/config/config.js.map +1 -1
  18. package/dist/config/secrets.d.ts +19 -10
  19. package/dist/config/secrets.d.ts.map +1 -1
  20. package/dist/config/secrets.js +19 -10
  21. package/dist/config/secrets.js.map +1 -1
  22. package/dist/config/value.d.ts +7 -5
  23. package/dist/config/value.d.ts.map +1 -1
  24. package/dist/config/value.js +10 -7
  25. package/dist/config/value.js.map +1 -1
  26. package/dist/cron/mod.d.ts +5 -1
  27. package/dist/cron/mod.d.ts.map +1 -1
  28. package/dist/cron/mod.js +8 -1
  29. package/dist/cron/mod.js.map +1 -1
  30. package/dist/frontends/mod.d.ts +39 -0
  31. package/dist/frontends/mod.d.ts.map +1 -0
  32. package/dist/frontends/mod.js +47 -0
  33. package/dist/frontends/mod.js.map +1 -0
  34. package/dist/gateway/mod.d.ts +3 -2
  35. package/dist/gateway/mod.d.ts.map +1 -1
  36. package/dist/gateway/mod.js +3 -2
  37. package/dist/gateway/mod.js.map +1 -1
  38. package/dist/gateways/mod.d.ts +42 -0
  39. package/dist/gateways/mod.d.ts.map +1 -0
  40. package/dist/gateways/mod.js +55 -0
  41. package/dist/gateways/mod.js.map +1 -0
  42. package/dist/internal/fetch.d.ts +4 -0
  43. package/dist/internal/fetch.d.ts.map +1 -1
  44. package/dist/internal/fetch.js +12 -1
  45. package/dist/internal/fetch.js.map +1 -1
  46. package/dist/internal/otel/http.d.ts +11 -0
  47. package/dist/internal/otel/http.d.ts.map +1 -0
  48. package/dist/internal/otel/http.js +64 -0
  49. package/dist/internal/otel/http.js.map +1 -0
  50. package/dist/internal/otel/index.d.ts +1 -1
  51. package/dist/internal/otel/index.d.ts.map +1 -1
  52. package/dist/internal/otel/index.js +1 -1
  53. package/dist/internal/otel/index.js.map +1 -1
  54. package/dist/internal/otel/provider.d.ts +3 -0
  55. package/dist/internal/otel/provider.d.ts.map +1 -1
  56. package/dist/internal/otel/provider.js +3 -0
  57. package/dist/internal/otel/provider.js.map +1 -1
  58. package/dist/internal/otel/span.d.ts +11 -1
  59. package/dist/internal/otel/span.d.ts.map +1 -1
  60. package/dist/internal/otel/span.js +25 -2
  61. package/dist/internal/otel/span.js.map +1 -1
  62. package/dist/internal/reqfields.d.ts +26 -6
  63. package/dist/internal/reqfields.d.ts.map +1 -1
  64. package/dist/internal/reqfields.js +44 -7
  65. package/dist/internal/reqfields.js.map +1 -1
  66. package/dist/internal/runtime/napi/napi.cjs +36 -4
  67. package/dist/internal/runtime/napi/napi.d.cts +99 -4
  68. package/dist/internal/testing/carry.d.ts +49 -0
  69. package/dist/internal/testing/carry.d.ts.map +1 -0
  70. package/dist/internal/testing/carry.js +77 -0
  71. package/dist/internal/testing/carry.js.map +1 -0
  72. package/dist/internal/testing/scope.d.ts +34 -6
  73. package/dist/internal/testing/scope.d.ts.map +1 -1
  74. package/dist/internal/testing/scope.js +103 -5
  75. package/dist/internal/testing/scope.js.map +1 -1
  76. package/dist/internal/testing/steps.d.ts +55 -0
  77. package/dist/internal/testing/steps.d.ts.map +1 -0
  78. package/dist/internal/testing/steps.js +295 -0
  79. package/dist/internal/testing/steps.js.map +1 -0
  80. package/dist/internal/testing/telemetry.d.ts +305 -0
  81. package/dist/internal/testing/telemetry.d.ts.map +1 -0
  82. package/dist/internal/testing/telemetry.js +188 -0
  83. package/dist/internal/testing/telemetry.js.map +1 -0
  84. package/dist/mod.d.ts +1 -1
  85. package/dist/mod.d.ts.map +1 -1
  86. package/dist/mod.js.map +1 -1
  87. package/dist/pubsub/mod.d.ts +1 -1
  88. package/dist/pubsub/mod.d.ts.map +1 -1
  89. package/dist/pubsub/subscription.d.ts +6 -5
  90. package/dist/pubsub/subscription.d.ts.map +1 -1
  91. package/dist/pubsub/subscription.js.map +1 -1
  92. package/dist/pubsub/topic.d.ts +14 -8
  93. package/dist/pubsub/topic.d.ts.map +1 -1
  94. package/dist/pubsub/topic.js +36 -22
  95. package/dist/pubsub/topic.js.map +1 -1
  96. package/dist/reqctx/mod.d.ts +1 -18
  97. package/dist/reqctx/mod.d.ts.map +1 -1
  98. package/dist/reqctx/mod.js +1 -17
  99. package/dist/reqctx/mod.js.map +1 -1
  100. package/dist/services/index.d.ts +2 -1
  101. package/dist/services/index.d.ts.map +1 -1
  102. package/dist/services/index.js +2 -1
  103. package/dist/services/index.js.map +1 -1
  104. package/dist/storage/objects/bucket.d.ts +2 -1
  105. package/dist/storage/objects/bucket.d.ts.map +1 -1
  106. package/dist/storage/objects/bucket.js +2 -1
  107. package/dist/storage/objects/bucket.js.map +1 -1
  108. package/dist/storage/postgres/database.d.ts +5 -1
  109. package/dist/storage/postgres/database.d.ts.map +1 -1
  110. package/dist/storage/postgres/database.js +7 -3
  111. package/dist/storage/postgres/database.js.map +1 -1
  112. package/dist/storage/redis/commands.d.ts +5 -5
  113. package/dist/storage/redis/commands.d.ts.map +1 -1
  114. package/dist/storage/redis/commands.js +5 -5
  115. package/dist/storage/redis/commands.js.map +1 -1
  116. package/dist/testing/mod.d.ts +28 -5
  117. package/dist/testing/mod.d.ts.map +1 -1
  118. package/dist/testing/mod.js +52 -8
  119. package/dist/testing/mod.js.map +1 -1
  120. package/dist/testing/playwright.d.ts +93 -0
  121. package/dist/testing/playwright.d.ts.map +1 -0
  122. package/dist/testing/playwright.js +164 -0
  123. package/dist/testing/playwright.js.map +1 -0
  124. package/dist/testing/puppeteer.d.ts +36 -0
  125. package/dist/testing/puppeteer.d.ts.map +1 -0
  126. package/dist/testing/puppeteer.js +70 -0
  127. package/dist/testing/puppeteer.js.map +1 -0
  128. package/dist/testing/system.d.ts +181 -0
  129. package/dist/testing/system.d.ts.map +1 -0
  130. package/dist/testing/system.js +255 -0
  131. package/dist/testing/system.js.map +1 -0
  132. package/dist/tracing/http.d.ts +11 -0
  133. package/dist/tracing/http.d.ts.map +1 -0
  134. package/dist/tracing/http.js +34 -0
  135. package/dist/tracing/http.js.map +1 -0
  136. package/dist/tracing/mod.d.ts +1 -0
  137. package/dist/tracing/mod.d.ts.map +1 -1
  138. package/dist/tracing/mod.js +1 -0
  139. package/dist/tracing/mod.js.map +1 -1
  140. package/dist/tracing/node.d.ts +10 -0
  141. package/dist/tracing/node.d.ts.map +1 -0
  142. package/dist/tracing/node.js +142 -0
  143. package/dist/tracing/node.js.map +1 -0
  144. package/dist/tsconfig.build.tsbuildinfo +1 -1
  145. package/frontends/mod.test.ts +51 -0
  146. package/frontends/mod.ts +50 -0
  147. package/gateway/mod.ts +3 -2
  148. package/gateways/mod.ts +60 -0
  149. package/internal/fetch.ts +12 -1
  150. package/internal/otel/http.ts +91 -0
  151. package/internal/otel/index.ts +1 -1
  152. package/internal/otel/provider.ts +3 -0
  153. package/internal/otel/span.ts +25 -2
  154. package/internal/reqfields.ts +43 -10
  155. package/internal/runtime/napi/napi.cjs +36 -4
  156. package/internal/runtime/napi/napi.d.cts +99 -4
  157. package/internal/testing/carry.test.ts +242 -0
  158. package/internal/testing/carry.ts +101 -0
  159. package/internal/testing/scope.ts +106 -7
  160. package/internal/testing/steps.test.ts +152 -0
  161. package/internal/testing/steps.ts +342 -0
  162. package/internal/testing/telemetry.test.ts +210 -0
  163. package/internal/testing/telemetry.ts +466 -0
  164. package/mod.ts +1 -0
  165. package/package.json +26 -1
  166. package/pubsub/mod.ts +6 -1
  167. package/pubsub/pubsub.test.ts +1 -0
  168. package/pubsub/subscription.ts +6 -5
  169. package/pubsub/topic.ts +45 -21
  170. package/reqctx/mod.ts +1 -18
  171. package/reqctx/reqctx.test.ts +23 -0
  172. package/scripts/postprocess-docs.test.ts +11 -1
  173. package/services/index.ts +2 -1
  174. package/storage/objects/bucket.ts +2 -1
  175. package/storage/postgres/database.ts +7 -3
  176. package/storage/redis/commands.ts +5 -5
  177. package/testing/mod.ts +63 -7
  178. package/testing/playwright.ts +247 -0
  179. package/testing/puppeteer.ts +101 -0
  180. package/testing/system.test.ts +108 -0
  181. package/testing/system.ts +373 -0
  182. package/tracing/http.ts +49 -0
  183. package/tracing/mod.ts +1 -0
  184. package/tracing/native.test.ts +101 -4
  185. package/tracing/node.ts +176 -0
  186. package/tracing/tracing.test.ts +660 -24
@@ -0,0 +1,51 @@
1
+ import {describe, expect, mock, test} from 'bun:test';
2
+ import type {AppMeta} from '../app_meta';
3
+
4
+ const meta = {
5
+ frontends: {
6
+ 'web-app': {
7
+ name: 'web-app',
8
+ url: 'https://example.com',
9
+ origins: ['https://example.com/', 'https://*.example.com'],
10
+ },
11
+ },
12
+ gateways: {
13
+ api: {
14
+ name: 'api',
15
+ url: 'https://api.example.com',
16
+ origins: ['https://api.example.com', '*'],
17
+ },
18
+ internal: {name: 'internal', url: '', origins: []},
19
+ },
20
+ } as unknown as AppMeta;
21
+
22
+ mock.module('../app_meta', () => ({appMeta: () => meta}));
23
+
24
+ const frontends = await import('./mod');
25
+ const gateways = await import('../gateways/mod');
26
+
27
+ describe('frontends.url', () => {
28
+ test('is the first origin, without a trailing slash', () => {
29
+ expect(frontends.url('web-app')).toBe('https://example.com');
30
+ });
31
+
32
+ test('throws for a name the app has not, spelled one way', () => {
33
+ expect(() => frontends.url('web_app')).toThrow(
34
+ 'no URL is known for frontend "web_app"',
35
+ );
36
+ expect(() => frontends.url('nope')).toThrow(
37
+ 'no URL is known for frontend "nope"',
38
+ );
39
+ });
40
+ });
41
+
42
+ describe('gateways.url', () => {
43
+ test('is the first origin', () => {
44
+ expect(gateways.url('api')).toBe('https://api.example.com');
45
+ });
46
+
47
+ test('throws for a gateway with no origins, or of no name', () => {
48
+ expect(() => gateways.url('internal')).toThrow('gives it no origins');
49
+ expect(() => gateways.url('a_pi')).toThrow('no gateway of that name');
50
+ });
51
+ });
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Where the app's frontends are reached.
3
+ *
4
+ * {@link url} is a frontend's URL in the environment the code runs in, as to
5
+ * send a user there or to build a link to one of its pages:
6
+ *
7
+ * ```ts
8
+ * import * as frontends from '@encore.dev/sdk/frontends';
9
+ *
10
+ * const reset = `${frontends.url('web')}/reset?token=${token}`;
11
+ * ```
12
+ *
13
+ * Looking a frontend's URL up links the calling service to it. Encore reads
14
+ * the link from the code, as it reads which services a service depends on: so
15
+ * the name must be a string literal, written as the frontend declares it, the
16
+ * function must be called directly rather than passed around, and the call
17
+ * must be in a service.
18
+ *
19
+ * @module
20
+ */
21
+
22
+ import {appMeta} from '../app_meta';
23
+
24
+ /**
25
+ * The URL `frontend` is reached at in this environment, without a trailing
26
+ * slash: a path goes after it, `` `${url("web")}/reset` ``. It is the first of
27
+ * the frontend's origins, as {@link appMeta} lists them.
28
+ *
29
+ * The name is the one the frontend is declared with, in its
30
+ * `encore.frontend.json` or as the service hosting it: `web_app` does not find
31
+ * `web-app`.
32
+ *
33
+ * Throws if the runtime knows no URL for `frontend`: the app has no frontend of
34
+ * that name, which Encore's parser reports, or the environment gives it no
35
+ * origins.
36
+ *
37
+ * @example
38
+ * import {url} from "@encore.dev/sdk/frontends";
39
+ * const home = url("web");
40
+ */
41
+ export function url(frontend: string): string {
42
+ const found = appMeta().frontends[frontend]?.origins[0]?.replace(/\/+$/, '');
43
+ if (!found) {
44
+ throw new Error(
45
+ `encore: no URL is known for frontend ${JSON.stringify(frontend)}: the app has no ` +
46
+ 'frontend of that name, or the environment gives it no origins',
47
+ );
48
+ }
49
+ return found;
50
+ }
package/gateway/mod.ts CHANGED
@@ -61,8 +61,9 @@
61
61
  * only as the hook reads it.
62
62
  *
63
63
  * Middleware see only public requests the gateway routes: calls between
64
- * services, Pub/Sub pushes, CORS preflights and requests for paths the
65
- * gateway does not expose are Encore's alone.
64
+ * services, Pub/Sub pushes and requests for paths the gateway does not
65
+ * expose are Encore's alone, and so are CORS preflights, but for a gateway
66
+ * whose CORS is off (`"cors": false`), which routes them as any request.
66
67
  *
67
68
  * ## Answering a request
68
69
  *
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Where the app's gateways are reached.
3
+ *
4
+ * {@link url} is a gateway's URL in the environment the code runs in, as to
5
+ * hand a client outside the app the address of its API:
6
+ *
7
+ * ```ts
8
+ * import * as gateways from '@encore.dev/sdk/gateways';
9
+ *
10
+ * const callback = `${gateways.url('api')}/webhooks/stripe`;
11
+ * ```
12
+ *
13
+ * A service calls the app's other services with `@encore.dev/sdk/services`,
14
+ * not through a gateway. A gateway's middleware is `@encore.dev/sdk/gateway`'s.
15
+ *
16
+ * Looking a gateway's URL up links the calling service to it. Encore reads the
17
+ * link from the code, as it reads which services a service depends on: so the
18
+ * name must be a string literal, written as the gateway declares it, the
19
+ * function must be called directly rather than passed around, and the call
20
+ * must be in a service.
21
+ *
22
+ * @module
23
+ */
24
+
25
+ import {appMeta} from '../app_meta';
26
+
27
+ /**
28
+ * The URL `gateway` is reached at in this environment, without a trailing
29
+ * slash: a path goes after it, `` `${url("api")}/webhooks/stripe` ``. It is the
30
+ * first of the gateway's origins, as {@link appMeta} lists them.
31
+ *
32
+ * The name is the one the gateway is declared with, in its
33
+ * `encore.gateway.json` or as the service hosting it: `public_api` does not
34
+ * find `public-api`.
35
+ *
36
+ * Throws if the runtime knows no URL for `gateway`: the app has no gateway of
37
+ * that name, which Encore's parser reports, or the environment gives it no
38
+ * origins.
39
+ *
40
+ * @example
41
+ * import {url} from "@encore.dev/sdk/gateways";
42
+ * const api = url("api");
43
+ */
44
+ export function url(gateway: string): string {
45
+ const gw = appMeta().gateways[gateway];
46
+ if (gw === undefined) {
47
+ throw new Error(
48
+ `encore: no URL is known for gateway ${JSON.stringify(gateway)}: the app has no ` +
49
+ 'gateway of that name',
50
+ );
51
+ }
52
+ const found = gw.origins[0]?.replace(/\/+$/, '');
53
+ if (!found) {
54
+ throw new Error(
55
+ `encore: no URL is known for gateway ${JSON.stringify(gateway)}: the environment ` +
56
+ 'gives it no origins',
57
+ );
58
+ }
59
+ return found;
60
+ }
package/internal/fetch.ts CHANGED
@@ -11,6 +11,7 @@ import {isSpanContextValid, trace, type Context} from '@opentelemetry/api';
11
11
  import {activeContext} from './otel/context';
12
12
  import {W3CPropagator} from './otel/propagator';
13
13
  import * as reqfields from './reqfields';
14
+ import {outgoingContext, outgoingContextIfKnown} from './testing/carry';
14
15
 
15
16
  /**
16
17
  * The global `fetch`, carrying the trace and Request Context of the active
@@ -28,6 +29,10 @@ import * as reqfields from './reqfields';
28
29
  * base URL `baseUrl`, `serviceUrl` or `client` of `@encore.dev/sdk/services`
29
30
  * returned in this process, as every service URL is made from one.
30
31
  *
32
+ * In a system test (`system` of `@encore.dev/sdk/testing`) a request also
33
+ * carries the test it is made for: the test's id, as a Request Context
34
+ * field, and the test's span where the context has none.
35
+ *
31
36
  * A request made in a context with a trace or Request Context follows its
32
37
  * redirects here, rather than in the global `fetch`, so that each is sent
33
38
  * what its own URL is due: a redirect away from the app's services carries
@@ -62,7 +67,13 @@ export function wrapFetch(
62
67
  const request = input instanceof Request ? input : undefined;
63
68
  const url = request?.url ?? String(input);
64
69
  const headers = new Headers(init?.headers ?? request?.headers);
65
- const ctx = activeContext();
70
+ // In a system test, the context with the test added: its calls carry
71
+ // the test's id, and continue its span where they have none. A call
72
+ // to a service whose test cannot be told is refused; one to anything
73
+ // else carries no test anyway.
74
+ const ctx = origins.has(originOf(url) ?? '')
75
+ ? outgoingContext(activeContext())
76
+ : outgoingContextIfKnown(activeContext());
66
77
  prepare(url, headers, ctx);
67
78
  const redirect = init?.redirect ?? request?.redirect ?? 'follow';
68
79
  if (!hasContext(ctx) || redirect !== 'follow') {
@@ -0,0 +1,91 @@
1
+ import {
2
+ ROOT_CONTEXT,
3
+ SpanKind,
4
+ SpanStatusCode,
5
+ trace,
6
+ type Attributes,
7
+ type Span,
8
+ type TextMapGetter,
9
+ } from '@opentelemetry/api';
10
+ import {tracerProvider} from '../../otel';
11
+ import {extract, type HeaderSource} from '../../reqctx/mod';
12
+ import {W3CPropagator} from './propagator';
13
+
14
+ const propagator = new W3CPropagator();
15
+ const methods = new Set([
16
+ 'CONNECT',
17
+ 'DELETE',
18
+ 'GET',
19
+ 'HEAD',
20
+ 'OPTIONS',
21
+ 'PATCH',
22
+ 'POST',
23
+ 'PUT',
24
+ 'TRACE',
25
+ ]);
26
+
27
+ export function startHTTPSpan<Headers extends HeaderSource>(
28
+ headers: Headers,
29
+ getter: TextMapGetter<Headers>,
30
+ requestMethod: string,
31
+ url: URL,
32
+ ) {
33
+ const parent = extract(
34
+ headers,
35
+ propagator.extract(ROOT_CONTEXT, headers, getter),
36
+ );
37
+ const method = methods.has(requestMethod) ? requestMethod : '_OTHER';
38
+ const attributes: Attributes = {
39
+ 'http.request.method': method,
40
+ 'url.scheme': url.protocol.slice(0, -1),
41
+ 'server.address': url.hostname.startsWith('[')
42
+ ? url.hostname.slice(1, -1)
43
+ : url.hostname,
44
+ };
45
+ if (method === '_OTHER') {
46
+ attributes['http.request.method_original'] = requestMethod;
47
+ }
48
+ const port =
49
+ url.port ||
50
+ (url.protocol === 'https:' ? '443' : url.protocol === 'http:' ? '80' : '');
51
+ if (port) attributes['server.port'] = Number(port);
52
+
53
+ const span = tracerProvider()
54
+ .getTracer('encore')
55
+ .startSpan(
56
+ method === '_OTHER' ? 'HTTP' : method,
57
+ {
58
+ kind: SpanKind.SERVER,
59
+ attributes,
60
+ },
61
+ parent,
62
+ );
63
+ return {span, context: trace.setSpan(parent, span)};
64
+ }
65
+
66
+ export function recordHTTPStatus(span: Span, status: number): void {
67
+ span.setAttribute('http.response.status_code', status);
68
+ if (status >= 500 && status <= 599) {
69
+ span.setStatus({code: SpanStatusCode.ERROR});
70
+ span.setAttribute('error.type', String(status));
71
+ }
72
+ }
73
+
74
+ export function recordHTTPError(span: Span, error: unknown): void {
75
+ span.setStatus({code: SpanStatusCode.ERROR});
76
+ span.setAttribute('error.type', 'Error');
77
+ try {
78
+ span.setAttribute(
79
+ 'error.type',
80
+ error instanceof Error ? error.name || 'Error' : typeof error,
81
+ );
82
+ span.recordException(error instanceof Error ? error : String(error));
83
+ } catch {
84
+ span.recordException('Unserializable thrown value');
85
+ }
86
+ }
87
+
88
+ export function recordHTTPConnectionClosed(span: Span): void {
89
+ span.setStatus({code: SpanStatusCode.ERROR});
90
+ span.setAttribute('error.type', 'connection_closed');
91
+ }
@@ -10,5 +10,5 @@ export {ContextManager} from './context_manager';
10
10
  export {W3CPropagator, formatTraceparent, parseTraceparent} from './propagator';
11
11
  export {Meter, MeterProvider} from './meter';
12
12
  export {TracerProvider} from './provider';
13
- export {activeCtxBytes, Span} from './span';
13
+ export {activeCtxBytes, contextCtxBytes, Span} from './span';
14
14
  export {Tracer} from './tracer';
@@ -9,8 +9,11 @@ import {Tracer} from './tracer';
9
9
  export class TracerProvider implements ApiTracerProvider {
10
10
  private readonly tracers = new Map<string, Tracer>();
11
11
 
12
+ /** @internal */
12
13
  constructor(private readonly backend: Backend) {}
13
14
 
15
+ /** The tracer of the instrumentation scope `name` (at `version`), the same
16
+ * one each time it is asked for. */
14
17
  getTracer(name: string, version?: string): ApiTracer {
15
18
  const key = `${name}\0${version ?? ''}`;
16
19
  let tracer = this.tracers.get(key);
@@ -16,6 +16,8 @@ import {
16
16
  type SpanStatus,
17
17
  type TimeInput,
18
18
  } from '@opentelemetry/api';
19
+ import {current as currentFields, TEST_FIELD} from '../reqfields';
20
+ import {outgoingContextIfKnown} from '../testing/carry';
19
21
  import type {Backend} from './backend';
20
22
  import {activeContext} from './context';
21
23
  import {
@@ -232,10 +234,31 @@ export function spanCtxBytes(span: ApiSpan): Buffer | undefined {
232
234
  return isSpanContextValid(sc) ? ctxBytes(sc) : undefined;
233
235
  }
234
236
 
235
- /** The 25-byte context of the span in `ctx`, if any. */
237
+ /** No span, where a call has only the test it is made for to say. */
238
+ const NO_SPAN = Buffer.alloc(25);
239
+
240
+ /**
241
+ * What an infra call hands the runtime of `ctx`, for the spans the runtime
242
+ * records for it: the 25-byte context of the span in `ctx`, their parent, if
243
+ * any.
244
+ *
245
+ * Under test, where `ctx` holds the id of the test the call is made for, the
246
+ * field's wire form follows, after 25 zero bytes where there is no span: the
247
+ * runtime's spans then carry the test's id, as the process's own do, which
248
+ * is what a test's spans are found by. A system test's own infra calls are
249
+ * made for the test, and under its span, where `ctx` says neither.
250
+ */
236
251
  export function contextCtxBytes(ctx: Context): Buffer | undefined {
252
+ // In a system test's process, what the test's own code does is the
253
+ // test's: a child of its span, as its calls are. Where no test can be
254
+ // told from another, a span is recorded as no test's: the operation
255
+ // itself says so if it needs one.
256
+ ctx = outgoingContextIfKnown(ctx);
237
257
  const span = trace.getSpan(ctx);
238
- return span ? spanCtxBytes(span) : undefined;
258
+ const bytes = span ? spanCtxBytes(span) : undefined;
259
+ const test = currentFields(ctx)[TEST_FIELD];
260
+ if (test === undefined) return bytes;
261
+ return Buffer.concat([bytes ?? NO_SPAN, Buffer.from(test, 'latin1')]);
239
262
  }
240
263
 
241
264
  /** The active span's 25-byte context, if any. */
@@ -29,6 +29,10 @@ export const HEADER_PREFIX = 'x-encore-meta-ctx-';
29
29
  export const ATTRIBUTE_PREFIX = 'encore-ctx-';
30
30
  /** The span attribute a field declared with `trace` is, before its name. */
31
31
  export const SPAN_ATTRIBUTE_PREFIX = 'encore.ctx.';
32
+ /** Encore's own field under test: the id of the test a request is made for. */
33
+ export const TEST_FIELD = 'encore-test';
34
+ /** The span attribute the test's id is, on every span of what it caused. */
35
+ export const TEST_ID_ATTRIBUTE = 'encore.test.id';
32
36
 
33
37
  /** The most one field encodes to, in bytes. */
34
38
  export const MAX_VALUE_SIZE = 4096;
@@ -345,26 +349,55 @@ export function fromMessageAttributes(attributes: Record<string, string>): {
345
349
  return {fields, rest};
346
350
  }
347
351
 
348
- /** The span attributes of the fields of `ctx` declared with `trace`: each
349
- * the value's JSON, as a string. */
352
+ /**
353
+ * The span attributes of the fields of `ctx` declared with `trace`: each
354
+ * `encore.ctx.<name>`, the value's JSON, as a string. Encore's own field
355
+ * under test is `encore.test.id`, the test's id as it is: one name and one
356
+ * form, whichever SDK's process records the span, is what a test's spans are
357
+ * found by.
358
+ */
350
359
  export function spanAttributes(ctx: Context): Record<string, string> {
351
360
  const out: Record<string, string> = {};
352
361
  for (const [name, value] of Object.entries(current(ctx))) {
353
362
  if (!configOf(name).trace || !BASE64URL.test(value)) continue;
354
- out[SPAN_ATTRIBUTE_PREFIX + name] = Buffer.from(
355
- value,
356
- 'base64url',
357
- ).toString('utf8');
363
+ const json = Buffer.from(value, 'base64url').toString('utf8');
364
+ if (name === TEST_FIELD) {
365
+ const id = testId(json);
366
+ if (id !== undefined) out[TEST_ID_ATTRIBUTE] = id;
367
+ continue;
368
+ }
369
+ out[SPAN_ATTRIBUTE_PREFIX + name] = json;
358
370
  }
359
371
  return out;
360
372
  }
361
373
 
374
+ /** The test's id the field under test holds: its JSON is a string's. */
375
+ function testId(json: string): string | undefined {
376
+ try {
377
+ const id: unknown = JSON.parse(json);
378
+ return typeof id === 'string' ? id : undefined;
379
+ } catch {
380
+ return undefined;
381
+ }
382
+ }
383
+
362
384
  /**
363
- * Extracts the fields a request carries into its context; injects none.
385
+ * An OpenTelemetry propagator that extracts the fields a request carries into
386
+ * its context, and injects none. Compose it into the app's global propagator,
387
+ * so a server instrumented for tracing has them:
388
+ *
389
+ * ```ts
390
+ * propagation.setGlobalPropagator(
391
+ * new CompositePropagator({
392
+ * propagators: [new W3CTraceContextPropagator(), new reqctx.Propagator()],
393
+ * }),
394
+ * );
395
+ * ```
364
396
  *
365
- * An instrumented client sends whatever the global propagator injects to
366
- * whatever it calls, the app's own services or not, so fields are sent only
367
- * where the app asks, to its services.
397
+ * It never injects: an instrumented client sends whatever the global
398
+ * propagator injects to whatever it calls, the app's own services or not, so
399
+ * fields are sent only where the app asks. Send them to the app's services
400
+ * with `reqctx.inject`.
368
401
  */
369
402
  export class Propagator implements TextMapPropagator {
370
403
  /** `ctx` with the fields `carrier` carries, in place of its own. */
@@ -1,5 +1,5 @@
1
1
  // The version of the runtime this JS bundle was generated for.
2
- const version = "v2.0.0-beta.8";
2
+ const version = "v2.0.0-beta.9";
3
3
 
4
4
  // Load the native module. ENCORE_RUNTIME_LIB overrides the location; by
5
5
  // default the library is found by walking up from this file (which the
@@ -7,8 +7,8 @@ const version = "v2.0.0-beta.8";
7
7
  // @encore.dev/sdk package even when node_modules holds symlinks), checking each
8
8
  // directory and its dist/ subdirectory — the library ships in the package's
9
9
  // dist/ folder — making the package relocatable. Failing that, it is the
10
- // Encore installation's: for a process Encore did not start, such as a test
11
- // runner's or a script's.
10
+ // Encore installation's, or its runtime component: for a process Encore did
11
+ // not start, such as a test runner's or a script's.
12
12
  function findRuntimeLib(name, hint) {
13
13
  const path = require("path");
14
14
  const fs = require("fs");
@@ -34,7 +34,7 @@ function findRuntimeLib(name, hint) {
34
34
  return installed;
35
35
  }
36
36
  throw new Error(
37
- `could not find the Encore runtime library ('${name}') in ${__dirname} or any parent directory, nor in an Encore installation (ENCORE_RUNTIMES_PATH, or the encore on PATH). ${hint}`
37
+ `could not find the Encore runtime library ('${name}') in ${__dirname} or any parent directory, nor in an Encore installation (ENCORE_RUNTIMES_PATH, or the encore on PATH) or its ${runtimeComponent(name)} component (\`encore component add ${runtimeComponent(name)}\`). ${hint}`
38
38
  );
39
39
  }
40
40
 
@@ -68,9 +68,39 @@ function findInstalledRuntimeLib(name) {
68
68
  return candidate;
69
69
  }
70
70
  }
71
+ // An installation whose runtimes are components: the encore command says
72
+ // where the component is, installing it first if it isn't.
73
+ const component = exe && componentDir(exe, runtimeComponent(name));
74
+ if (component) {
75
+ const candidate = path.join(component, name);
76
+ if (fs.existsSync(candidate)) {
77
+ return candidate;
78
+ }
79
+ }
71
80
  return null;
72
81
  }
73
82
 
83
+ // The component a runtime library is in.
84
+ function runtimeComponent(name) {
85
+ return name === "encore-runtime-gateway.node" ? "runtime/ts-gateway" : "runtime/ts";
86
+ }
87
+
88
+ // Where the component `component` is installed, as `encore component path
89
+ // --install` says, installing it if it isn't; null if that fails.
90
+ function componentDir(exe, component) {
91
+ try {
92
+ const out = require("child_process").execFileSync(
93
+ exe,
94
+ ["component", "path", component, "--install"],
95
+ { encoding: "utf8", stdio: ["ignore", "pipe", "inherit"], windowsHide: true }
96
+ );
97
+ const lines = out.trim().split(/\r?\n/);
98
+ return lines[lines.length - 1] || null;
99
+ } catch {
100
+ return null;
101
+ }
102
+ }
103
+
74
104
  // The encore command: ENCORE_BIN, else the first on PATH.
75
105
  function findEncoreCommand() {
76
106
  const path = require("path");
@@ -178,6 +208,7 @@ const {
178
208
  Secret,
179
209
  SqlConn,
180
210
  SqlDatabase,
211
+ SystemTest,
181
212
  TestScope,
182
213
  TestScopes,
183
214
  Transaction,
@@ -231,6 +262,7 @@ module.exports = {
231
262
  Secret,
232
263
  SqlConn,
233
264
  SqlDatabase,
265
+ SystemTest,
234
266
  TestScope,
235
267
  TestScopes,
236
268
  Transaction,
@@ -5,8 +5,16 @@
5
5
  export interface AppMeta {
6
6
  appId: string
7
7
  appSlug: string
8
- /** The API gateways serving the application, keyed by gateway name. */
8
+ /**
9
+ * The API gateways the service is given, keyed by gateway name: those
10
+ * its code names, and the one it hosts.
11
+ */
9
12
  gateways: Record<string, GatewayMeta>
13
+ /**
14
+ * The frontends the service is given, keyed by name: those its code
15
+ * names, and the one it hosts.
16
+ */
17
+ frontends: Record<string, FrontendMeta>
10
18
  environment: EnvironmentMeta
11
19
  build: BuildMeta
12
20
  deploy: DeployMeta
@@ -103,7 +111,7 @@ export interface ConfigRevision {
103
111
  number: number
104
112
  /**
105
113
  * The value, as JSON text, with a placeholder
106
- * (`{"$encore_secret": {"name", "scope"}}`) for each secret field.
114
+ * (`{"$encore_secret": "<name>"}`) for each secret field.
107
115
  */
108
116
  value: string
109
117
  }
@@ -183,6 +191,12 @@ export interface ExtendRetentionOptions {
183
191
  version?: string
184
192
  }
185
193
 
194
+ export interface FrontendMeta {
195
+ name: string
196
+ url: string
197
+ origins: Array<string>
198
+ }
199
+
186
200
  /**
187
201
  * An attribute of a request's edge span: an integer when `integer` is set
188
202
  * and `value` a number.
@@ -232,7 +246,8 @@ export class GatewayHeaders {
232
246
 
233
247
  export interface GatewayMeta {
234
248
  name: string
235
- baseUrl: string
249
+ url: string
250
+ origins: Array<string>
236
251
  }
237
252
 
238
253
  /**
@@ -789,7 +804,11 @@ export class SqlDatabase {
789
804
  /** Begins a transaction, with `options` if given. */
790
805
  begin(options?: SqlTransactionOptions | undefined | null, source?: Buffer | undefined | null): Promise<Transaction>
791
806
  query(query: string, args: QueryArgs, source?: Buffer | undefined | null): Promise<Cursor>
792
- acquire(): Promise<SQLConn>
807
+ /**
808
+ * Takes a connection out of the pool, in the context `source` names:
809
+ * the host's active span context, as a query is given it.
810
+ */
811
+ acquire(source?: Buffer | undefined | null): Promise<SQLConn>
793
812
  }
794
813
  export type SQLDatabase = SqlDatabase
795
814
 
@@ -804,6 +823,43 @@ export interface SqlTransactionOptions {
804
823
  }
805
824
  export type SQLTransactionOptions = SqlTransactionOptions
806
825
 
826
+ /** The test session a system test's process runs against. */
827
+ export class SystemTest {
828
+ /** The suite the process's tests are of. */
829
+ get suite(): string
830
+ /** The test session's id, as `encore run ls` lists it. */
831
+ get session(): string
832
+ /** The session's service proxy: `/<service>/…` there reaches the service. */
833
+ get proxyUrl(): string
834
+ /**
835
+ * The URL of the gateway or frontend `name` in the session, or null if
836
+ * the app has neither.
837
+ */
838
+ url(name: string): string | null
839
+ /** The names of the session's gateways, sorted. */
840
+ gateways(): Array<string>
841
+ }
842
+
843
+ /**
844
+ * What a system test's calls and messages carry of the test, for those
845
+ * whose context does not already hold it.
846
+ */
847
+ export interface TestCarried {
848
+ /** The name of the Request Context field that holds the test's id. */
849
+ fieldName: string
850
+ /** The field's value, in a field's wire form. */
851
+ field: string
852
+ /**
853
+ * The headers a call made for the test carries, by lowercase name: the
854
+ * field, and the test's span as `traceparent` and `tracestate`.
855
+ */
856
+ headers: Record<string, string>
857
+ /** The test's span as a `traceparent`, where the process records spans. */
858
+ traceparent?: string
859
+ /** The `tracestate` that goes with it. */
860
+ tracestate?: string
861
+ }
862
+
807
863
  /**
808
864
  * A message to hand a subscription's handler, and which delivery of it this
809
865
  * is: 1 the first time.
@@ -827,6 +883,40 @@ export interface TestPublished {
827
883
  export class TestScope {
828
884
  /** The scope's id: what its resources are provisioned under. */
829
885
  get id(): string
886
+ /**
887
+ * What the test's calls and messages carry of it, when it is a system
888
+ * test: null for a service's test.
889
+ */
890
+ carried(): TestCarried | null
891
+ /**
892
+ * Resolves once nothing the tests set in motion is still running or
893
+ * queued in the test session, waiting for at most `timeoutMs`, or the
894
+ * core's 30 seconds. Rejects, saying what was still under way, if it did
895
+ * not settle in time, and for a test that is no system test.
896
+ */
897
+ settled(timeoutMs?: number | undefined | null): Promise<void>
898
+ /**
899
+ * What the test session recorded for the test so far, as the JSON of
900
+ * the core's model (`Telemetry::to_json`): once the session has settled
901
+ * with `settle`, waiting as `settled` does. Rejects for a test that is no
902
+ * system test.
903
+ */
904
+ telemetry(settle: boolean, timeoutMs?: number | undefined | null): Promise<string>
905
+ /**
906
+ * The test's browser, which the test session runs for it, as JSON
907
+ * (`wsEndpoint`, `urls`, `recording`, `stepsUrl`): started at the first ask, the
908
+ * same one after that. `record` says when what it records is kept
909
+ * (`"failed"`, `"all"` or `"off"`), `args` are more arguments for it,
910
+ * and `width` and `height` its window's size. Rejects for a test that
911
+ * is no system test.
912
+ */
913
+ browser(record?: string | undefined | null, args?: Array<string> | undefined | null, width?: number | undefined | null, height?: number | undefined | null): Promise<string>
914
+ /**
915
+ * Says how the test ended, for the session to record when the test
916
+ * ends: `"passed"`, `"failed"` or `"skipped"`. Nothing for a test that is
917
+ * no system test.
918
+ */
919
+ setOutcome(outcome: 'passed' | 'failed' | 'skipped'): void
830
920
  /**
831
921
  * Ends the test: its resources are released, unless they are a
832
922
  * fixture's. Its handles fail from then on.
@@ -906,6 +996,11 @@ export class TestScopes {
906
996
  * that publishes to its own topic for ever.
907
997
  */
908
998
  get maxDeliveries(): number
999
+ /**
1000
+ * The test session the process's tests run against, when they are
1001
+ * system tests: null for the tests of a service.
1002
+ */
1003
+ system(): SystemTest | null
909
1004
  /**
910
1005
  * Asks for the fixture `name`, which starts from the fixture `parent` if
911
1006
  * there is one. Resolves to null once it is built — by this process or