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

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 (356) hide show
  1. package/README.md +55 -0
  2. package/app_meta.ts +8 -0
  3. package/config/config.test.ts +10 -3
  4. package/config/config.ts +75 -21
  5. package/config/mod.ts +4 -3
  6. package/config/secrets.ts +72 -55
  7. package/cron/mod.ts +32 -0
  8. package/dist/app_meta.d.ts +7 -0
  9. package/dist/app_meta.d.ts.map +1 -0
  10. package/dist/app_meta.js +1 -0
  11. package/dist/app_meta.js.map +1 -1
  12. package/dist/config/config.d.ts +44 -18
  13. package/dist/config/config.d.ts.map +1 -0
  14. package/dist/config/config.js +43 -18
  15. package/dist/config/config.js.map +1 -1
  16. package/dist/config/mod.d.ts +5 -4
  17. package/dist/config/mod.d.ts.map +1 -0
  18. package/dist/config/mod.js +2 -2
  19. package/dist/config/mod.js.map +1 -1
  20. package/dist/config/secrets.d.ts +62 -39
  21. package/dist/config/secrets.d.ts.map +1 -0
  22. package/dist/config/secrets.js +21 -37
  23. package/dist/config/secrets.js.map +1 -1
  24. package/dist/config/value.d.ts +1 -0
  25. package/dist/config/value.d.ts.map +1 -0
  26. package/dist/cron/mod.d.ts +31 -0
  27. package/dist/cron/mod.d.ts.map +1 -0
  28. package/dist/cron/mod.js +23 -0
  29. package/dist/cron/mod.js.map +1 -1
  30. package/dist/gateway/errors.d.ts +101 -0
  31. package/dist/gateway/errors.d.ts.map +1 -0
  32. package/dist/gateway/errors.js +146 -0
  33. package/dist/gateway/errors.js.map +1 -0
  34. package/dist/gateway/match.d.ts +127 -0
  35. package/dist/gateway/match.d.ts.map +1 -0
  36. package/dist/gateway/match.js +206 -0
  37. package/dist/gateway/match.js.map +1 -0
  38. package/dist/gateway/middleware.d.ts +108 -0
  39. package/dist/gateway/middleware.d.ts.map +1 -0
  40. package/dist/gateway/middleware.js +9 -0
  41. package/dist/gateway/middleware.js.map +1 -0
  42. package/dist/gateway/mod.d.ts +129 -0
  43. package/dist/gateway/mod.d.ts.map +1 -0
  44. package/dist/gateway/mod.js +187 -0
  45. package/dist/gateway/mod.js.map +1 -0
  46. package/dist/gateway/request.d.ts +304 -0
  47. package/dist/gateway/request.d.ts.map +1 -0
  48. package/dist/gateway/request.js +403 -0
  49. package/dist/gateway/request.js.map +1 -0
  50. package/dist/gateway/serve.d.ts +114 -0
  51. package/dist/gateway/serve.d.ts.map +1 -0
  52. package/dist/gateway/serve.js +510 -0
  53. package/dist/gateway/serve.js.map +1 -0
  54. package/dist/internal/clients/call.d.ts +147 -0
  55. package/dist/internal/clients/call.d.ts.map +1 -0
  56. package/dist/internal/clients/call.js +274 -0
  57. package/dist/internal/clients/call.js.map +1 -0
  58. package/dist/internal/clients/grpc.d.ts +90 -0
  59. package/dist/internal/clients/grpc.d.ts.map +1 -0
  60. package/dist/internal/clients/grpc.js +355 -0
  61. package/dist/internal/clients/grpc.js.map +1 -0
  62. package/dist/internal/clients/mod.d.ts +81 -0
  63. package/dist/internal/clients/mod.d.ts.map +1 -0
  64. package/dist/internal/clients/mod.js +237 -0
  65. package/dist/internal/clients/mod.js.map +1 -0
  66. package/dist/internal/fetch.d.ts +54 -0
  67. package/dist/internal/fetch.d.ts.map +1 -0
  68. package/dist/internal/fetch.js +240 -0
  69. package/dist/internal/fetch.js.map +1 -0
  70. package/dist/internal/otel/backend.d.ts +2 -0
  71. package/dist/internal/otel/backend.d.ts.map +1 -0
  72. package/dist/internal/otel/context.d.ts +1 -0
  73. package/dist/internal/otel/context.d.ts.map +1 -0
  74. package/dist/internal/otel/context_manager.d.ts +1 -0
  75. package/dist/internal/otel/context_manager.d.ts.map +1 -0
  76. package/dist/internal/otel/encode.d.ts +2 -0
  77. package/dist/internal/otel/encode.d.ts.map +1 -0
  78. package/dist/internal/otel/index.d.ts +2 -2
  79. package/dist/internal/otel/index.d.ts.map +1 -0
  80. package/dist/internal/otel/index.js +1 -2
  81. package/dist/internal/otel/index.js.map +1 -1
  82. package/dist/internal/otel/meter.d.ts +1 -0
  83. package/dist/internal/otel/meter.d.ts.map +1 -0
  84. package/dist/internal/otel/propagator.d.ts +1 -0
  85. package/dist/internal/otel/propagator.d.ts.map +1 -0
  86. package/dist/internal/otel/provider.d.ts +1 -0
  87. package/dist/internal/otel/provider.d.ts.map +1 -0
  88. package/dist/internal/otel/span.d.ts +4 -0
  89. package/dist/internal/otel/span.d.ts.map +1 -0
  90. package/dist/internal/otel/span.js +5 -0
  91. package/dist/internal/otel/span.js.map +1 -1
  92. package/dist/internal/otel/tracer.d.ts +1 -0
  93. package/dist/internal/otel/tracer.d.ts.map +1 -0
  94. package/dist/internal/otel/tracer.js +11 -5
  95. package/dist/internal/otel/tracer.js.map +1 -1
  96. package/dist/internal/reqfields.d.ts +150 -0
  97. package/dist/internal/reqfields.d.ts.map +1 -0
  98. package/dist/internal/reqfields.js +312 -0
  99. package/dist/internal/reqfields.js.map +1 -0
  100. package/dist/internal/runtime/meter.d.ts +1 -0
  101. package/dist/internal/runtime/meter.d.ts.map +1 -0
  102. package/dist/internal/runtime/mod.d.ts +6 -0
  103. package/dist/internal/runtime/mod.d.ts.map +1 -0
  104. package/dist/internal/runtime/mod.js +32 -2
  105. package/dist/internal/runtime/mod.js.map +1 -1
  106. package/dist/internal/runtime/napi/napi.cjs +160 -16
  107. package/dist/internal/runtime/napi/napi.d.cts +474 -29
  108. package/dist/internal/runtime/shutdown.d.ts +5 -0
  109. package/dist/internal/runtime/shutdown.d.ts.map +1 -0
  110. package/dist/internal/runtime/shutdown.js +9 -1
  111. package/dist/internal/runtime/shutdown.js.map +1 -1
  112. package/dist/internal/testing/runner.d.ts +2 -0
  113. package/dist/internal/testing/runner.d.ts.map +1 -0
  114. package/dist/internal/testing/runner.js +10 -0
  115. package/dist/internal/testing/runner.js.map +1 -0
  116. package/dist/internal/testing/scope.d.ts +81 -0
  117. package/dist/internal/testing/scope.d.ts.map +1 -0
  118. package/dist/internal/testing/scope.js +237 -0
  119. package/dist/internal/testing/scope.js.map +1 -0
  120. package/dist/internal/utils/constraints.d.ts +1 -0
  121. package/dist/internal/utils/constraints.d.ts.map +1 -0
  122. package/dist/log/index.d.ts +1 -0
  123. package/dist/log/index.d.ts.map +1 -0
  124. package/dist/log/logger.d.ts +2 -0
  125. package/dist/log/logger.d.ts.map +1 -0
  126. package/dist/log/runtime.d.ts +2 -0
  127. package/dist/log/runtime.d.ts.map +1 -0
  128. package/dist/log/stderr.d.ts +1 -0
  129. package/dist/log/stderr.d.ts.map +1 -0
  130. package/dist/metrics/mod.d.ts +45 -118
  131. package/dist/metrics/mod.d.ts.map +1 -0
  132. package/dist/metrics/mod.js +44 -179
  133. package/dist/metrics/mod.js.map +1 -1
  134. package/dist/mod.d.ts +1 -2
  135. package/dist/mod.d.ts.map +1 -0
  136. package/dist/mod.js +0 -1
  137. package/dist/mod.js.map +1 -1
  138. package/dist/otel.d.ts +1 -0
  139. package/dist/otel.d.ts.map +1 -0
  140. package/dist/pubsub/encoding.d.ts +5 -0
  141. package/dist/pubsub/encoding.d.ts.map +1 -0
  142. package/dist/pubsub/encoding.js +10 -2
  143. package/dist/pubsub/encoding.js.map +1 -1
  144. package/dist/pubsub/mod.d.ts +4 -3
  145. package/dist/pubsub/mod.d.ts.map +1 -0
  146. package/dist/pubsub/mod.js +2 -2
  147. package/dist/pubsub/mod.js.map +1 -1
  148. package/dist/pubsub/refs.d.ts +8 -0
  149. package/dist/pubsub/refs.d.ts.map +1 -0
  150. package/dist/pubsub/refs.js.map +1 -1
  151. package/dist/pubsub/subscription.d.ts +104 -10
  152. package/dist/pubsub/subscription.d.ts.map +1 -0
  153. package/dist/pubsub/subscription.js +98 -16
  154. package/dist/pubsub/subscription.js.map +1 -1
  155. package/dist/pubsub/topic.d.ts +87 -23
  156. package/dist/pubsub/topic.d.ts.map +1 -0
  157. package/dist/pubsub/topic.js +143 -40
  158. package/dist/pubsub/topic.js.map +1 -1
  159. package/dist/reqctx/mod.d.ts +191 -0
  160. package/dist/reqctx/mod.d.ts.map +1 -0
  161. package/dist/reqctx/mod.js +160 -0
  162. package/dist/reqctx/mod.js.map +1 -0
  163. package/dist/services/index.d.ts +145 -4
  164. package/dist/services/index.d.ts.map +1 -0
  165. package/dist/services/index.js +155 -8
  166. package/dist/services/index.js.map +1 -1
  167. package/dist/shutdown/mod.d.ts +1 -0
  168. package/dist/shutdown/mod.d.ts.map +1 -0
  169. package/dist/storage/objects/bucket.d.ts +312 -7
  170. package/dist/storage/objects/bucket.d.ts.map +1 -0
  171. package/dist/storage/objects/bucket.js +305 -15
  172. package/dist/storage/objects/bucket.js.map +1 -1
  173. package/dist/storage/objects/error.d.ts +10 -0
  174. package/dist/storage/objects/error.d.ts.map +1 -0
  175. package/dist/storage/objects/error.js +25 -1
  176. package/dist/storage/objects/error.js.map +1 -1
  177. package/dist/storage/objects/mod.d.ts +4 -3
  178. package/dist/storage/objects/mod.d.ts.map +1 -0
  179. package/dist/storage/objects/mod.js +1 -1
  180. package/dist/storage/objects/mod.js.map +1 -1
  181. package/dist/storage/objects/refs.d.ts +20 -4
  182. package/dist/storage/objects/refs.d.ts.map +1 -0
  183. package/dist/storage/objects/refs.js +6 -0
  184. package/dist/storage/objects/refs.js.map +1 -1
  185. package/dist/storage/postgres/database.d.ts +81 -25
  186. package/dist/storage/postgres/database.d.ts.map +1 -0
  187. package/dist/storage/postgres/database.js +125 -37
  188. package/dist/storage/postgres/database.js.map +1 -1
  189. package/dist/storage/postgres/errors.d.ts +120 -0
  190. package/dist/storage/postgres/errors.d.ts.map +1 -0
  191. package/dist/storage/postgres/errors.js +162 -0
  192. package/dist/storage/postgres/errors.js.map +1 -0
  193. package/dist/storage/postgres/interval.d.ts +44 -0
  194. package/dist/storage/postgres/interval.d.ts.map +1 -0
  195. package/dist/storage/postgres/interval.js +153 -0
  196. package/dist/storage/postgres/interval.js.map +1 -0
  197. package/dist/storage/postgres/mod.d.ts +4 -1
  198. package/dist/storage/postgres/mod.d.ts.map +1 -0
  199. package/dist/storage/postgres/mod.js +2 -0
  200. package/dist/storage/postgres/mod.js.map +1 -1
  201. package/dist/storage/redis/bitfield.d.ts +67 -0
  202. package/dist/storage/redis/bitfield.d.ts.map +1 -0
  203. package/dist/storage/redis/bitfield.js +114 -0
  204. package/dist/storage/redis/bitfield.js.map +1 -0
  205. package/dist/storage/redis/command.d.ts +45 -0
  206. package/dist/storage/redis/command.d.ts.map +1 -0
  207. package/dist/storage/redis/command.js +78 -0
  208. package/dist/storage/redis/command.js.map +1 -0
  209. package/dist/storage/redis/commands.d.ts +223 -139
  210. package/dist/storage/redis/commands.d.ts.map +1 -0
  211. package/dist/storage/redis/commands.js +128 -6
  212. package/dist/storage/redis/commands.js.map +1 -1
  213. package/dist/storage/redis/database.d.ts +56 -22
  214. package/dist/storage/redis/database.d.ts.map +1 -0
  215. package/dist/storage/redis/database.js +62 -0
  216. package/dist/storage/redis/database.js.map +1 -1
  217. package/dist/storage/redis/mod.d.ts +31 -4
  218. package/dist/storage/redis/mod.d.ts.map +1 -0
  219. package/dist/storage/redis/mod.js +26 -1
  220. package/dist/storage/redis/mod.js.map +1 -1
  221. package/dist/storage/redis/native.d.ts +8 -0
  222. package/dist/storage/redis/native.d.ts.map +1 -0
  223. package/dist/storage/redis/native.js +10 -0
  224. package/dist/storage/redis/native.js.map +1 -1
  225. package/dist/storage/redis/options.d.ts +1 -0
  226. package/dist/storage/redis/options.d.ts.map +1 -0
  227. package/dist/storage/redis/pubsub.d.ts +2 -0
  228. package/dist/storage/redis/pubsub.d.ts.map +1 -0
  229. package/dist/storage/redis/reply.d.ts +34 -0
  230. package/dist/storage/redis/reply.d.ts.map +1 -0
  231. package/dist/storage/redis/reply.js +40 -1
  232. package/dist/storage/redis/reply.js.map +1 -1
  233. package/dist/storage/redis/scan.d.ts +1 -0
  234. package/dist/storage/redis/scan.d.ts.map +1 -0
  235. package/dist/storage/redis/script.d.ts +1 -0
  236. package/dist/storage/redis/script.d.ts.map +1 -0
  237. package/dist/storage/redis/target.d.ts +5 -3
  238. package/dist/storage/redis/target.d.ts.map +1 -0
  239. package/dist/storage/redis/target.js +39 -28
  240. package/dist/storage/redis/target.js.map +1 -1
  241. package/dist/storage/redis/wire.d.ts +7 -10
  242. package/dist/storage/redis/wire.d.ts.map +1 -0
  243. package/dist/storage/redis/wire.js +8 -32
  244. package/dist/storage/redis/wire.js.map +1 -1
  245. package/dist/testing/bun.d.ts +8 -0
  246. package/dist/testing/bun.d.ts.map +1 -0
  247. package/dist/testing/bun.js +13 -0
  248. package/dist/testing/bun.js.map +1 -0
  249. package/dist/testing/jest.d.ts +8 -0
  250. package/dist/testing/jest.d.ts.map +1 -0
  251. package/dist/testing/jest.js +11 -0
  252. package/dist/testing/jest.js.map +1 -0
  253. package/dist/testing/mod.d.ts +160 -0
  254. package/dist/testing/mod.d.ts.map +1 -0
  255. package/dist/testing/mod.js +227 -0
  256. package/dist/testing/mod.js.map +1 -0
  257. package/dist/testing/node.d.ts +9 -0
  258. package/dist/testing/node.d.ts.map +1 -0
  259. package/dist/testing/node.js +12 -0
  260. package/dist/testing/node.js.map +1 -0
  261. package/dist/testing/vitest.d.ts +8 -0
  262. package/dist/testing/vitest.d.ts.map +1 -0
  263. package/dist/testing/vitest.js +13 -0
  264. package/dist/testing/vitest.js.map +1 -0
  265. package/dist/tracing/mod.d.ts +19 -0
  266. package/dist/tracing/mod.d.ts.map +1 -0
  267. package/dist/tracing/mod.js +46 -0
  268. package/dist/tracing/mod.js.map +1 -0
  269. package/dist/tsconfig.build.tsbuildinfo +1 -1
  270. package/dist/types/mod.d.ts +1 -0
  271. package/dist/types/mod.d.ts.map +1 -0
  272. package/gateway/errors.ts +172 -0
  273. package/gateway/gateway.e2e.test.ts +297 -0
  274. package/gateway/gateway.test.ts +891 -0
  275. package/gateway/match.ts +239 -0
  276. package/gateway/middleware.ts +134 -0
  277. package/gateway/mod.ts +210 -0
  278. package/gateway/request.ts +578 -0
  279. package/gateway/serve.ts +738 -0
  280. package/internal/clients/call.ts +389 -0
  281. package/internal/clients/grpc.test.ts +368 -0
  282. package/internal/clients/grpc.ts +485 -0
  283. package/internal/clients/mod.test.ts +464 -0
  284. package/internal/clients/mod.ts +337 -0
  285. package/internal/fetch.ts +276 -0
  286. package/internal/otel/index.ts +1 -7
  287. package/internal/otel/span.ts +6 -0
  288. package/internal/otel/tracer.test.ts +43 -15
  289. package/internal/otel/tracer.ts +12 -5
  290. package/internal/reqfields.ts +390 -0
  291. package/internal/runtime/mod.ts +41 -2
  292. package/internal/runtime/napi/napi.cjs +160 -16
  293. package/internal/runtime/napi/napi.d.cts +474 -29
  294. package/internal/runtime/shutdown.ts +11 -1
  295. package/internal/testing/runner.ts +10 -0
  296. package/internal/testing/scope.ts +273 -0
  297. package/metrics/mod.test.ts +13 -16
  298. package/metrics/mod.ts +57 -226
  299. package/mod.ts +0 -8
  300. package/otel.test.ts +13 -6
  301. package/package.json +67 -15
  302. package/pubsub/encoding.ts +11 -1
  303. package/pubsub/mod.ts +10 -3
  304. package/pubsub/pubsub.test.ts +232 -14
  305. package/pubsub/refs.ts +16 -0
  306. package/pubsub/subscription.ts +194 -16
  307. package/pubsub/topic.test.ts +26 -0
  308. package/pubsub/topic.ts +220 -25
  309. package/reqctx/mod.ts +284 -0
  310. package/reqctx/reqctx.test.ts +193 -0
  311. package/scripts/postprocess-docs.test.ts +48 -0
  312. package/services/index.test.ts +341 -1
  313. package/services/index.ts +183 -8
  314. package/storage/objects/bucket.test.ts +573 -0
  315. package/storage/objects/bucket.ts +649 -20
  316. package/storage/objects/error.ts +28 -1
  317. package/storage/objects/mod.ts +15 -0
  318. package/storage/objects/refs.ts +51 -3
  319. package/storage/postgres/database.integration.test.ts +275 -0
  320. package/storage/postgres/database.test.ts +193 -6
  321. package/storage/postgres/database.ts +202 -55
  322. package/storage/postgres/errors.ts +186 -0
  323. package/storage/postgres/interval.test.ts +72 -0
  324. package/storage/postgres/interval.ts +170 -0
  325. package/storage/postgres/mod.ts +4 -0
  326. package/storage/redis/bitfield.ts +162 -0
  327. package/storage/redis/command.ts +84 -0
  328. package/storage/redis/commands.ts +271 -21
  329. package/storage/redis/database.ts +77 -23
  330. package/storage/redis/mod.ts +38 -2
  331. package/storage/redis/native.ts +11 -0
  332. package/storage/redis/redis.test.ts +170 -10
  333. package/storage/redis/reply.ts +76 -1
  334. package/storage/redis/runtime.test.ts +15 -0
  335. package/storage/redis/target.ts +47 -44
  336. package/storage/redis/wire.ts +8 -32
  337. package/testing/bun.ts +13 -0
  338. package/testing/jest.ts +11 -0
  339. package/testing/mod.ts +337 -0
  340. package/testing/node.ts +12 -0
  341. package/testing/vitest.ts +13 -0
  342. package/tracing/mod.ts +82 -0
  343. package/tracing/native.test.ts +170 -0
  344. package/tracing/tracing.test.ts +317 -0
  345. package/dist/internal/otel/request_context.d.ts +0 -11
  346. package/dist/internal/otel/request_context.js +0 -20
  347. package/dist/internal/otel/request_context.js.map +0 -1
  348. package/dist/internal/reqtrack/mod.d.ts +0 -6
  349. package/dist/internal/reqtrack/mod.js +0 -28
  350. package/dist/internal/reqtrack/mod.js.map +0 -1
  351. package/dist/req_meta.d.ts +0 -47
  352. package/dist/req_meta.js +0 -26
  353. package/dist/req_meta.js.map +0 -1
  354. package/internal/otel/request_context.ts +0 -32
  355. package/internal/reqtrack/mod.ts +0 -39
  356. package/req_meta.ts +0 -75
