@krak-stack/registry 0.1.49 → 0.1.51

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,4 @@
1
+ import { Effect } from "effect";
2
+ import { Migrator, SqlClient } from "effect/sql";
3
+ export declare const eventsMigrations: Migrator.Loader<never>;
4
+ export declare const migrateEvents: Effect.Effect<readonly (readonly [id: number, name: string])[], Migrator.MigrationError | import("effect/sql/SqlError").SqlError, SqlClient.SqlClient>;
@@ -0,0 +1,42 @@
1
+ // ../../src/services/events/migrations.ts
2
+ import { Effect } from "effect";
3
+ import { Migrator, SqlClient } from "effect/sql";
4
+ var eventsMigrations = Migrator.fromRecord({
5
+ "1_events_initial": Effect.gen(function* () {
6
+ const sql = yield* SqlClient.SqlClient;
7
+ const payloadType = sql.onDialectOrElse({
8
+ pg: () => sql.literal("jsonb"),
9
+ orElse: () => sql.literal("text")
10
+ });
11
+ yield* sql`CREATE TABLE events (
12
+ service_name text NOT NULL,
13
+ source text NOT NULL CHECK (source IN ('browser', 'server')),
14
+ event_id text NOT NULL,
15
+ event_name text NOT NULL,
16
+ event_type text NOT NULL,
17
+ occurred_at double precision NOT NULL,
18
+ received_at double precision NOT NULL,
19
+ organization_id text,
20
+ user_id text,
21
+ session_id text,
22
+ anonymous_id text,
23
+ payload_json ${payloadType} NOT NULL,
24
+ PRIMARY KEY (service_name, source, event_id)
25
+ )`;
26
+ yield* sql`CREATE INDEX events_organization_time ON events (service_name, organization_id, occurred_at)`;
27
+ yield* sql`CREATE INDEX events_visitor_time ON events (service_name, anonymous_id, received_at DESC, event_id DESC)`;
28
+ yield* sql`CREATE INDEX events_session_time ON events (service_name, session_id, occurred_at, event_id)`;
29
+ yield* sql.onDialectOrElse({
30
+ pg: () => sql`CREATE INDEX events_payload ON events USING gin (payload_json jsonb_path_ops)`,
31
+ orElse: () => Effect.void
32
+ });
33
+ })
34
+ });
35
+ var migrateEvents = Migrator.make({})({
36
+ loader: eventsMigrations,
37
+ table: "events_migrations"
38
+ });
39
+ export {
40
+ eventsMigrations,
41
+ migrateEvents
42
+ };
@@ -0,0 +1,6 @@
1
+ import type { EventAttributes } from "../opentelemetry/schema.js";
2
+ import { type EventGeolocation } from "./schema.js";
3
+ /** Enable only behind a verified Cloudflare ingress that prevents origin bypass. */
4
+ export declare const cloudflareGeolocation: (headers: Readonly<Record<string, string | undefined>>) => EventGeolocation;
5
+ export declare const geolocationAttributes: (location: EventGeolocation | null) => Record<string, string | number | boolean | readonly string[] | readonly number[] | readonly boolean[]>;
6
+ export declare const deviceContext: (userAgent: string) => EventAttributes;
@@ -0,0 +1,196 @@
1
+ import { Schema } from "effect";
2
+ export declare const EventUuid: Schema.String;
3
+ export declare const EventId: Schema.NonEmptyString;
4
+ export declare const BrowserEventPath: Schema.String;
5
+ export declare const EventIdentity: Schema.Struct<{
6
+ readonly userId: Schema.optional<Schema.NonEmptyString>;
7
+ readonly organizationId: Schema.optional<Schema.NonEmptyString>;
8
+ }>;
9
+ export type EventIdentity = typeof EventIdentity.Type;
10
+ export declare const EventIpAddress: Schema.String;
11
+ export declare const EventCountry: Schema.String;
12
+ export declare const EventRegion: Schema.String;
13
+ export declare const EventCity: Schema.NonEmptyString;
14
+ export declare const EventGeolocation: Schema.Struct<{
15
+ readonly ip: Schema.optional<Schema.String>;
16
+ readonly country: Schema.optional<Schema.String>;
17
+ readonly region: Schema.optional<Schema.String>;
18
+ readonly city: Schema.optional<Schema.NonEmptyString>;
19
+ }>;
20
+ export type EventGeolocation = typeof EventGeolocation.Type;
21
+ declare const EventGeolocationError_base: Schema.Class<EventGeolocationError, Schema.TaggedStruct<"EventGeolocationError", {}>, import("effect/Cause").YieldableError>;
22
+ export declare class EventGeolocationError extends EventGeolocationError_base {
23
+ }
24
+ export declare const BrowserEventOptions: Schema.Struct<{
25
+ readonly messageId: Schema.optional<Schema.NonEmptyString>;
26
+ readonly timestamp: Schema.optional<Schema.DateTimeUtc>;
27
+ readonly context: Schema.optional<Schema.$Record<Schema.String, Schema.Union<readonly [Schema.String, Schema.Finite, Schema.Boolean, Schema.$Array<Schema.String>, Schema.$Array<Schema.Finite>, Schema.$Array<Schema.Boolean>]>>>;
28
+ }>;
29
+ export declare const BrowserPage: Schema.Struct<{
30
+ readonly name: Schema.optional<Schema.NonEmptyString>;
31
+ readonly category: Schema.optional<Schema.NonEmptyString>;
32
+ readonly path: Schema.optional<Schema.NonEmptyString>;
33
+ readonly properties: Schema.optional<Schema.$Record<Schema.String, Schema.Union<readonly [Schema.String, Schema.Finite, Schema.Boolean, Schema.$Array<Schema.String>, Schema.$Array<Schema.Finite>, Schema.$Array<Schema.Boolean>]>>>;
34
+ readonly options: Schema.optional<Schema.Struct<{
35
+ readonly messageId: Schema.optional<Schema.NonEmptyString>;
36
+ readonly timestamp: Schema.optional<Schema.DateTimeUtc>;
37
+ readonly context: Schema.optional<Schema.$Record<Schema.String, Schema.Union<readonly [Schema.String, Schema.Finite, Schema.Boolean, Schema.$Array<Schema.String>, Schema.$Array<Schema.Finite>, Schema.$Array<Schema.Boolean>]>>>;
38
+ }>>;
39
+ }>;
40
+ export type BrowserEventOptions = typeof BrowserEventOptions.Type;
41
+ export type BrowserPageOptions = typeof BrowserPage.Type;
42
+ export declare const TrackEvent: Schema.Struct<{
43
+ readonly eventId: Schema.NonEmptyString;
44
+ readonly name: Schema.NonEmptyString;
45
+ readonly properties: Schema.optional<Schema.$Record<Schema.String, Schema.Union<readonly [Schema.String, Schema.Finite, Schema.Boolean, Schema.$Array<Schema.String>, Schema.$Array<Schema.Finite>, Schema.$Array<Schema.Boolean>]>>>;
46
+ readonly identity: Schema.optional<Schema.Struct<{
47
+ readonly userId: Schema.optional<Schema.NonEmptyString>;
48
+ readonly organizationId: Schema.optional<Schema.NonEmptyString>;
49
+ }>>;
50
+ readonly timestamp: Schema.optional<Schema.DateTimeUtc>;
51
+ readonly category: Schema.optional<Schema.Literals<readonly ["analytics", "audit"]>>;
52
+ }>;
53
+ export type TrackEvent = typeof TrackEvent.Type;
54
+ /** Minimal attribution contract; actor types and resolution belong to auth. */
55
+ export declare const AuditAttribution: Schema.Struct<{
56
+ readonly "app.actor.type": Schema.NonEmptyString;
57
+ readonly "app.actor.id": Schema.NonEmptyString;
58
+ }>;
59
+ /** Verified request attribution, never decoded from browser event attributes. */
60
+ export declare const RequestActorAttribution: Schema.Struct<{
61
+ readonly "app.actor.type": Schema.NonEmptyString;
62
+ readonly "app.actor.id": Schema.NonEmptyString;
63
+ readonly "app.actor.owner.type": Schema.optional<Schema.NonEmptyString>;
64
+ readonly "app.actor.owner.id": Schema.optional<Schema.NonEmptyString>;
65
+ }>;
66
+ declare const EventsPersistenceError_base: Schema.Class<EventsPersistenceError, Schema.TaggedStruct<"EventsPersistenceError", {
67
+ readonly operation: Schema.String;
68
+ }>, import("effect/Cause").YieldableError>;
69
+ export declare class EventsPersistenceError extends EventsPersistenceError_base {
70
+ }
71
+ declare const EventConflictError_base: Schema.Class<EventConflictError, Schema.TaggedStruct<"EventConflictError", {
72
+ readonly eventId: Schema.NonEmptyString;
73
+ }>, import("effect/Cause").YieldableError>;
74
+ export declare class EventConflictError extends EventConflictError_base {
75
+ }
76
+ export declare const EventSource: Schema.Literals<readonly ["browser", "server"]>;
77
+ export type EventSource = typeof EventSource.Type;
78
+ export declare const ExistingEventRequest: Schema.Struct<{
79
+ readonly eventId: Schema.NonEmptyString;
80
+ readonly source: Schema.Literals<readonly ["browser", "server"]>;
81
+ }>;
82
+ export declare const StoredEventRequest: Schema.Struct<{
83
+ readonly source: Schema.Literals<readonly ["browser", "server"]>;
84
+ readonly event_id: Schema.NonEmptyString;
85
+ readonly event_name: Schema.NonEmptyString;
86
+ readonly event_type: Schema.Literals<readonly ["page", "track"]>;
87
+ readonly occurred_at: Schema.Finite;
88
+ readonly received_at: Schema.Finite;
89
+ readonly organization_id: Schema.NullOr<Schema.NonEmptyString>;
90
+ readonly user_id: Schema.NullOr<Schema.NonEmptyString>;
91
+ readonly session_id: Schema.NullOr<Schema.NonEmptyString>;
92
+ readonly anonymous_id: Schema.NullOr<Schema.NonEmptyString>;
93
+ readonly payload_json: Schema.String;
94
+ }>;
95
+ export declare const StoredEventId: Schema.Struct<{
96
+ readonly event_id: Schema.NonEmptyString;
97
+ }>;
98
+ export declare const EventAttribute: Schema.Struct<{
99
+ readonly key: Schema.NonEmptyString;
100
+ readonly value: Schema.Union<readonly [Schema.Union<readonly [Schema.Struct<{
101
+ readonly stringValue: Schema.String;
102
+ }>, Schema.Struct<{
103
+ readonly intValue: Schema.Union<readonly [Schema.String, Schema.Int]>;
104
+ }>, Schema.Struct<{
105
+ readonly doubleValue: Schema.Finite;
106
+ }>, Schema.Struct<{
107
+ readonly boolValue: Schema.Boolean;
108
+ }>]>, Schema.Struct<{
109
+ readonly arrayValue: Schema.Struct<{
110
+ readonly values: Schema.$Array<Schema.Union<readonly [Schema.Struct<{
111
+ readonly stringValue: Schema.String;
112
+ }>, Schema.Struct<{
113
+ readonly intValue: Schema.Union<readonly [Schema.String, Schema.Int]>;
114
+ }>, Schema.Struct<{
115
+ readonly doubleValue: Schema.Finite;
116
+ }>, Schema.Struct<{
117
+ readonly boolValue: Schema.Boolean;
118
+ }>]>>;
119
+ }>;
120
+ }>]>;
121
+ }>;
122
+ export declare const EventLogRecord: Schema.Struct<{
123
+ readonly eventName: Schema.NonEmptyString;
124
+ readonly timeUnixNano: Schema.String;
125
+ readonly observedTimeUnixNano: Schema.optional<Schema.String>;
126
+ readonly severityNumber: Schema.optional<Schema.Int>;
127
+ readonly traceId: Schema.optional<Schema.String>;
128
+ readonly spanId: Schema.optional<Schema.String>;
129
+ readonly attributes: Schema.$Array<Schema.Struct<{
130
+ readonly key: Schema.NonEmptyString;
131
+ readonly value: Schema.Union<readonly [Schema.Union<readonly [Schema.Struct<{
132
+ readonly stringValue: Schema.String;
133
+ }>, Schema.Struct<{
134
+ readonly intValue: Schema.Union<readonly [Schema.String, Schema.Int]>;
135
+ }>, Schema.Struct<{
136
+ readonly doubleValue: Schema.Finite;
137
+ }>, Schema.Struct<{
138
+ readonly boolValue: Schema.Boolean;
139
+ }>]>, Schema.Struct<{
140
+ readonly arrayValue: Schema.Struct<{
141
+ readonly values: Schema.$Array<Schema.Union<readonly [Schema.Struct<{
142
+ readonly stringValue: Schema.String;
143
+ }>, Schema.Struct<{
144
+ readonly intValue: Schema.Union<readonly [Schema.String, Schema.Int]>;
145
+ }>, Schema.Struct<{
146
+ readonly doubleValue: Schema.Finite;
147
+ }>, Schema.Struct<{
148
+ readonly boolValue: Schema.Boolean;
149
+ }>]>>;
150
+ }>;
151
+ }>]>;
152
+ }>>;
153
+ }>;
154
+ export declare const OtlpLogs: Schema.StructWithRest<Schema.Struct<{
155
+ readonly resourceLogs: Schema.withDecodingDefaultKey<Schema.$Array<Schema.StructWithRest<Schema.Struct<{
156
+ readonly scopeLogs: Schema.withDecodingDefaultKey<Schema.$Array<Schema.StructWithRest<Schema.Struct<{
157
+ readonly scope: Schema.optional<Schema.StructWithRest<Schema.Struct<{
158
+ readonly name: Schema.optional<Schema.String>;
159
+ }>, readonly [Schema.$Record<Schema.String, Schema.Unknown>]>>;
160
+ readonly logRecords: Schema.withDecodingDefaultKey<Schema.$Array<Schema.Unknown>, never>;
161
+ }>, readonly [Schema.$Record<Schema.String, Schema.Unknown>]>>, never>;
162
+ }>, readonly [Schema.$Record<Schema.String, Schema.Unknown>]>>, never>;
163
+ }>, readonly [Schema.$Record<Schema.String, Schema.Unknown>]>;
164
+ export declare const StoredEventPayload: Schema.Struct<{
165
+ readonly payload_json: Schema.Union<readonly [Schema.StructWithRest<Schema.Struct<{
166
+ readonly resourceLogs: Schema.withDecodingDefaultKey<Schema.$Array<Schema.StructWithRest<Schema.Struct<{
167
+ readonly scopeLogs: Schema.withDecodingDefaultKey<Schema.$Array<Schema.StructWithRest<Schema.Struct<{
168
+ readonly scope: Schema.optional<Schema.StructWithRest<Schema.Struct<{
169
+ readonly name: Schema.optional<Schema.String>;
170
+ }>, readonly [Schema.$Record<Schema.String, Schema.Unknown>]>>;
171
+ readonly logRecords: Schema.withDecodingDefaultKey<Schema.$Array<Schema.Unknown>, never>;
172
+ }>, readonly [Schema.$Record<Schema.String, Schema.Unknown>]>>, never>;
173
+ }>, readonly [Schema.$Record<Schema.String, Schema.Unknown>]>>, never>;
174
+ }>, readonly [Schema.$Record<Schema.String, Schema.Unknown>]>, Schema.fromJsonString<Schema.StructWithRest<Schema.Struct<{
175
+ readonly resourceLogs: Schema.withDecodingDefaultKey<Schema.$Array<Schema.StructWithRest<Schema.Struct<{
176
+ readonly scopeLogs: Schema.withDecodingDefaultKey<Schema.$Array<Schema.StructWithRest<Schema.Struct<{
177
+ readonly scope: Schema.optional<Schema.StructWithRest<Schema.Struct<{
178
+ readonly name: Schema.optional<Schema.String>;
179
+ }>, readonly [Schema.$Record<Schema.String, Schema.Unknown>]>>;
180
+ readonly logRecords: Schema.withDecodingDefaultKey<Schema.$Array<Schema.Unknown>, never>;
181
+ }>, readonly [Schema.$Record<Schema.String, Schema.Unknown>]>>, never>;
182
+ }>, readonly [Schema.$Record<Schema.String, Schema.Unknown>]>>, never>;
183
+ }>, readonly [Schema.$Record<Schema.String, Schema.Unknown>]>>]>;
184
+ }>;
185
+ export declare const VisitorEventsRequest: Schema.Struct<{
186
+ readonly visitorId: Schema.NonEmptyString;
187
+ }>;
188
+ export declare const VisitorEventSession: Schema.Struct<{
189
+ readonly event_id: Schema.NonEmptyString;
190
+ readonly session_id: Schema.NullOr<Schema.NonEmptyString>;
191
+ readonly received_at: Schema.Finite;
192
+ }>;
193
+ export type EventLogRecord = typeof EventLogRecord.Type;
194
+ export type EventAttribute = typeof EventAttribute.Type;
195
+ export type OtlpLogs = typeof OtlpLogs.Type;
196
+ export {};
@@ -1,5 +1,7 @@
1
1
  import { Config, Layer } from "effect";
