@encore.dev/sdk 0.0.0 → 2.0.0-beta.5

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 (250) hide show
  1. package/LICENSE +362 -0
  2. package/README.md +122 -2
  3. package/app_meta.test.ts +134 -0
  4. package/app_meta.ts +186 -0
  5. package/config/config.test.ts +381 -0
  6. package/config/config.ts +178 -0
  7. package/config/mod.ts +14 -0
  8. package/config/secrets.ts +147 -0
  9. package/config/value.ts +243 -0
  10. package/cron/mod.ts +23 -0
  11. package/dist/app_meta.d.ts +93 -0
  12. package/dist/app_meta.js +65 -0
  13. package/dist/app_meta.js.map +1 -0
  14. package/dist/config/config.d.ts +105 -0
  15. package/dist/config/config.js +87 -0
  16. package/dist/config/config.js.map +1 -0
  17. package/dist/config/mod.d.ts +4 -0
  18. package/dist/config/mod.js +3 -0
  19. package/dist/config/mod.js.map +1 -0
  20. package/dist/config/secrets.d.ts +92 -0
  21. package/dist/config/secrets.js +80 -0
  22. package/dist/config/secrets.js.map +1 -0
  23. package/dist/config/value.d.ts +51 -0
  24. package/dist/config/value.js +178 -0
  25. package/dist/config/value.js.map +1 -0
  26. package/dist/cron/mod.d.ts +22 -0
  27. package/dist/cron/mod.js +9 -0
  28. package/dist/cron/mod.js.map +1 -0
  29. package/dist/internal/otel/backend.d.ts +50 -0
  30. package/dist/internal/otel/backend.js +2 -0
  31. package/dist/internal/otel/backend.js.map +1 -0
  32. package/dist/internal/otel/context.d.ts +10 -0
  33. package/dist/internal/otel/context.js +34 -0
  34. package/dist/internal/otel/context.js.map +1 -0
  35. package/dist/internal/otel/context_manager.d.ts +22 -0
  36. package/dist/internal/otel/context_manager.js +120 -0
  37. package/dist/internal/otel/context_manager.js.map +1 -0
  38. package/dist/internal/otel/encode.d.ts +112 -0
  39. package/dist/internal/otel/encode.js +290 -0
  40. package/dist/internal/otel/encode.js.map +1 -0
  41. package/dist/internal/otel/index.d.ts +9 -0
  42. package/dist/internal/otel/index.js +9 -0
  43. package/dist/internal/otel/index.js.map +1 -0
  44. package/dist/internal/otel/meter.d.ts +73 -0
  45. package/dist/internal/otel/meter.js +265 -0
  46. package/dist/internal/otel/meter.js.map +1 -0
  47. package/dist/internal/otel/propagator.d.ts +14 -0
  48. package/dist/internal/otel/propagator.js +61 -0
  49. package/dist/internal/otel/propagator.js.map +1 -0
  50. package/dist/internal/otel/provider.d.ts +9 -0
  51. package/dist/internal/otel/provider.js +19 -0
  52. package/dist/internal/otel/provider.js.map +1 -0
  53. package/dist/internal/otel/request_context.d.ts +11 -0
  54. package/dist/internal/otel/request_context.js +20 -0
  55. package/dist/internal/otel/request_context.js.map +1 -0
  56. package/dist/internal/otel/span.d.ts +61 -0
  57. package/dist/internal/otel/span.js +206 -0
  58. package/dist/internal/otel/span.js.map +1 -0
  59. package/dist/internal/otel/tracer.d.ts +15 -0
  60. package/dist/internal/otel/tracer.js +65 -0
  61. package/dist/internal/otel/tracer.js.map +1 -0
  62. package/dist/internal/reqtrack/mod.d.ts +6 -0
  63. package/dist/internal/reqtrack/mod.js +28 -0
  64. package/dist/internal/reqtrack/mod.js.map +1 -0
  65. package/dist/internal/runtime/meter.d.ts +11 -0
  66. package/dist/internal/runtime/meter.js +22 -0
  67. package/dist/internal/runtime/meter.js.map +1 -0
  68. package/dist/internal/runtime/mod.d.ts +12 -0
  69. package/dist/internal/runtime/mod.js +28 -0
  70. package/dist/internal/runtime/mod.js.map +1 -0
  71. package/dist/internal/runtime/napi/napi.cjs +122 -0
  72. package/dist/internal/runtime/napi/napi.d.cts +601 -0
  73. package/dist/internal/runtime/shutdown.d.ts +13 -0
  74. package/dist/internal/runtime/shutdown.js +56 -0
  75. package/dist/internal/runtime/shutdown.js.map +1 -0
  76. package/dist/internal/utils/constraints.d.ts +9 -0
  77. package/dist/internal/utils/constraints.js +2 -0
  78. package/dist/internal/utils/constraints.js.map +1 -0
  79. package/dist/log/index.d.ts +39 -0
  80. package/dist/log/index.js +44 -0
  81. package/dist/log/index.js.map +1 -0
  82. package/dist/log/logger.d.ts +123 -0
  83. package/dist/log/logger.js +203 -0
  84. package/dist/log/logger.js.map +1 -0
  85. package/dist/log/runtime.d.ts +19 -0
  86. package/dist/log/runtime.js +22 -0
  87. package/dist/log/runtime.js.map +1 -0
  88. package/dist/log/stderr.d.ts +9 -0
  89. package/dist/log/stderr.js +25 -0
  90. package/dist/log/stderr.js.map +1 -0
  91. package/dist/metrics/mod.d.ts +315 -0
  92. package/dist/metrics/mod.js +488 -0
  93. package/dist/metrics/mod.js.map +1 -0
  94. package/dist/mod.d.ts +6 -0
  95. package/dist/mod.js +4 -0
  96. package/dist/mod.js.map +1 -0
  97. package/dist/otel.d.ts +9 -0
  98. package/dist/otel.js +13 -0
  99. package/dist/otel.js.map +1 -0
  100. package/dist/pubsub/encoding.d.ts +3 -0
  101. package/dist/pubsub/encoding.js +10 -0
  102. package/dist/pubsub/encoding.js.map +1 -0
  103. package/dist/pubsub/mod.d.ts +6 -0
  104. package/dist/pubsub/mod.js +3 -0
  105. package/dist/pubsub/mod.js.map +1 -0
  106. package/dist/pubsub/refs.d.ts +12 -0
  107. package/dist/pubsub/refs.js +11 -0
  108. package/dist/pubsub/refs.js.map +1 -0
  109. package/dist/pubsub/subscription.d.ts +128 -0
  110. package/dist/pubsub/subscription.js +39 -0
  111. package/dist/pubsub/subscription.js.map +1 -0
  112. package/dist/pubsub/topic.d.ts +148 -0
  113. package/dist/pubsub/topic.js +164 -0
  114. package/dist/pubsub/topic.js.map +1 -0
  115. package/dist/req_meta.d.ts +47 -0
  116. package/dist/req_meta.js +26 -0
  117. package/dist/req_meta.js.map +1 -0
  118. package/dist/services/index.d.ts +12 -0
  119. package/dist/services/index.js +22 -0
  120. package/dist/services/index.js.map +1 -0
  121. package/dist/shutdown/mod.d.ts +23 -0
  122. package/dist/shutdown/mod.js +24 -0
  123. package/dist/shutdown/mod.js.map +1 -0
  124. package/dist/storage/objects/bucket.d.ts +216 -0
  125. package/dist/storage/objects/bucket.js +123 -0
  126. package/dist/storage/objects/bucket.js.map +1 -0
  127. package/dist/storage/objects/error.d.ts +14 -0
  128. package/dist/storage/objects/error.js +81 -0
  129. package/dist/storage/objects/error.js.map +1 -0
  130. package/dist/storage/objects/mod.d.ts +4 -0
  131. package/dist/storage/objects/mod.js +3 -0
  132. package/dist/storage/objects/mod.js.map +1 -0
  133. package/dist/storage/objects/refs.d.ts +31 -0
  134. package/dist/storage/objects/refs.js +20 -0
  135. package/dist/storage/objects/refs.js.map +1 -0
  136. package/dist/storage/postgres/database.d.ts +295 -0
  137. package/dist/storage/postgres/database.js +378 -0
  138. package/dist/storage/postgres/database.js.map +1 -0
  139. package/dist/storage/postgres/mod.d.ts +2 -0
  140. package/dist/storage/postgres/mod.js +2 -0
  141. package/dist/storage/postgres/mod.js.map +1 -0
  142. package/dist/storage/redis/commands.d.ts +573 -0
  143. package/dist/storage/redis/commands.js +637 -0
  144. package/dist/storage/redis/commands.js.map +1 -0
  145. package/dist/storage/redis/database.d.ts +302 -0
  146. package/dist/storage/redis/database.js +336 -0
  147. package/dist/storage/redis/database.js.map +1 -0
  148. package/dist/storage/redis/mod.d.ts +88 -0
  149. package/dist/storage/redis/mod.js +84 -0
  150. package/dist/storage/redis/mod.js.map +1 -0
  151. package/dist/storage/redis/native.d.ts +8 -0
  152. package/dist/storage/redis/native.js +11 -0
  153. package/dist/storage/redis/native.js.map +1 -0
  154. package/dist/storage/redis/options.d.ts +89 -0
  155. package/dist/storage/redis/options.js +53 -0
  156. package/dist/storage/redis/options.js.map +1 -0
  157. package/dist/storage/redis/pubsub.d.ts +53 -0
  158. package/dist/storage/redis/pubsub.js +88 -0
  159. package/dist/storage/redis/pubsub.js.map +1 -0
  160. package/dist/storage/redis/reply.d.ts +256 -0
  161. package/dist/storage/redis/reply.js +572 -0
  162. package/dist/storage/redis/reply.js.map +1 -0
  163. package/dist/storage/redis/scan.d.ts +11 -0
  164. package/dist/storage/redis/scan.js +76 -0
  165. package/dist/storage/redis/scan.js.map +1 -0
  166. package/dist/storage/redis/script.d.ts +91 -0
  167. package/dist/storage/redis/script.js +143 -0
  168. package/dist/storage/redis/script.js.map +1 -0
  169. package/dist/storage/redis/target.d.ts +47 -0
  170. package/dist/storage/redis/target.js +82 -0
  171. package/dist/storage/redis/target.js.map +1 -0
  172. package/dist/storage/redis/wire.d.ts +105 -0
  173. package/dist/storage/redis/wire.js +333 -0
  174. package/dist/storage/redis/wire.js.map +1 -0
  175. package/dist/tsconfig.build.tsbuildinfo +1 -0
  176. package/dist/types/mod.d.ts +42 -0
  177. package/dist/types/mod.js +65 -0
  178. package/dist/types/mod.js.map +1 -0
  179. package/internal/otel/backend.ts +60 -0
  180. package/internal/otel/context.test.ts +70 -0
  181. package/internal/otel/context.ts +48 -0
  182. package/internal/otel/context_manager.test.ts +154 -0
  183. package/internal/otel/context_manager.ts +141 -0
  184. package/internal/otel/encode.test.ts +266 -0
  185. package/internal/otel/encode.ts +408 -0
  186. package/internal/otel/index.ts +20 -0
  187. package/internal/otel/meter.test.ts +231 -0
  188. package/internal/otel/meter.ts +332 -0
  189. package/internal/otel/propagator.test.ts +105 -0
  190. package/internal/otel/propagator.ts +68 -0
  191. package/internal/otel/provider.ts +23 -0
  192. package/internal/otel/request_context.ts +32 -0
  193. package/internal/otel/span.ts +252 -0
  194. package/internal/otel/tracer.test.ts +352 -0
  195. package/internal/otel/tracer.ts +104 -0
  196. package/internal/reqtrack/mod.ts +39 -0
  197. package/internal/runtime/meter.ts +26 -0
  198. package/internal/runtime/mod.ts +41 -0
  199. package/internal/runtime/napi/napi.cjs +122 -0
  200. package/internal/runtime/napi/napi.d.cts +601 -0
  201. package/internal/runtime/shutdown.test.ts +248 -0
  202. package/internal/runtime/shutdown.ts +64 -0
  203. package/internal/utils/constraints.ts +12 -0
  204. package/log/index.ts +107 -0
  205. package/log/logger.test.ts +194 -0
  206. package/log/logger.ts +308 -0
  207. package/log/runtime.test.ts +65 -0
  208. package/log/runtime.ts +40 -0
  209. package/log/stderr.test.ts +23 -0
  210. package/log/stderr.ts +24 -0
  211. package/metrics/export.test.ts +337 -0
  212. package/metrics/mod.test.ts +180 -0
  213. package/metrics/mod.ts +619 -0
  214. package/mod.ts +22 -0
  215. package/otel.test.ts +84 -0
  216. package/otel.ts +17 -0
  217. package/package.json +121 -5
  218. package/pubsub/encoding.ts +8 -0
  219. package/pubsub/mod.ts +14 -0
  220. package/pubsub/pubsub.test.ts +186 -0
  221. package/pubsub/refs.ts +22 -0
  222. package/pubsub/subscription.ts +180 -0
  223. package/pubsub/topic.test.ts +121 -0
  224. package/pubsub/topic.ts +212 -0
  225. package/req_meta.ts +75 -0
  226. package/services/index.test.ts +30 -0
  227. package/services/index.ts +21 -0
  228. package/shutdown/mod.ts +24 -0
  229. package/storage/objects/bucket.ts +338 -0
  230. package/storage/objects/error.ts +94 -0
  231. package/storage/objects/mod.ts +35 -0
  232. package/storage/objects/refs.ts +69 -0
  233. package/storage/postgres/database.integration.test.ts +175 -0
  234. package/storage/postgres/database.test.ts +241 -0
  235. package/storage/postgres/database.ts +497 -0
  236. package/storage/postgres/mod.ts +15 -0
  237. package/storage/redis/commands.ts +1221 -0
  238. package/storage/redis/database.ts +466 -0
  239. package/storage/redis/mod.ts +135 -0
  240. package/storage/redis/native.ts +11 -0
  241. package/storage/redis/options.ts +119 -0
  242. package/storage/redis/pubsub.ts +92 -0
  243. package/storage/redis/redis.test.ts +706 -0
  244. package/storage/redis/reply.ts +705 -0
  245. package/storage/redis/runtime.test.ts +233 -0
  246. package/storage/redis/scan.ts +125 -0
  247. package/storage/redis/script.ts +162 -0
  248. package/storage/redis/target.ts +131 -0
  249. package/storage/redis/wire.ts +369 -0
  250. package/types/mod.ts +92 -0