@@ -0,0 +1,193 @@
1
+ import {describe, expect, mock, test} from 'bun:test';
2
+ import {
3
+ defaultTextMapGetter,
4
+ ROOT_CONTEXT,
5
+ type Context,
6
+ } from '@opentelemetry/api';
7
+
8
+ const warnings = mock((..._args: unknown[]) => {});
9
+ mock.module('../log/index', () => ({default: {warn: warnings}}));
10
+
11
+ const {Field, Propagator, extract, inject} = await import('./mod');
12
+ const reqfields = await import('../internal/reqfields');
13
+
14
+ interface User {
15
+ id: string;
16
+ admin?: boolean;
17
+ }
18
+
19
+ const user = new Field<User>('user');
20
+ const tenant = new Field<string>('tenant-id', {pubsub: true, trace: true});
21
+
22
+ function wire(value: unknown): string {
23
+ return Buffer.from(JSON.stringify(value)).toString('base64url');
24
+ }
25
+
26
+ describe('Field', () => {
27
+ test('reads what was set for the code it runs, across awaits', async () => {
28
+ expect(user.get()).toBeUndefined();
29
+ const seen = await user.with({id: 'u1'}, async () => {
30
+ await new Promise(r => setTimeout(r, 1));
31
+ const inner = user.without(() => user.get());
32
+ return {value: user.get(), inner};
33
+ });
34
+ expect(seen).toEqual({value: {id: 'u1'}, inner: undefined});
35
+ expect(user.get()).toBeUndefined();
36
+ });
37
+
38
+ test('each read is a fresh value', () => {
39
+ user.with({id: 'u1'}, () => {
40
+ user.get()!.id = 'changed';
41
+ expect(user.get()).toEqual({id: 'u1'});
42
+ });
43
+ });
44
+
45
+ test('a named reference is the same field', () => {
46
+ const byName = Field.named<User>('user');
47
+ const ctx = user.context({id: 'u2', admin: true}, ROOT_CONTEXT);
48
+ expect(byName.get(ctx)).toEqual({id: 'u2', admin: true});
49
+ expect(byName.name).toBe('user');
50
+ expect(byName.get(byName.contextWithout(ctx))).toBeUndefined();
51
+ });
52
+
53
+ test('explicit contexts leave the active one alone', () => {
54
+ const ctx: Context = tenant.context('acme', ROOT_CONTEXT);
55
+ expect(tenant.get(ctx)).toBe('acme');
56
+ expect(tenant.get()).toBeUndefined();
57
+ expect(reqfields.current(ctx)).toEqual({'tenant-id': wire('acme')});
58
+ });
59
+
60
+ test('a request carries only names a field could have', () => {
61
+ // As the parser has them; it checks the declarations.
62
+ for (const name of ['a', 'tenant-id', 'a--b', 'a'.repeat(63)]) {
63
+ expect(reqfields.validName(name)).toBe(true);
64
+ }
65
+ for (const name of [
66
+ 'User',
67
+ 'tenant_id',
68
+ '2fa',
69
+ '-a',
70
+ 'a-',
71
+ '',
72
+ 'a'.repeat(64),
73
+ ]) {
74
+ expect(reqfields.validName(name)).toBe(false);
75
+ }
76
+ });
77
+
78
+ test('limits fail where the value is set', () => {
79
+ expect(() => user.with({id: 'a'.repeat(4000)}, () => {})).toThrow(
80
+ RangeError,
81
+ );
82
+ expect(() => user.context({id: 'a'.repeat(4000)})).toThrow(
83
+ /^reqctx: field "user": the value encodes to \d+ bytes, more than the 4096 a field may$/,
84
+ );
85
+ expect(() => tenant.context('a'.repeat(1000))).toThrow(
86
+ 'carried on Pub/Sub messages',
87
+ );
88
+ const big = 'a'.repeat(2900);
89
+ const ctx = ['a', 'b'].reduce(
90
+ (c, n) => Field.named<string>(`big-${n}`).context(big, c),
91
+ ROOT_CONTEXT,
92
+ );
93
+ expect(() => user.context({id: big}, ctx)).toThrow(
94
+ "makes the request's fields encode to",
95
+ );
96
+ });
97
+
98
+ test('values without a JSON form throw a TypeError', () => {
99
+ const cycle: Record<string, unknown> = {};
100
+ cycle.self = cycle;
101
+ for (const value of [undefined, 1n, cycle, () => 1]) {
102
+ expect(() => Field.named<unknown>('any').context(value)).toThrow(
103
+ TypeError,
104
+ );
105
+ }
106
+ });
107
+
108
+ test('undecodable values read as unset and are logged once, without the value', () => {
109
+ warnings.mockClear();
110
+ const plan = Field.named<string>('plan');
111
+ for (const value of ['!!', wire('x').slice(0, 1), 'eyJzZWNyZXQiOg']) {
112
+ const ctx = reqfields.withFields({plan: value}, ROOT_CONTEXT);
113
+ expect(plan.get(ctx)).toBeUndefined();
114
+ }
115
+ expect(warnings).toHaveBeenCalledTimes(1);
116
+ expect(String(warnings.mock.calls[0]![0])).toContain('"plan"');
117
+ expect(String(warnings.mock.calls[0]![0])).not.toContain('secret');
118
+ });
119
+ });
120
+
121
+ describe('headers', () => {
122
+ test('are read in any case, the first value of each', () => {
123
+ const ctx = extract(
124
+ {
125
+ 'X-Encore-Meta-Ctx-User': [wire({id: 'u1'}), wire({id: 'u2'})],
126
+ 'x-encore-meta-ctx-Bad_Name': wire(1),
127
+ 'x-encore-meta-caller': 'x',
128
+ },
129
+ ROOT_CONTEXT,
130
+ );
131
+ expect(user.get(ctx)).toEqual({id: 'u1'});
132
+ expect(reqfields.current(ctx)).toEqual({user: wire({id: 'u1'})});
133
+
134
+ const headers = new Headers({'x-encore-meta-ctx-tenant-id': wire('acme')});
135
+ expect(tenant.get(extract(headers, ROOT_CONTEXT))).toBe('acme');
136
+ // None carried: the context is the one given.
137
+ expect(extract({}, ROOT_CONTEXT)).toBe(ROOT_CONTEXT);
138
+ });
139
+
140
+ test('injecting replaces the fields a request carried', () => {
141
+ const ctx = user.context({id: 'u1'}, ROOT_CONTEXT);
142
+ const record: Record<string, string> = {
143
+ 'X-Encore-Meta-Ctx-Stale': 'e30',
144
+ accept: '*/*',
145
+ };
146
+ inject(record, ctx);
147
+ expect(record).toEqual({
148
+ accept: '*/*',
149
+ 'x-encore-meta-ctx-user': wire({id: 'u1'}),
150
+ });
151
+ const headers = new Headers({'x-encore-meta-ctx-stale': 'e30'});
152
+ inject(headers, ctx);
153
+ expect([...headers.keys()]).toEqual(['x-encore-meta-ctx-user']);
154
+ });
155
+
156
+ test('the propagator extracts fields and injects none', () => {
157
+ const propagator = new Propagator();
158
+ const carrier: Record<string, string> = {
159
+ 'x-encore-meta-ctx-user': wire({id: 'u1'}),
160
+ };
161
+ const ctx = propagator.extract(ROOT_CONTEXT, carrier, defaultTextMapGetter);
162
+ expect(user.get(ctx)).toEqual({id: 'u1'});
163
+ const out: Record<string, string> = {};
164
+ propagator.inject();
165
+ expect(out).toEqual({});
166
+ expect(propagator.fields()).toEqual([]);
167
+ });
168
+ });
169
+
170
+ describe('the runtime config', () => {
171
+ test('says how a field travels, wherever it is declared', () => {
172
+ const plan = Field.named<string>('declared-elsewhere');
173
+ expect(() => plan.context('a'.repeat(2000))).not.toThrow();
174
+ reqfields.setDeclaredLookup(name =>
175
+ name === 'declared-elsewhere' ? {pubsub: true, trace: true} : null,
176
+ );
177
+ try {
178
+ expect(() => plan.context('a'.repeat(2000))).toThrow(
179
+ 'carried on Pub/Sub messages',
180
+ );
181
+ expect(reqfields.spanAttributes(plan.context('x', ROOT_CONTEXT))).toEqual(
182
+ {'encore.ctx.declared-elsewhere': '"x"'},
183
+ );
184
+ // A field the runtime config does not list has its own declaration.
185
+ expect(reqfields.configOf('tenant-id')).toEqual({
186
+ pubsub: true,
187
+ trace: true,
188
+ });
189
+ } finally {
190
+ reqfields.setDeclaredLookup(() => null);
191
+ }
192
+ });
193
+ });
@@ -0,0 +1,48 @@
1
+ import {
2
+ copyFileSync,
3
+ mkdirSync,
4
+ mkdtempSync,
5
+ readFileSync,
6
+ rmSync,
7
+ writeFileSync,
8
+ } from 'node:fs';
9
+ import {tmpdir} from 'node:os';
10
+ import {join} from 'node:path';
11
+ import {describe, expect, test} from 'bun:test';
12
+
13
+ const script = new URL('./postprocess-docs.mjs', import.meta.url);
14
+
15
+ describe('postprocess-docs', () => {
16
+ test.each([false, true])(
17
+ 'tracing docs with existing frontmatter: %s',
18
+ existing => {
19
+ const root = mkdtempSync(join(tmpdir(), 'encore-docs-'));
20
+ const sdkScripts = join(root, 'sdk/ts/infra/scripts');
21
+ const docs = join(root, 'docs/ts/runtime');
22
+ mkdirSync(sdkScripts, {recursive: true});
23
+ mkdirSync(docs, {recursive: true});
24
+ copyFileSync(script, join(sdkScripts, 'postprocess-docs.mjs'));
25
+ writeFileSync(
26
+ join(docs, 'tracing.mod.mdx'),
27
+ existing ? '---\nlang: ts\n---\n# Tracing\n' : '# Tracing\n',
28
+ );
29
+ writeFileSync(join(docs, 'other.mdx'), '[Tracing](tracing.mod.mdx)\n');
30
+
31
+ try {
32
+ const result = Bun.spawnSync({
33
+ cmd: [process.execPath, join(sdkScripts, 'postprocess-docs.mjs')],
34
+ });
35
+ expect(result.exitCode).toBe(0);
36
+ const page = readFileSync(join(docs, 'tracing.mdx'), 'utf8');
37
+ expect(Bun.YAML.parse(page.split('---\n')[1]!)).toMatchObject({
38
+ title: '@encore.dev/sdk/tracing',
39
+ });
40
+ expect(readFileSync(join(docs, 'other.mdx'), 'utf8')).toContain(
41
+ '[Tracing](/ts/runtime/tracing)',
42
+ );
43
+ } finally {
44
+ rmSync(root, {recursive: true, force: true});
45
+ }
46
+ },
47
+ );
48
+ });
@@ -7,8 +7,29 @@ mock.module('../internal/runtime/mod', () => ({
7
7
  runtimeConfig: () => config,
8
8
  }));
