@encore.dev/sdk 0.0.0 → 2.0.0-beta.4
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.
- package/LICENSE +362 -0
- package/README.md +122 -2
- package/app_meta.test.ts +134 -0
- package/app_meta.ts +186 -0
- package/config/config.test.ts +381 -0
- package/config/config.ts +178 -0
- package/config/mod.ts +14 -0
- package/config/secrets.ts +147 -0
- package/config/value.ts +243 -0
- package/cron/mod.ts +23 -0
- package/dist/app_meta.d.ts +93 -0
- package/dist/app_meta.js +65 -0
- package/dist/app_meta.js.map +1 -0
- package/dist/config/config.d.ts +105 -0
- package/dist/config/config.js +87 -0
- package/dist/config/config.js.map +1 -0
- package/dist/config/mod.d.ts +4 -0
- package/dist/config/mod.js +3 -0
- package/dist/config/mod.js.map +1 -0
- package/dist/config/secrets.d.ts +92 -0
- package/dist/config/secrets.js +80 -0
- package/dist/config/secrets.js.map +1 -0
- package/dist/config/value.d.ts +51 -0
- package/dist/config/value.js +178 -0
- package/dist/config/value.js.map +1 -0
- package/dist/cron/mod.d.ts +22 -0
- package/dist/cron/mod.js +9 -0
- package/dist/cron/mod.js.map +1 -0
- package/dist/internal/otel/backend.d.ts +50 -0
- package/dist/internal/otel/backend.js +2 -0
- package/dist/internal/otel/backend.js.map +1 -0
- package/dist/internal/otel/context.d.ts +10 -0
- package/dist/internal/otel/context.js +34 -0
- package/dist/internal/otel/context.js.map +1 -0
- package/dist/internal/otel/context_manager.d.ts +22 -0
- package/dist/internal/otel/context_manager.js +120 -0
- package/dist/internal/otel/context_manager.js.map +1 -0
- package/dist/internal/otel/encode.d.ts +112 -0
- package/dist/internal/otel/encode.js +290 -0
- package/dist/internal/otel/encode.js.map +1 -0
- package/dist/internal/otel/index.d.ts +9 -0
- package/dist/internal/otel/index.js +9 -0
- package/dist/internal/otel/index.js.map +1 -0
- package/dist/internal/otel/meter.d.ts +73 -0
- package/dist/internal/otel/meter.js +265 -0
- package/dist/internal/otel/meter.js.map +1 -0
- package/dist/internal/otel/propagator.d.ts +14 -0
- package/dist/internal/otel/propagator.js +61 -0
- package/dist/internal/otel/propagator.js.map +1 -0
- package/dist/internal/otel/provider.d.ts +9 -0
- package/dist/internal/otel/provider.js +19 -0
- package/dist/internal/otel/provider.js.map +1 -0
- package/dist/internal/otel/request_context.d.ts +11 -0
- package/dist/internal/otel/request_context.js +20 -0
- package/dist/internal/otel/request_context.js.map +1 -0
- package/dist/internal/otel/span.d.ts +61 -0
- package/dist/internal/otel/span.js +206 -0
- package/dist/internal/otel/span.js.map +1 -0
- package/dist/internal/otel/tracer.d.ts +15 -0
- package/dist/internal/otel/tracer.js +65 -0
- package/dist/internal/otel/tracer.js.map +1 -0
- package/dist/internal/reqtrack/mod.d.ts +6 -0
- package/dist/internal/reqtrack/mod.js +28 -0
- package/dist/internal/reqtrack/mod.js.map +1 -0
- package/dist/internal/runtime/meter.d.ts +11 -0
- package/dist/internal/runtime/meter.js +22 -0
- package/dist/internal/runtime/meter.js.map +1 -0
- package/dist/internal/runtime/mod.d.ts +12 -0
- package/dist/internal/runtime/mod.js +28 -0
- package/dist/internal/runtime/mod.js.map +1 -0
- package/dist/internal/runtime/napi/napi.cjs +122 -0
- package/dist/internal/runtime/napi/napi.d.cts +601 -0
- package/dist/internal/runtime/shutdown.d.ts +13 -0
- package/dist/internal/runtime/shutdown.js +56 -0
- package/dist/internal/runtime/shutdown.js.map +1 -0
- package/dist/internal/utils/constraints.d.ts +9 -0
- package/dist/internal/utils/constraints.js +2 -0
- package/dist/internal/utils/constraints.js.map +1 -0
- package/dist/log/index.d.ts +39 -0
- package/dist/log/index.js +44 -0
- package/dist/log/index.js.map +1 -0
- package/dist/log/logger.d.ts +123 -0
- package/dist/log/logger.js +203 -0
- package/dist/log/logger.js.map +1 -0
- package/dist/log/runtime.d.ts +19 -0
- package/dist/log/runtime.js +22 -0
- package/dist/log/runtime.js.map +1 -0
- package/dist/log/stderr.d.ts +9 -0
- package/dist/log/stderr.js +25 -0
- package/dist/log/stderr.js.map +1 -0
- package/dist/metrics/mod.d.ts +315 -0
- package/dist/metrics/mod.js +488 -0
- package/dist/metrics/mod.js.map +1 -0
- package/dist/mod.d.ts +6 -0
- package/dist/mod.js +4 -0
- package/dist/mod.js.map +1 -0
- package/dist/otel.d.ts +9 -0
- package/dist/otel.js +13 -0
- package/dist/otel.js.map +1 -0
- package/dist/pubsub/encoding.d.ts +3 -0
- package/dist/pubsub/encoding.js +10 -0
- package/dist/pubsub/encoding.js.map +1 -0
- package/dist/pubsub/mod.d.ts +6 -0
- package/dist/pubsub/mod.js +3 -0
- package/dist/pubsub/mod.js.map +1 -0
- package/dist/pubsub/refs.d.ts +12 -0
- package/dist/pubsub/refs.js +11 -0
- package/dist/pubsub/refs.js.map +1 -0
- package/dist/pubsub/subscription.d.ts +128 -0
- package/dist/pubsub/subscription.js +39 -0
- package/dist/pubsub/subscription.js.map +1 -0
- package/dist/pubsub/topic.d.ts +148 -0
- package/dist/pubsub/topic.js +164 -0
- package/dist/pubsub/topic.js.map +1 -0
- package/dist/req_meta.d.ts +47 -0
- package/dist/req_meta.js +26 -0
- package/dist/req_meta.js.map +1 -0
- package/dist/services/index.d.ts +7 -0
- package/dist/services/index.js +17 -0
- package/dist/services/index.js.map +1 -0
- package/dist/shutdown/mod.d.ts +23 -0
- package/dist/shutdown/mod.js +24 -0
- package/dist/shutdown/mod.js.map +1 -0
- package/dist/storage/objects/bucket.d.ts +216 -0
- package/dist/storage/objects/bucket.js +123 -0
- package/dist/storage/objects/bucket.js.map +1 -0
- package/dist/storage/objects/error.d.ts +14 -0
- package/dist/storage/objects/error.js +81 -0
- package/dist/storage/objects/error.js.map +1 -0
- package/dist/storage/objects/mod.d.ts +4 -0
- package/dist/storage/objects/mod.js +3 -0
- package/dist/storage/objects/mod.js.map +1 -0
- package/dist/storage/objects/refs.d.ts +31 -0
- package/dist/storage/objects/refs.js +20 -0
- package/dist/storage/objects/refs.js.map +1 -0
- package/dist/storage/postgres/database.d.ts +295 -0
- package/dist/storage/postgres/database.js +378 -0
- package/dist/storage/postgres/database.js.map +1 -0
- package/dist/storage/postgres/mod.d.ts +2 -0
- package/dist/storage/postgres/mod.js +2 -0
- package/dist/storage/postgres/mod.js.map +1 -0
- package/dist/storage/redis/commands.d.ts +573 -0
- package/dist/storage/redis/commands.js +637 -0
- package/dist/storage/redis/commands.js.map +1 -0
- package/dist/storage/redis/database.d.ts +302 -0
- package/dist/storage/redis/database.js +336 -0
- package/dist/storage/redis/database.js.map +1 -0
- package/dist/storage/redis/mod.d.ts +88 -0
- package/dist/storage/redis/mod.js +84 -0
- package/dist/storage/redis/mod.js.map +1 -0
- package/dist/storage/redis/native.d.ts +8 -0
- package/dist/storage/redis/native.js +11 -0
- package/dist/storage/redis/native.js.map +1 -0
- package/dist/storage/redis/options.d.ts +89 -0
- package/dist/storage/redis/options.js +53 -0
- package/dist/storage/redis/options.js.map +1 -0
- package/dist/storage/redis/pubsub.d.ts +53 -0
- package/dist/storage/redis/pubsub.js +88 -0
- package/dist/storage/redis/pubsub.js.map +1 -0
- package/dist/storage/redis/reply.d.ts +256 -0
- package/dist/storage/redis/reply.js +572 -0
- package/dist/storage/redis/reply.js.map +1 -0
- package/dist/storage/redis/scan.d.ts +11 -0
- package/dist/storage/redis/scan.js +76 -0
- package/dist/storage/redis/scan.js.map +1 -0
- package/dist/storage/redis/script.d.ts +91 -0
- package/dist/storage/redis/script.js +143 -0
- package/dist/storage/redis/script.js.map +1 -0
- package/dist/storage/redis/target.d.ts +47 -0
- package/dist/storage/redis/target.js +82 -0
- package/dist/storage/redis/target.js.map +1 -0
- package/dist/storage/redis/wire.d.ts +105 -0
- package/dist/storage/redis/wire.js +333 -0
- package/dist/storage/redis/wire.js.map +1 -0
- package/dist/tsconfig.build.tsbuildinfo +1 -0
- package/dist/types/mod.d.ts +42 -0
- package/dist/types/mod.js +65 -0
- package/dist/types/mod.js.map +1 -0
- package/internal/otel/backend.ts +60 -0
- package/internal/otel/context.test.ts +70 -0
- package/internal/otel/context.ts +48 -0
- package/internal/otel/context_manager.test.ts +154 -0
- package/internal/otel/context_manager.ts +141 -0
- package/internal/otel/encode.test.ts +266 -0
- package/internal/otel/encode.ts +408 -0
- package/internal/otel/index.ts +20 -0
- package/internal/otel/meter.test.ts +231 -0
- package/internal/otel/meter.ts +332 -0
- package/internal/otel/propagator.test.ts +105 -0
- package/internal/otel/propagator.ts +68 -0
- package/internal/otel/provider.ts +23 -0
- package/internal/otel/request_context.ts +32 -0
- package/internal/otel/span.ts +252 -0
- package/internal/otel/tracer.test.ts +352 -0
- package/internal/otel/tracer.ts +104 -0
- package/internal/reqtrack/mod.ts +39 -0
- package/internal/runtime/meter.ts +26 -0
- package/internal/runtime/mod.ts +41 -0
- package/internal/runtime/napi/napi.cjs +122 -0
- package/internal/runtime/napi/napi.d.cts +601 -0
- package/internal/runtime/shutdown.test.ts +248 -0
- package/internal/runtime/shutdown.ts +64 -0
- package/internal/utils/constraints.ts +12 -0
- package/log/index.ts +107 -0
- package/log/logger.test.ts +194 -0
- package/log/logger.ts +308 -0
- package/log/runtime.test.ts +65 -0
- package/log/runtime.ts +40 -0
- package/log/stderr.test.ts +23 -0
- package/log/stderr.ts +24 -0
- package/metrics/export.test.ts +337 -0
- package/metrics/mod.test.ts +180 -0
- package/metrics/mod.ts +619 -0
- package/mod.ts +22 -0
- package/otel.test.ts +84 -0
- package/otel.ts +17 -0
- package/package.json +121 -5
- package/pubsub/encoding.ts +8 -0
- package/pubsub/mod.ts +14 -0
- package/pubsub/pubsub.test.ts +186 -0
- package/pubsub/refs.ts +22 -0
- package/pubsub/subscription.ts +180 -0
- package/pubsub/topic.test.ts +121 -0
- package/pubsub/topic.ts +212 -0
- package/req_meta.ts +75 -0
- package/services/index.test.ts +30 -0
- package/services/index.ts +16 -0
- package/shutdown/mod.ts +24 -0
- package/storage/objects/bucket.ts +338 -0
- package/storage/objects/error.ts +94 -0
- package/storage/objects/mod.ts +35 -0
- package/storage/objects/refs.ts +69 -0
- package/storage/postgres/database.integration.test.ts +175 -0
- package/storage/postgres/database.test.ts +241 -0
- package/storage/postgres/database.ts +497 -0
- package/storage/postgres/mod.ts +15 -0
- package/storage/redis/commands.ts +1221 -0
- package/storage/redis/database.ts +466 -0
- package/storage/redis/mod.ts +135 -0
- package/storage/redis/native.ts +11 -0
- package/storage/redis/options.ts +119 -0
- package/storage/redis/pubsub.ts +92 -0
- package/storage/redis/redis.test.ts +706 -0
- package/storage/redis/reply.ts +705 -0
- package/storage/redis/runtime.test.ts +233 -0
- package/storage/redis/scan.ts +125 -0
- package/storage/redis/script.ts +162 -0
- package/storage/redis/target.ts +131 -0
- package/storage/redis/wire.ts +369 -0
- package/types/mod.ts +92 -0
package/otel.test.ts
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import {describe, expect, test} from 'bun:test';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The runtime registers no OpenTelemetry API global; Encore's providers are
|
|
5
|
+
* reached through `tracerProvider()` and `meterProvider()`, and requests are
|
|
6
|
+
* tracked without a global context manager. Runs in a child process, which
|
|
7
|
+
* starts with the runtime config in its environment and no globals
|
|
8
|
+
* registered by other test files.
|
|
9
|
+
*/
|
|
10
|
+
const probe = `
|
|
11
|
+
import { context, metrics, propagation, ROOT_CONTEXT, createContextKey, trace } from "@opentelemetry/api";
|
|
12
|
+
import { meterProvider, tracerProvider } from ${JSON.stringify(`${import.meta.dir}/mod`)};
|
|
13
|
+
import { TracerProvider, MeterProvider, activeCtxBytes } from ${JSON.stringify(`${import.meta.dir}/internal/otel/index`)};
|
|
14
|
+
import { getCurrentRequest, runWithRequest } from ${JSON.stringify(`${import.meta.dir}/internal/reqtrack/mod`)};
|
|
15
|
+
|
|
16
|
+
const key = createContextKey("probe");
|
|
17
|
+
const ctx = Buffer.alloc(25, 1);
|
|
18
|
+
const req = { spanContext: () => ({ ctx, tracestate: "" }) };
|
|
19
|
+
const tracked = await runWithRequest(req, async () => {
|
|
20
|
+
await new Promise((r) => setTimeout(r, 1));
|
|
21
|
+
return {
|
|
22
|
+
request: getCurrentRequest() === req,
|
|
23
|
+
ctxBytes: activeCtxBytes()?.toString("hex")
|
|
24
|
+
};
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
console.log(JSON.stringify({
|
|
28
|
+
tracer: trace.getTracer("app").startSpan("s").spanContext().traceId,
|
|
29
|
+
meterProvider: metrics.getMeterProvider() === meterProvider(),
|
|
30
|
+
propagatorFields: propagation.fields(),
|
|
31
|
+
contextManager: context.with(ROOT_CONTEXT.setValue(key, 1), () => context.active().getValue(key)) === 1,
|
|
32
|
+
tracerProvider: tracerProvider() instanceof TracerProvider && tracerProvider() === tracerProvider(),
|
|
33
|
+
encoreMeterProvider: meterProvider() instanceof MeterProvider && meterProvider() === meterProvider(),
|
|
34
|
+
tracked,
|
|
35
|
+
expectedCtxBytes: ctx.toString("hex")
|
|
36
|
+
}));
|
|
37
|
+
`;
|
|
38
|
+
|
|
39
|
+
const result = (() => {
|
|
40
|
+
const proc = Bun.spawnSync({
|
|
41
|
+
cmd: [process.execPath, '-e', probe],
|
|
42
|
+
cwd: import.meta.dir,
|
|
43
|
+
env: {...process.env, ENCORE_RUNTIME_CONFIG: runtimeConfig()},
|
|
44
|
+
});
|
|
45
|
+
const stdout = proc.stdout.toString();
|
|
46
|
+
if (proc.exitCode !== 0) {
|
|
47
|
+
throw new Error(
|
|
48
|
+
`otel probe failed (exit ${proc.exitCode}):\n${stdout}\n${proc.stderr.toString()}`,
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
const lines = stdout.trim().split('\n');
|
|
52
|
+
return JSON.parse(lines[lines.length - 1]!);
|
|
53
|
+
})();
|
|
54
|
+
|
|
55
|
+
describe('OpenTelemetry globals', () => {
|
|
56
|
+
test('the runtime registers none', () => {
|
|
57
|
+
expect(result.tracer).toBe('00000000000000000000000000000000');
|
|
58
|
+
expect(result.meterProvider).toBe(false);
|
|
59
|
+
expect(result.propagatorFields).toEqual([]);
|
|
60
|
+
expect(result.contextManager).toBe(false);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
test("Encore's providers are reached through their accessors", () => {
|
|
64
|
+
expect(result.tracerProvider).toBe(true);
|
|
65
|
+
expect(result.encoreMeterProvider).toBe(true);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
test('requests are tracked without a global context manager', () => {
|
|
69
|
+
expect(result.tracked).toEqual({
|
|
70
|
+
request: true,
|
|
71
|
+
ctxBytes: result.expectedCtxBytes,
|
|
72
|
+
});
|
|
73
|
+
});
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
/** A serialized `encore.runtime.v1.RuntimeConfig` with an app id, base64. */
|
|
77
|
+
function runtimeConfig(): string {
|
|
78
|
+
const appId = [...new TextEncoder().encode('app-id')];
|
|
79
|
+
// RuntimeConfig{environment=1: Environment{app_id=1}}
|
|
80
|
+
const environment = [0x0a, appId.length, ...appId];
|
|
81
|
+
return Buffer.from([0x0a, environment.length, ...environment]).toString(
|
|
82
|
+
'base64',
|
|
83
|
+
);
|
|
84
|
+
}
|
package/otel.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import {TracerProvider} from './internal/otel/index';
|
|
2
|
+
import {meterProvider} from './internal/runtime/meter';
|
|
3
|
+
import {RT} from './internal/runtime/mod';
|
|
4
|
+
|
|
5
|
+
export {meterProvider};
|
|
6
|
+
export type {MeterProvider} from './internal/otel/meter';
|
|
7
|
+
export type {TracerProvider};
|
|
8
|
+
|
|
9
|
+
let tracers: TracerProvider | undefined;
|
|
10
|
+
|
|
11
|
+
/** Encore's tracer provider, recording into the runtime's telemetry
|
|
12
|
+
* pipeline. Encore records its own spans without it; pass it to an
|
|
13
|
+
* instrumentation, or register it with `trace.setGlobalTracerProvider`. */
|
|
14
|
+
export function tracerProvider(): TracerProvider {
|
|
15
|
+
tracers ??= new TracerProvider(RT.telemetry());
|
|
16
|
+
return tracers;
|
|
17
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,123 @@
|
|
|
1
1
|
{
|
|
2
|
-
"
|
|
3
|
-
|
|
4
|
-
|
|
2
|
+
"bugs": {
|
|
3
|
+
"url": "https://github.com/encoredev/encore/issues"
|
|
4
|
+
},
|
|
5
|
+
"description": "Encore's TypeScript Infra SDK",
|
|
6
|
+
"devDependencies": {
|
|
7
|
+
"@eslint/js": "10.0.1",
|
|
8
|
+
"@opentelemetry/api": "^1.9.0",
|
|
9
|
+
"@types/bun": "^1.4.3",
|
|
10
|
+
"@types/node": "^20.11.19",
|
|
11
|
+
"eslint": "10.13.0",
|
|
12
|
+
"eslint-config-prettier": "10.1.8",
|
|
13
|
+
"prettier": "3.9.10",
|
|
14
|
+
"tsc-esm-fix": "^2.20.26",
|
|
15
|
+
"typedoc": "^0.28.19",
|
|
16
|
+
"typedoc-plugin-frontmatter": "^1.3.1",
|
|
17
|
+
"typedoc-plugin-markdown": "^4.11.0",
|
|
18
|
+
"typescript": "^5.3.3",
|
|
19
|
+
"typescript-eslint": "8.72.0"
|
|
20
|
+
},
|
|
21
|
+
"engines": {
|
|
22
|
+
"node": ">=18.0.0"
|
|
23
|
+
},
|
|
24
|
+
"exports": {
|
|
25
|
+
".": {
|
|
26
|
+
"bun": "./mod.ts",
|
|
27
|
+
"default": "./dist/mod.js",
|
|
28
|
+
"types": "./mod.ts"
|
|
29
|
+
},
|
|
30
|
+
"./config": {
|
|
31
|
+
"bun": "./config/mod.ts",
|
|
32
|
+
"default": "./dist/config/mod.js",
|
|
33
|
+
"types": "./config/mod.ts"
|
|
34
|
+
},
|
|
35
|
+
"./cron": {
|
|
36
|
+
"bun": "./cron/mod.ts",
|
|
37
|
+
"default": "./dist/cron/mod.js",
|
|
38
|
+
"types": "./cron/mod.ts"
|
|
39
|
+
},
|
|
40
|
+
"./internal/*": {
|
|
41
|
+
"bun": "./internal/*.ts",
|
|
42
|
+
"default": "./dist/internal/*.js",
|
|
43
|
+
"types": "./internal/*.ts"
|
|
44
|
+
},
|
|
45
|
+
"./log": {
|
|
46
|
+
"bun": "./log/index.ts",
|
|
47
|
+
"default": "./dist/log/index.js",
|
|
48
|
+
"types": "./log/index.ts"
|
|
49
|
+
},
|
|
50
|
+
"./metrics": {
|
|
51
|
+
"bun": "./metrics/mod.ts",
|
|
52
|
+
"default": "./dist/metrics/mod.js",
|
|
53
|
+
"types": "./metrics/mod.ts"
|
|
54
|
+
},
|
|
55
|
+
"./pubsub": {
|
|
56
|
+
"bun": "./pubsub/mod.ts",
|
|
57
|
+
"default": "./dist/pubsub/mod.js",
|
|
58
|
+
"types": "./pubsub/mod.ts"
|
|
59
|
+
},
|
|
60
|
+
"./services": {
|
|
61
|
+
"bun": "./services/index.ts",
|
|
62
|
+
"default": "./dist/services/index.js",
|
|
63
|
+
"types": "./services/index.ts"
|
|
64
|
+
},
|
|
65
|
+
"./shutdown": {
|
|
66
|
+
"bun": "./shutdown/mod.ts",
|
|
67
|
+
"default": "./dist/shutdown/mod.js",
|
|
68
|
+
"types": "./shutdown/mod.ts"
|
|
69
|
+
},
|
|
70
|
+
"./storage/objects": {
|
|
71
|
+
"bun": "./storage/objects/mod.ts",
|
|
72
|
+
"default": "./dist/storage/objects/mod.js",
|
|
73
|
+
"types": "./storage/objects/mod.ts"
|
|
74
|
+
},
|
|
75
|
+
"./storage/postgres": {
|
|
76
|
+
"bun": "./storage/postgres/mod.ts",
|
|
77
|
+
"default": "./dist/storage/postgres/mod.js",
|
|
78
|
+
"types": "./storage/postgres/mod.ts"
|
|
79
|
+
},
|
|
80
|
+
"./storage/redis": {
|
|
81
|
+
"bun": "./storage/redis/mod.ts",
|
|
82
|
+
"default": "./dist/storage/redis/mod.js",
|
|
83
|
+
"types": "./storage/redis/mod.ts"
|
|
84
|
+
},
|
|
85
|
+
"./types": {
|
|
86
|
+
"bun": "./types/mod.ts",
|
|
87
|
+
"default": "./dist/types/mod.js",
|
|
88
|
+
"types": "./types/mod.ts"
|
|
89
|
+
}
|
|
90
|
+
},
|
|
91
|
+
"files": [
|
|
92
|
+
"dist/",
|
|
93
|
+
"*.ts",
|
|
94
|
+
"**/*.ts",
|
|
95
|
+
"*.cjs",
|
|
96
|
+
"*.cts",
|
|
97
|
+
"README.md",
|
|
98
|
+
"LICENSE"
|
|
99
|
+
],
|
|
5
100
|
"license": "MPL-2.0",
|
|
6
|
-
"
|
|
7
|
-
|
|
101
|
+
"name": "@encore.dev/sdk",
|
|
102
|
+
"peerDependencies": {
|
|
103
|
+
"@opentelemetry/api": "^1.9.0"
|
|
104
|
+
},
|
|
105
|
+
"repository": {
|
|
106
|
+
"directory": "sdk/ts/infra",
|
|
107
|
+
"type": "git",
|
|
108
|
+
"url": "https://github.com/encoredev/encore"
|
|
109
|
+
},
|
|
110
|
+
"scripts": {
|
|
111
|
+
"build": "tsc -b tsconfig.build.json",
|
|
112
|
+
"docs": "typedoc && node scripts/postprocess-docs.mjs",
|
|
113
|
+
"format": "prettier --write .",
|
|
114
|
+
"format:check": "prettier --check .",
|
|
115
|
+
"lint": "eslint . --max-warnings=0",
|
|
116
|
+
"lint:fix": "eslint . --fix --max-warnings=0",
|
|
117
|
+
"test": "bun test",
|
|
118
|
+
"typecheck": "tsc --noEmit"
|
|
119
|
+
},
|
|
120
|
+
"sideEffects": false,
|
|
121
|
+
"type": "module",
|
|
122
|
+
"version": "2.0.0-beta.4"
|
|
123
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** Serialize JSON values, or preserve raw byte payloads. */
|
|
2
|
+
export function encodePayload(value: unknown): Buffer {
|
|
3
|
+
if (value instanceof Uint8Array) return Buffer.from(value);
|
|
4
|
+
const json = JSON.stringify(value);
|
|
5
|
+
if (json === undefined)
|
|
6
|
+
throw new TypeError('Pub/Sub payload must be JSON or bytes');
|
|
7
|
+
return Buffer.from(json);
|
|
8
|
+
}
|
package/pubsub/mod.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export {Topic, OrderedTopic} from './topic';
|
|
2
|
+
export type {TopicConfig, OrderedTopicConfig, DeliveryGuarantee} from './topic';
|
|
3
|
+
|
|
4
|
+
export {Subscription} from './subscription';
|
|
5
|
+
export type {SubscriptionConfig, RetryPolicy, Message} from './subscription';
|
|
6
|
+
|
|
7
|
+
export type {
|
|
8
|
+
TopicPerms,
|
|
9
|
+
Publisher,
|
|
10
|
+
OrderedTopicPerms,
|
|
11
|
+
OrderedPublisher,
|
|
12
|
+
} from './refs';
|
|
13
|
+
|
|
14
|
+
export type {DurationString} from '../types/mod';
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import {beforeEach, expect, mock, test} from 'bun:test';
|
|
2
|
+
import type {Message, SubscriptionConfig} from './subscription';
|
|
3
|
+
|
|
4
|
+
const publish = mock(async (..._args: unknown[]) => 'message-id');
|
|
5
|
+
const subscribe = mock(() => new Promise<void>(() => {}));
|
|
6
|
+
const errors = mock((..._args: unknown[]) => {});
|
|
7
|
+
let dispatch: (req: unknown, message: unknown) => Promise<void>;
|
|
8
|
+
mock.module('../internal/runtime/mod', () => ({
|
|
9
|
+
RT: {
|
|
10
|
+
pubsubTopic: () => ({publish}),
|
|
11
|
+
pubsubSubscription: (cfg: {handler: typeof dispatch}) => {
|
|
12
|
+
dispatch = cfg.handler;
|
|
13
|
+
return {subscribe};
|
|
14
|
+
},
|
|
15
|
+
},
|
|
16
|
+
}));
|
|
17
|
+
mock.module('../internal/otel/index', () => ({
|
|
18
|
+
activeCtxBytes: () => undefined,
|
|
19
|
+
}));
|
|
20
|
+
mock.module('../internal/reqtrack/mod', () => ({
|
|
21
|
+
runWithRequest: (_req: unknown, fn: () => unknown) => fn(),
|
|
22
|
+
}));
|
|
23
|
+
mock.module('../log/index', () => ({default: {error: errors}}));
|
|
24
|
+
const {Topic, OrderedTopic} = await import('./topic');
|
|
25
|
+
const {Subscription} = await import('./subscription');
|
|
26
|
+
|
|
27
|
+
beforeEach(() => {
|
|
28
|
+
publish.mockClear();
|
|
29
|
+
subscribe.mockClear();
|
|
30
|
+
subscribe.mockImplementation(() => new Promise<void>(() => {}));
|
|
31
|
+
errors.mockClear();
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
function native(data: Buffer, orderingKey?: string) {
|
|
35
|
+
return {
|
|
36
|
+
data,
|
|
37
|
+
orderingKey,
|
|
38
|
+
id: 'id',
|
|
39
|
+
attributes: {customer: '123'},
|
|
40
|
+
deliveryAttempt: 2,
|
|
41
|
+
publishTime: new Date(0),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
test('publishes JSON values and raw bytes without JSON-encoding bytes', async () => {
|
|
46
|
+
const topic = new Topic<unknown>('events');
|
|
47
|
+
for (const value of [{id: 1}, [1, 2], 'hello', 42, true, null]) {
|
|
48
|
+
expect(await topic.publish(value, {a: 'b'})).toBe('message-id');
|
|
49
|
+
expect(publish.mock.lastCall).toEqual([
|
|
50
|
+
Buffer.from(JSON.stringify(value)),
|
|
51
|
+
{a: 'b'},
|
|
52
|
+
undefined,
|
|
53
|
+
]);
|
|
54
|
+
}
|
|
55
|
+
for (const bytes of [Buffer.from([0, 255]), new Uint8Array([1, 2])]) {
|
|
56
|
+
await topic.publish(bytes);
|
|
57
|
+
expect(publish.mock.lastCall?.[0]).toEqual(Buffer.from(bytes));
|
|
58
|
+
}
|
|
59
|
+
expect(topic.publish(undefined)).rejects.toThrow('JSON or bytes');
|
|
60
|
+
expect(topic.publish(1n)).rejects.toThrow();
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
test('ordered and named topics forward explicit ordering keys separately from attributes', async () => {
|
|
64
|
+
for (const topic of [
|
|
65
|
+
new OrderedTopic<string>('events'),
|
|
66
|
+
OrderedTopic.named<string>('events'),
|
|
67
|
+
]) {
|
|
68
|
+
await topic.publish('hello', 'customer-123', {a: 'b'});
|
|
69
|
+
expect(publish.mock.lastCall).toEqual([
|
|
70
|
+
Buffer.from('"hello"'),
|
|
71
|
+
{a: 'b'},
|
|
72
|
+
undefined,
|
|
73
|
+
'customer-123',
|
|
74
|
+
]);
|
|
75
|
+
expect(
|
|
76
|
+
topic.publish('hello', undefined as unknown as string),
|
|
77
|
+
).rejects.toThrow('orderingKey');
|
|
78
|
+
}
|
|
79
|
+
await Topic.named<string>('other').publish('hello');
|
|
80
|
+
expect(publish.mock.lastCall?.length).toBe(3);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
test('ordered topics reject empty keys before calling the native publisher', () => {
|
|
84
|
+
for (const topic of [
|
|
85
|
+
new OrderedTopic<string>('events'),
|
|
86
|
+
OrderedTopic.named<string>('events'),
|
|
87
|
+
]) {
|
|
88
|
+
expect(topic.publish('hello', '')).rejects.toThrow(TypeError);
|
|
89
|
+
expect(topic.publish('hello', '')).rejects.toThrow(
|
|
90
|
+
'orderingKey must be a non-empty string',
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
expect(publish).not.toHaveBeenCalled();
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
test('automatically starts subscriptions and delivers decoded JSON with original bytes and metadata', async () => {
|
|
97
|
+
let received!: Message<{id: number}>;
|
|
98
|
+
new Subscription(new OrderedTopic<{id: number}>('events'), 'handler', {
|
|
99
|
+
handler: async message => {
|
|
100
|
+
received = message;
|
|
101
|
+
},
|
|
102
|
+
});
|
|
103
|
+
expect(subscribe).toHaveBeenCalledTimes(1);
|
|
104
|
+
const rawData = Buffer.from('{"id":123}');
|
|
105
|
+
await dispatch({}, native(rawData, 'customer-123'));
|
|
106
|
+
expect(received).toEqual({
|
|
107
|
+
...native(rawData),
|
|
108
|
+
data: {id: 123},
|
|
109
|
+
rawData,
|
|
110
|
+
orderingKey: 'customer-123',
|
|
111
|
+
});
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
test('raw subscriptions preserve arbitrary non-JSON bytes', async () => {
|
|
115
|
+
let received!: Message<Buffer>;
|
|
116
|
+
new Subscription(new Topic<Buffer>('bytes'), 'handler', {
|
|
117
|
+
encoding: 'raw',
|
|
118
|
+
handler: async message => {
|
|
119
|
+
received = message;
|
|
120
|
+
},
|
|
121
|
+
});
|
|
122
|
+
const bytes = Buffer.from([0, 255, 128]);
|
|
123
|
+
await dispatch({}, native(bytes));
|
|
124
|
+
expect(received.data).toBe(bytes);
|
|
125
|
+
expect(received.rawData).toBe(bytes);
|
|
126
|
+
expect(received.orderingKey).toBeNull();
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
test('invalid JSON and validation failures reject delivery before invoking the handler', async () => {
|
|
130
|
+
const handler = mock(async (_message: Message<{id: number}>) => {});
|
|
131
|
+
new Subscription(new Topic<{id: number}>('events'), 'handler', {
|
|
132
|
+
decode(data) {
|
|
133
|
+
if (
|
|
134
|
+
typeof data !== 'object' ||
|
|
135
|
+
data === null ||
|
|
136
|
+
!('id' in data) ||
|
|
137
|
+
typeof data.id !== 'number'
|
|
138
|
+
) {
|
|
139
|
+
throw new Error('invalid id');
|
|
140
|
+
}
|
|
141
|
+
return {id: data.id};
|
|
142
|
+
},
|
|
143
|
+
handler,
|
|
144
|
+
});
|
|
145
|
+
expect(dispatch({}, native(Buffer.from('not json')))).rejects.toThrow();
|
|
146
|
+
expect(dispatch({}, native(Buffer.from([34, 255, 34])))).rejects.toThrow();
|
|
147
|
+
expect(dispatch({}, native(Buffer.from('{"id":"bad"}')))).rejects.toThrow(
|
|
148
|
+
'invalid id',
|
|
149
|
+
);
|
|
150
|
+
expect(handler).not.toHaveBeenCalled();
|
|
151
|
+
await dispatch({}, native(Buffer.from('{"id":123}')));
|
|
152
|
+
expect(handler).toHaveBeenCalledTimes(1);
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
test('handler errors propagate to the runtime for nack', async () => {
|
|
156
|
+
new Subscription(new Topic<unknown>('events'), 'handler', {
|
|
157
|
+
handler: async () => {
|
|
158
|
+
throw new Error('handler failed');
|
|
159
|
+
},
|
|
160
|
+
});
|
|
161
|
+
expect(dispatch({}, native(Buffer.from('null')))).rejects.toThrow(
|
|
162
|
+
'handler failed',
|
|
163
|
+
);
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
test('consumer failures are logged and normal completion does not restart', async () => {
|
|
167
|
+
subscribe.mockImplementationOnce(() =>
|
|
168
|
+
Promise.reject(new Error('consumer failed')),
|
|
169
|
+
);
|
|
170
|
+
new Subscription(new Topic<unknown>('events'), 'failed', {
|
|
171
|
+
handler: async () => {},
|
|
172
|
+
});
|
|
173
|
+
await Promise.resolve();
|
|
174
|
+
expect(errors).toHaveBeenCalledTimes(1);
|
|
175
|
+
subscribe.mockImplementationOnce(() => Promise.resolve());
|
|
176
|
+
new Subscription(new Topic<unknown>('events'), 'done', {
|
|
177
|
+
handler: async () => {},
|
|
178
|
+
});
|
|
179
|
+
await new Promise(resolve => setTimeout(resolve, 1100));
|
|
180
|
+
expect(subscribe).toHaveBeenCalledTimes(2);
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
// Byte subscriptions must explicitly opt out of JSON decoding.
|
|
184
|
+
// @ts-expect-error raw subscriptions require encoding: "raw"
|
|
185
|
+
const invalidConfig: SubscriptionConfig<Buffer> = {handler: async () => {}};
|
|
186
|
+
void invalidConfig;
|
package/pubsub/refs.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export abstract class TopicPerms {
|
|
2
|
+
private topicPerms(): void {}
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
export abstract class Publisher<Msg> extends TopicPerms {
|
|
6
|
+
abstract publish(
|
|
7
|
+
msg: Msg,
|
|
8
|
+
attributes?: Record<string, string>,
|
|
9
|
+
): Promise<string>;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export abstract class OrderedTopicPerms {
|
|
13
|
+
private orderedTopicPerms(): void {}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export abstract class OrderedPublisher<Msg> extends OrderedTopicPerms {
|
|
17
|
+
abstract publish(
|
|
18
|
+
msg: Msg,
|
|
19
|
+
orderingKey: string,
|
|
20
|
+
attributes?: Record<string, string>,
|
|
21
|
+
): Promise<string>;
|
|
22
|
+
}
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import log from '../log/index';
|
|
2
|
+
import {runWithRequest} from '../internal/reqtrack/mod';
|
|
3
|
+
import {DurationString} from '../types/mod';
|
|
4
|
+
import {OrderedTopic, Topic} from './topic';
|
|
5
|
+
import * as runtime from '../internal/runtime/mod';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* A delivered payload with its original bytes and provider metadata.
|
|
9
|
+
*
|
|
10
|
+
* `orderingKey` is the key a message on an ordered topic was published with,
|
|
11
|
+
* and `null` on an unordered topic.
|
|
12
|
+
*/
|
|
13
|
+
export interface Message<T = unknown> {
|
|
14
|
+
data: T;
|
|
15
|
+
rawData: Buffer;
|
|
16
|
+
id: string;
|
|
17
|
+
attributes: Record<string, string>;
|
|
18
|
+
deliveryAttempt: number;
|
|
19
|
+
publishTime: Date;
|
|
20
|
+
orderingKey: string | null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export class Subscription<Msg> {
|
|
24
|
+
private readonly topic: Topic<Msg> | OrderedTopic<Msg>;
|
|
25
|
+
private readonly name: string;
|
|
26
|
+
private readonly impl: runtime.PubSubSubscription;
|
|
27
|
+
|
|
28
|
+
constructor(
|
|
29
|
+
topic: Topic<Msg> | OrderedTopic<Msg>,
|
|
30
|
+
name: string,
|
|
31
|
+
cfg: SubscriptionConfig<Msg>,
|
|
32
|
+
) {
|
|
33
|
+
this.topic = topic;
|
|
34
|
+
this.name = name;
|
|
35
|
+
|
|
36
|
+
const handler = (req: runtime.Request, msg: runtime.PubSubMessage) =>
|
|
37
|
+
runWithRequest(req, async () => {
|
|
38
|
+
const rawData = msg.data;
|
|
39
|
+
const data =
|
|
40
|
+
cfg.encoding === 'raw'
|
|
41
|
+
? rawData
|
|
42
|
+
: JSON.parse(
|
|
43
|
+
new TextDecoder('utf-8', {fatal: true}).decode(rawData),
|
|
44
|
+
);
|
|
45
|
+
await cfg.handler({
|
|
46
|
+
data: cfg.decode ? cfg.decode(data) : data,
|
|
47
|
+
rawData,
|
|
48
|
+
id: msg.id,
|
|
49
|
+
attributes: msg.attributes,
|
|
50
|
+
deliveryAttempt: msg.deliveryAttempt,
|
|
51
|
+
publishTime: msg.publishTime,
|
|
52
|
+
orderingKey: msg.orderingKey ?? null,
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
this.impl = runtime.RT.pubsubSubscription({
|
|
57
|
+
topicName: topic.name,
|
|
58
|
+
subscriptionName: name,
|
|
59
|
+
handler,
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
this.startSubscribing();
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
private startSubscribing() {
|
|
66
|
+
void this.impl.subscribe().catch((error: unknown) => {
|
|
67
|
+
log.error(
|
|
68
|
+
error,
|
|
69
|
+
`Encore subscription ${this.topic.name}/${this.name} failed`,
|
|
70
|
+
);
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* SubscriptionConfig is used when creating a subscription
|
|
77
|
+
*
|
|
78
|
+
* The values given here may be clamped to the supported values by
|
|
79
|
+
* the target cloud. (i.e. ack deadline may be brought within the supported range
|
|
80
|
+
* by the target cloud pubsub implementation).
|
|
81
|
+
*/
|
|
82
|
+
/**
|
|
83
|
+
* Decode JSON by default; byte subscriptions must select `encoding: "raw"`.
|
|
84
|
+
* `decode` optionally validates/transforms JSON, or decodes a custom raw format.
|
|
85
|
+
*/
|
|
86
|
+
export type SubscriptionConfig<Msg> = SubscriptionOptions<Msg> &
|
|
87
|
+
([Msg] extends [Uint8Array]
|
|
88
|
+
? {encoding: 'raw'; decode?: never}
|
|
89
|
+
: | {encoding?: 'json'; decode?: (data: unknown) => Msg}
|
|
90
|
+
| {encoding: 'raw'; decode: (data: unknown) => Msg});
|
|
91
|
+
|
|
92
|
+
export interface SubscriptionOptions<Msg> {
|
|
93
|
+
/**
|
|
94
|
+
* Handler is the function which will be called to process a message
|
|
95
|
+
* sent on the topic.
|
|
96
|
+
*
|
|
97
|
+
* It receives a {@link Message} with decoded `data` and original `rawData`.
|
|
98
|
+
* TypeScript types do not validate JSON; use `decode` for runtime validation.
|
|
99
|
+
*
|
|
100
|
+
* When this function returns an error the message will be
|
|
101
|
+
* negatively acknowledged (nacked), which will cause a redelivery
|
|
102
|
+
* attempt to be made (unless the retry policy's MaxRetries has been reached).
|
|
103
|
+
*/
|
|
104
|
+
handler: (msg: Message<Msg>) => Promise<unknown>;
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* MaxConcurrency is the maximum number of messages which will be processed
|
|
108
|
+
* simultaneously per instance of the service for this subscription.
|
|
109
|
+
*
|
|
110
|
+
* Note that this is per instance of the service, so if your service has
|
|
111
|
+
* scaled to 10 instances and this is set to 10, then 100 messages could be
|
|
112
|
+
* processed simultaneously.
|
|
113
|
+
*
|
|
114
|
+
* If the value is negative, then there will be no limit on the number
|
|
115
|
+
* of messages processed simultaneously.
|
|
116
|
+
*
|
|
117
|
+
* Note: This is not supported by all cloud providers; specifically on GCP
|
|
118
|
+
* when using Cloud Run instances on an unordered topic the subscription will
|
|
119
|
+
* be configured as a Push Subscription and will have an adaptive concurrency
|
|
120
|
+
* See [GCP Push Delivery Rate](https://cloud.google.com/pubsub/docs/push#push_delivery_rate).
|
|
121
|
+
*
|
|
122
|
+
* This setting also has no effect on Encore Cloud environments.
|
|
123
|
+
* If not set, it uses a reasonable default based on the cloud provider.
|
|
124
|
+
*/
|
|
125
|
+
maxConcurrency?: number;
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* AckDeadline is the time a consumer has to process a message
|
|
129
|
+
* before it's returned to the subscription
|
|
130
|
+
*
|
|
131
|
+
* Default is 30 seconds, however the ack deadline must be at least
|
|
132
|
+
* 1 second.
|
|
133
|
+
*/
|
|
134
|
+
ackDeadline?: DurationString;
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* MessageRetention is how long an undelivered message is kept
|
|
138
|
+
* on the topic before it's purged.
|
|
139
|
+
*
|
|
140
|
+
* Default is 7 days.
|
|
141
|
+
*/
|
|
142
|
+
messageRetention?: DurationString;
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* RetryPolicy defines how a message should be retried when
|
|
146
|
+
* the subscriber returns an error
|
|
147
|
+
*/
|
|
148
|
+
retryPolicy?: RetryPolicy;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* RetryPolicy defines how a subscription should handle retries
|
|
153
|
+
* after errors either delivering the message or processing the message.
|
|
154
|
+
*
|
|
155
|
+
* The values given to this structure are parsed at compile time, such that
|
|
156
|
+
* the correct Cloud resources can be provisioned to support the queue.
|
|
157
|
+
*
|
|
158
|
+
* As such the values given here may be clamped to the supported values by
|
|
159
|
+
* the target cloud. (i.e. min/max values brought within the supported range
|
|
160
|
+
* by the target cloud).
|
|
161
|
+
*/
|
|
162
|
+
export interface RetryPolicy {
|
|
163
|
+
/**
|
|
164
|
+
* The minimum time to wait between retries. Defaults to 10 seconds.
|
|
165
|
+
*/
|
|
166
|
+
minBackoff?: DurationString;
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* The maximum time to wait between retries. Defaults to 10 minutes.
|
|
170
|
+
*/
|
|
171
|
+
maxBackoff?: DurationString;
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* MaxRetries is used to control deadletter queuing logic, when:
|
|
175
|
+
* n == 0: A default value of 100 retries will be used
|
|
176
|
+
* n > 0: Encore will forward a message to a dead letter queue after n retries
|
|
177
|
+
* n == pubsub.InfiniteRetries: Messages will not be forwarded to the dead letter queue by the Encore framework
|
|
178
|
+
*/
|
|
179
|
+
maxRetries?: number;
|
|
180
|
+
}
|