Skip to content

Open Telemetry #28

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: next
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/common-bananas-knock.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@chialab/sveltekit-utils": patch
---

Add OpenTelemetry for observability
2 changes: 2 additions & 0 deletions packages/utils/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@
"@aws-sdk/client-s3": "^3.828.0",
"@chialab/isomorphic-dom": "workspace:*",
"@heyputer/kv.js": "fquffio/kv.js#fix/strict-mode",
"@opentelemetry/api": "^1.9.0",
"@opentelemetry/semantic-conventions": "^1.36.0",
"cookie": "^1.0.2",
"html-entities": "^2.6.0",
"pino": "^9.5.0",
Expand Down
3 changes: 3 additions & 0 deletions packages/utils/src/lib/server/cache/base.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import type { JitterFn, JitterMode } from '../../utils/misc.js';
import type { StorageReadWriter } from '../storage.js';
import { ATTR_PEER_SERVICE, trace } from '../telemetry.js';
import { SpanKind } from '@opentelemetry/api';

/**
* Base class for caching.
Expand Down Expand Up @@ -75,6 +77,7 @@ export abstract class BaseCache<V> implements StorageReadWriter<V> {
ttl?: number | undefined,
jitter?: JitterMode | JitterFn | undefined,
): Promise<V | undefined>;
@trace({ kind: SpanKind.CLIENT, attributes: { [ATTR_PEER_SERVICE]: 'cache' } })
public async remember(
key: string,
callback: () => PromiseLike<V | undefined>,
Expand Down
1 change: 1 addition & 0 deletions packages/utils/src/lib/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ export * from './cache/index.js';
export * from './hooks/index.js';
export * from './session.js';
export * from './sitemap.js';
export { traceDecoratorFactory, ATTR_PEER_SERVICE } from './telemetry.js';
export * from './utils.js';

import type { Session } from './session.js';
Expand Down
61 changes: 61 additions & 0 deletions packages/utils/src/lib/server/telemetry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import api, { type Span, type SpanOptions, SpanStatusCode } from '@opentelemetry/api';

/**
* Replaces deprecated SEMATTRS_PEER_SERVICE attribute.
* See {@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}.
*/
export const ATTR_PEER_SERVICE = 'peer.service' as const;

export const traceDecoratorFactory = (name: string, version?: string) => {
const tracer = api.trace.getTracer(name, version);

return <This, Value extends (this: This, ...args: any) => unknown>(options: SpanOptions = {}) =>
(target: Value, ctx: ClassMethodDecoratorContext<This, Value>): Value => {
type R = ReturnType<Value>;

return function (this: This, ...args: Parameters<Value>): R {
// @ts-expect-error Typing this properly would be cumbersome.
const className = ctx.static ? this.name : this.constructor.name;

return tracer.startActiveSpan([className, ctx.name].filter(Boolean).join('.'), options, (span: Span): R => {
try {
const result = target.call(this, ...args) as R;
if (result && typeof result === 'object' && 'then' in result && typeof result.then === 'function') {
return result.then(
(result: R) => {
span.end();

return result;
},
(err: unknown) => {
span.setStatus({ code: SpanStatusCode.ERROR });
if (err instanceof Error) {
span.recordException(err);
}
span.end();

throw err;
},
);
}

return result;
} catch (err: unknown) {
span.setStatus({ code: SpanStatusCode.ERROR });
if (err instanceof Error) {
span.recordException(err);
}

throw err;
} finally {
span.end();
}
});
} as Value;
};
};

/**
* Decorator to trace a method or function by wrapping it in a new active span.
*/
export const trace = traceDecoratorFactory('@chialab/sveltekit-utils');
3 changes: 2 additions & 1 deletion packages/utils/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true
"strict": true,
"target": "es2022"
},
"exclude": ["./tests/coverage/**"]
// Path aliases are handled by https://kit.svelte.dev/docs/configuration#alias
Expand Down
18 changes: 18 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.