@krak-stack/registry 0.1.50 → 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.
- package/CHANGELOG.md +16 -0
- package/README.md +16 -424
- package/dist/lib/docs.js +2 -2
- package/dist/services/agent/client/index.js +1 -1
- package/dist/services/events/browser.d.ts +26 -0
- package/dist/services/events/browser.js +423 -0
- package/dist/services/events/index.d.ts +82 -0
- package/dist/services/events/index.js +798 -0
- package/dist/services/events/migrations.d.ts +4 -0
- package/dist/services/events/migrations.js +42 -0
- package/dist/services/events/request-context.d.ts +6 -0
- package/dist/services/events/schema.d.ts +196 -0
- package/dist/services/opentelemetry/api.d.ts +3 -1
- package/dist/services/opentelemetry/api.js +133 -64
- package/dist/services/opentelemetry/browser.d.ts +17 -20
- package/dist/services/opentelemetry/browser.js +58 -162
- package/dist/services/opentelemetry/events.d.ts +3 -1
- package/dist/services/opentelemetry/{server.d.ts → index.d.ts} +8 -5
- package/dist/services/opentelemetry/{server.js → index.js} +66 -48
- package/dist/services/opentelemetry/processor.d.ts +19 -0
- package/dist/services/opentelemetry/schema.d.ts +8 -20
- package/dist/services/opentelemetry/web-vitals.d.ts +15 -0
- package/dist/services/opentelemetry/web-vitals.js +229 -0
- package/package.json +23 -5
|
@@ -0,0 +1,798 @@
|
|
|
1
|
+
// ../../src/services/events/index.ts
|
|
2
|
+
import { createHmac, randomUUID } from "node:crypto";
|
|
3
|
+
import {
|
|
4
|
+
Context as Context4,
|
|
5
|
+
DateTime as DateTime2,
|
|
6
|
+
Effect as Effect6,
|
|
7
|
+
Layer as Layer3,
|
|
8
|
+
Option as Option4,
|
|
9
|
+
Predicate,
|
|
10
|
+
Redacted,
|
|
11
|
+
References as References2,
|
|
12
|
+
Schema as Schema7
|
|
13
|
+
} from "effect";
|
|
14
|
+
import { HttpServerRequest } from "effect/http";
|
|
15
|
+
import { SqlClient as SqlClient2, SqlSchema } from "effect/sql";
|
|
16
|
+
|
|
17
|
+
// ../../src/services/opentelemetry/processor.ts
|
|
18
|
+
import { Context, Schema } from "effect";
|
|
19
|
+
|
|
20
|
+
class OtlpProcessingError extends Schema.TaggedError()("OtlpProcessingError", { status: Schema.Literals([400, 403, 409, 413, 503]) }) {
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
class OtlpLogsProcessor extends Context.Service()("krakstack/opentelemetry/OtlpLogsProcessor") {
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// ../../src/services/events/index.ts
|
|
27
|
+
import { OtlpResource as OtlpResource3 } from "effect/observability";
|
|
28
|
+
|
|
29
|
+
// ../../src/services/opentelemetry/index.ts
|
|
30
|
+
import { Config, Context as Context3, Effect as Effect3, Layer as Layer2, Schema as Schema4 } from "effect";
|
|
31
|
+
import { FetchHttpClient } from "effect/http";
|
|
32
|
+
import {
|
|
33
|
+
Otlp as EffectOtlp,
|
|
34
|
+
OtlpExporter as OtlpExporter2,
|
|
35
|
+
OtlpResource as OtlpResource2,
|
|
36
|
+
OtlpSerialization as OtlpSerialization2
|
|
37
|
+
} from "effect/observability";
|
|
38
|
+
|
|
39
|
+
// ../../src/services/opentelemetry/events.ts
|
|
40
|
+
import {
|
|
41
|
+
Clock,
|
|
42
|
+
Context as Context2,
|
|
43
|
+
DateTime,
|
|
44
|
+
Effect as Effect2,
|
|
45
|
+
Layer,
|
|
46
|
+
Option,
|
|
47
|
+
References,
|
|
48
|
+
Schema as Schema3
|
|
49
|
+
} from "effect";
|
|
50
|
+
import {
|
|
51
|
+
OtlpExporter,
|
|
52
|
+
OtlpResource,
|
|
53
|
+
OtlpSerialization
|
|
54
|
+
} from "effect/observability";
|
|
55
|
+
|
|
56
|
+
// ../../src/services/opentelemetry/schema.ts
|
|
57
|
+
import { Schema as Schema2 } from "effect";
|
|
58
|
+
var BrowserWebVital = Schema2.Struct({
|
|
59
|
+
name: Schema2.Literals(["LCP", "INP", "CLS", "FCP", "TTFB"]),
|
|
60
|
+
id: Schema2.NonEmptyString.check(Schema2.isMaxLength(64)),
|
|
61
|
+
value: Schema2.Finite.check(Schema2.isGreaterThanOrEqualTo(0)),
|
|
62
|
+
delta: Schema2.Finite,
|
|
63
|
+
rating: Schema2.Literals(["good", "needs-improvement", "poor"]),
|
|
64
|
+
navigationType: Schema2.Literals([
|
|
65
|
+
"navigate",
|
|
66
|
+
"reload",
|
|
67
|
+
"back-forward",
|
|
68
|
+
"back-forward-cache",
|
|
69
|
+
"prerender",
|
|
70
|
+
"restore"
|
|
71
|
+
])
|
|
72
|
+
}).annotate({ identifier: "BrowserWebVital" });
|
|
73
|
+
var EventAttributeValue = Schema2.Union([
|
|
74
|
+
Schema2.String,
|
|
75
|
+
Schema2.Finite,
|
|
76
|
+
Schema2.Boolean,
|
|
77
|
+
Schema2.Array(Schema2.String),
|
|
78
|
+
Schema2.Array(Schema2.Finite),
|
|
79
|
+
Schema2.Array(Schema2.Boolean)
|
|
80
|
+
]);
|
|
81
|
+
var EventAttributesSchema = Schema2.Record(Schema2.String, EventAttributeValue).annotate({ identifier: "EventAttributes" });
|
|
82
|
+
var EventOptionsSchema = Schema2.Struct({
|
|
83
|
+
userId: Schema2.optional(Schema2.NonEmptyString),
|
|
84
|
+
anonymousId: Schema2.optional(Schema2.NonEmptyString),
|
|
85
|
+
sessionId: Schema2.optional(Schema2.NonEmptyString),
|
|
86
|
+
messageId: Schema2.optional(Schema2.NonEmptyString),
|
|
87
|
+
timestamp: Schema2.optional(Schema2.DateTimeUtc),
|
|
88
|
+
context: Schema2.optional(EventAttributesSchema)
|
|
89
|
+
}).annotate({ identifier: "EventOptions" });
|
|
90
|
+
var TelemetryEvent = Schema2.Struct({
|
|
91
|
+
name: Schema2.NonEmptyString,
|
|
92
|
+
properties: Schema2.optional(EventAttributesSchema),
|
|
93
|
+
options: Schema2.optional(EventOptionsSchema)
|
|
94
|
+
}).annotate({ identifier: "TelemetryEvent" });
|
|
95
|
+
|
|
96
|
+
// ../../src/services/opentelemetry/events.ts
|
|
97
|
+
class OtlpEvents extends Context2.Service()("krakstack/opentelemetry/Events") {
|
|
98
|
+
static disabledLayer = Layer.succeed(this, { push: () => {} });
|
|
99
|
+
static layer = (options) => Layer.effect(this, Effect2.gen(function* () {
|
|
100
|
+
const serialization = yield* OtlpSerialization.OtlpSerialization;
|
|
101
|
+
const resource = yield* OtlpResource.fromConfig(options.resource);
|
|
102
|
+
return yield* OtlpExporter.make({
|
|
103
|
+
...options,
|
|
104
|
+
label: "OtlpEvents",
|
|
105
|
+
body: (logRecords) => {
|
|
106
|
+
const scopes = new Map;
|
|
107
|
+
for (const { scopeName, ...record } of logRecords) {
|
|
108
|
+
const name = scopeName ?? options.scopeName ?? "krakstack.events";
|
|
109
|
+
const records = scopes.get(name);
|
|
110
|
+
if (records)
|
|
111
|
+
records.push(record);
|
|
112
|
+
else
|
|
113
|
+
scopes.set(name, [record]);
|
|
114
|
+
}
|
|
115
|
+
return [
|
|
116
|
+
serialization.logs({
|
|
117
|
+
resourceLogs: [
|
|
118
|
+
{
|
|
119
|
+
resource,
|
|
120
|
+
scopeLogs: Array.from(scopes, ([name, records]) => ({
|
|
121
|
+
scope: { name },
|
|
122
|
+
logRecords: records
|
|
123
|
+
}))
|
|
124
|
+
}
|
|
125
|
+
]
|
|
126
|
+
}),
|
|
127
|
+
Effect2.void
|
|
128
|
+
];
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
}));
|
|
132
|
+
}
|
|
133
|
+
var event = Effect2.fnUntraced(function* (name, properties, options) {
|
|
134
|
+
const decoded = yield* Schema3.decodeUnknownEffect(TelemetryEvent)({
|
|
135
|
+
name,
|
|
136
|
+
properties,
|
|
137
|
+
options
|
|
138
|
+
});
|
|
139
|
+
const events = yield* OtlpEvents;
|
|
140
|
+
const clock = yield* Clock.Clock;
|
|
141
|
+
const observedTime = clock.currentTimeNanosUnsafe().toString();
|
|
142
|
+
const timestamp = decoded.options?.timestamp ? (BigInt(DateTime.toEpochMillis(decoded.options.timestamp)) * 1000000n).toString() : observedTime;
|
|
143
|
+
const span = yield* Effect2.currentSpan.pipe(Effect2.option);
|
|
144
|
+
const attributes = { ...decoded.options?.context, ...decoded.properties };
|
|
145
|
+
if (decoded.options?.userId)
|
|
146
|
+
attributes["user.id"] = decoded.options.userId;
|
|
147
|
+
if (decoded.options?.anonymousId)
|
|
148
|
+
attributes["analytics.anonymous_id"] = decoded.options.anonymousId;
|
|
149
|
+
if (decoded.options?.sessionId)
|
|
150
|
+
attributes["session.id"] = decoded.options.sessionId;
|
|
151
|
+
if (decoded.options?.messageId)
|
|
152
|
+
attributes["log.record.uid"] = decoded.options.messageId;
|
|
153
|
+
const annotations = yield* References.CurrentLogAnnotations;
|
|
154
|
+
events.push({
|
|
155
|
+
eventName: decoded.name,
|
|
156
|
+
timeUnixNano: timestamp,
|
|
157
|
+
observedTimeUnixNano: observedTime,
|
|
158
|
+
severityNumber: 9,
|
|
159
|
+
attributes: OtlpResource.entriesToAttributes(Object.entries({
|
|
160
|
+
...attributes,
|
|
161
|
+
...annotations
|
|
162
|
+
})),
|
|
163
|
+
droppedAttributesCount: 0,
|
|
164
|
+
traceId: Option.isSome(span) ? span.value.traceId : undefined,
|
|
165
|
+
spanId: Option.isSome(span) ? span.value.spanId : undefined
|
|
166
|
+
});
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
// ../../src/services/opentelemetry/index.ts
|
|
170
|
+
var ServerEventsLive = Layer2.unwrap(Effect3.gen(function* () {
|
|
171
|
+
const disabled = yield* Config.Boolean("OTEL_SDK_DISABLED").pipe(Config.withDefault(false));
|
|
172
|
+
const exporters = yield* Config.Array(Schema4.String, "OTEL_LOGS_EXPORTER").pipe(Config.withDefault([]));
|
|
173
|
+
if (disabled || !exporters.some((value) => value.trim().toLowerCase() === "otlp")) {
|
|
174
|
+
return OtlpEvents.disabledLayer;
|
|
175
|
+
}
|
|
176
|
+
const endpoint = yield* Config.URL("OTEL_EXPORTER_OTLP_LOGS_ENDPOINT").pipe(Config.orElse(() => Config.URL("OTEL_EXPORTER_OTLP_ENDPOINT").pipe(Config.map((url) => {
|
|
177
|
+
url.pathname += `${url.pathname.endsWith("/") ? "" : "/"}v1/logs`;
|
|
178
|
+
return url;
|
|
179
|
+
}))), Config.withDefault(undefined));
|
|
180
|
+
if (!endpoint) {
|
|
181
|
+
return OtlpEvents.disabledLayer;
|
|
182
|
+
}
|
|
183
|
+
const headersConfig = (name) => Config.Record(Schema4.String, Schema4.StringFromUriComponent, name);
|
|
184
|
+
const headers = yield* headersConfig("OTEL_EXPORTER_OTLP_LOGS_HEADERS").pipe(Config.orElse(() => headersConfig("OTEL_EXPORTER_OTLP_HEADERS")), Config.withDefault(undefined));
|
|
185
|
+
return OtlpEvents.layer({
|
|
186
|
+
url: endpoint.toString(),
|
|
187
|
+
headers,
|
|
188
|
+
exportInterval: "1 second",
|
|
189
|
+
maxBatchSize: 1000,
|
|
190
|
+
shutdownTimeout: "3 seconds"
|
|
191
|
+
});
|
|
192
|
+
}).pipe(Effect3.orDie));
|
|
193
|
+
|
|
194
|
+
class Otlp extends Context3.Service()("krakstack/opentelemetry/Otlp") {
|
|
195
|
+
static event = event;
|
|
196
|
+
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));
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// ../../src/services/events/request-context.ts
|
|
200
|
+
import Bowser from "bowser";
|
|
201
|
+
import { Option as Option3, Schema as Schema6 } from "effect";
|
|
202
|
+
|
|
203
|
+
// ../../src/services/events/schema.ts
|
|
204
|
+
import { Effect as Effect4, Option as Option2, Schema as Schema5 } from "effect";
|
|
205
|
+
var EventUuid = Schema5.String.check(Schema5.isUUID());
|
|
206
|
+
var EventId = Schema5.NonEmptyString.check(Schema5.isMaxLength(100));
|
|
207
|
+
var BrowserEventPath = Schema5.String.check(Schema5.isMaxLength(2048), Schema5.isPattern(/^\/(?!\/)[^?#]*$/));
|
|
208
|
+
var EventIdentity = Schema5.Struct({
|
|
209
|
+
userId: Schema5.optional(Schema5.NonEmptyString),
|
|
210
|
+
organizationId: Schema5.optional(Schema5.NonEmptyString)
|
|
211
|
+
}).annotate({ identifier: "EventIdentity" });
|
|
212
|
+
var EventIpAddress = Schema5.String.check(Schema5.makeFilter((value) => Option2.isSome(Schema5.decodeUnknownOption(Schema5.IpAddressFromString)(value)) || "Invalid IP address")).annotate({ identifier: "EventIpAddress" });
|
|
213
|
+
var EventCountry = Schema5.String.check(Schema5.isPattern(/^[A-Z]{2}$/), Schema5.makeFilter((value) => !["XX", "T1"].includes(value) || "Unknown country")).annotate({ identifier: "EventCountry" });
|
|
214
|
+
var EventRegion = Schema5.String.check(Schema5.isPattern(/^[A-Z0-9]{1,3}$/)).annotate({ identifier: "EventRegion" });
|
|
215
|
+
var EventCity = Schema5.NonEmptyString.check(Schema5.isMaxLength(128)).annotate({ identifier: "EventCity" });
|
|
216
|
+
var EventGeolocation = Schema5.Struct({
|
|
217
|
+
ip: Schema5.optional(EventIpAddress),
|
|
218
|
+
country: Schema5.optional(EventCountry),
|
|
219
|
+
region: Schema5.optional(EventRegion),
|
|
220
|
+
city: Schema5.optional(EventCity)
|
|
221
|
+
}).annotate({ identifier: "EventGeolocation" });
|
|
222
|
+
|
|
223
|
+
class EventGeolocationError extends Schema5.TaggedError()("EventGeolocationError", {}) {
|
|
224
|
+
}
|
|
225
|
+
var BrowserEventOptions = Schema5.Struct({
|
|
226
|
+
messageId: Schema5.optional(EventId),
|
|
227
|
+
timestamp: Schema5.optional(Schema5.DateTimeUtc),
|
|
228
|
+
context: Schema5.optional(EventAttributesSchema)
|
|
229
|
+
}).annotate({ identifier: "BrowserEventOptions" });
|
|
230
|
+
var BrowserPage = Schema5.Struct({
|
|
231
|
+
name: Schema5.optional(Schema5.NonEmptyString),
|
|
232
|
+
category: Schema5.optional(Schema5.NonEmptyString),
|
|
233
|
+
path: Schema5.optional(Schema5.NonEmptyString),
|
|
234
|
+
properties: Schema5.optional(EventAttributesSchema),
|
|
235
|
+
options: Schema5.optional(BrowserEventOptions)
|
|
236
|
+
}).annotate({ identifier: "BrowserPage" });
|
|
237
|
+
var TrackEvent = Schema5.Struct({
|
|
238
|
+
eventId: EventId,
|
|
239
|
+
name: Schema5.NonEmptyString.check(Schema5.isMaxLength(128)),
|
|
240
|
+
properties: Schema5.optional(EventAttributesSchema),
|
|
241
|
+
identity: Schema5.optional(EventIdentity),
|
|
242
|
+
timestamp: Schema5.optional(Schema5.DateTimeUtc),
|
|
243
|
+
category: Schema5.optional(Schema5.Literals(["analytics", "audit"]))
|
|
244
|
+
}).annotate({ identifier: "TrackEvent" });
|
|
245
|
+
var AuditAttribution = Schema5.Struct({
|
|
246
|
+
"app.actor.type": Schema5.NonEmptyString,
|
|
247
|
+
"app.actor.id": Schema5.NonEmptyString
|
|
248
|
+
}).annotate({ identifier: "AuditAttribution" });
|
|
249
|
+
var RequestActorAttribution = Schema5.Struct({
|
|
250
|
+
...AuditAttribution.fields,
|
|
251
|
+
"app.actor.owner.type": Schema5.optional(Schema5.NonEmptyString),
|
|
252
|
+
"app.actor.owner.id": Schema5.optional(Schema5.NonEmptyString)
|
|
253
|
+
}).annotate({ identifier: "RequestActorAttribution" });
|
|
254
|
+
|
|
255
|
+
class EventsPersistenceError extends Schema5.TaggedError()("EventsPersistenceError", { operation: Schema5.String }) {
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
class EventConflictError extends Schema5.TaggedError()("EventConflictError", { eventId: EventId }) {
|
|
259
|
+
}
|
|
260
|
+
var EventSource = Schema5.Literals(["browser", "server"]).annotate({
|
|
261
|
+
identifier: "EventSource"
|
|
262
|
+
});
|
|
263
|
+
var ExistingEventRequest = Schema5.Struct({
|
|
264
|
+
eventId: EventId,
|
|
265
|
+
source: EventSource
|
|
266
|
+
}).annotate({ identifier: "ExistingEventRequest" });
|
|
267
|
+
var StoredEventRequest = Schema5.Struct({
|
|
268
|
+
source: EventSource,
|
|
269
|
+
event_id: EventId,
|
|
270
|
+
event_name: Schema5.NonEmptyString,
|
|
271
|
+
event_type: Schema5.Literals(["page", "track"]),
|
|
272
|
+
occurred_at: Schema5.Finite,
|
|
273
|
+
received_at: Schema5.Finite,
|
|
274
|
+
organization_id: Schema5.NullOr(Schema5.NonEmptyString),
|
|
275
|
+
user_id: Schema5.NullOr(Schema5.NonEmptyString),
|
|
276
|
+
session_id: Schema5.NullOr(Schema5.NonEmptyString),
|
|
277
|
+
anonymous_id: Schema5.NullOr(Schema5.NonEmptyString),
|
|
278
|
+
payload_json: Schema5.String
|
|
279
|
+
}).annotate({ identifier: "StoredEventRequest" });
|
|
280
|
+
var StoredEventId = Schema5.Struct({
|
|
281
|
+
event_id: EventId
|
|
282
|
+
}).annotate({ identifier: "StoredEventId" });
|
|
283
|
+
var PrimitiveValue = Schema5.Union([
|
|
284
|
+
Schema5.Struct({ stringValue: Schema5.String.check(Schema5.isMaxLength(2048)) }),
|
|
285
|
+
Schema5.Struct({
|
|
286
|
+
intValue: Schema5.Union([
|
|
287
|
+
Schema5.String.check(Schema5.isPattern(/^-?\d{1,20}$/)),
|
|
288
|
+
Schema5.Int
|
|
289
|
+
])
|
|
290
|
+
}),
|
|
291
|
+
Schema5.Struct({ doubleValue: Schema5.Finite }),
|
|
292
|
+
Schema5.Struct({ boolValue: Schema5.Boolean })
|
|
293
|
+
]);
|
|
294
|
+
var AttributeValue = Schema5.Union([
|
|
295
|
+
PrimitiveValue,
|
|
296
|
+
Schema5.Struct({
|
|
297
|
+
arrayValue: Schema5.Struct({
|
|
298
|
+
values: Schema5.Array(PrimitiveValue).check(Schema5.isMaxLength(32))
|
|
299
|
+
})
|
|
300
|
+
})
|
|
301
|
+
]);
|
|
302
|
+
var EventAttribute = Schema5.Struct({
|
|
303
|
+
key: Schema5.NonEmptyString.check(Schema5.isMaxLength(128)),
|
|
304
|
+
value: AttributeValue
|
|
305
|
+
}).annotate({ identifier: "EventAttribute" });
|
|
306
|
+
var EventLogRecord = Schema5.Struct({
|
|
307
|
+
eventName: Schema5.NonEmptyString.check(Schema5.isMaxLength(128), Schema5.isPattern(/^[^\r\n]+$/)),
|
|
308
|
+
timeUnixNano: Schema5.String.check(Schema5.isPattern(/^\d{1,20}$/)),
|
|
309
|
+
observedTimeUnixNano: Schema5.optional(Schema5.String.check(Schema5.isPattern(/^\d{1,20}$/))),
|
|
310
|
+
severityNumber: Schema5.optional(Schema5.Int),
|
|
311
|
+
traceId: Schema5.optional(Schema5.String.check(Schema5.isPattern(/^[a-f0-9]{32}$/))),
|
|
312
|
+
spanId: Schema5.optional(Schema5.String.check(Schema5.isPattern(/^[a-f0-9]{16}$/))),
|
|
313
|
+
attributes: Schema5.Array(EventAttribute).check(Schema5.isMaxLength(64), Schema5.makeFilter((values) => new Set(values.map(({ key }) => key)).size === values.length || "Duplicate attribute keys"))
|
|
314
|
+
}).annotate({ identifier: "EventLogRecord" });
|
|
315
|
+
var extensions = Schema5.Record(Schema5.String, Schema5.Unknown);
|
|
316
|
+
var OtlpLogs = Schema5.StructWithRest(Schema5.Struct({
|
|
317
|
+
resourceLogs: Schema5.Array(Schema5.StructWithRest(Schema5.Struct({
|
|
318
|
+
scopeLogs: Schema5.Array(Schema5.StructWithRest(Schema5.Struct({
|
|
319
|
+
scope: Schema5.optional(Schema5.StructWithRest(Schema5.Struct({ name: Schema5.optional(Schema5.String) }), [extensions])),
|
|
320
|
+
logRecords: Schema5.Array(Schema5.Unknown).pipe(Schema5.withDecodingDefaultKey(Effect4.succeed([])))
|
|
321
|
+
}), [extensions])).pipe(Schema5.withDecodingDefaultKey(Effect4.succeed([])))
|
|
322
|
+
}), [extensions])).pipe(Schema5.withDecodingDefaultKey(Effect4.succeed([])))
|
|
323
|
+
}), [extensions]).annotate({ identifier: "EventsOtlpLogs" });
|
|
324
|
+
var StoredEventPayload = Schema5.Struct({
|
|
325
|
+
payload_json: Schema5.Union([OtlpLogs, Schema5.fromJsonString(OtlpLogs)])
|
|
326
|
+
}).annotate({ identifier: "StoredEventPayload" });
|
|
327
|
+
var VisitorEventsRequest = Schema5.Struct({
|
|
328
|
+
visitorId: Schema5.NonEmptyString
|
|
329
|
+
}).annotate({ identifier: "VisitorEventsRequest" });
|
|
330
|
+
var VisitorEventSession = Schema5.Struct({
|
|
331
|
+
event_id: EventId,
|
|
332
|
+
session_id: Schema5.NullOr(Schema5.NonEmptyString),
|
|
333
|
+
received_at: Schema5.Finite
|
|
334
|
+
}).annotate({ identifier: "VisitorEventSession" });
|
|
335
|
+
|
|
336
|
+
// ../../src/services/events/request-context.ts
|
|
337
|
+
var cloudflareGeolocation = (headers) => ({
|
|
338
|
+
ip: Option3.getOrUndefined(Schema6.decodeUnknownOption(EventIpAddress)(headers["cf-connecting-ip"])),
|
|
339
|
+
country: Option3.getOrUndefined(Schema6.decodeUnknownOption(EventCountry)(headers["cf-ipcountry"])),
|
|
340
|
+
region: Option3.getOrUndefined(Schema6.decodeUnknownOption(EventRegion)(headers["cf-region-code"])),
|
|
341
|
+
city: Option3.getOrUndefined(Schema6.decodeUnknownOption(EventCity)(headers["cf-ipcity"]))
|
|
342
|
+
});
|
|
343
|
+
var geolocationAttributes = (location) => {
|
|
344
|
+
const attributes = {};
|
|
345
|
+
if (location?.country) {
|
|
346
|
+
attributes["geo.country.iso_code"] = location.country;
|
|
347
|
+
if (location.region)
|
|
348
|
+
attributes["geo.region.iso_code"] = `${location.country}-${location.region}`;
|
|
349
|
+
}
|
|
350
|
+
if (location?.city)
|
|
351
|
+
attributes["geo.locality.name"] = location.city;
|
|
352
|
+
return attributes;
|
|
353
|
+
};
|
|
354
|
+
var deviceContext = (userAgent) => {
|
|
355
|
+
const parsed = userAgent ? Bowser.parse(userAgent) : undefined;
|
|
356
|
+
return {
|
|
357
|
+
"browser.name": parsed?.browser.name ?? "unknown",
|
|
358
|
+
"os.name": parsed?.os.name ?? "unknown",
|
|
359
|
+
"device.type": parsed?.platform.type ?? "unknown"
|
|
360
|
+
};
|
|
361
|
+
};
|
|
362
|
+
|
|
363
|
+
// ../../src/services/events/migrations.ts
|
|
364
|
+
import { Effect as Effect5 } from "effect";
|
|
365
|
+
import { Migrator, SqlClient } from "effect/sql";
|
|
366
|
+
var eventsMigrations = Migrator.fromRecord({
|
|
367
|
+
"1_events_initial": Effect5.gen(function* () {
|
|
368
|
+
const sql = yield* SqlClient.SqlClient;
|
|
369
|
+
const payloadType = sql.onDialectOrElse({
|
|
370
|
+
pg: () => sql.literal("jsonb"),
|
|
371
|
+
orElse: () => sql.literal("text")
|
|
372
|
+
});
|
|
373
|
+
yield* sql`CREATE TABLE events (
|
|
374
|
+
service_name text NOT NULL,
|
|
375
|
+
source text NOT NULL CHECK (source IN ('browser', 'server')),
|
|
376
|
+
event_id text NOT NULL,
|
|
377
|
+
event_name text NOT NULL,
|
|
378
|
+
event_type text NOT NULL,
|
|
379
|
+
occurred_at double precision NOT NULL,
|
|
380
|
+
received_at double precision NOT NULL,
|
|
381
|
+
organization_id text,
|
|
382
|
+
user_id text,
|
|
383
|
+
session_id text,
|
|
384
|
+
anonymous_id text,
|
|
385
|
+
payload_json ${payloadType} NOT NULL,
|
|
386
|
+
PRIMARY KEY (service_name, source, event_id)
|
|
387
|
+
)`;
|
|
388
|
+
yield* sql`CREATE INDEX events_organization_time ON events (service_name, organization_id, occurred_at)`;
|
|
389
|
+
yield* sql`CREATE INDEX events_visitor_time ON events (service_name, anonymous_id, received_at DESC, event_id DESC)`;
|
|
390
|
+
yield* sql`CREATE INDEX events_session_time ON events (service_name, session_id, occurred_at, event_id)`;
|
|
391
|
+
yield* sql.onDialectOrElse({
|
|
392
|
+
pg: () => sql`CREATE INDEX events_payload ON events USING gin (payload_json jsonb_path_ops)`,
|
|
393
|
+
orElse: () => Effect5.void
|
|
394
|
+
});
|
|
395
|
+
})
|
|
396
|
+
});
|
|
397
|
+
var migrateEvents = Migrator.make({})({
|
|
398
|
+
loader: eventsMigrations,
|
|
399
|
+
table: "events_migrations"
|
|
400
|
+
});
|
|
401
|
+
|
|
402
|
+
// ../../src/services/events/index.ts
|
|
403
|
+
var SESSION_TIMEOUT_MS = 30 * 60 * 1000;
|
|
404
|
+
var identityAttributes = (identity) => {
|
|
405
|
+
const attributes = {};
|
|
406
|
+
if (identity?.userId)
|
|
407
|
+
attributes["user.id"] = identity.userId;
|
|
408
|
+
if (identity?.organizationId)
|
|
409
|
+
attributes["organization.id"] = identity.organizationId;
|
|
410
|
+
return attributes;
|
|
411
|
+
};
|
|
412
|
+
var actorAttributeKeys = [
|
|
413
|
+
"app.actor.type",
|
|
414
|
+
"app.actor.id",
|
|
415
|
+
"app.actor.owner.type",
|
|
416
|
+
"app.actor.owner.id"
|
|
417
|
+
];
|
|
418
|
+
var reservedBrowserAttribute = (key) => key.startsWith("app.actor.") || key.startsWith("app.audit.") || key.startsWith("app.executor.") || key === "app.access.channel";
|
|
419
|
+
var Configuration = Schema7.Struct({
|
|
420
|
+
serviceName: Schema7.NonEmptyString,
|
|
421
|
+
origin: Schema7.URLFromString.check(Schema7.makeFilter((url) => (url.protocol === "https:" || url.protocol === "http:") && !url.username && !url.password && url.pathname === "/" && !url.search && !url.hash || "Expected an HTTP origin")),
|
|
422
|
+
geolocation: Schema7.optional(Schema7.Union([
|
|
423
|
+
Schema7.Literal("cloudflare"),
|
|
424
|
+
Schema7.declare((value) => Predicate.isFunction(value))
|
|
425
|
+
])),
|
|
426
|
+
secret: Schema7.String.check(Schema7.isMinLength(32))
|
|
427
|
+
}).annotate({ identifier: "EventsConfiguration" });
|
|
428
|
+
|
|
429
|
+
class EventsConfigurationError extends Schema7.TaggedError()("EventsConfigurationError", { message: Schema7.String }) {
|
|
430
|
+
}
|
|
431
|
+
var codec = Schema7.fromJsonString(OtlpLogs);
|
|
432
|
+
var textAttribute = (record, key) => {
|
|
433
|
+
const value = record.attributes.find((attribute) => attribute.key === key)?.value;
|
|
434
|
+
return value && "stringValue" in value ? value.stringValue : undefined;
|
|
435
|
+
};
|
|
436
|
+
var contextKeys = new Set([
|
|
437
|
+
"url.path",
|
|
438
|
+
"url.referrer",
|
|
439
|
+
"browser.language",
|
|
440
|
+
"analytics.locale",
|
|
441
|
+
"analytics.page_view.id",
|
|
442
|
+
"log.record.uid",
|
|
443
|
+
"app.event.schema.version",
|
|
444
|
+
"analytics.page.name",
|
|
445
|
+
"analytics.page.category",
|
|
446
|
+
"utm.source",
|
|
447
|
+
"utm.medium",
|
|
448
|
+
"utm.campaign",
|
|
449
|
+
"utm.content",
|
|
450
|
+
"utm.term"
|
|
451
|
+
]);
|
|
452
|
+
var eventContent = (record, source, compareTimestamp = source === "browser") => JSON.stringify({
|
|
453
|
+
name: record.eventName,
|
|
454
|
+
timestamp: compareTimestamp ? record.timeUnixNano : undefined,
|
|
455
|
+
attributes: record.attributes.filter(({ key }) => source === "browser" ? (contextKeys.has(key) || key.startsWith("app.")) && !reservedBrowserAttribute(key) && !key.startsWith("app.event.") : key.startsWith("app.") && ![
|
|
456
|
+
"app.event.type",
|
|
457
|
+
"app.event.source",
|
|
458
|
+
"app.event.schema.version"
|
|
459
|
+
].includes(key) || key === "user.id" || key === "organization.id").sort((a, b) => a.key.localeCompare(b.key))
|
|
460
|
+
});
|
|
461
|
+
var dailyVisitorId = (input) => createHmac("sha256", Redacted.value(input.secret)).update(JSON.stringify([
|
|
462
|
+
"analytics.visitor.v1",
|
|
463
|
+
input.serviceName,
|
|
464
|
+
input.day,
|
|
465
|
+
input.ip,
|
|
466
|
+
input.userAgent
|
|
467
|
+
])).digest("hex");
|
|
468
|
+
|
|
469
|
+
class Events extends Context4.Service()("krakstack/events/Events", {
|
|
470
|
+
make: (options) => Effect6.gen(function* () {
|
|
471
|
+
const telemetry = yield* Otlp;
|
|
472
|
+
const resource = options.serviceName ? yield* OtlpResource3.fromConfig({ serviceName: options.serviceName }) : yield* telemetry.resource;
|
|
473
|
+
const configuration = yield* Schema7.decodeUnknownEffect(Configuration)({
|
|
474
|
+
...options,
|
|
475
|
+
serviceName: OtlpResource3.serviceNameUnsafe(resource),
|
|
476
|
+
secret: Redacted.value(options.secret)
|
|
477
|
+
}).pipe(Effect6.mapError(() => new EventsConfigurationError({
|
|
478
|
+
message: "Events requires an OTel service name, HTTP origin, and server secret of at least 32 characters"
|
|
479
|
+
})));
|
|
480
|
+
const client = yield* Effect6.serviceOption(SqlClient2.SqlClient);
|
|
481
|
+
const storage = Option4.isSome(client) ? yield* Effect6.gen(function* () {
|
|
482
|
+
const sql = client.value.withoutTransforms();
|
|
483
|
+
if (!sql.onDialectOrElse({
|
|
484
|
+
pg: () => true,
|
|
485
|
+
sqlite: () => true,
|
|
486
|
+
orElse: () => false
|
|
487
|
+
})) {
|
|
488
|
+
return yield* new EventsConfigurationError({
|
|
489
|
+
message: "Events supports PostgreSQL and SQLite"
|
|
490
|
+
});
|
|
491
|
+
}
|
|
492
|
+
const latestSession = SqlSchema.findOneOption({
|
|
493
|
+
Request: VisitorEventsRequest,
|
|
494
|
+
Result: VisitorEventSession,
|
|
495
|
+
execute: ({ visitorId }) => sql`
|
|
496
|
+
SELECT event_id, session_id, received_at FROM events
|
|
497
|
+
WHERE service_name = ${configuration.serviceName} AND anonymous_id = ${visitorId}
|
|
498
|
+
AND session_id IS NOT NULL
|
|
499
|
+
ORDER BY received_at DESC, event_id DESC LIMIT 1
|
|
500
|
+
`
|
|
501
|
+
});
|
|
502
|
+
const existingEvent = SqlSchema.findOne({
|
|
503
|
+
Request: ExistingEventRequest,
|
|
504
|
+
Result: StoredEventPayload,
|
|
505
|
+
execute: ({ source, eventId }) => sql`
|
|
506
|
+
SELECT payload_json FROM events
|
|
507
|
+
WHERE service_name = ${configuration.serviceName} AND source = ${source} AND event_id = ${eventId}
|
|
508
|
+
`
|
|
509
|
+
});
|
|
510
|
+
const lockVisitor = (visitorId) => sql.onDialectOrElse({
|
|
511
|
+
pg: () => sql`SELECT pg_advisory_xact_lock(hashtextextended(${JSON.stringify(["analytics.visit.v1", configuration.serviceName, visitorId])}, 0))`,
|
|
512
|
+
orElse: () => sql`UPDATE events SET received_at = received_at WHERE 1 = 0`
|
|
513
|
+
});
|
|
514
|
+
const insertEvent = SqlSchema.findOneOption({
|
|
515
|
+
Request: StoredEventRequest,
|
|
516
|
+
Result: StoredEventId,
|
|
517
|
+
execute: (event) => sql`
|
|
518
|
+
INSERT INTO events ${sql.insert({ service_name: configuration.serviceName, ...event })}
|
|
519
|
+
ON CONFLICT (service_name, source, event_id) DO NOTHING RETURNING event_id
|
|
520
|
+
`
|
|
521
|
+
});
|
|
522
|
+
const persist = Effect6.fnUntraced(function* (input) {
|
|
523
|
+
const { record, payload, now, source } = input;
|
|
524
|
+
const eventId = textAttribute(record, "log.record.uid");
|
|
525
|
+
const payloadJson = yield* Schema7.encodeEffect(codec)(payload);
|
|
526
|
+
const inserted = yield* insertEvent({
|
|
527
|
+
source,
|
|
528
|
+
event_id: eventId,
|
|
529
|
+
event_name: record.eventName,
|
|
530
|
+
event_type: record.eventName === "browser.page_view" ? "page" : "track",
|
|
531
|
+
occurred_at: Number(BigInt(record.timeUnixNano) / 1000000n),
|
|
532
|
+
received_at: now,
|
|
533
|
+
organization_id: textAttribute(record, "organization.id") ?? null,
|
|
534
|
+
user_id: textAttribute(record, "user.id") ?? null,
|
|
535
|
+
session_id: textAttribute(record, "session.id") ?? null,
|
|
536
|
+
anonymous_id: textAttribute(record, "analytics.anonymous_id") ?? null,
|
|
537
|
+
payload_json: payloadJson
|
|
538
|
+
});
|
|
539
|
+
if (Option4.isSome(inserted))
|
|
540
|
+
return { eventId, inserted: true, record };
|
|
541
|
+
const existing = yield* existingEvent({ source, eventId });
|
|
542
|
+
const original = yield* Schema7.decodeUnknownEffect(EventLogRecord)(existing.payload_json.resourceLogs[0]?.scopeLogs[0]?.logRecords[0]);
|
|
543
|
+
const identityChanged = source === "browser" && ["user.id", "organization.id"].some((key) => textAttribute(original, key) !== textAttribute(record, key));
|
|
544
|
+
if (identityChanged || eventContent(original, source, input.compareTimestamp) !== eventContent(record, source, input.compareTimestamp)) {
|
|
545
|
+
return yield* new EventConflictError({ eventId });
|
|
546
|
+
}
|
|
547
|
+
return { eventId, inserted: false, record: original };
|
|
548
|
+
});
|
|
549
|
+
return {
|
|
550
|
+
sql,
|
|
551
|
+
persist,
|
|
552
|
+
latestSession,
|
|
553
|
+
lockVisitor
|
|
554
|
+
};
|
|
555
|
+
}) : undefined;
|
|
556
|
+
const resolveGeolocation = Effect6.fnUntraced(function* (request) {
|
|
557
|
+
const location = configuration.geolocation === "cloudflare" ? cloudflareGeolocation(request.headers) : configuration.geolocation ? yield* configuration.geolocation(request) : null;
|
|
558
|
+
return yield* Schema7.decodeUnknownEffect(Schema7.NullOr(EventGeolocation))(location);
|
|
559
|
+
}, Effect6.mapError(() => new EventGeolocationError({})));
|
|
560
|
+
const resolveRequestContext = Effect6.fnUntraced(function* (request, now, location) {
|
|
561
|
+
const userAgent = request.headers["user-agent"]?.slice(0, 2048) ?? "";
|
|
562
|
+
const visitorId = location?.ip && userAgent ? dailyVisitorId({
|
|
563
|
+
serviceName: configuration.serviceName,
|
|
564
|
+
secret: options.secret,
|
|
565
|
+
ip: location.ip,
|
|
566
|
+
userAgent,
|
|
567
|
+
day: DateTime2.formatIsoDate(now)
|
|
568
|
+
}) : undefined;
|
|
569
|
+
let sessionId;
|
|
570
|
+
if (visitorId && storage) {
|
|
571
|
+
yield* storage.lockVisitor(visitorId);
|
|
572
|
+
const latest = yield* storage.latestSession({ visitorId });
|
|
573
|
+
sessionId = Option4.isSome(latest) && latest.value.received_at > DateTime2.toEpochMillis(now) - SESSION_TIMEOUT_MS ? latest.value.session_id : randomUUID();
|
|
574
|
+
}
|
|
575
|
+
const identity = {};
|
|
576
|
+
if (visitorId)
|
|
577
|
+
identity["analytics.anonymous_id"] = visitorId;
|
|
578
|
+
if (sessionId)
|
|
579
|
+
identity["session.id"] = sessionId;
|
|
580
|
+
return {
|
|
581
|
+
...deviceContext(userAgent),
|
|
582
|
+
...geolocationAttributes(location),
|
|
583
|
+
"analytics.identity.mode": visitorId ? "daily" : "unattributed",
|
|
584
|
+
...identity
|
|
585
|
+
};
|
|
586
|
+
});
|
|
587
|
+
const track = Effect6.fn("Events.track")(function* (input) {
|
|
588
|
+
const event = yield* Schema7.decodeUnknownEffect(TrackEvent)(input);
|
|
589
|
+
const category = event.category ?? "analytics";
|
|
590
|
+
if (!storage)
|
|
591
|
+
return yield* new EventsPersistenceError({
|
|
592
|
+
operation: "persistence-disabled"
|
|
593
|
+
});
|
|
594
|
+
const receivedAt = yield* DateTime2.now;
|
|
595
|
+
const now = DateTime2.toEpochMillis(receivedAt);
|
|
596
|
+
const request = yield* Effect6.serviceOption(HttpServerRequest.HttpServerRequest);
|
|
597
|
+
const annotations = yield* References2.CurrentLogAnnotations;
|
|
598
|
+
const hasIdentity = [
|
|
599
|
+
"user.id",
|
|
600
|
+
"organization.id",
|
|
601
|
+
...actorAttributeKeys
|
|
602
|
+
].some((key) => annotations[key] !== undefined);
|
|
603
|
+
const identity = hasIdentity ? yield* Schema7.decodeUnknownEffect(EventIdentity)({
|
|
604
|
+
userId: annotations["user.id"],
|
|
605
|
+
organizationId: annotations["organization.id"]
|
|
606
|
+
}) : event.identity;
|
|
607
|
+
if (category === "audit") {
|
|
608
|
+
yield* Schema7.decodeUnknownEffect(AuditAttribution)(annotations);
|
|
609
|
+
}
|
|
610
|
+
const attributes = {};
|
|
611
|
+
for (const [key, value] of Object.entries(event.properties ?? {})) {
|
|
612
|
+
const name = key.startsWith("app.") ? key : `app.${key}`;
|
|
613
|
+
if (!reservedBrowserAttribute(name))
|
|
614
|
+
attributes[name] = value;
|
|
615
|
+
}
|
|
616
|
+
Object.assign(attributes, identityAttributes(identity));
|
|
617
|
+
Object.assign(attributes, annotations);
|
|
618
|
+
attributes["log.record.uid"] = event.eventId;
|
|
619
|
+
attributes["app.event.schema.version"] = "1";
|
|
620
|
+
attributes["app.event.type"] = "track";
|
|
621
|
+
attributes["app.event.source"] = "server";
|
|
622
|
+
attributes["app.event.category"] = category;
|
|
623
|
+
const span = yield* Effect6.currentSpan.pipe(Effect6.option);
|
|
624
|
+
const location = Option4.isSome(request) ? yield* resolveGeolocation(request.value).pipe(Effect6.mapError(() => new EventsPersistenceError({ operation: "geolocation" }))) : null;
|
|
625
|
+
const entry = {
|
|
626
|
+
eventName: event.name,
|
|
627
|
+
timeUnixNano: (BigInt(event.timestamp ? DateTime2.toEpochMillis(event.timestamp) : now) * 1000000n).toString(),
|
|
628
|
+
observedTimeUnixNano: (BigInt(now) * 1000000n).toString()
|
|
629
|
+
};
|
|
630
|
+
return yield* Effect6.gen(function* () {
|
|
631
|
+
const requestContext = Option4.isSome(request) ? yield* resolveRequestContext(request.value, receivedAt, location) : {};
|
|
632
|
+
const validated = yield* Schema7.decodeUnknownEffect(EventLogRecord)({
|
|
633
|
+
...entry,
|
|
634
|
+
attributes: OtlpResource3.entriesToAttributes(Object.entries({ ...requestContext, ...attributes })),
|
|
635
|
+
traceId: Option4.isSome(span) ? span.value.traceId : undefined,
|
|
636
|
+
spanId: Option4.isSome(span) ? span.value.spanId : undefined
|
|
637
|
+
});
|
|
638
|
+
return yield* storage.persist({
|
|
639
|
+
source: "server",
|
|
640
|
+
compareTimestamp: event.timestamp !== undefined,
|
|
641
|
+
record: validated,
|
|
642
|
+
now,
|
|
643
|
+
payload: {
|
|
644
|
+
resourceLogs: [
|
|
645
|
+
{
|
|
646
|
+
resource,
|
|
647
|
+
scopeLogs: [
|
|
648
|
+
{
|
|
649
|
+
scope: { name: "krakstack.application.events" },
|
|
650
|
+
logRecords: [validated]
|
|
651
|
+
}
|
|
652
|
+
]
|
|
653
|
+
}
|
|
654
|
+
]
|
|
655
|
+
}
|
|
656
|
+
});
|
|
657
|
+
}).pipe(storage.sql.withTransaction, Effect6.map(({ eventId, inserted }) => ({ eventId, inserted })), Effect6.mapError((error) => error._tag === "EventConflictError" ? error : new EventsPersistenceError({
|
|
658
|
+
operation: "track"
|
|
659
|
+
})));
|
|
660
|
+
});
|
|
661
|
+
const process = Effect6.fnUntraced(function* (body) {
|
|
662
|
+
const request = yield* HttpServerRequest.HttpServerRequest;
|
|
663
|
+
const payload = yield* Schema7.decodeUnknownEffect(codec)(new TextDecoder().decode(body)).pipe(Effect6.mapError(() => new OtlpProcessingError({ status: 400 })));
|
|
664
|
+
const analyticsScopes = payload.resourceLogs.flatMap((resource) => resource.scopeLogs).filter((scope) => scope.scope?.name === "krakstack.application.events");
|
|
665
|
+
if (analyticsScopes.length === 0)
|
|
666
|
+
return { body, persisted: false };
|
|
667
|
+
if (request.headers.origin !== configuration.origin.origin || request.headers["sec-fetch-site"] === "cross-site") {
|
|
668
|
+
return yield* new OtlpProcessingError({ status: 403 });
|
|
669
|
+
}
|
|
670
|
+
const rawRecords = analyticsScopes.flatMap((scope) => scope.logRecords);
|
|
671
|
+
const records = yield* Schema7.decodeUnknownEffect(Schema7.Array(EventLogRecord).check(Schema7.isMinLength(1), Schema7.isMaxLength(100)))(rawRecords).pipe(Effect6.mapError(() => new OtlpProcessingError({ status: 400 })));
|
|
672
|
+
const now = yield* DateTime2.now;
|
|
673
|
+
const nowMillis = DateTime2.toEpochMillis(now);
|
|
674
|
+
for (const record of records) {
|
|
675
|
+
const timestamp = BigInt(record.timeUnixNano) / 1000000n;
|
|
676
|
+
if (timestamp < BigInt(nowMillis - 60 * 60 * 1000) || timestamp > BigInt(nowMillis + 60000) || textAttribute(record, "app.event.schema.version") !== "1" || Option4.isNone(Schema7.decodeUnknownOption(EventUuid)(textAttribute(record, "analytics.page_view.id"))) || Option4.isNone(Schema7.decodeUnknownOption(EventId)(textAttribute(record, "log.record.uid"))) || Option4.isNone(Schema7.decodeUnknownOption(BrowserEventPath)(textAttribute(record, "url.path")))) {
|
|
677
|
+
return yield* new OtlpProcessingError({ status: 400 });
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
const annotations = yield* References2.CurrentLogAnnotations;
|
|
681
|
+
const hasIdentity = [
|
|
682
|
+
"user.id",
|
|
683
|
+
"organization.id",
|
|
684
|
+
...actorAttributeKeys
|
|
685
|
+
].some((key) => annotations[key] !== undefined);
|
|
686
|
+
const trustedIdentity = yield* (hasIdentity ? Schema7.decodeUnknownEffect(EventIdentity)({
|
|
687
|
+
userId: annotations["user.id"],
|
|
688
|
+
organizationId: annotations["organization.id"]
|
|
689
|
+
}) : options.identity ? options.identity(request).pipe(Effect6.flatMap(Schema7.decodeUnknownEffect(Schema7.NullOr(EventIdentity)))) : Effect6.succeed(null)).pipe(Effect6.mapError(() => new OtlpProcessingError({ status: 503 })));
|
|
690
|
+
const trustedActor = actorAttributeKeys.some((key) => annotations[key] !== undefined) ? yield* Schema7.decodeUnknownEffect(RequestActorAttribution)(Object.fromEntries(actorAttributeKeys.filter((key) => annotations[key] !== undefined).map((key) => [key, annotations[key]]))).pipe(Effect6.mapError(() => new OtlpProcessingError({ status: 503 }))) : {};
|
|
691
|
+
const trustedAttributes = {
|
|
692
|
+
...identityAttributes(trustedIdentity),
|
|
693
|
+
...trustedActor
|
|
694
|
+
};
|
|
695
|
+
const location = yield* resolveGeolocation(request).pipe(Effect6.mapError(() => new OtlpProcessingError({ status: 503 })));
|
|
696
|
+
const ingest = Effect6.gen(function* () {
|
|
697
|
+
const requestContext = yield* resolveRequestContext(request, now, location);
|
|
698
|
+
let index = 0;
|
|
699
|
+
const resourceLogs = payload.resourceLogs.map((resource) => ({
|
|
700
|
+
...resource,
|
|
701
|
+
scopeLogs: resource.scopeLogs.map((scope) => scope.scope?.name !== "krakstack.application.events" ? scope : {
|
|
702
|
+
...scope,
|
|
703
|
+
logRecords: scope.logRecords.map(() => {
|
|
704
|
+
const record = records[index++];
|
|
705
|
+
return {
|
|
706
|
+
...record,
|
|
707
|
+
observedTimeUnixNano: (BigInt(nowMillis) * 1000000n).toString(),
|
|
708
|
+
attributes: [
|
|
709
|
+
...record.attributes.filter(({ key }) => (contextKeys.has(key) || key.startsWith("app.")) && !reservedBrowserAttribute(key) && !key.startsWith("app.event.")),
|
|
710
|
+
{
|
|
711
|
+
key: "app.event.type",
|
|
712
|
+
value: {
|
|
713
|
+
stringValue: record.eventName === "browser.page_view" ? "page" : "track"
|
|
714
|
+
}
|
|
715
|
+
},
|
|
716
|
+
...OtlpResource3.entriesToAttributes(Object.entries({
|
|
717
|
+
...requestContext,
|
|
718
|
+
...trustedAttributes,
|
|
719
|
+
"app.event.category": "analytics",
|
|
720
|
+
"app.event.source": "browser",
|
|
721
|
+
"app.event.schema.version": "1"
|
|
722
|
+
}))
|
|
723
|
+
]
|
|
724
|
+
};
|
|
725
|
+
})
|
|
726
|
+
})
|
|
727
|
+
}));
|
|
728
|
+
const persistedRecords = new Map;
|
|
729
|
+
if (storage) {
|
|
730
|
+
for (const resource of resourceLogs) {
|
|
731
|
+
for (const scope of resource.scopeLogs) {
|
|
732
|
+
if (scope.scope?.name !== "krakstack.application.events")
|
|
733
|
+
continue;
|
|
734
|
+
for (const raw of scope.logRecords) {
|
|
735
|
+
const record = yield* Schema7.decodeUnknownEffect(EventLogRecord)(raw);
|
|
736
|
+
const persisted = yield* storage.persist({
|
|
737
|
+
source: "browser",
|
|
738
|
+
record,
|
|
739
|
+
now: nowMillis,
|
|
740
|
+
payload: {
|
|
741
|
+
...payload,
|
|
742
|
+
resourceLogs: [
|
|
743
|
+
{
|
|
744
|
+
...resource,
|
|
745
|
+
scopeLogs: [{ ...scope, logRecords: [record] }]
|
|
746
|
+
}
|
|
747
|
+
]
|
|
748
|
+
}
|
|
749
|
+
});
|
|
750
|
+
persistedRecords.set(raw, persisted.record);
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
const encoded = yield* Schema7.encodeEffect(codec)({
|
|
756
|
+
...payload,
|
|
757
|
+
resourceLogs: resourceLogs.map((resource) => ({
|
|
758
|
+
...resource,
|
|
759
|
+
scopeLogs: resource.scopeLogs.map((scope) => ({
|
|
760
|
+
...scope,
|
|
761
|
+
logRecords: scope.logRecords.map((raw) => persistedRecords.get(raw) ?? raw)
|
|
762
|
+
}))
|
|
763
|
+
}))
|
|
764
|
+
});
|
|
765
|
+
const persisted = Boolean(storage) && payload.resourceLogs.every((resource) => resource.scopeLogs.every((scope) => scope.scope?.name === "krakstack.application.events" || scope.logRecords.length === 0));
|
|
766
|
+
return { body: new TextEncoder().encode(encoded), persisted };
|
|
767
|
+
});
|
|
768
|
+
return yield* (storage ? ingest.pipe(storage.sql.withTransaction) : ingest).pipe(Effect6.mapError((error) => new OtlpProcessingError({
|
|
769
|
+
status: error._tag === "EventConflictError" ? 409 : 503
|
|
770
|
+
})));
|
|
771
|
+
});
|
|
772
|
+
return { process, track };
|
|
773
|
+
})
|
|
774
|
+
}) {
|
|
775
|
+
static baseLayer = (options) => Layer3.effect(this, this.make(options));
|
|
776
|
+
static layer = (options) => this.baseLayer(options).pipe(Layer3.provide(Layer3.effectDiscard(Effect6.gen(function* () {
|
|
777
|
+
const client = yield* Effect6.serviceOption(SqlClient2.SqlClient);
|
|
778
|
+
if (Option4.isNone(client))
|
|
779
|
+
return;
|
|
780
|
+
if (!client.value.onDialectOrElse({
|
|
781
|
+
pg: () => true,
|
|
782
|
+
sqlite: () => true,
|
|
783
|
+
orElse: () => false
|
|
784
|
+
})) {
|
|
785
|
+
return yield* new EventsConfigurationError({
|
|
786
|
+
message: "Events supports PostgreSQL and SQLite"
|
|
787
|
+
});
|
|
788
|
+
}
|
|
789
|
+
yield* migrateEvents.pipe(Effect6.provideService(SqlClient2.SqlClient, client.value));
|
|
790
|
+
}))));
|
|
791
|
+
static ingestionLayer = Layer3.effect(OtlpLogsProcessor, Events);
|
|
792
|
+
}
|
|
793
|
+
export {
|
|
794
|
+
Events,
|
|
795
|
+
EventsConfigurationError,
|
|
796
|
+
SESSION_TIMEOUT_MS,
|
|
797
|
+
dailyVisitorId
|
|
798
|
+
};
|