@@ -0,0 +1,121 @@
1
+ import {describe, expect, test} from 'bun:test';
2
+
3
+ /**
4
+ * What publishing to each topic makes of the ordering key, as the core says.
5
+ * The native runtime reads its config from the environment when it is first
6
+ * imported, so this runs in a child process, as `app_meta.test.ts` does. Its
7
+ * topics, `changes`, ordered, and `events`, are on a provider that publishes
8
+ * nothing: a message that gets past the core's checks fails with "topic not
9
+ * configured".
10
+ */
11
+ const outcomes = (() => {
12
+ const probe = `
13
+ import { OrderedTopic, Topic } from ${JSON.stringify(`${import.meta.dir}/topic`)};
14
+ const outcome = (p) => p.then(() => "published", (e) => String(e.message ?? e));
15
+ const changes = OrderedTopic.named("changes");
16
+ console.log(JSON.stringify({
17
+ keyed: await outcome(changes.publish({ id: "1" }, "user-1", { source: "web" })),
18
+ empty: await outcome(changes.publish({ id: "1" }, "")),
19
+ // A plain topic of the same name has no key to give it.
20
+ unkeyed: await outcome(Topic.named("changes").publish({ id: "1" })),
21
+ // An unordered topic refuses one.
22
+ unordered: await outcome(OrderedTopic.named("events").publish({ id: "1" }, "user-1")),
23
+ }));
24
+ `;
25
+ const proc = Bun.spawnSync({
26
+ cmd: [process.execPath, '-e', probe],
27
+ cwd: import.meta.dir,
28
+ env: {...process.env, ENCORE_RUNTIME_CONFIG: runtimeConfig()},
29
+ });
30
+ const stdout = proc.stdout.toString();
31
+ if (proc.exitCode !== 0) {
32
+ throw new Error(
33
+ `publish probe failed (exit ${proc.exitCode}):\n${stdout}\n${proc.stderr.toString()}`,
34
+ );
35
+ }
36
+ // The core logs to stdout as it initializes; the probe's JSON is the last line.
37
+ const lines = stdout.trim().split('\n');
38
+ return JSON.parse(lines[lines.length - 1]!);
39
+ })();
40
+
41
+ describe('ordered topics', () => {
42
+ test('a message is published with its ordering key', () => {
43
+ expect(outcomes.keyed).toContain('topic not configured');
44
+ });
45
+
46
+ test('a key cannot be empty', () => {
47
+ expect(outcomes.empty).toContain('cannot be empty');
48
+ });
49
+
50
+ test("an ordered topic's message needs a key", () => {
51
+ expect(outcomes.unkeyed).toContain('needs an ordering key');
52
+ });
53
+
54
+ test("an unordered topic's message cannot have one", () => {
55
+ expect(outcomes.unordered).toContain('is not ordered');
56
+ });
57
+ });
58
+
59
+ /**
60
+ * A serialized `encore.runtime.v1.RuntimeConfig` with an ordered topic,
61
+ * base64-encoded as the runtime expects it. Hand-encoded, as in
62
+ * `app_meta.test.ts`.
63
+ */
64
+ function runtimeConfig(): string {
65
+ const varint = (n: number): number[] => {
66
+ const out: number[] = [];
67
+ for (;;) {
68
+ const b = n & 0x7f;
69
+ n >>>= 7;
70
+ out.push(n ? b | 0x80 : b);
71
+ if (!n) return out;
72
+ }
73
+ };
74
+ const tag = (field: number, wire: number) => varint((field << 3) | wire);
75
+ const str = (field: number, value: string): number[] => {
76
+ const raw = [...new TextEncoder().encode(value)];
77
+ return [...tag(field, 2), ...varint(raw.length), ...raw];
78
+ };
79
+ const msg = (field: number, body: number[]): number[] => [
80
+ ...tag(field, 2),
81
+ ...varint(body.length),
82
+ ...body,
83
+ ];
84
+ const varintField = (field: number, value: number): number[] => [
85
+ ...tag(field, 0),
86
+ ...varint(value),
87
+ ];
88
+
89
+ // Environment{app_id=1, app_slug=2, env_id=3, env_name=4, env_type=5, cloud=6}
90
+ const environment = [
91
+ ...str(1, 'app-id'),
92
+ ...str(2, 'my-app'),
93
+ ...str(3, 'env-1'),
94
+ ...str(4, 'local'),
95
+ ...varintField(5, 1), // TYPE_DEVELOPMENT
96
+ ...varintField(6, 1), // CLOUD_LOCAL
97
+ ];
98
+ // PubSubTopic{rid=1, encore_name=2, cloud_name=3, ordered=6}
99
+ const topic = (name: string, ordered: boolean) => [
100
+ ...str(1, `topic:${name}`),
101
+ ...str(2, name),
102
+ ...str(3, name),
103
+ ...(ordered ? varintField(6, 1) : []),
104
+ ];
105
+ // PubSubCluster{rid=1, topics=2, encore=5}: Encore Cloud's provider, which
106
+ // the core does not publish to.
107
+ const cluster = [
108
+ ...str(1, 'pubsub:cluster'),
109
+ ...msg(2, topic('changes', true)),
110
+ ...msg(2, topic('events', false)),
111
+ ...msg(5, []),
112
+ ];
113
+ // Infrastructure.Resources{pubsub_clusters=3}; Infrastructure{resources=1}
114
+ const infra = msg(1, msg(3, cluster));
115
+ // Deployment{deploy_id=1, hosted_services=5}
116
+ const deployment = [...str(1, 'deploy-1'), ...msg(5, str(1, 'svc'))];
117
+
118
+ // RuntimeConfig{environment=1, infra=2, deployment=3}
119
+ const cfg = [...msg(1, environment), ...msg(2, infra), ...msg(3, deployment)];
120
+ return Buffer.from(Uint8Array.from(cfg)).toString('base64');
121
+ }
@@ -0,0 +1,212 @@
1
+ import {activeCtxBytes} from '../internal/otel/index';
2
+ import * as runtime from '../internal/runtime/mod';
3
+ import {encodePayload} from './encoding';
4
+ import {
5
+ OrderedPublisher,
6
+ OrderedTopicPerms,
7
+ Publisher,
8
+ TopicPerms,
9
+ } from './refs';
10
+
11
+ /**
12
+ * A topic is a resource to which you can publish messages
13
+ * to be delivered to subscribers of that topic.
14
+ */
15
+ export class Topic<Msg> extends TopicPerms implements Publisher<Msg> {
16
+ readonly name: string;
17
+ /**
18
+ * The topic's configuration, as declared. `undefined` for a topic referenced
19
+ * with `Topic.named`, which is configured where it is declared.
20
+ */
21
+ readonly cfg?: TopicConfig<Msg>;
22
+ private impl: runtime.PubSubTopic;
23
+
24
+ constructor(name: string, cfg?: TopicConfig<Msg>) {
25
+ super();
26
+ this.name = name;
27
+ this.cfg = cfg;
28
+ this.impl = runtime.RT.pubsubTopic(name);
29
+ }
30
+
31
+ /**
32
+ * Reference an existing topic by name — one another service declares,
33
+ * possibly in another language. To declare a new topic, use
34
+ * `new Topic(...)` instead.
35
+ *
36
+ * The message type cannot be inferred, so it must be given:
37
+ *
38
+ * const signups = Topic.named<SignupEvent>("signups");
39
+ *
40
+ * The name must be a string literal, so Encore can resolve it statically.
41
+ */
42
+ static named<Msg>(name: string): Topic<Msg> {
43
+ // Configured where it is declared, so it has no `cfg` of its own.
44
+ return new Topic<Msg>(name);
45
+ }
46
+
47
+ /**
48
+ * Publish a message to the topic, returning its unique id.
49
+ *
50
+ * JSON values are serialized as the payload; Buffer and Uint8Array payloads
51
+ * are sent as raw bytes. Messages are delivered to subscribers verbatim.
52
+ * `attributes` are delivered alongside the payload.
53
+ */
54
+ async publish(
55
+ msg: Msg,
56
+ attributes?: Record<string, string>,
57
+ ): Promise<string> {
58
+ const source = activeCtxBytes();
59
+ const payload = encodePayload(msg);
60
+ return this.impl.publish(payload, attributes, source);
61
+ }
62
+
63
+ ref<P extends TopicPerms>(): P {
64
+ return this as unknown as P;
65
+ }
66
+ }
67
+
68
+ /**
69
+ * An ordered topic is a topic that delivers the messages sharing an ordering
70
+ * key in the order they were published. Each message is published with its
71
+ * key:
72
+ *
73
+ * const userEvents = new OrderedTopic<UserEvent>("user-events", {
74
+ * deliveryGuarantee: "at-least-once",
75
+ * });
76
+ *
77
+ * await userEvents.publish({ action: "login" }, "user-1"); // Delivered before the logout
78
+ * await userEvents.publish({ action: "login" }, "user-2"); // Delivered at any time: a different key
79
+ * await userEvents.publish({ action: "logout" }, "user-1"); // Delivered after the first login
80
+ *
81
+ * A message whose handler fails is retried before the next one with its key
82
+ * is delivered, so depending on the retry policy a backlog can build up
83
+ * behind it. Once it has been retried as often as the subscription allows, it
84
+ * is dead-lettered and the next message with its key delivered. Reason about
85
+ * your failure modes and set the retry policy accordingly.
86
+ *
87
+ * Its throughput is limited by the cloud provider:
88
+ *
89
+ * - AWS: 300 messages per second for the topic (see [AWS SQS Quotas]).
90
+ * - GCP: 1MB/s for each ordering key (see [GCP PubSub Quotas]).
91
+ *
92
+ * Locally (`encore run`, `encore test`) messages are delivered in order too:
93
+ * a message waits until the earlier ones with the same key are processed or
94
+ * dead-lettered.
95
+ *
96
+ * [AWS SQS Quotas]: https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/quotas-messages.html
97
+ * [GCP PubSub Quotas]: https://cloud.google.com/pubsub/quotas#resource_limits
98
+ */
99
+ export class OrderedTopic<Msg>
100
+ extends OrderedTopicPerms
101
+ implements OrderedPublisher<Msg>
102
+ {
103
+ readonly name: string;
104
+ /**
105
+ * The topic's configuration, as declared. `undefined` for a topic referenced
106
+ * with `OrderedTopic.named`, which is configured where it is declared.
107
+ */
108
+ readonly cfg?: OrderedTopicConfig<Msg>;
109
+ private impl: runtime.PubSubTopic;
110
+
111
+ constructor(name: string, cfg?: OrderedTopicConfig<Msg>) {
112
+ super();
113
+ this.name = name;
114
+ this.cfg = cfg;
115
+ this.impl = runtime.RT.pubsubTopic(name);
116
+ }
117
+
118
+ /**
119
+ * Reference an existing ordered topic by name. See `Topic.named`.
120
+ *
121
+ * const changes = OrderedTopic.named<ChangeEvent>("changes");
122
+ */
123
+ static named<Msg>(name: string): OrderedTopic<Msg> {
124
+ // Configured where it is declared, so it has no `cfg` of its own.
125
+ return new OrderedTopic<Msg>(name);
126
+ }
127
+
128
+ /**
129
+ * Publish a message to the topic, returning its unique id. Messages
130
+ * published with the same `orderingKey`, which cannot be empty, are
131
+ * delivered in the order they were published.
132
+ *
133
+ * JSON values are serialized as the payload; Buffer and Uint8Array payloads
134
+ * are sent as raw bytes. Messages are delivered to subscribers verbatim.
135
+ * `attributes` are delivered alongside the payload.
136
+ */
137
+ async publish(
138
+ msg: Msg,
139
+ orderingKey: string,
140
+ attributes?: Record<string, string>,
141
+ ): Promise<string> {
142
+ if (typeof orderingKey !== 'string' || orderingKey.length === 0) {
143
+ throw new TypeError('orderingKey must be a non-empty string');
144
+ }
145
+ const source = activeCtxBytes();
146
+ const payload = encodePayload(msg);
147
+ return this.impl.publish(payload, attributes, source, orderingKey);
148
+ }
149
+
150
+ ref<P extends OrderedTopicPerms>(): P {
151
+ return this as unknown as P;
152
+ }
153
+ }
154
+
155
+ /**
156
+ * DeliveryGuarantee is used to configure the delivery contract for a topic.
157
+ */
158
+ export type DeliveryGuarantee = 'at-least-once' | 'exactly-once';
159
+
160
+ /**
161
+ * At Least Once delivery guarantees that a message for a subscription is delivered to
162
+ * a consumer at least once.
163
+ *
164
+ * On AWS and GCP there is no limit to the throughput for a topic.
165
+ */
166
+ export const atLeastOnce: DeliveryGuarantee = 'at-least-once';
167
+
168
+ /**
169
+ * ExactlyOnce guarantees that a message for a subscription is delivered to
170
+ * a consumer exactly once, to the best of the system's ability.
171
+ *
172
+ * However, there are edge cases when a message might be redelivered.
173
+ * For example, if a networking issue causes the acknowledgement of success
174
+ * processing the message to be lost before the cloud provider receives it.
175
+ *
176
+ * It is also important to note that the ExactlyOnce delivery guarantee only
177
+ * applies to the delivery of the message to the consumer, and not to the
178
+ * original publishing of the message, such that if a message is published twice,
179
+ * such as due to an retry within the application logic, it will be delivered twice.
180
+ * (i.e. ExactlyOnce delivery does not imply message deduplication on publish)
181
+ *
182
+ * As such it's recommended that the subscription handler function is idempotent
183
+ * and is able to handle duplicate messages.
184
+ *
185
+ * Subscriptions attached to ExactlyOnce topics have higher message delivery latency compared to AtLeastOnce.
186
+ *
187
+ * By using ExactlyOnce semantics on a topic, the throughput will be limited depending on the cloud provider:
188
+ * - AWS: 300 messages per second for the topic (see [AWS SQS Quotas]).
189
+ * - GCP: At least 3,000 messages per second across all topics in the region
190
+ * (can be higher on the region see [GCP PubSub Quotas]).
191
+ *
192
+ * [AWS SQS Quotas]: https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/quotas-messages.html
193
+ * [GCP PubSub Quotas]: https://cloud.google.com/pubsub/quotas#quotas
194
+ */
195
+ export const exactlyOnce: DeliveryGuarantee = 'exactly-once';
196
+
197
+ /**
198
+ * TopicConfig is used when creating a Topic
199
+ */
200
+ export interface TopicConfig<_Msg> {
201
+ /**
202
+ * DeliveryGuarantee is used to configure the delivery guarantee of a Topic.
203
+ * Defaults to at-least-once.
204
+ */
205
+ deliveryGuarantee?: DeliveryGuarantee;
206
+ }
207
+
208
+ /**
209
+ * OrderedTopicConfig is used when creating an OrderedTopic. It configures what
210
+ * a TopicConfig does; the ordering key is given with each message.
211
+ */
212
+ export type OrderedTopicConfig<Msg = unknown> = TopicConfig<Msg>;
package/req_meta.ts ADDED
@@ -0,0 +1,75 @@
1
+ import {getCurrentRequest} from './internal/reqtrack/mod';
2
+
3
+ /** Describes a Pub/Sub message being processed. */
4
+ export interface PubSubMessageMeta {
5
+ /** Specifies that the request is a Pub/Sub message. */
6
+ type: 'pubsub-message';
7
+
8
+ /** The service processing the message. */
9
+ service: string;
10
+
11
+ /** The name of the Pub/Sub topic. */
12
+ topic: string;
13
+
14
+ /** The name of the Pub/Sub subscription. */
15
+ subscription: string;
16
+
17
+ /**
18
+ * The unique id of the Pub/Sub message.
19
+ * It is the same id returned by `topic.publish()`.
20
+ * The message id stays the same across delivery attempts.
21
+ */
22
+ messageId: string;
23
+
24
+ /**
25
+ * The delivery attempt. The first attempt starts at 1,
26
+ * and increases by 1 for each retry.
27
+ */
28
+ deliveryAttempt: number;
29
+ }
30
+
31
+ /** Provides information about the active trace. */
32
+ export interface TraceData {
33
+ /** The trace id, 32 lowercase hex characters. */
34
+ traceId: string;
35
+ /**
36
+ * The span id of the request's trace context, the calling gateway's span,
37
+ * 16 lowercase hex characters.
38
+ */
39
+ spanId: string;
40
+ }
41
+
42
+ /** Common fields shared by all request meta types. */
43
+ export interface BaseRequestMeta {
44
+ /** The request's trace context; unset if the request arrived without one. */
45
+ trace?: TraceData;
46
+ }
47
+
48
+ /** Describes the Pub/Sub message being processed. */
49
+ export type RequestMeta = PubSubMessageMeta & BaseRequestMeta;
50
+
51
+ /**
52
+ * Returns information about the running Encore request: the Pub/Sub
53
+ * message being processed.
54
+ *
55
+ * Returns undefined only if no request is being processed,
56
+ * such as during system initialization.
57
+ */
58
+ export function currentRequest(): RequestMeta | undefined {
59
+ const req = getCurrentRequest();
60
+ if (!req) {
61
+ return undefined;
62
+ }
63
+ const meta = req.meta();
64
+
65
+ const msg = meta.pubsubMessage;
66
+ return {
67
+ type: 'pubsub-message',
68
+ service: msg.service,
69
+ topic: msg.topic,
70
+ subscription: msg.subscription,
71
+ messageId: msg.id,
72
+ deliveryAttempt: msg.deliveryAttempt,
73
+ trace: meta.trace,
74
+ };
75
+ }
@@ -0,0 +1,30 @@
1
+ import {describe, expect, mock, test} from 'bun:test';
2
+ import type {RuntimeConfig} from '../internal/runtime/mod';
3
+
4
+ const config: RuntimeConfig = {services: {}};
5
+
6
+ mock.module('../internal/runtime/mod', () => ({
7
+ runtimeConfig: () => config,
8
+ }));
9
+
10
+ const {serviceUrl} = await import('.');
11
+
12
+ describe('serviceUrl', () => {
13
+ test('resolves relative paths under the base', () => {
14
+ config.services = {users: 'http://127.0.0.1:4000/users'};
15
+ expect(serviceUrl('users').href).toBe('http://127.0.0.1:4000/users/');
16
+ expect(new URL('1', serviceUrl('users')).href).toBe(
17
+ 'http://127.0.0.1:4000/users/1',
18
+ );
19
+ });
20
+
21
+ test('keeps an existing trailing slash', () => {
22
+ config.services = {users: 'http://127.0.0.1:4000/'};
23
+ expect(serviceUrl('users').href).toBe('http://127.0.0.1:4000/');
24
+ });
25
+
26
+ test('throws for an unknown service', () => {
27
+ config.services = {};
28
+ expect(() => serviceUrl('nope')).toThrow('unknown service');
29
+ });
30
+ });
@@ -0,0 +1,21 @@
1
+ import {runtimeConfig} from '../internal/runtime/mod';
2
+
3
+ /**
4
+ * The base URL of `service`, ending in `/`. Resolve relative paths against
5
+ * it: `new URL("orders/1", serviceUrl("orders"))`. Throws if the service is
6
+ * unknown to this process.
7
+ *
8
+ * No service runs under `encore test`. Every service still has a base URL
9
+ * there, but a call to it is answered with `501 Not Implemented` and an error
10
+ * saying which service and path the test called: mock the call in the test
11
+ * instead.
12
+ */
13
+ export function serviceUrl(service: string): URL {
14
+ const base = runtimeConfig().services[service];
15
+ if (base === undefined) {
16
+ throw new Error(`encore: unknown service ${JSON.stringify(service)}`);
17
+ }
18
+ const u = new URL(base);
19
+ if (!u.pathname.endsWith('/')) u.pathname += '/';
20
+ return u;
21
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Graceful shutdown on SIGTERM or SIGINT.
3
+ *
4
+ * On the signal Encore stops Pub/Sub intake, waits for in-flight message
5
+ * handlers, flushes metrics and telemetry, and exits: 0 when this finished
6
+ * within the shutdown deadline, else 1.
7
+ *
8
+ * An app serving requests drains them first by registering a drain:
9
+ *
10
+ * ```typescript
11
+ * import { onShutdown } from "@encore.dev/sdk/shutdown";
12
+ *
13
+ * const server = app.listen(port);
14
+ * onShutdown(() => new Promise((resolve) => server.close(() => resolve())));
15
+ * ```
16
+ *
17
+ * Encore cleans up once every drain settles or the shutdown deadline passes,
18
+ * whichever comes first.
19
+ *
20
+ * @module
21
+ */
22
+ import '../internal/runtime/mod';
23
+
24
+ export {onShutdown} from '../internal/runtime/shutdown';