raiton 6.8.9-beta.25 → 6.10.0-beta.28
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/CHANGELOG.md +44 -0
- package/README.md +46 -1
- package/benchmarks/README.md +16 -0
- package/benchmarks/latest.json +172 -0
- package/benchmarks/latest.md +66 -0
- package/build/bin/index.mjs +33550 -21725
- package/build/types/bin/bootstrapper.d.ts +2 -0
- package/build/types/bin/cli-output.d.ts +46 -0
- package/build/types/bin/cli-tools.d.ts +13 -0
- package/build/types/bin/cli.d.ts +3 -0
- package/build/types/bin/commands.registry.d.ts +4 -0
- package/build/types/bin/constants.d.ts +3 -0
- package/build/types/bin/file-utils.d.ts +21 -0
- package/build/types/bin/index.d.ts +2 -0
- package/build/types/bin/name-utils.d.ts +4 -0
- package/build/types/bin/project-utils.d.ts +12 -0
- package/build/types/commands/artifact.command.d.ts +7 -0
- package/build/types/commands/build.command.d.ts +8 -0
- package/build/types/commands/client.command.d.ts +7 -0
- package/build/types/commands/contract.command.d.ts +8 -0
- package/build/types/commands/develop.command.d.ts +9 -0
- package/build/types/commands/docs.command.d.ts +8 -0
- package/build/types/commands/doctor.command.d.ts +9 -0
- package/build/types/commands/generate.command.d.ts +7 -0
- package/build/types/commands/inspect.command.d.ts +7 -0
- package/build/types/commands/mcp.command.d.ts +11 -0
- package/build/types/commands/new.command.d.ts +7 -0
- package/build/types/commands/openapi.command.d.ts +7 -0
- package/build/types/commands/routes.command.d.ts +7 -0
- package/build/types/commands/start.command.d.ts +9 -0
- package/build/types/commands/why.command.d.ts +7 -0
- package/build/types/contracts/decorators.d.ts +41 -0
- package/build/types/contracts/errors.d.ts +42 -0
- package/build/types/contracts/index.d.ts +4 -0
- package/build/types/contracts/schema.d.ts +70 -0
- package/build/types/contracts/typebox.d.ts +81 -0
- package/build/types/core/application.d.ts +37 -0
- package/build/types/core/artifacts/artifact.d.ts +3 -0
- package/build/types/core/artifacts/index.d.ts +1 -0
- package/build/types/core/artifacts/runner.d.ts +1 -0
- package/build/types/core/builder.d.ts +42 -0
- package/build/types/core/bytes.util.d.ts +3 -0
- package/build/types/core/command.d.ts +13 -0
- package/build/types/core/commands.d.ts +10 -0
- package/build/types/core/config/config.d.ts +27 -0
- package/build/types/core/config/define.d.ts +8 -0
- package/build/types/core/config/index.d.ts +3 -0
- package/build/types/core/config/schema.d.ts +24 -0
- package/build/types/core/context.d.ts +11 -0
- package/build/types/core/controller/builder.d.ts +26 -0
- package/build/types/core/controller/compiler.d.ts +2 -0
- package/build/types/core/controller/index.d.ts +4 -0
- package/build/types/core/controller/metadata.d.ts +3 -0
- package/build/types/core/controller/tracker.d.ts +9 -0
- package/build/types/core/directories.d.ts +10 -0
- package/build/types/core/guards.d.ts +11 -0
- package/build/types/core/helpers/index.d.ts +1 -0
- package/build/types/core/helpers/raiton.d.ts +1 -0
- package/build/types/core/hooks.d.ts +14 -0
- package/build/types/core/index.d.ts +17 -0
- package/build/types/core/injection/index.d.ts +1 -0
- package/build/types/core/injection/injection.d.ts +37 -0
- package/build/types/core/mcp/builder.d.ts +2 -0
- package/build/types/core/mcp/index.d.ts +3 -0
- package/build/types/core/mcp/metadata.d.ts +9 -0
- package/build/types/core/mcp/tracker.d.ts +9 -0
- package/build/types/core/middleware/compose.d.ts +8 -0
- package/build/types/core/middleware/index.d.ts +2 -0
- package/build/types/core/middleware/pipeline.d.ts +12 -0
- package/build/types/core/plugins/index.d.ts +2 -0
- package/build/types/core/plugins/plugin.d.ts +2 -0
- package/build/types/core/plugins/scope.d.ts +15 -0
- package/build/types/core/process.util.d.ts +1 -0
- package/build/types/core/raiton.d.ts +15 -0
- package/build/types/core/router/handler.d.ts +2 -0
- package/build/types/core/router/handler.utils.d.ts +37 -0
- package/build/types/core/router/index.d.ts +4 -0
- package/build/types/core/router/matcher.d.ts +50 -0
- package/build/types/core/router/route.d.ts +52 -0
- package/build/types/core/router/router.d.ts +23 -0
- package/build/types/core/scheduler/builder.d.ts +2 -0
- package/build/types/core/scheduler/cron.d.ts +32 -0
- package/build/types/core/scheduler/duration.d.ts +7 -0
- package/build/types/core/scheduler/index.d.ts +6 -0
- package/build/types/core/scheduler/manager.d.ts +47 -0
- package/build/types/core/scheduler/metadata.d.ts +8 -0
- package/build/types/core/scheduler/queue/backend.d.ts +42 -0
- package/build/types/core/scheduler/queue/index.d.ts +3 -0
- package/build/types/core/scheduler/queue/rabbitmq.backend.d.ts +37 -0
- package/build/types/core/scheduler/queue/redis.backend.d.ts +38 -0
- package/build/types/core/server.d.ts +9 -0
- package/build/types/core/socket/builder.d.ts +1 -0
- package/build/types/core/socket/index.d.ts +2 -0
- package/build/types/core/socket/metadata.d.ts +14 -0
- package/build/types/core/thread.d.ts +21 -0
- package/build/types/framework/artifacts.d.ts +20 -0
- package/build/types/framework/cache/cache.d.ts +84 -0
- package/build/types/framework/cache/cache.decorator.d.ts +21 -0
- package/build/types/framework/cache/etag.d.ts +62 -0
- package/build/types/framework/cache/index.d.ts +4 -0
- package/build/types/framework/cache/types.d.ts +89 -0
- package/build/types/framework/constants/decorators.constant.d.ts +28 -0
- package/build/types/framework/constants/index.d.ts +2 -0
- package/build/types/framework/constants/microservices.constant.d.ts +3 -0
- package/build/types/framework/controllers.d.ts +2 -0
- package/build/types/framework/data-transfer-object.d.ts +5 -0
- package/build/types/framework/decorators/access-guard.decorator.d.ts +1 -0
- package/build/types/framework/decorators/api-response.decorator.d.ts +66 -0
- package/build/types/framework/decorators/api.decorator.d.ts +160 -0
- package/build/types/framework/decorators/controllable.decorator.d.ts +3 -0
- package/build/types/framework/decorators/csrf-guard.decorator.d.ts +2 -0
- package/build/types/framework/decorators/csrf-token.decorator.d.ts +1 -0
- package/build/types/framework/decorators/guard.decorator.d.ts +2 -0
- package/build/types/framework/decorators/health-check.decorator.d.ts +17 -0
- package/build/types/framework/decorators/index.d.ts +15 -0
- package/build/types/framework/decorators/injection.decorator.d.ts +5 -0
- package/build/types/framework/decorators/mcp.decorator.d.ts +68 -0
- package/build/types/framework/decorators/middleware.decorator.d.ts +3 -0
- package/build/types/framework/decorators/parametrable.decorator.d.ts +9 -0
- package/build/types/framework/decorators/routable.decorator.d.ts +12 -0
- package/build/types/framework/decorators/route-interaction.decorator.d.ts +81 -0
- package/build/types/framework/decorators/scheduler.decorator.d.ts +54 -0
- package/build/types/framework/decorators/socket.decorator.d.ts +5 -0
- package/build/types/framework/encryption.d.ts +25 -0
- package/build/types/framework/enums/csrf.enum.d.ts +4 -0
- package/build/types/framework/enums/encrypted.enum.d.ts +20 -0
- package/build/types/framework/enums/event.message.enum.d.ts +4 -0
- package/build/types/framework/enums/http-method.enum.d.ts +10 -0
- package/build/types/framework/enums/http-parameters.enum.d.ts +11 -0
- package/build/types/framework/enums/http-status.enum.d.ts +64 -0
- package/build/types/framework/enums/index.d.ts +9 -0
- package/build/types/framework/enums/runtime.enum.d.ts +5 -0
- package/build/types/framework/enums/scheduler.enum.d.ts +21 -0
- package/build/types/framework/enums/timestamp.enum.d.ts +6 -0
- package/build/types/framework/env.d.ts +3 -0
- package/build/types/framework/errors/catalog.d.ts +42 -0
- package/build/types/framework/exceptions/http-exception.d.ts +18 -0
- package/build/types/framework/exceptions/index.d.ts +2 -0
- package/build/types/framework/exceptions/throwable.d.ts +76 -0
- package/build/types/framework/health-check.d.ts +42 -0
- package/build/types/framework/index.d.ts +20 -0
- package/build/types/framework/mcp/audit.d.ts +12 -0
- package/build/types/framework/mcp/conformance.d.ts +31 -0
- package/build/types/framework/mcp/handler.d.ts +11 -0
- package/build/types/framework/mcp/index.d.ts +5 -0
- package/build/types/framework/mcp/protocol.d.ts +17 -0
- package/build/types/framework/mcp/rate-limit.d.ts +10 -0
- package/build/types/framework/mcp/stdio.d.ts +40 -0
- package/build/types/framework/mcp/streamable-http.d.ts +17 -0
- package/build/types/framework/observability/index.d.ts +6 -0
- package/build/types/framework/observability/metrics.d.ts +23 -0
- package/build/types/framework/observability/plugin.d.ts +20 -0
- package/build/types/framework/observability/readiness.d.ts +9 -0
- package/build/types/framework/observability/request.d.ts +7 -0
- package/build/types/framework/observability/shutdown.d.ts +21 -0
- package/build/types/framework/observability/trace.d.ts +96 -0
- package/build/types/framework/parameter-bag.d.ts +14 -0
- package/build/types/framework/plugins/body-parser.plugin.d.ts +3 -0
- package/build/types/framework/plugins/dev.plugin.d.ts +12 -0
- package/build/types/framework/plugins/index.d.ts +5 -0
- package/build/types/framework/plugins/mcp.plugin.d.ts +15 -0
- package/build/types/framework/plugins/openapi.plugin.d.ts +58 -0
- package/build/types/framework/plugins/security/body-limit.d.ts +1 -0
- package/build/types/framework/plugins/security/cors.d.ts +10 -0
- package/build/types/framework/plugins/security/csrf.d.ts +2 -0
- package/build/types/framework/plugins/security/headers.d.ts +1 -0
- package/build/types/framework/plugins/security/index.d.ts +13 -0
- package/build/types/framework/plugins/security/method-guard.d.ts +1 -0
- package/build/types/framework/plugins/security/rate-limit.d.ts +5 -0
- package/build/types/framework/repositories.d.ts +5 -0
- package/build/types/framework/responses/error.d.ts +13 -0
- package/build/types/framework/responses/helpers.d.ts +7 -0
- package/build/types/framework/responses/http-throwable.d.ts +14 -0
- package/build/types/framework/responses/http.d.ts +13 -0
- package/build/types/framework/responses/index.d.ts +4 -0
- package/build/types/framework/runtime/bun/server.d.ts +2 -0
- package/build/types/framework/runtime/deno/server.d.ts +2 -0
- package/build/types/framework/runtime/index.d.ts +17 -0
- package/build/types/framework/runtime/node/reply.d.ts +12 -0
- package/build/types/framework/runtime/node/request.d.ts +33 -0
- package/build/types/framework/runtime/node/server.d.ts +2 -0
- package/build/types/framework/runtime/web/server.d.ts +1 -0
- package/build/types/framework/services.d.ts +5 -0
- package/build/types/framework/utilities/alias-path.util.d.ts +1 -0
- package/build/types/framework/utilities/artifact.util.d.ts +7 -0
- package/build/types/framework/utilities/callable.util.d.ts +1 -0
- package/build/types/framework/utilities/cookie.util.d.ts +1 -0
- package/build/types/framework/utilities/csrf.util.d.ts +26 -0
- package/build/types/framework/utilities/https.util.d.ts +49 -0
- package/build/types/framework/utilities/index.d.ts +12 -0
- package/build/types/framework/utilities/ip.util.d.ts +15 -0
- package/build/types/framework/utilities/json.util.d.ts +10 -0
- package/build/types/framework/utilities/openapi.utils.d.ts +7 -0
- package/build/types/framework/utilities/openapi.utils.impl.d.ts +18 -0
- package/build/types/framework/utilities/path.util.d.ts +3 -0
- package/build/types/framework/utilities/route-suggestion.util.d.ts +10 -0
- package/build/types/framework/utilities/url.util.d.ts +1 -0
- package/build/types/framework/utilities/utilities.util.d.ts +3 -0
- package/build/types/framework/utilities/validation.util.d.ts +8 -0
- package/build/types/framework/view-model.d.ts +4 -0
- package/build/types/generators/artifact.templates.d.ts +7 -0
- package/build/types/generators/index.d.ts +2 -0
- package/build/types/generators/project.templates.d.ts +21 -0
- package/build/types/manifest/client.d.ts +12 -0
- package/build/types/manifest/contract.d.ts +25 -0
- package/build/types/manifest/index.d.ts +5 -0
- package/build/types/manifest/introspect.d.ts +18 -0
- package/build/types/manifest/manifest.d.ts +18 -0
- package/build/types/manifest/schema.d.ts +177 -0
- package/build/types/requirements.d.ts +1 -0
- package/build/types/types/access-guards.d.ts +4 -0
- package/build/types/types/application.d.ts +32 -0
- package/build/types/types/artifact.d.ts +8 -0
- package/build/types/types/builder.d.ts +37 -0
- package/build/types/types/config.d.ts +62 -0
- package/build/types/types/controller.d.ts +27 -0
- package/build/types/types/contruct.d.ts +1 -0
- package/build/types/types/core.d.ts +11 -0
- package/build/types/types/csrf.d.ts +33 -0
- package/build/types/types/directory.d.ts +6 -0
- package/build/types/types/encryption.d.ts +14 -0
- package/build/types/types/generic.d.ts +2 -0
- package/build/types/types/guard.d.ts +9 -0
- package/build/types/types/http-responses.d.ts +7 -0
- package/build/types/types/index.d.ts +27 -0
- package/build/types/types/injection.d.ts +11 -0
- package/build/types/types/lifecycle.d.ts +9 -0
- package/build/types/types/mcp.d.ts +148 -0
- package/build/types/types/middleware.d.ts +12 -0
- package/build/types/types/parseable.d.ts +3 -0
- package/build/types/types/plugin.d.ts +6 -0
- package/build/types/types/raiton.d.ts +13 -0
- package/build/types/types/responses.d.ts +20 -0
- package/build/types/types/router.d.ts +13 -0
- package/build/types/types/runtime.d.ts +48 -0
- package/build/types/types/scheduler.d.ts +140 -0
- package/build/types/types/scheme.d.ts +125 -0
- package/build/types/types/server.d.ts +10 -0
- package/build/types/types/socket.d.ts +11 -0
- package/build/types/types/thread.d.ts +25 -0
- package/build/types/types/utilities.d.ts +4 -0
- package/build/types/types/values.d.ts +2 -0
- package/docs/AGENTS.md +55 -0
- package/docs/CLAUDE.md +55 -0
- package/docs/README.md +5 -0
- package/docs/contributors/cli/README.md +17 -3
- package/docs/contributors/cli/commands.md +28 -17
- package/docs/contributors/framework/plugins/openapi.md +12 -3
- package/docs/generated/cli/commands.md +26 -0
- package/docs/generated/config-schema.json +150 -0
- package/docs/generated/manifest-schema.json +236 -0
- package/docs/generated/manifest.json +101 -0
- package/docs/llms-full.txt +1271 -0
- package/docs/llms.txt +46 -0
- package/docs/user-guide/README.md +18 -12
- package/docs/user-guide/cli.md +21 -0
- package/docs/user-guide/config.md +14 -0
- package/docs/user-guide/contracts.md +67 -0
- package/docs/user-guide/en/README.md +83 -0
- package/docs/user-guide/getting-started.md +13 -1
- package/docs/user-guide/mcp.md +45 -2
- package/docs/user-guide/observability.md +74 -0
- package/docs/user-guide/openapi/plugin.md +10 -0
- package/docs/user-guide/recipes/README.md +32 -0
- package/docs/user-guide/recipes/contracts.md +52 -0
- package/docs/user-guide/recipes/doctor.md +16 -0
- package/docs/user-guide/recipes/generate.md +28 -0
- package/docs/user-guide/recipes/manifest.md +17 -0
- package/docs/user-guide/recipes/mcp-stdio.md +35 -0
- package/docs/user-guide/recipes/new-project.md +34 -0
- package/docs/user-guide/recipes/observability.md +17 -0
- package/package.json +40 -7
- package/scripts/bench.ts +586 -0
- package/scripts/postinstall.mjs +15 -0
- package/source/bin/cli-output.ts +139 -0
- package/source/bin/commands.registry.ts +23 -3
- package/source/bin/file-utils.ts +95 -0
- package/source/bin/name-utils.ts +26 -0
- package/source/bin/project-utils.ts +78 -0
- package/source/commands/artifact.command.ts +30 -15
- package/source/commands/client.command.ts +64 -0
- package/source/commands/contract.command.ts +104 -0
- package/source/commands/docs.command.ts +263 -0
- package/source/commands/doctor.command.ts +226 -0
- package/source/commands/generate.command.ts +58 -0
- package/source/commands/inspect.command.ts +108 -0
- package/source/commands/mcp.command.ts +258 -0
- package/source/commands/new.command.ts +135 -0
- package/source/commands/openapi.command.ts +95 -0
- package/source/commands/routes.command.ts +39 -0
- package/source/commands/why.command.ts +61 -0
- package/source/contracts/decorators.ts +151 -0
- package/source/contracts/errors.ts +76 -0
- package/source/contracts/index.ts +4 -0
- package/source/contracts/schema.ts +377 -0
- package/source/contracts/typebox.ts +193 -0
- package/source/core/application.ts +215 -73
- package/source/core/builder.ts +6 -2
- package/source/core/config/config.ts +144 -26
- package/source/core/config/define.ts +35 -8
- package/source/core/config/index.ts +2 -1
- package/source/core/config/schema.ts +263 -0
- package/source/core/controller/builder.ts +38 -13
- package/source/core/controller/compiler.ts +14 -7
- package/source/core/controller/metadata.ts +1 -1
- package/source/core/hooks.ts +13 -1
- package/source/core/injection/injection.ts +47 -9
- package/source/core/mcp/builder.ts +13 -2
- package/source/core/mcp/metadata.ts +2 -1
- package/source/core/middleware/compose.ts +48 -0
- package/source/core/middleware/pipeline.ts +69 -46
- package/source/core/raiton.ts +8 -0
- package/source/core/router/handler.ts +91 -31
- package/source/core/router/handler.utils.ts +107 -51
- package/source/core/router/matcher.ts +195 -24
- package/source/core/router/route.ts +100 -31
- package/source/core/router/router.ts +27 -2
- package/source/core/scheduler/metadata.ts +1 -1
- package/source/core/socket/metadata.ts +1 -1
- package/source/core/thread.ts +37 -2
- package/source/framework/artifacts.ts +47 -15
- package/source/framework/cache/cache.ts +48 -3
- package/source/framework/constants/decorators.constant.ts +5 -0
- package/source/framework/data-transfer-object.ts +4 -3
- package/source/framework/decorators/controllable.decorator.ts +3 -3
- package/source/framework/decorators/csrf-guard.decorator.ts +3 -2
- package/source/framework/decorators/csrf-token.decorator.ts +1 -1
- package/source/framework/decorators/guard.decorator.ts +3 -2
- package/source/framework/decorators/health-check.decorator.ts +1 -1
- package/source/framework/decorators/mcp.decorator.ts +38 -7
- package/source/framework/decorators/middleware.decorator.ts +2 -2
- package/source/framework/decorators/parametrable.decorator.ts +2 -1
- package/source/framework/decorators/routable.decorator.ts +3 -3
- package/source/framework/decorators/route-interaction.decorator.ts +2 -2
- package/source/framework/decorators/scheduler.decorator.ts +3 -3
- package/source/framework/decorators/socket.decorator.ts +3 -3
- package/source/framework/encryption.ts +46 -7
- package/source/framework/errors/catalog.ts +159 -0
- package/source/framework/exceptions/http-exception.ts +1 -1
- package/source/framework/health-check.ts +18 -0
- package/source/framework/index.ts +2 -0
- package/source/framework/mcp/audit.ts +57 -0
- package/source/framework/mcp/conformance.ts +195 -0
- package/source/framework/mcp/handler.ts +131 -9
- package/source/framework/mcp/index.ts +6 -1
- package/source/framework/mcp/protocol.ts +6 -0
- package/source/framework/mcp/rate-limit.ts +33 -0
- package/source/framework/mcp/stdio.ts +150 -0
- package/source/framework/mcp/streamable-http.ts +36 -5
- package/source/framework/observability/index.ts +6 -0
- package/source/framework/observability/metrics.ts +162 -0
- package/source/framework/observability/plugin.ts +151 -0
- package/source/framework/observability/readiness.ts +22 -0
- package/source/framework/observability/request.ts +31 -0
- package/source/framework/observability/shutdown.ts +68 -0
- package/source/framework/observability/trace.ts +241 -0
- package/source/framework/plugins/body-parser.plugin.ts +88 -85
- package/source/framework/plugins/dev.plugin.ts +227 -0
- package/source/framework/plugins/index.ts +2 -1
- package/source/framework/plugins/mcp.plugin.ts +14 -3
- package/source/framework/plugins/openapi.plugin.ts +56 -13
- package/source/framework/responses/helpers.ts +4 -4
- package/source/framework/responses/http-throwable.ts +1 -1
- package/source/framework/runtime/bun/server.ts +2 -1
- package/source/framework/runtime/deno/server.ts +2 -1
- package/source/framework/runtime/index.ts +45 -13
- package/source/framework/runtime/node/request.ts +59 -13
- package/source/framework/utilities/index.ts +3 -1
- package/source/framework/utilities/openapi.utils.impl.ts +705 -0
- package/source/framework/utilities/openapi.utils.ts +6 -636
- package/source/framework/utilities/route-suggestion.util.ts +59 -0
- package/source/framework/utilities/validation.util.ts +20 -0
- package/source/generators/artifact.templates.ts +230 -0
- package/source/generators/index.ts +2 -0
- package/source/generators/project.templates.ts +392 -0
- package/source/manifest/client.ts +299 -0
- package/source/manifest/contract.ts +138 -0
- package/source/manifest/index.ts +5 -0
- package/source/manifest/introspect.ts +52 -0
- package/source/manifest/manifest.ts +341 -0
- package/source/manifest/schema.ts +149 -0
- package/source/types/builder.ts +5 -0
- package/source/types/config.ts +64 -2
- package/source/types/mcp.ts +63 -1
- package/tsconfig.build.json +13 -0
- package/source/commands/grafts.command.ts +0 -27
- package/tests/artifact-resolution.test.ts +0 -60
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
export interface MetricLabels {
|
|
2
|
+
[key: string]: string | number | boolean | undefined;
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
const DEFAULT_BUCKETS = [0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10];
|
|
6
|
+
|
|
7
|
+
function labelKey(labels?: MetricLabels): string {
|
|
8
|
+
if (!labels) return "";
|
|
9
|
+
const entries = Object.entries(labels)
|
|
10
|
+
.filter(([, value]) => value !== undefined)
|
|
11
|
+
.sort(([a], [b]) => a.localeCompare(b))
|
|
12
|
+
.map(([key, value]) => `${key}="${String(value).replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n")}"`);
|
|
13
|
+
return entries.length ? `{${entries.join(",")}}` : "";
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function metricName(name: string): string {
|
|
17
|
+
return name.replace(/[^a-zA-Z0-9_:]/g, "_");
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
interface CounterEntry {
|
|
21
|
+
name: string;
|
|
22
|
+
help: string;
|
|
23
|
+
values: Map<string, number>;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
interface HistogramEntry {
|
|
27
|
+
name: string;
|
|
28
|
+
help: string;
|
|
29
|
+
buckets: number[];
|
|
30
|
+
values: Map<string, {counts: number[]; sum: number; count: number}>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Dependency-free Prometheus registry. It is only touched when the
|
|
35
|
+
* `metrics` observability mode is enabled, so the hot path stays unchanged
|
|
36
|
+
* when observability is off.
|
|
37
|
+
*/
|
|
38
|
+
export class MetricsRegistry {
|
|
39
|
+
private counters = new Map<string, CounterEntry>();
|
|
40
|
+
private histograms = new Map<string, HistogramEntry>();
|
|
41
|
+
|
|
42
|
+
counter(name: string, help = ""): this {
|
|
43
|
+
const key = metricName(name);
|
|
44
|
+
if (!this.counters.has(key)) this.counters.set(key, {name: key, help, values: new Map()});
|
|
45
|
+
return this;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
increment(name: string, labels?: MetricLabels, value = 1): this {
|
|
49
|
+
const key = metricName(name);
|
|
50
|
+
let entry = this.counters.get(key);
|
|
51
|
+
if (!entry) {
|
|
52
|
+
entry = {name: key, help: `${name} counter`, values: new Map()};
|
|
53
|
+
this.counters.set(key, entry);
|
|
54
|
+
}
|
|
55
|
+
const labelsKey = labelKey(labels);
|
|
56
|
+
entry.values.set(labelsKey, (entry.values.get(labelsKey) ?? 0) + value);
|
|
57
|
+
return this;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
histogram(name: string, help = "", buckets = DEFAULT_BUCKETS): this {
|
|
61
|
+
const key = metricName(name);
|
|
62
|
+
if (!this.histograms.has(key)) {
|
|
63
|
+
this.histograms.set(key, {
|
|
64
|
+
name: key,
|
|
65
|
+
help,
|
|
66
|
+
buckets: [...buckets].sort((a, b) => a - b),
|
|
67
|
+
values: new Map(),
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
return this;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
observe(name: string, value: number, labels?: MetricLabels): this {
|
|
74
|
+
const key = metricName(name);
|
|
75
|
+
let entry = this.histograms.get(key);
|
|
76
|
+
if (!entry) {
|
|
77
|
+
entry = {
|
|
78
|
+
name: key,
|
|
79
|
+
help: `${name} histogram`,
|
|
80
|
+
buckets: DEFAULT_BUCKETS,
|
|
81
|
+
values: new Map(),
|
|
82
|
+
};
|
|
83
|
+
this.histograms.set(key, entry);
|
|
84
|
+
}
|
|
85
|
+
const labelsKey = labelKey(labels);
|
|
86
|
+
let bucketData = entry.values.get(labelsKey);
|
|
87
|
+
if (!bucketData) {
|
|
88
|
+
bucketData = {counts: new Array(entry.buckets.length).fill(0), sum: 0, count: 0};
|
|
89
|
+
entry.values.set(labelsKey, bucketData);
|
|
90
|
+
}
|
|
91
|
+
bucketData.sum += value;
|
|
92
|
+
bucketData.count += 1;
|
|
93
|
+
for (let index = 0; index < entry.buckets.length; index++) {
|
|
94
|
+
if (value <= entry.buckets[index]) bucketData.counts[index] += 1;
|
|
95
|
+
}
|
|
96
|
+
return this;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
reset(): void {
|
|
100
|
+
this.counters.clear();
|
|
101
|
+
this.histograms.clear();
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
snapshot(): Record<string, any> {
|
|
105
|
+
return {
|
|
106
|
+
counters: Object.fromEntries([...this.counters].map(([name, entry]) => [
|
|
107
|
+
name,
|
|
108
|
+
Object.fromEntries(entry.values),
|
|
109
|
+
])),
|
|
110
|
+
histograms: Object.fromEntries([...this.histograms].map(([name, entry]) => [
|
|
111
|
+
name,
|
|
112
|
+
{
|
|
113
|
+
buckets: entry.buckets,
|
|
114
|
+
values: Object.fromEntries([...entry.values].map(([labels, value]) => [labels, {
|
|
115
|
+
count: value.count,
|
|
116
|
+
sum: value.sum,
|
|
117
|
+
}])),
|
|
118
|
+
},
|
|
119
|
+
])),
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Prometheus text exposition format (version 0.0.4).
|
|
125
|
+
*/
|
|
126
|
+
render(): string {
|
|
127
|
+
const lines: string[] = [];
|
|
128
|
+
|
|
129
|
+
for (const entry of this.counters.values()) {
|
|
130
|
+
if (entry.help) lines.push(`# HELP ${entry.name} ${entry.help}`);
|
|
131
|
+
lines.push(`# TYPE ${entry.name} counter`);
|
|
132
|
+
if (entry.values.size === 0) lines.push(`${entry.name} 0`);
|
|
133
|
+
for (const [labels, value] of entry.values) {
|
|
134
|
+
lines.push(`${entry.name}${labels} ${value}`);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
for (const entry of this.histograms.values()) {
|
|
139
|
+
if (entry.help) lines.push(`# HELP ${entry.name} ${entry.help}`);
|
|
140
|
+
lines.push(`# TYPE ${entry.name} histogram`);
|
|
141
|
+
for (const [labels, data] of entry.values) {
|
|
142
|
+
for (let index = 0; index < entry.buckets.length; index++) {
|
|
143
|
+
const bucketLabels = labelKeyWithExtra(labels, `le="${entry.buckets[index]}"`);
|
|
144
|
+
lines.push(`${entry.name}_bucket${bucketLabels} ${data.counts[index]}`);
|
|
145
|
+
}
|
|
146
|
+
const infLabels = labelKeyWithExtra(labels, 'le="+Inf"');
|
|
147
|
+
lines.push(`${entry.name}_bucket${infLabels} ${data.count}`);
|
|
148
|
+
lines.push(`${entry.name}_sum${labels} ${data.sum}`);
|
|
149
|
+
lines.push(`${entry.name}_count${labels} ${data.count}`);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
return lines.join("\n") + (lines.length ? "\n" : "");
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function labelKeyWithExtra(labels: string, extra: string): string {
|
|
158
|
+
if (!labels) return `{${extra}}`;
|
|
159
|
+
return `{${labels.slice(1, -1)},${extra}}`;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export const metrics = new MetricsRegistry();
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import type {PluginInterface} from "../../types/plugin.ts";
|
|
2
|
+
import type {ContextInterface} from "../../types/core.ts";
|
|
3
|
+
import type {PluginScope} from "../../core/plugins/scope.ts";
|
|
4
|
+
import {Logger} from "@protorians/logger";
|
|
5
|
+
import {metrics} from "./metrics.ts";
|
|
6
|
+
import {configureTraceExporter, parseTraceparent, traceparent, withSpan} from "./trace.ts";
|
|
7
|
+
import {readHeader, resolveRequestId} from "./request.ts";
|
|
8
|
+
import type {ObservabilityMode} from "../../types/config.ts";
|
|
9
|
+
|
|
10
|
+
export interface ObservabilityOptions {
|
|
11
|
+
mode?: ObservabilityMode;
|
|
12
|
+
metricsPath?: string;
|
|
13
|
+
otelEndpoint?: string;
|
|
14
|
+
requestIdHeader?: string;
|
|
15
|
+
serviceName?: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
interface ResolvedOptions {
|
|
19
|
+
mode: ObservabilityMode;
|
|
20
|
+
metricsPath: string;
|
|
21
|
+
otelEndpoint: string;
|
|
22
|
+
requestIdHeader: string;
|
|
23
|
+
serviceName: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function resolveOptions(options: ObservabilityOptions): ResolvedOptions {
|
|
27
|
+
const mode = options.mode ?? "off";
|
|
28
|
+
return {
|
|
29
|
+
mode,
|
|
30
|
+
metricsPath: options.metricsPath || "/metrics",
|
|
31
|
+
otelEndpoint: options.otelEndpoint || "",
|
|
32
|
+
requestIdHeader: options.requestIdHeader || "x-request-id",
|
|
33
|
+
serviceName: options.serviceName || "raiton",
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function shouldUseMetrics(mode: ObservabilityMode): boolean {
|
|
38
|
+
return mode === "metrics" || mode === "all";
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function shouldUseTraces(mode: ObservabilityMode): boolean {
|
|
42
|
+
return mode === "traces" || mode === "all";
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Observability plugin.
|
|
47
|
+
*
|
|
48
|
+
* - `off`: the middleware is not registered at all.
|
|
49
|
+
* - `metrics`: correlation id, Prometheus counters/histograms, `/metrics`.
|
|
50
|
+
* - `traces`: correlation id, OTLP spans (incoming and `tracedFetch` outgoing).
|
|
51
|
+
* - `all`: both.
|
|
52
|
+
*/
|
|
53
|
+
export function observabilityPlugin(options: ObservabilityOptions = {}): PluginInterface {
|
|
54
|
+
const config = resolveOptions(options);
|
|
55
|
+
|
|
56
|
+
return {
|
|
57
|
+
name: "observability-plugin",
|
|
58
|
+
setup: (scope: PluginScope) => {
|
|
59
|
+
if (config.mode === "off") return;
|
|
60
|
+
|
|
61
|
+
if (shouldUseTraces(config.mode) && config.otelEndpoint) {
|
|
62
|
+
configureTraceExporter({
|
|
63
|
+
endpoint: config.otelEndpoint,
|
|
64
|
+
serviceName: config.serviceName,
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
metrics.counter("http_requests_total", "Total HTTP requests");
|
|
69
|
+
metrics.histogram("http_request_duration_seconds", "HTTP request duration in seconds");
|
|
70
|
+
|
|
71
|
+
scope.use(async ({context, next}: any) => {
|
|
72
|
+
const started = performance.now();
|
|
73
|
+
const method = String(context.req?.method ?? "GET").toUpperCase();
|
|
74
|
+
let requestId = context.state.requestId;
|
|
75
|
+
|
|
76
|
+
if (!requestId) {
|
|
77
|
+
requestId = resolveRequestId(context.req, config.requestIdHeader);
|
|
78
|
+
context.state.requestId = requestId;
|
|
79
|
+
context.reply.header(config.requestIdHeader, requestId);
|
|
80
|
+
}
|
|
81
|
+
context.state.responseStatus = context.state.responseStatus ?? 200;
|
|
82
|
+
|
|
83
|
+
const originalStatus = context.reply.status.bind(context.reply);
|
|
84
|
+
context.reply.status = (code: number) => {
|
|
85
|
+
context.state.responseStatus = code;
|
|
86
|
+
return originalStatus(code);
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
try {
|
|
90
|
+
if (shouldUseTraces(config.mode)) {
|
|
91
|
+
const parent = parseTraceparent(readHeader(context.req?.headers, "traceparent"));
|
|
92
|
+
await withSpan(`HTTP ${method}`, async (span) => {
|
|
93
|
+
span.setAttribute("http.method", method);
|
|
94
|
+
span.setAttribute("http.request_id", requestId);
|
|
95
|
+
context.state.traceId = span.traceId;
|
|
96
|
+
context.state.spanId = span.spanId;
|
|
97
|
+
await next();
|
|
98
|
+
}, {
|
|
99
|
+
parent,
|
|
100
|
+
attributes: {http_method: method, request_id: requestId},
|
|
101
|
+
});
|
|
102
|
+
} else {
|
|
103
|
+
await next();
|
|
104
|
+
}
|
|
105
|
+
} finally {
|
|
106
|
+
const status = Number(context.state.responseStatus ?? 200);
|
|
107
|
+
const route = context.state.matchedRoutePath ?? context.req?.url ?? "unknown";
|
|
108
|
+
const duration = (performance.now() - started) / 1000;
|
|
109
|
+
|
|
110
|
+
// Access logs are opt-in: they must not consume the
|
|
111
|
+
// observability performance budget. Error logs always
|
|
112
|
+
// carry the correlation id through the application.
|
|
113
|
+
if (process.env.RAITON_ACCESS_LOG === "1") {
|
|
114
|
+
Logger.info(
|
|
115
|
+
`[request] ${method} ${route} ${status} ${Math.round(duration * 1000)}ms ` +
|
|
116
|
+
`request_id=${requestId}` +
|
|
117
|
+
(context.state.traceId ? ` trace_id=${context.state.traceId}` : "")
|
|
118
|
+
);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
if (shouldUseMetrics(config.mode)) {
|
|
122
|
+
metrics.increment("http_requests_total", {
|
|
123
|
+
method,
|
|
124
|
+
route,
|
|
125
|
+
status,
|
|
126
|
+
});
|
|
127
|
+
metrics.observe(
|
|
128
|
+
"http_request_duration_seconds",
|
|
129
|
+
duration,
|
|
130
|
+
{method, route},
|
|
131
|
+
);
|
|
132
|
+
if (status >= 500) {
|
|
133
|
+
metrics.increment("http_errors_total", {method, route, status});
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
if (shouldUseMetrics(config.mode)) {
|
|
140
|
+
const handler = async ({reply}: ContextInterface) => {
|
|
141
|
+
reply.type("text/plain; version=0.0.4; charset=utf-8");
|
|
142
|
+
return metrics.render();
|
|
143
|
+
};
|
|
144
|
+
(handler as any)._raitonInternal = true;
|
|
145
|
+
scope.get(config.metricsPath, handler);
|
|
146
|
+
}
|
|
147
|
+
},
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export {traceparent};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
let ready = true;
|
|
2
|
+
let reason: string | undefined;
|
|
3
|
+
|
|
4
|
+
export class Readiness {
|
|
5
|
+
static markReady(): void {
|
|
6
|
+
ready = true;
|
|
7
|
+
reason = undefined;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
static markNotReady(nextReason = "shutting down"): void {
|
|
11
|
+
ready = false;
|
|
12
|
+
reason = nextReason;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
static get isReady(): boolean {
|
|
16
|
+
return ready;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
static snapshot(): {ready: boolean; reason?: string} {
|
|
20
|
+
return {ready, reason};
|
|
21
|
+
}
|
|
22
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
let counter = 0;
|
|
2
|
+
const VALID_REQUEST_ID = /^[A-Za-z0-9._:+\/-]{1,128}$/;
|
|
3
|
+
|
|
4
|
+
export function generateRequestId(): string {
|
|
5
|
+
counter = (counter + 1) % Number.MAX_SAFE_INTEGER;
|
|
6
|
+
return `${Date.now().toString(36)}-${counter.toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function readHeader(headers: any, name: string): string | undefined {
|
|
10
|
+
if (!headers) return undefined;
|
|
11
|
+
if (typeof headers.get === "function") {
|
|
12
|
+
return headers.get(name) ?? undefined;
|
|
13
|
+
}
|
|
14
|
+
const lower = name.toLowerCase();
|
|
15
|
+
if (typeof headers === "object") {
|
|
16
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
17
|
+
if (key.toLowerCase() === lower && value !== undefined) return String(value);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
return undefined;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Reuse a valid incoming request id, otherwise generate one. Invalid values are
|
|
25
|
+
* rejected rather than reflected, to avoid log injection.
|
|
26
|
+
*/
|
|
27
|
+
export function resolveRequestId(req: any, header = "x-request-id"): string {
|
|
28
|
+
const incoming = readHeader(req?.headers, header);
|
|
29
|
+
if (incoming && VALID_REQUEST_ID.test(incoming)) return incoming;
|
|
30
|
+
return generateRequestId();
|
|
31
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import {Readiness} from "./readiness.ts";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Tracks in-flight requests and drains them with a configurable upper bound.
|
|
5
|
+
* Readiness flips to `false` as soon as shutdown starts.
|
|
6
|
+
*/
|
|
7
|
+
export class ShutdownManager {
|
|
8
|
+
private inFlight = 0;
|
|
9
|
+
private waiters: Array<() => void> = [];
|
|
10
|
+
private draining = false;
|
|
11
|
+
private completedDrains = 0;
|
|
12
|
+
|
|
13
|
+
get activeRequests(): number {
|
|
14
|
+
return this.inFlight;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
get isDraining(): boolean {
|
|
18
|
+
return this.draining;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
get drains(): number {
|
|
22
|
+
return this.completedDrains;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
track(): () => void {
|
|
26
|
+
this.inFlight += 1;
|
|
27
|
+
let released = false;
|
|
28
|
+
return () => {
|
|
29
|
+
if (released) return;
|
|
30
|
+
released = true;
|
|
31
|
+
this.inFlight = Math.max(0, this.inFlight - 1);
|
|
32
|
+
if (this.inFlight === 0) this.flush();
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
private flush(): void {
|
|
37
|
+
const waiters = this.waiters;
|
|
38
|
+
this.waiters = [];
|
|
39
|
+
for (const resolve of waiters) resolve();
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async drain(timeoutMs = 10_000): Promise<{drained: boolean; remaining: number}> {
|
|
43
|
+
this.draining = true;
|
|
44
|
+
Readiness.markNotReady("shutting down");
|
|
45
|
+
|
|
46
|
+
if (this.inFlight === 0) {
|
|
47
|
+
this.completedDrains += 1;
|
|
48
|
+
return {drained: true, remaining: 0};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
await Promise.race([
|
|
52
|
+
new Promise<void>(resolve => this.waiters.push(resolve)),
|
|
53
|
+
new Promise<void>(resolve => setTimeout(resolve, Math.max(0, timeoutMs))),
|
|
54
|
+
]);
|
|
55
|
+
|
|
56
|
+
this.completedDrains += 1;
|
|
57
|
+
return {drained: this.inFlight === 0, remaining: this.inFlight};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
reset(): void {
|
|
61
|
+
this.inFlight = 0;
|
|
62
|
+
this.waiters = [];
|
|
63
|
+
this.draining = false;
|
|
64
|
+
Readiness.markReady();
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export const shutdown = new ShutdownManager();
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
import {AsyncLocalStorage} from "node:async_hooks";
|
|
2
|
+
|
|
3
|
+
export interface TraceContext {
|
|
4
|
+
traceId: string;
|
|
5
|
+
spanId: string;
|
|
6
|
+
parentSpanId?: string;
|
|
7
|
+
sampled: boolean;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export interface TraceSpanOptions {
|
|
11
|
+
attributes?: Record<string, any>;
|
|
12
|
+
parent?: TraceContext;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const storage = new AsyncLocalStorage<TraceContext>();
|
|
16
|
+
|
|
17
|
+
let idCounter = 0;
|
|
18
|
+
|
|
19
|
+
function randomHex(bytes = 16): string {
|
|
20
|
+
const cryptoObject: any = (globalThis as any).crypto;
|
|
21
|
+
if (cryptoObject?.getRandomValues) {
|
|
22
|
+
const array = new Uint8Array(bytes);
|
|
23
|
+
cryptoObject.getRandomValues(array);
|
|
24
|
+
return Array.from(array, value => value.toString(16).padStart(2, "0")).join("");
|
|
25
|
+
}
|
|
26
|
+
let output = "";
|
|
27
|
+
for (let index = 0; index < bytes * 2; index++) {
|
|
28
|
+
output += Math.floor(Math.random() * 16).toString(16);
|
|
29
|
+
}
|
|
30
|
+
return output;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function generateTraceId(): string {
|
|
34
|
+
return randomHex(16);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function generateSpanId(): string {
|
|
38
|
+
return randomHex(8);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function currentTrace(): TraceContext | undefined {
|
|
42
|
+
return storage.getStore();
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function parseTraceparent(value?: string | null): TraceContext | undefined {
|
|
46
|
+
if (!value) return undefined;
|
|
47
|
+
const [version, traceId, spanId, flags] = value.trim().split("-");
|
|
48
|
+
if (version !== "00" || !traceId || traceId.length !== 32 || !spanId || spanId.length !== 16) return undefined;
|
|
49
|
+
return {
|
|
50
|
+
traceId,
|
|
51
|
+
parentSpanId: spanId,
|
|
52
|
+
spanId: generateSpanId(),
|
|
53
|
+
sampled: (parseInt(flags ?? "01", 16) & 1) === 1,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function traceparent(context: TraceContext): string {
|
|
58
|
+
return `00-${context.traceId}-${context.spanId}-${context.sampled ? "01" : "00"}`;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export class TraceSpan {
|
|
62
|
+
public readonly traceId: string;
|
|
63
|
+
public readonly spanId: string;
|
|
64
|
+
public readonly parentSpanId?: string;
|
|
65
|
+
public readonly name: string;
|
|
66
|
+
public readonly startTime = Date.now();
|
|
67
|
+
public readonly attributes: Record<string, any>;
|
|
68
|
+
public readonly events: Array<{name: string; time: number; attributes?: Record<string, any>}> = [];
|
|
69
|
+
public status: "unset" | "ok" | "error" = "unset";
|
|
70
|
+
public error?: string;
|
|
71
|
+
|
|
72
|
+
constructor(name: string, context: TraceContext, attributes: Record<string, any> = {}) {
|
|
73
|
+
this.name = name;
|
|
74
|
+
this.traceId = context.traceId;
|
|
75
|
+
this.spanId = context.spanId;
|
|
76
|
+
this.parentSpanId = context.parentSpanId;
|
|
77
|
+
this.attributes = attributes;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
setAttribute(key: string, value: any): this {
|
|
81
|
+
this.attributes[key] = value;
|
|
82
|
+
return this;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
addEvent(name: string, attributes?: Record<string, any>): this {
|
|
86
|
+
this.events.push({name, time: Date.now(), attributes});
|
|
87
|
+
return this;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
setStatus(status: "ok" | "error", error?: string): this {
|
|
91
|
+
this.status = status;
|
|
92
|
+
if (error) this.error = error;
|
|
93
|
+
return this;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
get durationMs(): number {
|
|
97
|
+
return Date.now() - this.startTime;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
context(): TraceContext {
|
|
101
|
+
return {
|
|
102
|
+
traceId: this.traceId,
|
|
103
|
+
spanId: this.spanId,
|
|
104
|
+
parentSpanId: this.parentSpanId,
|
|
105
|
+
sampled: true,
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
toOtlp(serviceName: string) {
|
|
110
|
+
return {
|
|
111
|
+
traceId: this.traceId,
|
|
112
|
+
spanId: this.spanId,
|
|
113
|
+
parentSpanId: this.parentSpanId,
|
|
114
|
+
name: this.name,
|
|
115
|
+
kind: 1,
|
|
116
|
+
startTimeUnixNano: String(BigInt(this.startTime) * 1_000_000n),
|
|
117
|
+
endTimeUnixNano: String(BigInt(this.startTime + this.durationMs) * 1_000_000n),
|
|
118
|
+
attributes: Object.entries(this.attributes)
|
|
119
|
+
.filter(([, value]) => value !== undefined && value !== null)
|
|
120
|
+
.map(([key, value]) => ({
|
|
121
|
+
key,
|
|
122
|
+
value: typeof value === "number"
|
|
123
|
+
? {doubleValue: value}
|
|
124
|
+
: typeof value === "boolean"
|
|
125
|
+
? {boolValue: value}
|
|
126
|
+
: {stringValue: String(value)},
|
|
127
|
+
})),
|
|
128
|
+
events: this.events.map(event => ({
|
|
129
|
+
name: event.name,
|
|
130
|
+
timeUnixNano: String(BigInt(event.time) * 1_000_000n),
|
|
131
|
+
})),
|
|
132
|
+
status: this.status === "error"
|
|
133
|
+
? {code: 2, message: this.error ?? "error"}
|
|
134
|
+
: {code: 1},
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export interface TraceExporterOptions {
|
|
140
|
+
endpoint?: string;
|
|
141
|
+
serviceName?: string;
|
|
142
|
+
headers?: Record<string, string>;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Minimal OTLP/HTTP JSON exporter. Export is fire-and-forget so tracing never
|
|
147
|
+
* blocks a request; failures are swallowed (tracing must not break the app).
|
|
148
|
+
*/
|
|
149
|
+
export class OtlpExporter {
|
|
150
|
+
constructor(private readonly options: TraceExporterOptions = {}) {}
|
|
151
|
+
|
|
152
|
+
export(span: TraceSpan): void {
|
|
153
|
+
if (!this.options.endpoint) return;
|
|
154
|
+
const payload = {
|
|
155
|
+
resourceSpans: [{
|
|
156
|
+
resource: {
|
|
157
|
+
attributes: [{key: "service.name", value: {stringValue: this.options.serviceName ?? "raiton"}}],
|
|
158
|
+
},
|
|
159
|
+
scopeSpans: [{
|
|
160
|
+
scope: {name: "raiton"},
|
|
161
|
+
spans: [span.toOtlp(this.options.serviceName ?? "raiton")],
|
|
162
|
+
}],
|
|
163
|
+
}],
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
const endpoint = this.options.endpoint.replace(/\/$/, "");
|
|
167
|
+
const url = endpoint.endsWith("/v1/traces") ? endpoint : `${endpoint}/v1/traces`;
|
|
168
|
+
|
|
169
|
+
try {
|
|
170
|
+
void fetch(url, {
|
|
171
|
+
method: "POST",
|
|
172
|
+
headers: {"content-type": "application/json", ...(this.options.headers ?? {})},
|
|
173
|
+
body: JSON.stringify(payload),
|
|
174
|
+
}).catch(() => undefined);
|
|
175
|
+
} catch {
|
|
176
|
+
// Tracing is best-effort.
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
let defaultExporter = new OtlpExporter();
|
|
182
|
+
|
|
183
|
+
export function configureTraceExporter(options: TraceExporterOptions): void {
|
|
184
|
+
defaultExporter = new OtlpExporter(options);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export function startSpan(name: string, options: TraceSpanOptions = {}): TraceSpan {
|
|
188
|
+
const parent = options.parent ?? currentTrace();
|
|
189
|
+
const context: TraceContext = {
|
|
190
|
+
traceId: parent?.traceId ?? generateTraceId(),
|
|
191
|
+
spanId: generateSpanId(),
|
|
192
|
+
parentSpanId: parent?.spanId,
|
|
193
|
+
sampled: parent?.sampled ?? true,
|
|
194
|
+
};
|
|
195
|
+
return new TraceSpan(name, context, options.attributes);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Run a callback inside a trace. Nested spans share the trace id, which is how
|
|
200
|
+
* incoming and outgoing operations are correlated.
|
|
201
|
+
*/
|
|
202
|
+
export async function withSpan<T>(
|
|
203
|
+
name: string,
|
|
204
|
+
callable: (span: TraceSpan) => Promise<T> | T,
|
|
205
|
+
options: TraceSpanOptions = {},
|
|
206
|
+
): Promise<T> {
|
|
207
|
+
const span = startSpan(name, options);
|
|
208
|
+
try {
|
|
209
|
+
const result = await storage.run(span.context(), () => callable(span));
|
|
210
|
+
if (span.status === "unset") span.setStatus("ok");
|
|
211
|
+
return result;
|
|
212
|
+
} catch (error: any) {
|
|
213
|
+
span.setStatus("error", error?.message ?? String(error));
|
|
214
|
+
throw error;
|
|
215
|
+
} finally {
|
|
216
|
+
defaultExporter.export(span);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* `fetch` wrapper that propagates the active trace and records an outgoing span.
|
|
222
|
+
*/
|
|
223
|
+
export async function tracedFetch(input: any, init: RequestInit = {}): Promise<Response> {
|
|
224
|
+
const parent = currentTrace();
|
|
225
|
+
const headers = new Headers(init.headers ?? {});
|
|
226
|
+
|
|
227
|
+
return withSpan(
|
|
228
|
+
`HTTP ${init.method ?? "GET"} ${typeof input === "string" ? input : (input?.url ?? "outgoing")}`,
|
|
229
|
+
async (span) => {
|
|
230
|
+
// The outgoing operation is the child span; propagate its context
|
|
231
|
+
// so the remote service joins the same trace.
|
|
232
|
+
headers.set("traceparent", traceparent(span.context()));
|
|
233
|
+
span.setAttribute("http.method", init.method ?? "GET");
|
|
234
|
+
const response = await fetch(input, {...init, headers});
|
|
235
|
+
span.setAttribute("http.status_code", response.status);
|
|
236
|
+
if (!response.ok) span.setStatus("error", `HTTP ${response.status}`);
|
|
237
|
+
return response;
|
|
238
|
+
},
|
|
239
|
+
parent ? {parent} : {},
|
|
240
|
+
);
|
|
241
|
+
}
|