9
9
 
10
- const {serviceUrl} = await import('.');
10
+ const {baseUrl, serviceUrl} = await import('.');
11
11
 
12
+ describe('baseUrl', () => {
13
+ test('has no trailing slash, so a path goes after it', () => {
14
+ config.services = {users: 'http://127.0.0.1:4000/users'};
15
+ expect(baseUrl('users')).toBe('http://127.0.0.1:4000/users');
16
+ expect(`${baseUrl('users')}/1`).toBe('http://127.0.0.1:4000/users/1');
17
+ });
18
+
19
+ test('drops a trailing slash the runtime config has', () => {
20
+ config.services = {users: 'http://127.0.0.1:4000/users/'};
21
+ expect(baseUrl('users')).toBe('http://127.0.0.1:4000/users');
22
+ config.services = {users: 'http://127.0.0.1:4000/'};
23
+ expect(baseUrl('users')).toBe('http://127.0.0.1:4000');
24
+ });
25
+
26
+ test('throws for an unknown service', () => {
27
+ config.services = {};
28
+ expect(() => baseUrl('nope')).toThrow('unknown service');
29
+ });
30
+ });
31
+
32
+ // The deprecated alias keeps its URL, ending in `/`.
12
33
  describe('serviceUrl', () => {
13
34
  test('resolves relative paths under the base', () => {
14
35
  config.services = {users: 'http://127.0.0.1:4000/users'};
@@ -28,3 +49,322 @@ describe('serviceUrl', () => {
28
49
  expect(() => serviceUrl('nope')).toThrow('unknown service');
29
50
  });
30
51
  });
52
+
53
+ const {client, fetch} = await import('.');
54
+ const {withContext} = await import('../internal/otel/context');
55
+ const reqfields = await import('../internal/reqfields');
56
+ const {ROOT_CONTEXT, trace, createTraceState, TraceFlags} =
57
+ await import('@opentelemetry/api');
58
+
59
+ /** What a server received. */
60
+ interface Received {
61
+ path: string;
62
+ method: string;
63
+ headers: Record<string, string>;
64
+ body: string;
65
+ }
66
+
67
+ /** A local server recording what it receives; `routes` answers some paths
68
+ * itself. */
69
+ function server(routes: Record<string, (req: Request) => Response> = {}) {
70
+ const received: Received[] = [];
71
+ const srv = Bun.serve({
72
+ port: 0,
73
+ hostname: '127.0.0.1',
74
+ async fetch(req) {
75
+ const url = new URL(req.url);
76
+ received.push({
77
+ path: url.pathname + url.search,
78
+ method: req.method,
79
+ headers: Object.fromEntries(req.headers),
80
+ body: await req.text(),
81
+ });
82
+ return routes[url.pathname]?.(req) ?? new Response('ok');
83
+ },
84
+ });
85
+ return {
86
+ received,
87
+ url: `http://127.0.0.1:${srv.port}`,
88
+ stop: () => srv.stop(true),
89
+ };
90
+ }
91
+
92
+ /** That `received` carried no Request Context header. */
93
+ function no(received: Received): void {
94
+ for (const name of Object.keys(received.headers)) {
95
+ expect(name).not.toStartWith('x-encore-meta-ctx-');
96
+ }
97
+ }
98
+
99
+ const TRACE_ID = '0af7651916cd43dd8448eb211c80319c';
100
+ const SPAN_ID = 'b7ad6b7169203331';
101
+ const TRACEPARENT = `00-${TRACE_ID}-${SPAN_ID}-01`;
102
+
103
+ /** A request's context: a span with Encore's mark, and a field. */
104
+ const callContext = trace.setSpanContext(
105
+ reqfields.withFields({plan: 'InBybyI'}, ROOT_CONTEXT),
106
+ {
107
+ traceId: TRACE_ID,
108
+ spanId: SPAN_ID,
109
+ traceFlags: TraceFlags.SAMPLED,
110
+ isRemote: true,
111
+ traceState: createTraceState('encore=rc,vendor=1'),
112
+ },
113
+ );
114
+
115
+ /** The headers a handler received, as one copying them onto its own
116
+ * requests passes them on. */
117
+ const inbound = () => ({
118
+ 'x-encore-meta-ctx-plan': 'InN0YWxlIg',
119
+ 'x-encore-meta-ctx-stale': 'x',
120
+ accept: 'application/json',
121
+ });
122
+
123
+ describe('fetch', () => {
124
+ test('sends the context to services, and no Request Context elsewhere', async () => {
125
+ const svc = server();
126
+ const third = server();
127
+ try {
128
+ config.services = {billing: `${svc.url}/billing`};
129
+ const billing = client('billing');
130
+ await withContext(callContext, async () => {
131
+ await billing.fetch('/invoices', {headers: inbound()});
132
+ await fetch(`${third.url}/hook`, {headers: inbound()});
133
+ });
134
+ const [toService] = svc.received;
135
+ expect(toService!.path).toBe('/billing/invoices');
136
+ expect(toService!.headers['x-encore-meta-ctx-plan']).toBe('InBybyI');
137
+ expect(toService!.headers['x-encore-meta-ctx-stale']).toBeUndefined();
138
+ expect(toService!.headers.traceparent).toBe(TRACEPARENT);
139
+ expect(toService!.headers.tracestate).toBe('encore=rc,vendor=1');
140
+ expect(toService!.headers.accept).toBe('application/json');
141
+
142
+ const [toThirdParty] = third.received;
143
+ for (const name of Object.keys(toThirdParty!.headers)) {
144
+ expect(name).not.toStartWith('x-encore-meta-ctx-');
145
+ }
146
+ expect(toThirdParty!.headers.traceparent).toBeUndefined();
147
+ expect(toThirdParty!.headers.accept).toBe('application/json');
148
+ } finally {
149
+ svc.stop();
150
+ third.stop();
151
+ }
152
+ });
153
+
154
+ test('replaces a tracestate the request carries without a traceparent', async () => {
155
+ const svc = server();
156
+ try {
157
+ config.services = {billing: svc.url};
158
+ await withContext(callContext, () =>
159
+ client('billing').fetch('x', {
160
+ headers: {tracestate: 'encore=r,stale=1'},
161
+ }),
162
+ );
163
+ expect(svc.received[0]!.headers.tracestate).toBe('encore=rc,vendor=1');
164
+ } finally {
165
+ svc.stop();
166
+ }
167
+ });
168
+
169
+ test('keeps a traceparent the request carries', async () => {
170
+ const svc = server();
171
+ try {
172
+ config.services = {billing: svc.url};
173
+ const own = `00-${'1'.repeat(32)}-${'2'.repeat(16)}-01`;
174
+ await withContext(callContext, () =>
175
+ client('billing').fetch('x', {headers: {traceparent: own}}),
176
+ );
177
+ expect(svc.received[0]!.headers.traceparent).toBe(own);
178
+ } finally {
179
+ svc.stop();
180
+ }
181
+ });
182
+
183
+ test('takes a Request, whose headers and body it sends', async () => {
184
+ const svc = server();
185
+ try {
186
+ config.services = {billing: svc.url};
187
+ const base = client('billing').baseUrl;
188
+ const req = new Request(`${base}/charge`, {
189
+ method: 'POST',
190
+ headers: {'content-type': 'text/plain'},
191
+ body: 'ten',
192
+ });
193
+ await withContext(callContext, () => fetch(req));
194
+ expect(svc.received[0]).toMatchObject({
195
+ path: '/charge',
196
+ method: 'POST',
197
+ body: 'ten',
198
+ headers: {
199
+ 'content-type': 'text/plain',
200
+ 'x-encore-meta-ctx-plan': 'InBybyI',
201
+ },
202
+ });
203
+ } finally {
204
+ svc.stop();
205
+ }
206
+ });
207
+
208
+ test('a redirect away from a service does not carry its Request Context', async () => {
209
+ const third = server();
210
+ const svc = server({
211
+ '/away': () => Response.redirect(`${third.url}/landed`, 307),
212
+ '/here': () => Response.redirect('/billing/landed', 303),
213
+ });
214
+ try {
215
+ config.services = {billing: `${svc.url}/billing`};
216
+ const billing = client('billing');
217
+ const [away, here] = await withContext(callContext, () =>
218
+ Promise.all([
219
+ billing.fetch(`${svc.url}/away`, {
220
+ method: 'PUT',
221
+ body: 'payload',
222
+ headers: {authorization: 'Bearer t'},
223
+ }),
224
+ billing.fetch(`${svc.url}/here`, {method: 'POST', body: 'form'}),
225
+ ]),
226
+ );
227
+ expect(away.status).toBe(200);
228
+ expect(here.status).toBe(200);
229
+ expect([away.redirected, away.url]).toEqual([
230
+ true,
231
+ `${third.url}/landed`,
232
+ ]);
233
+
234
+ // 307 keeps the method and body, but not the credentials or fields.
235
+ const landed = third.received[0]!;
236
+ expect(landed).toMatchObject({
237
+ path: '/landed',
238
+ method: 'PUT',
239
+ body: 'payload',
240
+ });
241
+ expect(landed.headers.authorization).toBeUndefined();
242
+ for (const name of Object.keys(landed.headers)) {
243
+ expect(name).not.toStartWith('x-encore-meta-ctx-');
244
+ }
245
+
246
+ // 303 within the services turns into a GET, and still carries them.
247
+ const within = svc.received.find(r => r.path === '/billing/landed')!;
248
+ expect(within.method).toBe('GET');
249
+ expect(within.body).toBe('');
250
+ expect(within.headers['x-encore-meta-ctx-plan']).toBe('InBybyI');
251
+ } finally {
252
+ svc.stop();
253
+ third.stop();
254
+ }
255
+ });
256
+
257
+ test("a Request's body is streamed, so only a redirect that drops it is followed", async () => {
258
+ const svc = server({
259
+ '/again': () => Response.redirect('/landed', 307),
260
+ '/other': () => Response.redirect('/landed', 303),
261
+ });
262
+ try {
263
+ config.services = {billing: svc.url};
264
+ const base = client('billing').baseUrl;
265
+ const post = (path: string) =>
266
+ new Request(`${base}${path}`, {method: 'POST', body: 'upload'});
267
+ const res = await withContext(callContext, () => fetch(post('/other')));
268
+ expect(res.status).toBe(200);
269
+ expect(svc.received.map(r => [r.method, r.path, r.body])).toEqual([
270
+ ['POST', '/other', 'upload'],
271
+ ['GET', '/landed', ''],
272
+ ]);
273
+ await expect(
274
+ withContext(callContext, () => fetch(post('/again'))),
275
+ ).rejects.toThrow('streamed body');
276
+
277
+ // Its fetch policies go with it, those the runtime keeps on a Request.
278
+ const sent = mock(globalThis.fetch);
279
+ const real = globalThis.fetch;
280
+ globalThis.fetch = sent as unknown as typeof globalThis.fetch;
281
+ try {
282
+ // Node's types have no `cache` or `mode`; its Request has them.
283
+ const req = new Request(`${base}/other`, {
284
+ cache: 'no-store',
285
+ mode: 'same-origin',
286
+ } as RequestInit);
287
+ await withContext(callContext, () => fetch(req)).catch(() => {});
288
+ } finally {
289
+ globalThis.fetch = real;
290
+ }
291
+ const init = sent.mock.calls[0]![1] as Record<string, unknown>;
292
+ expect(init.cache).toBe('no-store');
293
+ expect(init.mode).toBe('same-origin');
294
+ } finally {
295
+ svc.stop();
296
+ }
297
+ });
298
+
299
+ test('a redirect from a third party to a service carries the context there', async () => {
300
+ const svc = server();
301
+ const third = server({
302
+ '/hop': () => Response.redirect(`${svc.url}/billing/landed`, 302),
303
+ });
304
+ try {
305
+ config.services = {billing: `${svc.url}/billing`};
306
+ client('billing');
307
+ const res = await withContext(callContext, () =>
308
+ fetch(`${third.url}/hop`),
309
+ );
310
+ expect(res.status).toBe(200);
311
+ no(third.received[0]!);
312
+ const landed = svc.received[0]!;
313
+ expect(landed.path).toBe('/billing/landed');
314
+ expect(landed.headers['x-encore-meta-ctx-plan']).toBe('InBybyI');
315
+ expect(landed.headers.traceparent).toBe(TRACEPARENT);
316
+ } finally {
317
+ svc.stop();
318
+ third.stop();
319
+ }
320
+ });
321
+
322
+ test("an option set to undefined leaves the Request's own", async () => {
323
+ const svc = server();
324
+ try {
325
+ config.services = {billing: svc.url};
326
+ const base = client('billing').baseUrl;
327
+ const req = new Request(`${base}/charge`, {method: 'PUT', body: 'ten'});
328
+ await withContext(callContext, () =>
329
+ fetch(req, {body: undefined, method: undefined}),
330
+ );
331
+ expect(svc.received[0]).toMatchObject({method: 'PUT', body: 'ten'});
332
+ } finally {
333
+ svc.stop();
334
+ }
335
+ });
336
+
337
+ test("a redirect without Request Context is fetch's own", async () => {
338
+ const third = server();
339
+ const svc = server({
340
+ '/away': () => Response.redirect(`${third.url}/landed`, 302),
341
+ });
342
+ try {
343
+ config.services = {billing: svc.url};
344
+ const res = await client('billing').fetch('/away');
345
+ expect(res.redirected).toBe(true);
346
+ expect(third.received[0]!.path).toBe('/landed');
347
+ } finally {
348
+ svc.stop();
349
+ third.stop();
350
+ }
351
+ });
352
+
353
+ test("is a typeof fetch, with the global fetch's members", () => {
354
+ for (const key of Object.getOwnPropertyNames(globalThis.fetch)) {
355
+ expect(key in fetch).toBe(true);
356
+ }
357
+ });
358
+ });
359
+
360
+ describe('client', () => {
361
+ test('joins paths with one slash and takes absolute URLs as they are', () => {
362
+ config.services = {users: 'http://127.0.0.1:4000/users/'};
363
+ expect(client('users').baseUrl).toBe('http://127.0.0.1:4000/users');
364
+ });
365
+
366
+ test('throws for an unknown service', () => {
367
+ config.services = {};
368
+ expect(() => client('nope')).toThrow('unknown service');
369
+ });
370
+ });