2
2
  import { HttpRouter } from "effect/http";
3
+ import { Otlp } from "./index.js";
4
+ export { OtlpLogsProcessor, OtlpProcessingError } from "./processor.js";
3
5
  export declare class HttpApiOtlp {
4
- static readonly layer: Layer.Layer<import("effect/FileSystem").FileSystem | import("effect/observability/OtlpExporter").Flusher | import("effect/http/Etag").Generator | import("effect/http/HttpPlatform").HttpPlatform | import("./events.js").OtlpEvents | import("effect/Path").Path, Config.ConfigError, HttpRouter.HttpRouter>;
6
+ static readonly layer: Layer.Layer<import("effect/FileSystem").FileSystem | import("effect/http/Etag").Generator | import("effect/http/HttpPlatform").HttpPlatform | import("effect/Path").Path, Config.ConfigError, HttpRouter.HttpRouter | Otlp>;
5
7
  }
@@ -1,5 +1,5 @@
1
1
  // ../../src/services/opentelemetry/api.ts
2
- import { Config as Config2, Effect as Effect3, Layer as Layer3, Schema as Schema4 } from "effect";
2
+ import { Config as Config2, Effect as Effect4, Layer as Layer3, Option as Option2, Schema as Schema5, Stream } from "effect";
3
3
  import {
4
4
  FetchHttpClient as FetchHttpClient2,
5
5
  HttpClient,
@@ -11,10 +11,15 @@ import {
11
11
  HttpServerResponse
12
12
  } from "effect/http";
13
13
 
14
- // ../../src/services/opentelemetry/server.ts
15
- import { Config, Effect as Effect2, Layer as Layer2, Schema as Schema3 } from "effect";
14
+ // ../../src/services/opentelemetry/index.ts
15
+ import { Config, Context as Context2, Effect as Effect2, Layer as Layer2, Schema as Schema3 } from "effect";
16
16
  import { FetchHttpClient } from "effect/http";
17
- import { Otlp, OtlpExporter as OtlpExporter2, OtlpSerialization as OtlpSerialization2 } from "effect/observability";
17
+ import {
18
+ Otlp as EffectOtlp,
19
+ OtlpExporter as OtlpExporter2,
20
+ OtlpResource as OtlpResource2,
21
+ OtlpSerialization as OtlpSerialization2
22
+ } from "effect/observability";
18
23
 
19
24
  // ../../src/services/opentelemetry/events.ts
20
25
  import {
@@ -35,6 +40,21 @@ import {
35
40
 
36
41
  // ../../src/services/opentelemetry/schema.ts
37
42
  import { Schema } from "effect";
43
+ var BrowserWebVital = Schema.Struct({
44
+ name: Schema.Literals(["LCP", "INP", "CLS", "FCP", "TTFB"]),
45
+ id: Schema.NonEmptyString.check(Schema.isMaxLength(64)),
46
+ value: Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0)),
47
+ delta: Schema.Finite,
48
+ rating: Schema.Literals(["good", "needs-improvement", "poor"]),
49
+ navigationType: Schema.Literals([
50
+ "navigate",
51
+ "reload",
52
+ "back-forward",
53
+ "back-forward-cache",
54
+ "prerender",
55
+ "restore"
56
+ ])
57
+ }).annotate({ identifier: "BrowserWebVital" });
38
58
  var EventAttributeValue = Schema.Union([
39
59
  Schema.String,
40
60
  Schema.Finite,
@@ -57,17 +77,6 @@ var TelemetryEvent = Schema.Struct({
57
77
  properties: Schema.optional(EventAttributesSchema),
58
78
  options: Schema.optional(EventOptionsSchema)
59
79
  }).annotate({ identifier: "TelemetryEvent" });
60
- var PageEvent = Schema.Struct({
61
- name: Schema.optional(Schema.NonEmptyString),
62
- category: Schema.optional(Schema.NonEmptyString),
63
- path: Schema.optional(Schema.NonEmptyString),
64
- properties: Schema.optional(EventAttributesSchema),
65
- options: Schema.optional(EventOptionsSchema)
66
- }).annotate({ identifier: "PageEvent" });
67
- var BrowserIdentity = Schema.Struct({
68
- userId: Schema.optional(Schema.NonEmptyString),
69
- organizationId: Schema.optional(Schema.NonEmptyString)
70
- }).annotate({ identifier: "BrowserTelemetryIdentity" });
71
80
 
72
81
  // ../../src/services/opentelemetry/events.ts
73
82
  class OtlpEvents extends Context.Service()("krakstack/opentelemetry/Events") {
@@ -78,27 +87,36 @@ class OtlpEvents extends Context.Service()("krakstack/opentelemetry/Events") {
78
87
  return yield* OtlpExporter.make({
79
88
  ...options,
80
89
  label: "OtlpEvents",
81
- body: (logRecords) => [
82
- serialization.logs({
83
- resourceLogs: [
84
- {
85
- resource,
86
- scopeLogs: [
87
- {
88
- scope: { name: "krakstack.events" },
89
- logRecords
90
- }
91
- ]
92
- }
93
- ]
94
- }),
95
- Effect.void
96
- ]
90
+ body: (logRecords) => {
91
+ const scopes = new Map;
92
+ for (const { scopeName, ...record } of logRecords) {
93
+ const name = scopeName ?? options.scopeName ?? "krakstack.events";
94
+ const records = scopes.get(name);
95
+ if (records)
96
+ records.push(record);
97
+ else
98
+ scopes.set(name, [record]);
99
+ }
100
+ return [
101
+ serialization.logs({
102
+ resourceLogs: [
103
+ {
104
+ resource,
105
+ scopeLogs: Array.from(scopes, ([name, records]) => ({
106
+ scope: { name },
107
+ logRecords: records
108
+ }))
109
+ }
110
+ ]
111
+ }),
112
+ Effect.void
113
+ ];
114
+ }
97
115
  });
98
116
  }));
99
117
  }
100
- var track = Effect.fnUntraced(function* (name, properties, options) {
101
- const event = yield* Schema2.decodeUnknownEffect(TelemetryEvent)({
118
+ var event = Effect.fnUntraced(function* (name, properties, options) {
119
+ const decoded = yield* Schema2.decodeUnknownEffect(TelemetryEvent)({
102
120
  name,
103
121
  properties,
104
122
  options
@@ -106,20 +124,20 @@ var track = Effect.fnUntraced(function* (name, properties, options) {
106
124
  const events = yield* OtlpEvents;
107
125
  const clock = yield* Clock.Clock;
108
126
  const observedTime = clock.currentTimeNanosUnsafe().toString();
109
- const timestamp = event.options?.timestamp ? (BigInt(DateTime.toEpochMillis(event.options.timestamp)) * 1000000n).toString() : observedTime;
127
+ const timestamp = decoded.options?.timestamp ? (BigInt(DateTime.toEpochMillis(decoded.options.timestamp)) * 1000000n).toString() : observedTime;
110
128
  const span = yield* Effect.currentSpan.pipe(Effect.option);
111
- const attributes = { ...event.options?.context, ...event.properties };
112
- if (event.options?.userId)
113
- attributes["user.id"] = event.options.userId;
114
- if (event.options?.anonymousId)
115
- attributes["analytics.anonymous_id"] = event.options.anonymousId;
116
- if (event.options?.sessionId)
117
- attributes["session.id"] = event.options.sessionId;
118
- if (event.options?.messageId)
119
- attributes["log.record.uid"] = event.options.messageId;
129
+ const attributes = { ...decoded.options?.context, ...decoded.properties };
130
+ if (decoded.options?.userId)
131
+ attributes["user.id"] = decoded.options.userId;
132
+ if (decoded.options?.anonymousId)
133
+ attributes["analytics.anonymous_id"] = decoded.options.anonymousId;
134
+ if (decoded.options?.sessionId)
135
+ attributes["session.id"] = decoded.options.sessionId;
136
+ if (decoded.options?.messageId)
137
+ attributes["log.record.uid"] = decoded.options.messageId;
120
138
  const annotations = yield* References.CurrentLogAnnotations;
121
139
  events.push({
122
- eventName: event.name,
140
+ eventName: decoded.name,
123
141
  timeUnixNano: timestamp,
124
142
  observedTimeUnixNano: observedTime,
125
143
  severityNumber: 9,
@@ -133,7 +151,7 @@ var track = Effect.fnUntraced(function* (name, properties, options) {
133
151
  });
134
152
  });
135
153
 
136
- // ../../src/services/opentelemetry/server.ts
154
+ // ../../src/services/opentelemetry/index.ts
137
155
  var ServerEventsLive = Layer2.unwrap(Effect2.gen(function* () {
138
156
  const disabled = yield* Config.Boolean("OTEL_SDK_DISABLED").pipe(Config.withDefault(false));
139
157
  const exporters = yield* Config.Array(Schema3.String, "OTEL_LOGS_EXPORTER").pipe(Config.withDefault([]));
@@ -158,9 +176,18 @@ var ServerEventsLive = Layer2.unwrap(Effect2.gen(function* () {
158
176
  });
159
177
  }).pipe(Effect2.orDie));
160
178
 
161
- class ServerOtlp {
162
- static track = track;
163
- static layer = Layer2.mergeAll(Otlp.layerFromConfig(), ServerEventsLive).pipe(Layer2.provideMerge(OtlpExporter2.layerFlusher), Layer2.provide(OtlpSerialization2.layerJson), Layer2.provide(FetchHttpClient.layer));
179
+ class Otlp extends Context2.Service()("krakstack/opentelemetry/Otlp") {
180
+ static event = event;
181
+ static layer = Layer2.mergeAll(Layer2.succeed(this, { resource: OtlpResource2.fromConfig() }), EffectOtlp.layerFromConfig(), ServerEventsLive).pipe(Layer2.provideMerge(OtlpExporter2.layerFlusher), Layer2.provide(OtlpSerialization2.layerJson), Layer2.provide(FetchHttpClient.layer));
182
+ }
183
+
184
+ // ../../src/services/opentelemetry/processor.ts
185
+ import { Context as Context3, Schema as Schema4 } from "effect";
186
+
187
+ class OtlpProcessingError extends Schema4.TaggedError()("OtlpProcessingError", { status: Schema4.Literals([400, 403, 409, 413, 503]) }) {
188
+ }
189
+
190
+ class OtlpLogsProcessor extends Context3.Service()("krakstack/opentelemetry/OtlpLogsProcessor") {
164
191
  }
165
192
 
166
193
  // ../../src/services/opentelemetry/api.ts
@@ -169,37 +196,79 @@ var otlpProxyPaths = [
169
196
  "/api/otel/v1/metrics",
170
197
  "/api/otel/v1/logs"
171
198
  ];
172
- var exporterConfig = (signal) => Config2.Array(Schema4.String, `OTEL_${signal}_EXPORTER`).pipe(Config2.map((exporters) => exporters.map((exporter) => exporter.toLowerCase().trim())), Config2.withDefault([]));
173
- var proxyOtlp = (baseUrl, signal) => Effect3.gen(function* () {
199
+ var exporterConfig = (signal) => Config2.Array(Schema5.String, `OTEL_${signal}_EXPORTER`).pipe(Config2.map((exporters) => exporters.map((exporter) => exporter.toLowerCase().trim())), Config2.withDefault([]));
200
+ var readProcessorBody = Effect4.fnUntraced(function* () {
201
+ const incoming = yield* HttpServerRequest.HttpServerRequest;
202
+ const collected = yield* incoming.stream.pipe(Stream.mapError(() => new OtlpProcessingError({ status: 400 })), Stream.runFoldEffect(() => ({
203
+ chunks: [],
204
+ size: 0
205
+ }), (state, chunk) => {
206
+ const size = state.size + chunk.byteLength;
207
+ if (size > 64 * 1024)
208
+ return Effect4.fail(new OtlpProcessingError({ status: 413 }));
209
+ state.chunks.push(chunk);
210
+ state.size = size;
211
+ return Effect4.succeed(state);
212
+ }));
213
+ const bytes = new Uint8Array(collected.size);
214
+ let offset = 0;
215
+ for (const chunk of collected.chunks) {
216
+ bytes.set(chunk, offset);
217
+ offset += chunk.byteLength;
218
+ }
219
+ return bytes;
220
+ });
221
+ var proxyOtlp = (baseUrl, signal, processor) => Effect4.gen(function* () {
174
222
  const incoming = yield* HttpServerRequest.HttpServerRequest;
175
223
  const client = yield* HttpClient.HttpClient;
176
224
  const contentType = incoming.headers["content-type"] ?? "application/json";
177
- const body = new Uint8Array(yield* incoming.arrayBuffer);
178
- const request = HttpClientRequest.get(baseUrl).pipe(HttpClientRequest.appendUrl(`/v1/${signal}`), HttpClientRequest.setMethod("POST"), HttpClientRequest.bodyUint8Array(body, contentType));
179
- const upstream = yield* client.execute(request);
180
- const responseBody = new Uint8Array(yield* upstream.arrayBuffer);
181
- return HttpServerResponse.uint8Array(responseBody, {
182
- status: upstream.status,
183
- contentType: upstream.headers["content-type"],
184
- headers: {
185
- "retry-after": upstream.headers["retry-after"]
225
+ const processLogs = signal === "logs" && Option2.isSome(processor);
226
+ if (processLogs && contentType.split(";", 1)[0]?.trim().toLowerCase() !== "application/json") {
227
+ return HttpServerResponse.empty({ status: 415 });
228
+ }
229
+ const bytes = processLogs ? yield* readProcessorBody() : new Uint8Array(yield* incoming.arrayBuffer);
230
+ const processed = processLogs ? yield* processor.value.process(bytes) : { body: bytes, persisted: false };
231
+ const request = HttpClientRequest.get(baseUrl).pipe(HttpClientRequest.appendUrl(`/v1/${signal}`), HttpClientRequest.setMethod("POST"), HttpClientRequest.bodyUint8Array(processed.body, contentType));
232
+ const forward = Effect4.gen(function* () {
233
+ const upstream = yield* client.execute(request);
234
+ const responseBody = new Uint8Array(yield* upstream.arrayBuffer);
235
+ if (processed.persisted) {
236
+ if (upstream.status < 200 || upstream.status >= 300)
237
+ yield* Effect4.logWarning("Collector rejected persisted analytics", {
238
+ status: upstream.status
239
+ });
240
+ return HttpServerResponse.jsonUnsafe({});
186
241
  }
242
+ return HttpServerResponse.uint8Array(responseBody, {
243
+ status: upstream.status,
244
+ contentType: upstream.headers["content-type"],
245
+ headers: {
246
+ "retry-after": upstream.headers["retry-after"]
247
+ }
248
+ });
187
249
  });
188
- }).pipe(Effect3.withTracerEnabled(false), HttpMiddleware.withLoggerDisabled, Effect3.catch((error) => Effect3.logError("Failed to proxy browser telemetry", error).pipe(Effect3.as(HttpServerResponse.empty({ status: 502 })))), Effect3.provide(FetchHttpClient2.layer));
189
- var otlpProxyLayer = Layer3.unwrap(Effect3.gen(function* () {
250
+ if (!processed.persisted)
251
+ return yield* forward;
252
+ return yield* forward.pipe(Effect4.timeout("5 seconds"), Effect4.catch((error) => Effect4.logWarning("Collector delivery failed after analytics commit", error).pipe(Effect4.as(HttpServerResponse.jsonUnsafe({})))));
253
+ }).pipe(Effect4.withTracerEnabled(false), HttpMiddleware.withLoggerDisabled, Effect4.catchTag("OtlpProcessingError", (error) => Effect4.succeed(HttpServerResponse.empty({ status: error.status }))), Effect4.catch((error) => Effect4.logError("Failed to proxy browser telemetry", error).pipe(Effect4.as(HttpServerResponse.empty({ status: 502 })))), Effect4.provide(FetchHttpClient2.layer));
254
+ var otlpProxyLayer = Layer3.unwrap(Effect4.gen(function* () {
255
+ yield* Otlp;
190
256
  const baseUrl = yield* Config2.URL("OTEL_EXPORTER_OTLP_ENDPOINT");
257
+ const processor = yield* Effect4.serviceOption(OtlpLogsProcessor);
191
258
  const exporters = yield* Config2.all({
192
259
  logs: exporterConfig("LOGS"),
193
260
  metrics: exporterConfig("METRICS"),
194
261
  traces: exporterConfig("TRACES")
195
262
  });
196
- return Layer3.mergeAll(exporters.traces.includes("otlp") ? HttpRouter.add("POST", otlpProxyPaths[0], proxyOtlp(baseUrl, "traces")) : Layer3.empty, exporters.metrics.includes("otlp") ? HttpRouter.add("POST", otlpProxyPaths[1], proxyOtlp(baseUrl, "metrics")) : Layer3.empty, exporters.logs.includes("otlp") ? HttpRouter.add("POST", otlpProxyPaths[2], proxyOtlp(baseUrl, "logs")) : Layer3.empty);
263
+ return Layer3.mergeAll(exporters.traces.includes("otlp") ? HttpRouter.add("POST", otlpProxyPaths[0], proxyOtlp(baseUrl, "traces", processor)) : Layer3.empty, exporters.metrics.includes("otlp") ? HttpRouter.add("POST", otlpProxyPaths[1], proxyOtlp(baseUrl, "metrics", processor)) : Layer3.empty, exporters.logs.includes("otlp") ? HttpRouter.add("POST", otlpProxyPaths[2], proxyOtlp(baseUrl, "logs", processor)) : Layer3.empty);
197
264
  }));
198
265
  var serverServices = HttpServer.layerServices.pipe(Layer3.provideMerge(HttpMiddleware.layerTracerDisabledForUrls(otlpProxyPaths)));
199
266
 
200
267
  class HttpApiOtlp {
201
- static layer = Layer3.mergeAll(ServerOtlp.layer, otlpProxyLayer, serverServices);
268
+ static layer = Layer3.mergeAll(otlpProxyLayer, serverServices);
202
269
  }
203
270
  export {
204
- HttpApiOtlp
271
+ HttpApiOtlp,
272
+ OtlpLogsProcessor,
273
+ OtlpProcessingError
205
274
  };
@@ -1,15 +1,7 @@
1
- import { Context, Effect, Layer, Ref, Schema } from "effect";
1
+ import { Effect, Layer, Schema } from "effect";
2
2
  import { type Otlp, OtlpExporter, OtlpLogger, OtlpMetrics, OtlpTracer } from "effect/observability";
3
3
  import { OtlpEvents, type EventExportOptions } from "./events.js";
4
- import { BrowserIdentity, type EventAttributes, type EventOptions, type PageOptions } from "./schema.js";
5
- export type { BrowserIdentity, EventAttributes, EventOptions, PageOptions, } from "./schema.js";
6
- declare const BrowserIdentityState_base: Context.ServiceClass<BrowserIdentityState, "krakstack/opentelemetry/BrowserIdentity", Ref.Ref<{
7
- readonly userId?: string | undefined;
8
- readonly organizationId?: string | undefined;
9
- }>>;
10
- declare class BrowserIdentityState extends BrowserIdentityState_base {
11
- static readonly layer: Layer.Layer<BrowserIdentityState, never, never>;
12
- }
4
+ export type { EventAttributes, EventOptions } from "./schema.js";
13
5
  type OtlpOptions = Parameters<typeof Otlp.layerJson>[0];
14
6
  type SignalOptions<Options> = Omit<Options, "url" | "resource" | "headers">;
15
7
  export interface BrowserOtlpOptions {
@@ -21,16 +13,21 @@ export interface BrowserOtlpOptions {
21
13
  readonly traces?: false | SignalOptions<Parameters<typeof OtlpTracer.layer>[0]>;
22
14
  readonly metrics?: false | SignalOptions<Parameters<typeof OtlpMetrics.layer>[0]>;
23
15
  readonly logs?: false | SignalOptions<Parameters<typeof OtlpLogger.layer>[0]>;
24
- readonly events?: false | (EventExportOptions & {
25
- /** Initial page and pathname changes; enabled by default. */
26
- readonly pageViews?: boolean;
27
- });
16
+ /** Named OTLP log events; no automatic page tracking or analytics enrichment. */
17
+ readonly events?: false | EventExportOptions;
28
18
  }
29
19
  export declare class BrowserOtlp {
30
- /** Uses the active browser layer; invalid identity warns without failing or changing state. */
31
- static readonly identify: (identity: BrowserIdentity | null) => Effect.Effect<void, never, never>;
32
- static readonly track: (name: string, properties?: EventAttributes, options?: EventOptions) => Effect.Effect<void, Schema.SchemaError, never>;
33
- static readonly page: (options?: PageOptions) => Effect.Effect<void, Schema.SchemaError, never>;
34
- static readonly pageView: (options?: PageOptions) => Effect.Effect<void, Schema.SchemaError, never>;
35
- static readonly layer: ({ attributes, baseUrl, logs, events, metrics, serviceName, serviceVersion, traces, headers, }: BrowserOtlpOptions) => Layer.Layer<BrowserIdentityState | OtlpExporter.Flusher | OtlpEvents, never, never>;
20
+ static readonly event: (name: string, properties?: {
21
+ readonly [x: string]: string | number | boolean | readonly string[] | readonly number[] | readonly boolean[];
22
+ } | undefined, options?: {
23
+ readonly userId?: string | undefined;
24
+ readonly anonymousId?: string | undefined;
25
+ readonly sessionId?: string | undefined;
26
+ readonly messageId?: string | undefined;
27
+ readonly timestamp?: import("effect/DateTime").Utc | undefined;
28
+ readonly context?: {
29
+ readonly [x: string]: string | number | boolean | readonly string[] | readonly number[] | readonly boolean[];
30
+ } | undefined;
31
+ } | undefined) => Effect.Effect<void, Schema.SchemaError, OtlpEvents>;
32
+ static readonly layer: ({ attributes, baseUrl, logs, events, metrics, serviceName, serviceVersion, traces, headers, }: BrowserOtlpOptions) => Layer.Layer<OtlpExporter.Flusher | OtlpEvents, never, never>;
36
33
  }