@equipe-tech/observability 0.1.0

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.
@@ -0,0 +1,35 @@
1
+ import { Schema } from "effect";
2
+ export declare const maxEventsPerBatch = 64;
3
+ export declare const maxFieldsPerEvent = 32;
4
+ export declare const maxFieldKeyLength = 128;
5
+ export declare const maxFieldValueLength = 1024;
6
+ export declare const maxEventNameLength = 128;
7
+ export declare const maxEventIdLength = 64;
8
+ declare const BrowserEventFields: Schema.$Record<Schema.NonEmptyString, Schema.Union<readonly [Schema.String, Schema.Number, Schema.Boolean]>>;
9
+ export type BrowserEventFields = typeof BrowserEventFields.Type;
10
+ declare const BrowserEvent_base: Schema.Class<BrowserEvent, Schema.Struct<{
11
+ readonly id: Schema.NonEmptyString;
12
+ readonly name: Schema.NonEmptyString;
13
+ readonly occurredAt: Schema.Number;
14
+ readonly fields: Schema.$Record<Schema.NonEmptyString, Schema.Union<readonly [Schema.String, Schema.Number, Schema.Boolean]>>;
15
+ }>, {}>;
16
+ export declare class BrowserEvent extends BrowserEvent_base {
17
+ }
18
+ declare const BrowserEventBatch_base: Schema.Class<BrowserEventBatch, Schema.Struct<{
19
+ readonly version: Schema.Literal<1>;
20
+ readonly events: Schema.$Array<typeof BrowserEvent>;
21
+ }>, {}>;
22
+ export declare class BrowserEventBatch extends BrowserEventBatch_base {
23
+ }
24
+ export declare const encodeBrowserEventBatch: (input: BrowserEventBatch, options?: import("effect/SchemaAST").ParseOptions) => import("effect/Effect").Effect<{
25
+ readonly version: 1;
26
+ readonly events: readonly {
27
+ readonly id: string;
28
+ readonly name: string;
29
+ readonly occurredAt: number;
30
+ readonly fields: {
31
+ readonly [x: string]: string | number | boolean;
32
+ };
33
+ }[];
34
+ }, Schema.SchemaError, never>;
35
+ export {};
@@ -0,0 +1,33 @@
1
+ import { Schema } from "effect";
2
+ export const maxEventsPerBatch = 64;
3
+ export const maxFieldsPerEvent = 32;
4
+ export const maxFieldKeyLength = 128;
5
+ export const maxFieldValueLength = 1024;
6
+ export const maxEventNameLength = 128;
7
+ export const maxEventIdLength = 64;
8
+ const BoundedFieldValue = Schema.Union([
9
+ Schema.String.check(Schema.isMaxLength(maxFieldValueLength)),
10
+ Schema.Number.check(Schema.isFinite()),
11
+ Schema.Boolean,
12
+ ]);
13
+ const BoundedFieldKey = Schema.NonEmptyString.check(Schema.isMaxLength(maxFieldKeyLength));
14
+ const BrowserEventFields = Schema.Record(BoundedFieldKey, BoundedFieldValue).check(Schema.makeFilter((fields) => Object.keys(fields).length <= maxFieldsPerEvent, {
15
+ expected: `at most ${maxFieldsPerEvent} fields per event`,
16
+ }));
17
+ export class BrowserEvent extends Schema.Class("@equipe-tech/observability/BrowserEvent")({
18
+ id: Schema.NonEmptyString.check(Schema.isMaxLength(maxEventIdLength)),
19
+ name: Schema.NonEmptyString.check(Schema.isMaxLength(maxEventNameLength)),
20
+ occurredAt: Schema.Number.check(Schema.isFinite(), Schema.makeFilter((millis) => millis >= 0, {
21
+ expected: "a non-negative epoch timestamp in milliseconds",
22
+ })),
23
+ fields: BrowserEventFields,
24
+ }) {
25
+ }
26
+ export class BrowserEventBatch extends Schema.Class("@equipe-tech/observability/BrowserEventBatch")({
27
+ version: Schema.Literal(1),
28
+ events: Schema.Array(BrowserEvent).check(Schema.makeFilter((events) => events.length <= maxEventsPerBatch, {
29
+ expected: `at most ${maxEventsPerBatch} events per batch`,
30
+ })),
31
+ }) {
32
+ }
33
+ export const encodeBrowserEventBatch = Schema.encodeEffect(BrowserEventBatch);
package/dist/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,7 @@
1
+ import { Layer } from "effect";
2
+ import { type HttpClient } from "effect/unstable/http";
3
+ import type { EnvironmentVariables, InvalidTelemetryEnvironment } from "./TelemetryConfig.js";
4
+ import { type TelemetryConfig } from "./TelemetryConfig.js";
5
+ export declare const layerOtlp: (config: TelemetryConfig) => Layer.Layer<never, never, HttpClient.HttpClient>;
6
+ export declare const layer: (config: TelemetryConfig) => Layer.Layer<never>;
7
+ export declare const layerFromEnv: (env: EnvironmentVariables) => Layer.Layer<never, InvalidTelemetryEnvironment>;
@@ -0,0 +1,16 @@
1
+ import { Effect, Layer } from "effect";
2
+ import { FetchHttpClient } from "effect/unstable/http";
3
+ import { Otlp } from "effect/unstable/observability";
4
+ import { telemetryConfigFromEnv } from "./TelemetryConfig.js";
5
+ export const layerOtlp = (config) => Otlp.layerJson({
6
+ baseUrl: config.otlpEndpoint.toString(),
7
+ resource: {
8
+ serviceName: config.serviceName,
9
+ serviceVersion: config.serviceVersion,
10
+ attributes: {
11
+ "deployment.environment.name": config.environment,
12
+ },
13
+ },
14
+ });
15
+ export const layer = (config) => layerOtlp(config).pipe(Layer.provide(FetchHttpClient.layer));
16
+ export const layerFromEnv = (env) => Layer.unwrap(Effect.map(telemetryConfigFromEnv(env), layer));
@@ -0,0 +1,21 @@
1
+ import { Effect, Schema } from "effect";
2
+ declare const TelemetryConfig_base: Schema.Class<TelemetryConfig, Schema.Struct<{
3
+ readonly serviceName: Schema.NonEmptyString;
4
+ readonly serviceVersion: Schema.NonEmptyString;
5
+ readonly environment: Schema.NonEmptyString;
6
+ readonly otlpEndpoint: Schema.URLFromString;
7
+ }>, {}>;
8
+ export declare class TelemetryConfig extends TelemetryConfig_base {
9
+ }
10
+ declare const InvalidTelemetryEnvironment_base: Schema.Class<InvalidTelemetryEnvironment, Schema.TaggedStruct<"InvalidTelemetryEnvironment", {
11
+ readonly code: Schema.Literal<"OBS_TELEMETRY_INVALID_ENVIRONMENT">;
12
+ readonly message: Schema.String;
13
+ readonly cause: Schema.Defect;
14
+ }>, import("effect/Cause").YieldableError>;
15
+ export declare class InvalidTelemetryEnvironment extends InvalidTelemetryEnvironment_base {
16
+ }
17
+ export type EnvironmentVariables = {
18
+ readonly [name: string]: string | undefined;
19
+ };
20
+ export declare const telemetryConfigFromEnv: (env: EnvironmentVariables) => Effect.Effect<TelemetryConfig, InvalidTelemetryEnvironment, never>;
21
+ export {};
@@ -0,0 +1,37 @@
1
+ import { Effect, Schema } from "effect";
2
+ const OtlpEndpoint = Schema.URLFromString.check(Schema.makeFilter((url) => (url.protocol === "http:" || url.protocol === "https:") &&
3
+ url.username === "" &&
4
+ url.password === "", { expected: "an HTTP or HTTPS URL without credentials" }));
5
+ export class TelemetryConfig extends Schema.Class("@equipe-tech/observability/TelemetryConfig")({
6
+ serviceName: Schema.NonEmptyString,
7
+ serviceVersion: Schema.NonEmptyString,
8
+ environment: Schema.NonEmptyString,
9
+ otlpEndpoint: OtlpEndpoint,
10
+ }) {
11
+ }
12
+ export class InvalidTelemetryEnvironment extends Schema.TaggedError()("InvalidTelemetryEnvironment", {
13
+ code: Schema.Literal("OBS_TELEMETRY_INVALID_ENVIRONMENT"),
14
+ message: Schema.String,
15
+ cause: Schema.Defect(),
16
+ }) {
17
+ }
18
+ const TelemetryEnvironment = Schema.Struct({
19
+ OTEL_SERVICE_NAME: Schema.NonEmptyString,
20
+ OTEL_SERVICE_VERSION: Schema.NonEmptyString.pipe(Schema.withDecodingDefault(Effect.succeed("0.0.0"))),
21
+ OTEL_DEPLOYMENT_ENVIRONMENT: Schema.NonEmptyString.pipe(Schema.withDecodingDefault(Effect.succeed("development"))),
22
+ OTEL_EXPORTER_OTLP_ENDPOINT: OtlpEndpoint.pipe(Schema.withDecodingDefault(Effect.succeed("http://localhost:4318"))),
23
+ });
24
+ const decodeTelemetryEnvironment = Schema.decodeUnknownEffect(TelemetryEnvironment);
25
+ export const telemetryConfigFromEnv = Effect.fn("telemetryConfigFromEnv")(function* (env) {
26
+ const variables = yield* decodeTelemetryEnvironment(env).pipe(Effect.mapError((cause) => new InvalidTelemetryEnvironment({
27
+ code: "OBS_TELEMETRY_INVALID_ENVIRONMENT",
28
+ message: "Telemetry environment is invalid. Set OTEL_SERVICE_NAME and use valid values for the remaining OTEL variables.",
29
+ cause,
30
+ })));
31
+ return new TelemetryConfig({
32
+ serviceName: variables.OTEL_SERVICE_NAME,
33
+ serviceVersion: variables.OTEL_SERVICE_VERSION,
34
+ environment: variables.OTEL_DEPLOYMENT_ENVIRONMENT,
35
+ otlpEndpoint: variables.OTEL_EXPORTER_OTLP_ENDPOINT,
36
+ });
37
+ });
@@ -0,0 +1,5 @@
1
+ import { Effect } from "effect";
2
+ export type WideEventFields = {
3
+ readonly [attribute: string]: string | number | boolean;
4
+ };
5
+ export declare const emit: (name: string, fields: WideEventFields) => Effect.Effect<void>;
@@ -0,0 +1,6 @@
1
+ import { Effect } from "effect";
2
+ export const emit = (name, fields) => Effect.logInfo(name).pipe(Effect.annotateLogs({
3
+ ...fields,
4
+ "event.name": name,
5
+ "event.kind": "wide",
6
+ }));
@@ -0,0 +1,35 @@
1
+ import { Context, Duration, Effect, Layer, Schema } from "effect";
2
+ import { BrowserEventBatch } from "../BrowserEvents.js";
3
+ import type { WideEventFields } from "../WideEvent.js";
4
+ export { BrowserEvent, BrowserEventBatch, maxEventNameLength, maxEventsPerBatch, maxFieldKeyLength, maxFieldsPerEvent, maxFieldValueLength, } from "../BrowserEvents.js";
5
+ export declare const defaultEventsEndpoint = "/_telemetry/events";
6
+ declare const BrowserEventDeliveryError_base: Schema.Class<BrowserEventDeliveryError, Schema.TaggedStruct<"BrowserEventDeliveryError", {
7
+ readonly code: Schema.Literal<"OBS_BROWSER_EVENTS_DELIVERY_FAILED">;
8
+ readonly message: Schema.String;
9
+ readonly retryable: Schema.Boolean;
10
+ readonly cause: Schema.Defect;
11
+ }>, import("effect/Cause").YieldableError>;
12
+ export declare class BrowserEventDeliveryError extends BrowserEventDeliveryError_base {
13
+ }
14
+ declare const BrowserEventTransport_base: Context.ServiceClass<BrowserEventTransport, "@equipe-tech/observability/BrowserEventTransport", {
15
+ send(batch: BrowserEventBatch): Effect.Effect<void, BrowserEventDeliveryError>;
16
+ }>;
17
+ export declare class BrowserEventTransport extends BrowserEventTransport_base {
18
+ static readonly layerFetch: (options?: {
19
+ readonly endpoint?: string;
20
+ }) => Layer.Layer<BrowserEventTransport>;
21
+ }
22
+ export type BrowserTelemetryOptions = {
23
+ readonly maxBatchSize?: number;
24
+ readonly maxQueueSize?: number;
25
+ readonly flushInterval?: Duration.Input;
26
+ };
27
+ declare const BrowserTelemetry_base: Context.ServiceClass<BrowserTelemetry, "@equipe-tech/observability/BrowserTelemetry", {
28
+ emit(name: string, fields?: WideEventFields): Effect.Effect<void>;
29
+ flush(): Effect.Effect<void, BrowserEventDeliveryError>;
30
+ pending(): Effect.Effect<number>;
31
+ dropped(): Effect.Effect<number>;
32
+ }>;
33
+ export declare class BrowserTelemetry extends BrowserTelemetry_base {
34
+ static readonly layer: (options?: BrowserTelemetryOptions) => Layer.Layer<BrowserTelemetry, never, BrowserEventTransport>;
35
+ }
@@ -0,0 +1,105 @@
1
+ import { Clock, Context, Duration, Effect, Layer, Predicate, Ref, Schema } from "effect";
2
+ import { BrowserEvent, BrowserEventBatch, encodeBrowserEventBatch, maxEventNameLength, maxEventsPerBatch, maxFieldKeyLength, maxFieldsPerEvent, maxFieldValueLength, } from "../BrowserEvents.js";
3
+ export { BrowserEvent, BrowserEventBatch, maxEventNameLength, maxEventsPerBatch, maxFieldKeyLength, maxFieldsPerEvent, maxFieldValueLength, } from "../BrowserEvents.js";
4
+ export const defaultEventsEndpoint = "/_telemetry/events";
5
+ export class BrowserEventDeliveryError extends Schema.TaggedError()("BrowserEventDeliveryError", {
6
+ code: Schema.Literal("OBS_BROWSER_EVENTS_DELIVERY_FAILED"),
7
+ message: Schema.String,
8
+ retryable: Schema.Boolean,
9
+ cause: Schema.Defect(),
10
+ }) {
11
+ }
12
+ export class BrowserEventTransport extends Context.Service()("@equipe-tech/observability/BrowserEventTransport") {
13
+ static layerFetch = (options) => {
14
+ const endpoint = options?.endpoint ?? defaultEventsEndpoint;
15
+ return Layer.succeed(BrowserEventTransport, BrowserEventTransport.of({
16
+ send: (batch) => Effect.gen(function* () {
17
+ const payload = yield* encodeBrowserEventBatch(batch).pipe(Effect.orDie);
18
+ const response = yield* Effect.tryPromise({
19
+ try: (signal) => fetch(endpoint, {
20
+ method: "POST",
21
+ headers: { "content-type": "application/json" },
22
+ body: JSON.stringify(payload),
23
+ keepalive: true,
24
+ signal,
25
+ }),
26
+ catch: (cause) => new BrowserEventDeliveryError({
27
+ code: "OBS_BROWSER_EVENTS_DELIVERY_FAILED",
28
+ message: "The browser events could not be sent. The events stay queued and the next flush retries the same batch.",
29
+ retryable: true,
30
+ cause,
31
+ }),
32
+ });
33
+ if (!response.ok) {
34
+ return yield* new BrowserEventDeliveryError({
35
+ code: "OBS_BROWSER_EVENTS_DELIVERY_FAILED",
36
+ message: `The telemetry endpoint rejected the batch with status ${response.status}. Check the /_telemetry/events route of the project API.`,
37
+ retryable: response.status === 429 || response.status >= 500,
38
+ cause: response.status,
39
+ });
40
+ }
41
+ }),
42
+ }));
43
+ };
44
+ }
45
+ const clampFields = (fields) => {
46
+ const clamped = {};
47
+ let count = 0;
48
+ for (const [key, value] of Object.entries(fields)) {
49
+ if (key === "" || count >= maxFieldsPerEvent) {
50
+ continue;
51
+ }
52
+ const boundedKey = key.slice(0, maxFieldKeyLength);
53
+ clamped[boundedKey] = Predicate.isString(value) ? value.slice(0, maxFieldValueLength) : value;
54
+ count += 1;
55
+ }
56
+ return clamped;
57
+ };
58
+ const makeBrowserTelemetry = Effect.fn("makeBrowserTelemetry")(function* (options) {
59
+ const transport = yield* BrowserEventTransport;
60
+ const maxBatchSize = Math.min(options?.maxBatchSize ?? 32, maxEventsPerBatch);
61
+ const maxQueueSize = options?.maxQueueSize ?? 256;
62
+ const flushInterval = Duration.fromInputUnsafe(options?.flushInterval ?? "5 seconds");
63
+ const queue = yield* Ref.make({ events: [], dropped: 0 });
64
+ const emit = (name, fields) => Effect.gen(function* () {
65
+ const occurredAt = yield* Clock.currentTimeMillis;
66
+ const event = new BrowserEvent({
67
+ id: crypto.randomUUID(),
68
+ name: name.slice(0, maxEventNameLength),
69
+ occurredAt,
70
+ fields: clampFields(fields ?? {}),
71
+ });
72
+ yield* Ref.update(queue, (state) => state.events.length >= maxQueueSize
73
+ ? { events: [...state.events.slice(1), event], dropped: state.dropped + 1 }
74
+ : { events: [...state.events, event], dropped: state.dropped });
75
+ });
76
+ const flush = Effect.gen(function* () {
77
+ while (true) {
78
+ const batchEvents = yield* Ref.modify(queue, (state) => [
79
+ state.events.slice(0, maxBatchSize),
80
+ { events: state.events.slice(maxBatchSize), dropped: state.dropped },
81
+ ]);
82
+ if (batchEvents.length === 0) {
83
+ return;
84
+ }
85
+ yield* transport.send(new BrowserEventBatch({ version: 1, events: batchEvents })).pipe(Effect.tapError(() => Ref.update(queue, (state) => {
86
+ const requeued = [...batchEvents, ...state.events];
87
+ return {
88
+ events: requeued.slice(0, maxQueueSize),
89
+ dropped: state.dropped + Math.max(0, requeued.length - maxQueueSize),
90
+ };
91
+ })));
92
+ }
93
+ });
94
+ yield* Effect.forkScoped(flush.pipe(Effect.ignore, Effect.delay(flushInterval), Effect.forever));
95
+ yield* Effect.addFinalizer(() => flush.pipe(Effect.ignore));
96
+ return {
97
+ emit,
98
+ flush: () => flush,
99
+ pending: () => Ref.get(queue).pipe(Effect.map((state) => state.events.length)),
100
+ dropped: () => Ref.get(queue).pipe(Effect.map((state) => state.dropped)),
101
+ };
102
+ });
103
+ export class BrowserTelemetry extends Context.Service()("@equipe-tech/observability/BrowserTelemetry") {
104
+ static layer = (options) => Layer.effect(BrowserTelemetry, makeBrowserTelemetry(options));
105
+ }
@@ -0,0 +1,4 @@
1
+ export * as BrowserEvents from "./BrowserEvents.js";
2
+ export * as Telemetry from "./Telemetry.js";
3
+ export { InvalidTelemetryEnvironment, TelemetryConfig, telemetryConfigFromEnv, } from "./TelemetryConfig.js";
4
+ export * as WideEvent from "./WideEvent.js";
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export * as BrowserEvents from "./BrowserEvents.js";
2
+ export * as Telemetry from "./Telemetry.js";
3
+ export { InvalidTelemetryEnvironment, TelemetryConfig, telemetryConfigFromEnv, } from "./TelemetryConfig.js";
4
+ export * as WideEvent from "./WideEvent.js";
@@ -0,0 +1,21 @@
1
+ import { Schema } from "effect";
2
+ import type { ManagedRuntime } from "effect";
3
+ import { type BrowserEventIngestReceipt } from "../node/BrowserEventIngest.js";
4
+ import { type RequestReference } from "./TelemetryInterceptor.js";
5
+ export declare const defaultBrowserEventsPath = "_telemetry/events";
6
+ declare const BrowserEventsRejection_base: Schema.Class<BrowserEventsRejection, Schema.Struct<{
7
+ readonly code: Schema.Literal<"OBS_BROWSER_EVENTS_INVALID_BATCH">;
8
+ readonly message: Schema.String;
9
+ readonly correlationId: Schema.String;
10
+ }>, {}>;
11
+ export declare class BrowserEventsRejection extends BrowserEventsRejection_base {
12
+ }
13
+ export type BrowserEventsControllerOptions = {
14
+ readonly path?: string;
15
+ };
16
+ export declare const createBrowserEventsController: <RuntimeError>(runtime: ManagedRuntime.ManagedRuntime<never, RuntimeError>, options?: BrowserEventsControllerOptions) => {
17
+ new (): {
18
+ events(request: RequestReference): Promise<BrowserEventIngestReceipt>;
19
+ };
20
+ };
21
+ export {};
@@ -0,0 +1,44 @@
1
+ import { Controller, HttpCode, HttpException, Post, Req } from "@nestjs/common";
2
+ import { Cause, Exit, Option, Schema } from "effect";
3
+ import { ingestBrowserEvents, InvalidBrowserEventBatch, } from "../node/BrowserEventIngest.js";
4
+ import { requestSpan, withRequestSpan } from "./TelemetryInterceptor.js";
5
+ export const defaultBrowserEventsPath = "_telemetry/events";
6
+ export class BrowserEventsRejection extends Schema.Class("@equipe-tech/observability/BrowserEventsRejection")({
7
+ code: Schema.Literal("OBS_BROWSER_EVENTS_INVALID_BATCH"),
8
+ message: Schema.String,
9
+ correlationId: Schema.String,
10
+ }) {
11
+ }
12
+ const RequestWithBody = Schema.Struct({ body: Schema.Unknown });
13
+ const decodeRequestWithBody = Schema.decodeUnknownOption(RequestWithBody);
14
+ const correlationId = (request) => requestSpan(request).pipe(Option.map((span) => span.traceId), Option.getOrElse(() => crypto.randomUUID()));
15
+ export const createBrowserEventsController = (runtime, options) => {
16
+ class BrowserEventsController {
17
+ async events(request) {
18
+ const body = decodeRequestWithBody(request).pipe(Option.map((parsed) => parsed.body), Option.getOrUndefined);
19
+ const exit = await runtime.runPromiseExit(ingestBrowserEvents(body).pipe(withRequestSpan(request)));
20
+ if (Exit.isSuccess(exit)) {
21
+ return exit.value;
22
+ }
23
+ const error = Cause.findErrorOption(exit.cause);
24
+ if (Option.isSome(error) && error.value instanceof InvalidBrowserEventBatch) {
25
+ throw new HttpException(new BrowserEventsRejection({
26
+ code: error.value.code,
27
+ message: error.value.message,
28
+ correlationId: correlationId(request),
29
+ }), 400);
30
+ }
31
+ throw Cause.squash(exit.cause);
32
+ }
33
+ }
34
+ const prototype = BrowserEventsController.prototype;
35
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, "events");
36
+ if (descriptor === undefined) {
37
+ throw new Error("The events handler is missing on the controller prototype.");
38
+ }
39
+ Controller()(BrowserEventsController);
40
+ Post(options?.path ?? defaultBrowserEventsPath)(prototype, "events", descriptor);
41
+ HttpCode(202)(prototype, "events", descriptor);
42
+ Req()(prototype, "events", 0);
43
+ return BrowserEventsController;
44
+ };
@@ -0,0 +1,12 @@
1
+ import type { CallHandler, ExecutionContext, NestInterceptor } from "@nestjs/common";
2
+ import { Effect, Option } from "effect";
3
+ import type { ManagedRuntime, Tracer } from "effect";
4
+ import { Observable } from "rxjs";
5
+ export type RequestReference = WeakKey;
6
+ export declare const requestSpan: (request: RequestReference) => Option.Option<Tracer.Span>;
7
+ export declare const withRequestSpan: (request: RequestReference) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
8
+ export declare class TelemetryInterceptor<RuntimeError> implements NestInterceptor {
9
+ #private;
10
+ constructor(runtime: ManagedRuntime.ManagedRuntime<never, RuntimeError>);
11
+ intercept(context: ExecutionContext, next: CallHandler): Observable<unknown>;
12
+ }
@@ -0,0 +1,102 @@
1
+ import { Context, Effect, Exit, Option, Schema } from "effect";
2
+ import { Observable } from "rxjs";
3
+ const HttpRequestBoundary = Schema.Struct({
4
+ method: Schema.NonEmptyString,
5
+ });
6
+ const decodeHttpRequestBoundary = Schema.decodeUnknownOption(HttpRequestBoundary);
7
+ const HttpResponseBoundary = Schema.Struct({
8
+ statusCode: Schema.Number.check(Schema.isInt()),
9
+ });
10
+ const decodeHttpResponseBoundary = Schema.decodeUnknownOption(HttpResponseBoundary);
11
+ const ClientErrorBoundary = Schema.Struct({
12
+ status: Schema.Number.check(Schema.isInt(), Schema.makeFilter((status) => status >= 400 && status <= 499, {
13
+ expected: "an HTTP client error status",
14
+ })),
15
+ });
16
+ const decodeClientErrorBoundary = Schema.decodeUnknownOption(ClientErrorBoundary);
17
+ const requestSpans = new WeakMap();
18
+ export const requestSpan = (request) => Option.fromNullishOr(requestSpans.get(request));
19
+ export const withRequestSpan = (request) => (effect) => Option.match(requestSpan(request), {
20
+ onNone: () => effect,
21
+ onSome: (span) => Effect.withParentSpan(effect, span),
22
+ });
23
+ export class TelemetryInterceptor {
24
+ #runtime;
25
+ #tracer;
26
+ #clock;
27
+ constructor(runtime) {
28
+ this.#runtime = runtime;
29
+ }
30
+ intercept(context, next) {
31
+ if (context.getType() !== "http") {
32
+ return next.handle();
33
+ }
34
+ try {
35
+ return this.#instrument(context, next);
36
+ }
37
+ catch {
38
+ return next.handle();
39
+ }
40
+ }
41
+ #instrument(context, next) {
42
+ const tracer = (this.#tracer ??= this.#runtime.runSync(Effect.tracer));
43
+ const clock = (this.#clock ??= this.#runtime.runSync(Effect.clockWith(Effect.succeed)));
44
+ const httpContext = context.switchToHttp();
45
+ const request = httpContext.getRequest();
46
+ const method = decodeHttpRequestBoundary(request).pipe(Option.map((boundary) => boundary.method.toUpperCase()), Option.getOrElse(() => "UNKNOWN"));
47
+ const controller = context.getClass().name;
48
+ const handler = context.getHandler().name;
49
+ const span = tracer.span({
50
+ name: `${method} ${controller}.${handler}`,
51
+ parent: Option.none(),
52
+ annotations: Context.empty(),
53
+ links: [],
54
+ startTime: clock.currentTimeNanosUnsafe(),
55
+ kind: "server",
56
+ root: true,
57
+ sampled: true,
58
+ });
59
+ span.attribute("http.request.method", method);
60
+ span.attribute("nestjs.controller", controller);
61
+ span.attribute("nestjs.handler", handler);
62
+ requestSpans.set(request, span);
63
+ return new Observable((subscriber) => {
64
+ let settled = false;
65
+ const finish = (exit, statusOverride) => {
66
+ if (settled) {
67
+ return;
68
+ }
69
+ settled = true;
70
+ const status = statusOverride.pipe(Option.orElse(() => decodeHttpResponseBoundary(httpContext.getResponse()).pipe(Option.map((boundary) => boundary.statusCode))));
71
+ if (Option.isSome(status)) {
72
+ span.attribute("http.response.status_code", status.value);
73
+ }
74
+ span.end(clock.currentTimeNanosUnsafe(), exit);
75
+ };
76
+ const subscription = next.handle().subscribe({
77
+ next: (value) => subscriber.next(value),
78
+ error: (cause) => {
79
+ const clientError = decodeClientErrorBoundary(cause);
80
+ if (Option.isSome(clientError)) {
81
+ finish(Exit.succeed(undefined), Option.some(clientError.value.status));
82
+ }
83
+ else {
84
+ finish(Exit.die(cause), Option.none());
85
+ }
86
+ subscriber.error(cause);
87
+ },
88
+ complete: () => {
89
+ finish(Exit.succeed(undefined), Option.none());
90
+ subscriber.complete();
91
+ },
92
+ });
93
+ return () => {
94
+ if (!settled) {
95
+ span.attribute("http.request.cancelled", true);
96
+ finish(Exit.interrupt(), Option.none());
97
+ }
98
+ subscription.unsubscribe();
99
+ };
100
+ });
101
+ }
102
+ }
@@ -0,0 +1,2 @@
1
+ export { BrowserEventsRejection, createBrowserEventsController, defaultBrowserEventsPath, type BrowserEventsControllerOptions, } from "./BrowserEventsController.js";
2
+ export { requestSpan, TelemetryInterceptor, withRequestSpan, type RequestReference, } from "./TelemetryInterceptor.js";
@@ -0,0 +1,2 @@
1
+ export { BrowserEventsRejection, createBrowserEventsController, defaultBrowserEventsPath, } from "./BrowserEventsController.js";
2
+ export { requestSpan, TelemetryInterceptor, withRequestSpan, } from "./TelemetryInterceptor.js";
@@ -0,0 +1,16 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { BrowserEventBatch } from "../BrowserEvents.js";
3
+ declare const InvalidBrowserEventBatch_base: Schema.Class<InvalidBrowserEventBatch, Schema.TaggedStruct<"InvalidBrowserEventBatch", {
4
+ readonly code: Schema.Literal<"OBS_BROWSER_EVENTS_INVALID_BATCH">;
5
+ readonly message: Schema.String;
6
+ readonly cause: Schema.Defect;
7
+ }>, import("effect/Cause").YieldableError>;
8
+ export declare class InvalidBrowserEventBatch extends InvalidBrowserEventBatch_base {
9
+ }
10
+ export declare const parseBrowserEventBatch: (input: unknown) => Effect.Effect<BrowserEventBatch, InvalidBrowserEventBatch>;
11
+ export type BrowserEventIngestReceipt = {
12
+ readonly accepted: number;
13
+ };
14
+ export declare const ingestBrowserEventBatch: (batch: BrowserEventBatch) => Effect.Effect<BrowserEventIngestReceipt, never, never>;
15
+ export declare const ingestBrowserEvents: (input: unknown) => Effect.Effect<BrowserEventIngestReceipt, InvalidBrowserEventBatch>;
16
+ export {};
@@ -0,0 +1,38 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { BrowserEventBatch } from "../BrowserEvents.js";
3
+ import * as WideEvent from "../WideEvent.js";
4
+ export class InvalidBrowserEventBatch extends Schema.TaggedError()("InvalidBrowserEventBatch", {
5
+ code: Schema.Literal("OBS_BROWSER_EVENTS_INVALID_BATCH"),
6
+ message: Schema.String,
7
+ cause: Schema.Defect(),
8
+ }) {
9
+ }
10
+ const decodeBrowserEventBatch = Schema.decodeUnknownEffect(BrowserEventBatch);
11
+ export const parseBrowserEventBatch = (input) => decodeBrowserEventBatch(input).pipe(Effect.mapError((cause) => new InvalidBrowserEventBatch({
12
+ code: "OBS_BROWSER_EVENTS_INVALID_BATCH",
13
+ message: "The browser event batch is invalid. Send a version 1 batch with bounded events and scalar fields.",
14
+ cause,
15
+ })));
16
+ const reservedFieldPrefixes = ["event.", "browser."];
17
+ const trustedFields = (fields) => {
18
+ const sanitized = {};
19
+ for (const [key, value] of Object.entries(fields)) {
20
+ if (reservedFieldPrefixes.some((prefix) => key.startsWith(prefix))) {
21
+ continue;
22
+ }
23
+ sanitized[key] = value;
24
+ }
25
+ return sanitized;
26
+ };
27
+ export const ingestBrowserEventBatch = Effect.fn("ingestBrowserEventBatch")(function* (batch) {
28
+ for (const event of batch.events) {
29
+ yield* WideEvent.emit(event.name, {
30
+ ...trustedFields(event.fields),
31
+ "event.source": "browser",
32
+ "browser.event.id": event.id,
33
+ "browser.event.occurred_at": event.occurredAt,
34
+ });
35
+ }
36
+ return { accepted: batch.events.length };
37
+ });
38
+ export const ingestBrowserEvents = (input) => parseBrowserEventBatch(input).pipe(Effect.flatMap(ingestBrowserEventBatch));
@@ -0,0 +1,10 @@
1
+ import { Effect, Runtime } from "effect";
2
+ import type { Layer } from "effect";
3
+ import type { EnvironmentVariables, InvalidTelemetryEnvironment } from "../TelemetryConfig.js";
4
+ export declare const layer: (env?: EnvironmentVariables) => Layer.Layer<never, InvalidTelemetryEnvironment>;
5
+ export type RunMainOptions = {
6
+ readonly env?: EnvironmentVariables;
7
+ readonly disableErrorReporting?: boolean;
8
+ readonly teardown?: Runtime.Teardown;
9
+ };
10
+ export declare const runMain: <A, E>(program: Effect.Effect<A, E>, options?: RunMainOptions) => void;
@@ -0,0 +1,25 @@
1
+ import { Effect, Runtime } from "effect";
2
+ import { layerFromEnv } from "../Telemetry.js";
3
+ export const layer = (env) => layerFromEnv(env ?? process.env);
4
+ const runProcessMain = Runtime.makeRunMain(({ fiber, teardown }) => {
5
+ let receivedSignal = false;
6
+ const onSignal = () => {
7
+ receivedSignal = true;
8
+ fiber.interruptUnsafe(fiber.id);
9
+ };
10
+ fiber.addObserver((exit) => {
11
+ process.removeListener("SIGINT", onSignal);
12
+ process.removeListener("SIGTERM", onSignal);
13
+ teardown(exit, (code) => {
14
+ if (receivedSignal || code !== 0) {
15
+ process.exit(code);
16
+ }
17
+ });
18
+ });
19
+ process.on("SIGINT", onSignal);
20
+ process.on("SIGTERM", onSignal);
21
+ });
22
+ export const runMain = (program, options) => runProcessMain(Effect.provide(program, layer(options?.env)), {
23
+ disableErrorReporting: options?.disableErrorReporting,
24
+ teardown: options?.teardown,
25
+ });
@@ -0,0 +1,2 @@
1
+ export { ingestBrowserEventBatch, ingestBrowserEvents, InvalidBrowserEventBatch, parseBrowserEventBatch, type BrowserEventIngestReceipt, } from "./BrowserEventIngest.js";
2
+ export { layer, runMain, type RunMainOptions } from "./Runtime.js";
@@ -0,0 +1,2 @@
1
+ export { ingestBrowserEventBatch, ingestBrowserEvents, InvalidBrowserEventBatch, parseBrowserEventBatch, } from "./BrowserEventIngest.js";
2
+ export { layer, runMain } from "./Runtime.js";
@@ -0,0 +1,54 @@
1
+ import { Effect, Layer, Option, type Exit } from "effect";
2
+ import { TelemetryConfig } from "../TelemetryConfig.js";
3
+ export type CapturedAttributeValue = string | number | boolean;
4
+ export type CapturedAttributes = ReadonlyMap<string, CapturedAttributeValue>;
5
+ export type CapturedSpan = {
6
+ readonly traceId: string;
7
+ readonly spanId: string;
8
+ readonly parentSpanId: Option.Option<string>;
9
+ readonly name: string;
10
+ readonly statusCode: number;
11
+ readonly statusMessage: Option.Option<string>;
12
+ readonly attributes: CapturedAttributes;
13
+ readonly resourceAttributes: CapturedAttributes;
14
+ };
15
+ export type CapturedLog = {
16
+ readonly traceId: Option.Option<string>;
17
+ readonly spanId: Option.Option<string>;
18
+ readonly severityText: Option.Option<string>;
19
+ readonly body: Option.Option<string>;
20
+ readonly attributes: CapturedAttributes;
21
+ readonly resourceAttributes: CapturedAttributes;
22
+ };
23
+ export type CapturedMetricPoint = {
24
+ readonly value: Option.Option<number>;
25
+ readonly attributes: CapturedAttributes;
26
+ };
27
+ export type CapturedMetric = {
28
+ readonly name: string;
29
+ readonly points: ReadonlyArray<CapturedMetricPoint>;
30
+ readonly resourceAttributes: CapturedAttributes;
31
+ };
32
+ export type CapturedTelemetry = {
33
+ readonly spans: ReadonlyArray<CapturedSpan>;
34
+ readonly logs: ReadonlyArray<CapturedLog>;
35
+ readonly metrics: ReadonlyArray<CapturedMetric>;
36
+ };
37
+ export type TelemetryRun<A, E> = {
38
+ readonly exit: Exit.Exit<A, E>;
39
+ readonly telemetry: CapturedTelemetry;
40
+ };
41
+ export declare const attribute: (attributes: CapturedAttributes, key: string) => Option.Option<CapturedAttributeValue>;
42
+ export type CapturedRequest = {
43
+ readonly path: string;
44
+ readonly payload: unknown;
45
+ };
46
+ export type RunOptions = {
47
+ readonly config?: TelemetryConfig;
48
+ };
49
+ export type TelemetryCapture = {
50
+ readonly layer: Layer.Layer<never>;
51
+ readonly telemetry: Effect.Effect<CapturedTelemetry>;
52
+ };
53
+ export declare const makeCapture: (options?: RunOptions | undefined) => Effect.Effect<TelemetryCapture, never, never>;
54
+ export declare const run: <A, E, R>(program: Effect.Effect<A, E, R>, options?: RunOptions) => Effect.Effect<TelemetryRun<A, E>, never, R>;
@@ -0,0 +1,184 @@
1
+ import { Effect, Layer, Option, Ref, Schema } from "effect";
2
+ import { HttpClient, HttpClientResponse } from "effect/unstable/http";
3
+ import { layerOtlp } from "../Telemetry.js";
4
+ import { TelemetryConfig } from "../TelemetryConfig.js";
5
+ const AttributeValue = Schema.Struct({
6
+ stringValue: Schema.String.pipe(Schema.optionalKey),
7
+ boolValue: Schema.Boolean.pipe(Schema.optionalKey),
8
+ intValue: Schema.Union([Schema.String, Schema.Number]).pipe(Schema.optionalKey),
9
+ doubleValue: Schema.Number.pipe(Schema.optionalKey),
10
+ });
11
+ const Attribute = Schema.Struct({
12
+ key: Schema.String,
13
+ value: AttributeValue,
14
+ });
15
+ const Attributes = Schema.Array(Attribute).pipe(Schema.withDecodingDefault(Effect.succeed([])));
16
+ const ExportedResource = Schema.Struct({
17
+ attributes: Attributes,
18
+ });
19
+ const ExportedSpan = Schema.Struct({
20
+ traceId: Schema.String,
21
+ spanId: Schema.String,
22
+ parentSpanId: Schema.String.pipe(Schema.optionalKey),
23
+ name: Schema.String,
24
+ status: Schema.Struct({
25
+ code: Schema.Number.pipe(Schema.withDecodingDefault(Effect.succeed(0))),
26
+ message: Schema.String.pipe(Schema.optionalKey),
27
+ }).pipe(Schema.withDecodingDefault(Effect.succeed({ code: 0 }))),
28
+ attributes: Attributes,
29
+ });
30
+ const SpanExport = Schema.Struct({
31
+ resourceSpans: Schema.Array(Schema.Struct({
32
+ resource: ExportedResource,
33
+ scopeSpans: Schema.Array(Schema.Struct({ spans: Schema.Array(ExportedSpan) })),
34
+ })),
35
+ });
36
+ const ExportedLogRecord = Schema.Struct({
37
+ traceId: Schema.String.pipe(Schema.optionalKey),
38
+ spanId: Schema.String.pipe(Schema.optionalKey),
39
+ severityText: Schema.String.pipe(Schema.optionalKey),
40
+ body: Schema.Struct({ stringValue: Schema.String.pipe(Schema.optionalKey) }).pipe(Schema.optionalKey),
41
+ attributes: Attributes,
42
+ });
43
+ const LogExport = Schema.Struct({
44
+ resourceLogs: Schema.Array(Schema.Struct({
45
+ resource: ExportedResource,
46
+ scopeLogs: Schema.Array(Schema.Struct({ logRecords: Schema.Array(ExportedLogRecord) })),
47
+ })),
48
+ });
49
+ const MetricDataPoint = Schema.Struct({
50
+ attributes: Attributes,
51
+ asDouble: Schema.Number.pipe(Schema.optionalKey),
52
+ asInt: Schema.Union([Schema.String, Schema.Number]).pipe(Schema.optionalKey),
53
+ });
54
+ const DataPoints = Schema.Struct({ dataPoints: Schema.Array(MetricDataPoint) });
55
+ const ExportedMetric = Schema.Struct({
56
+ name: Schema.String,
57
+ sum: DataPoints.pipe(Schema.optionalKey),
58
+ gauge: DataPoints.pipe(Schema.optionalKey),
59
+ });
60
+ const MetricExport = Schema.Struct({
61
+ resourceMetrics: Schema.Array(Schema.Struct({
62
+ resource: ExportedResource,
63
+ scopeMetrics: Schema.Array(Schema.Struct({ metrics: Schema.Array(ExportedMetric) })),
64
+ })),
65
+ });
66
+ const decodeSpanExport = Schema.decodeUnknownEffect(SpanExport);
67
+ const decodeLogExport = Schema.decodeUnknownEffect(LogExport);
68
+ const decodeMetricExport = Schema.decodeUnknownEffect(MetricExport);
69
+ const toAttributes = (attributes) => {
70
+ const converted = new Map();
71
+ for (const attribute of attributes) {
72
+ const value = attribute.value;
73
+ if (value.stringValue !== undefined) {
74
+ converted.set(attribute.key, value.stringValue);
75
+ }
76
+ else if (value.boolValue !== undefined) {
77
+ converted.set(attribute.key, value.boolValue);
78
+ }
79
+ else if (value.intValue !== undefined) {
80
+ converted.set(attribute.key, Number(value.intValue));
81
+ }
82
+ else if (value.doubleValue !== undefined) {
83
+ converted.set(attribute.key, value.doubleValue);
84
+ }
85
+ }
86
+ return converted;
87
+ };
88
+ export const attribute = (attributes, key) => Option.fromNullishOr(attributes.get(key));
89
+ const captureClient = (store) => HttpClient.make((request, url) => Effect.gen(function* () {
90
+ const body = request.body;
91
+ if (body._tag === "Uint8Array") {
92
+ const payload = yield* Effect.try(() => JSON.parse(new TextDecoder().decode(body.body))).pipe(Effect.option);
93
+ if (Option.isSome(payload)) {
94
+ yield* Ref.update(store, (requests) => [
95
+ ...requests,
96
+ { path: url.pathname, payload: payload.value },
97
+ ]);
98
+ }
99
+ }
100
+ return HttpClientResponse.fromWeb(request, new Response("{}", { status: 200 }));
101
+ }));
102
+ const decodeCapturedTelemetry = Effect.fn("decodeCapturedTelemetry")(function* (requests) {
103
+ const spans = [];
104
+ const logs = [];
105
+ const metrics = [];
106
+ for (const request of requests) {
107
+ if (request.path.endsWith("/v1/traces")) {
108
+ const spanExport = yield* decodeSpanExport(request.payload).pipe(Effect.orDie);
109
+ for (const resourceSpans of spanExport.resourceSpans) {
110
+ const resourceAttributes = toAttributes(resourceSpans.resource.attributes);
111
+ for (const scopeSpans of resourceSpans.scopeSpans) {
112
+ for (const span of scopeSpans.spans) {
113
+ spans.push({
114
+ traceId: span.traceId,
115
+ spanId: span.spanId,
116
+ parentSpanId: Option.fromNullishOr(span.parentSpanId),
117
+ name: span.name,
118
+ statusCode: span.status.code,
119
+ statusMessage: Option.fromNullishOr(span.status.message),
120
+ attributes: toAttributes(span.attributes),
121
+ resourceAttributes,
122
+ });
123
+ }
124
+ }
125
+ }
126
+ }
127
+ else if (request.path.endsWith("/v1/logs")) {
128
+ const logExport = yield* decodeLogExport(request.payload).pipe(Effect.orDie);
129
+ for (const resourceLogs of logExport.resourceLogs) {
130
+ const resourceAttributes = toAttributes(resourceLogs.resource.attributes);
131
+ for (const scopeLogs of resourceLogs.scopeLogs) {
132
+ for (const log of scopeLogs.logRecords) {
133
+ logs.push({
134
+ traceId: Option.fromNullishOr(log.traceId),
135
+ spanId: Option.fromNullishOr(log.spanId),
136
+ severityText: Option.fromNullishOr(log.severityText),
137
+ body: Option.fromNullishOr(log.body?.stringValue),
138
+ attributes: toAttributes(log.attributes),
139
+ resourceAttributes,
140
+ });
141
+ }
142
+ }
143
+ }
144
+ }
145
+ else if (request.path.endsWith("/v1/metrics")) {
146
+ const metricExport = yield* decodeMetricExport(request.payload).pipe(Effect.orDie);
147
+ for (const resourceMetrics of metricExport.resourceMetrics) {
148
+ const resourceAttributes = toAttributes(resourceMetrics.resource.attributes);
149
+ for (const scopeMetrics of resourceMetrics.scopeMetrics) {
150
+ for (const metric of scopeMetrics.metrics) {
151
+ const dataPoints = metric.sum?.dataPoints ?? metric.gauge?.dataPoints ?? [];
152
+ metrics.push({
153
+ name: metric.name,
154
+ points: dataPoints.map((dataPoint) => ({
155
+ value: Option.fromNullishOr(dataPoint.asDouble ?? dataPoint.asInt).pipe(Option.map(Number)),
156
+ attributes: toAttributes(dataPoint.attributes),
157
+ })),
158
+ resourceAttributes,
159
+ });
160
+ }
161
+ }
162
+ }
163
+ }
164
+ }
165
+ return { spans, logs, metrics };
166
+ });
167
+ const defaultConfig = new TelemetryConfig({
168
+ serviceName: "telemetry-testing",
169
+ serviceVersion: "0.0.0",
170
+ environment: "test",
171
+ otlpEndpoint: new URL("http://telemetry.invalid"),
172
+ });
173
+ export const makeCapture = Effect.fn("makeCapture")(function* (options) {
174
+ const store = yield* Ref.make([]);
175
+ const layer = layerOtlp(options?.config ?? defaultConfig).pipe(Layer.provide(Layer.succeed(HttpClient.HttpClient, captureClient(store))));
176
+ const telemetry = Ref.get(store).pipe(Effect.flatMap(decodeCapturedTelemetry));
177
+ return { layer, telemetry };
178
+ });
179
+ export const run = (program, options) => Effect.gen(function* () {
180
+ const capture = yield* makeCapture(options);
181
+ const exit = yield* program.pipe(Effect.provide(capture.layer), Effect.exit);
182
+ const telemetry = yield* capture.telemetry;
183
+ return { exit, telemetry };
184
+ });
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "@equipe-tech/observability",
3
+ "version": "0.1.0",
4
+ "description": "Contrato OpenTelemetry da Equipe Tech: configuracao, layer OTLP e wide events sobre Effect",
5
+ "license": "Apache-2.0",
6
+ "files": [
7
+ "dist"
8
+ ],
9
+ "type": "module",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.js"
14
+ },
15
+ "./node": {
16
+ "types": "./dist/node/index.d.ts",
17
+ "import": "./dist/node/index.js"
18
+ },
19
+ "./nestjs": {
20
+ "types": "./dist/nestjs/index.d.ts",
21
+ "import": "./dist/nestjs/index.js"
22
+ },
23
+ "./browser": {
24
+ "types": "./dist/browser/index.d.ts",
25
+ "import": "./dist/browser/index.js"
26
+ },
27
+ "./testing": {
28
+ "types": "./dist/testing/index.d.ts",
29
+ "import": "./dist/testing/index.js"
30
+ }
31
+ },
32
+ "scripts": {
33
+ "build": "bun ../../scripts/build-packages.ts",
34
+ "prepack": "bun run build"
35
+ },
36
+ "dependencies": {
37
+ "effect": "4.0.0-rc.111"
38
+ },
39
+ "devDependencies": {
40
+ "@nestjs/common": "^11.2.1",
41
+ "@nestjs/core": "^11.2.1",
42
+ "@nestjs/platform-express": "^11.2.1",
43
+ "reflect-metadata": "^0.2.2",
44
+ "rxjs": "^7.8.2"
45
+ },
46
+ "peerDependencies": {
47
+ "@nestjs/common": "^10.0.0 || ^11.0.0",
48
+ "rxjs": "^7.2.0"
49
+ },
50
+ "peerDependenciesMeta": {
51
+ "@nestjs/common": {
52
+ "optional": true
53
+ },
54
+ "rxjs": {
55
+ "optional": true
56
+ }
57
+ }
58
+ }