@krak-stack/registry 0.1.50 → 0.1.52
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 +34 -0
- package/README.md +16 -424
- package/dist/components/ui/data-table.d.ts +20 -1
- package/dist/components/ui/data-table.js +52 -1
- 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 +579 -0
- package/dist/services/events/client/audit-log-table.d.ts +53 -0
- package/dist/services/events/client/audit-log-table.js +3655 -0
- package/dist/services/events/index.d.ts +215 -0
- package/dist/services/events/index.js +1046 -0
- package/dist/services/events/migrations.d.ts +4 -0
- package/dist/services/events/migrations.js +42 -0
- package/dist/services/events/record.d.ts +3 -0
- package/dist/services/events/record.js +14 -0
- package/dist/services/events/request-context.d.ts +6 -0
- package/dist/services/events/schema.d.ts +237 -0
- package/dist/services/events/schema.js +361 -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 +35 -5
|
@@ -0,0 +1,1046 @@
|
|
|
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 Effect7,
|
|
7
|
+
Layer as Layer3,
|
|
8
|
+
Option as Option5,
|
|
9
|
+
Predicate,
|
|
10
|
+
Redacted,
|
|
11
|
+
References as References2,
|
|
12
|
+
Schema as Schema8
|
|
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 Option4, Schema as Schema7 } from "effect";
|
|
202
|
+
|
|
203
|
+
// ../../src/services/events/schema.ts
|
|
204
|
+
import { Effect as Effect5, Option as Option3, Schema as Schema6 } from "effect";
|
|
205
|
+
|
|
206
|
+
// ../../src/lib/query.ts
|
|
207
|
+
import {
|
|
208
|
+
Effect as Effect4,
|
|
209
|
+
Option as Option2,
|
|
210
|
+
Schema as Schema5,
|
|
211
|
+
SchemaGetter,
|
|
212
|
+
SchemaIssue,
|
|
213
|
+
SchemaTransformation
|
|
214
|
+
} from "effect";
|
|
215
|
+
var parseSortParam = (sort) => {
|
|
216
|
+
const id = sort.startsWith("-") ? sort.slice(1) : sort;
|
|
217
|
+
if (!id || id.includes(",") || id.includes(":")) {
|
|
218
|
+
return null;
|
|
219
|
+
}
|
|
220
|
+
return { id, direction: sort.startsWith("-") ? "desc" : "asc" };
|
|
221
|
+
};
|
|
222
|
+
var SortDirection = Schema5.Union([
|
|
223
|
+
Schema5.Literal("asc"),
|
|
224
|
+
Schema5.Literal("desc")
|
|
225
|
+
]).pipe(Schema5.annotate({
|
|
226
|
+
identifier: "SortDirection",
|
|
227
|
+
title: "Sort Direction",
|
|
228
|
+
description: "Sort direction for list query results.",
|
|
229
|
+
examples: ["asc", "desc"]
|
|
230
|
+
}));
|
|
231
|
+
var SortParam = Schema5.Struct({
|
|
232
|
+
id: Schema5.NonEmptyString,
|
|
233
|
+
direction: SortDirection
|
|
234
|
+
}).pipe(Schema5.annotate({
|
|
235
|
+
identifier: "SortParam",
|
|
236
|
+
title: "Sort Parameter",
|
|
237
|
+
description: "Decoded sort parameter with a field id and direction.",
|
|
238
|
+
examples: [{ id: "publicName", direction: "asc" }]
|
|
239
|
+
}));
|
|
240
|
+
var SortParamFromString = Schema5.String.pipe(Schema5.decodeTo(SortParam, SchemaTransformation.transformEffect({
|
|
241
|
+
decode: (sort) => {
|
|
242
|
+
const sortParam = parseSortParam(sort);
|
|
243
|
+
if (!sortParam) {
|
|
244
|
+
return Effect4.fail(new SchemaIssue.InvalidValue({ message: 'Expected sort in the format "field" or "-field"' }, sort));
|
|
245
|
+
}
|
|
246
|
+
return Effect4.succeed(sortParam);
|
|
247
|
+
},
|
|
248
|
+
encode: (sort) => Effect4.succeed(sort.direction === "desc" ? `-${sort.id}` : sort.id)
|
|
249
|
+
})), Schema5.annotate({
|
|
250
|
+
identifier: "SortParamFromString",
|
|
251
|
+
title: "Sort Parameter From String",
|
|
252
|
+
description: 'URL encoded single sort parameter where descending fields are prefixed with "-".',
|
|
253
|
+
examples: [{ id: "publicName", direction: "asc" }]
|
|
254
|
+
}));
|
|
255
|
+
var SortParamsFromString = Schema5.String.pipe(Schema5.decodeTo(Schema5.Array(SortParam), SchemaTransformation.transformEffect({
|
|
256
|
+
decode: (sort) => {
|
|
257
|
+
if (sort === "")
|
|
258
|
+
return Effect4.succeed([]);
|
|
259
|
+
const parts = sort.split(",");
|
|
260
|
+
const sortParams = [];
|
|
261
|
+
for (const part of parts) {
|
|
262
|
+
const sortParam = parseSortParam(part);
|
|
263
|
+
if (!sortParam) {
|
|
264
|
+
return Effect4.fail(new SchemaIssue.InvalidValue({ message: 'Expected sort in the format "field,-otherField"' }, sort));
|
|
265
|
+
}
|
|
266
|
+
sortParams.push(sortParam);
|
|
267
|
+
}
|
|
268
|
+
return Effect4.succeed(sortParams);
|
|
269
|
+
},
|
|
270
|
+
encode: (sort) => Effect4.succeed(sort.map((part) => Schema5.encodeSync(SortParamFromString)(part)).join(","))
|
|
271
|
+
})), Schema5.annotate({
|
|
272
|
+
identifier: "SortParamsFromString",
|
|
273
|
+
title: "Sort Parameters From String",
|
|
274
|
+
description: 'URL encoded sort parameters where descending fields are prefixed with "-" and multiple fields are comma-separated.',
|
|
275
|
+
examples: [
|
|
276
|
+
[
|
|
277
|
+
{ id: "name", direction: "desc" },
|
|
278
|
+
{ id: "age", direction: "asc" }
|
|
279
|
+
]
|
|
280
|
+
]
|
|
281
|
+
}));
|
|
282
|
+
var SortParamsArray = Schema5.Array(SortParam);
|
|
283
|
+
var SortParams = Schema5.declare(Schema5.is(SortParamsArray), {
|
|
284
|
+
identifier: "SortParams",
|
|
285
|
+
toCodec: () => Schema5.link()(SortParamsArray, SchemaTransformation.passthrough()),
|
|
286
|
+
toCodecStringTree: () => Schema5.link()(SortParamsFromString, SchemaTransformation.passthrough())
|
|
287
|
+
});
|
|
288
|
+
var Query = Schema5.Struct({
|
|
289
|
+
page: Schema5.optional(Schema5.Union([Schema5.Number, Schema5.NumberFromString]).check(Schema5.isInt(), Schema5.isGreaterThanOrEqualTo(0))).pipe(Schema5.decodeTo(Schema5.Int.check(Schema5.isGreaterThanOrEqualTo(0)), {
|
|
290
|
+
decode: SchemaGetter.withDefault(Effect4.succeed(0)),
|
|
291
|
+
encode: SchemaGetter.transformOptional(Option2.filter((page) => page !== 0))
|
|
292
|
+
})),
|
|
293
|
+
pageSize: Schema5.optional(Schema5.Union([Schema5.Number, Schema5.NumberFromString]).check(Schema5.isInt(), Schema5.isBetween({ minimum: 1, maximum: 100 }))).pipe(Schema5.decodeTo(Schema5.Int.check(Schema5.isBetween({ minimum: 1, maximum: 100 })), {
|
|
294
|
+
decode: SchemaGetter.withDefault(Effect4.succeed(20)),
|
|
295
|
+
encode: SchemaGetter.transformOptional(Option2.filter((pageSize) => pageSize !== 20))
|
|
296
|
+
})),
|
|
297
|
+
globalFilter: Schema5.optional(Schema5.String),
|
|
298
|
+
sort: Schema5.optional(SortParams)
|
|
299
|
+
}).annotate({
|
|
300
|
+
identifier: "Query",
|
|
301
|
+
title: "Query",
|
|
302
|
+
description: "Zero-based page request parameters with optional filtering and sorting for list endpoints.",
|
|
303
|
+
examples: [
|
|
304
|
+
{
|
|
305
|
+
page: 0,
|
|
306
|
+
pageSize: 20,
|
|
307
|
+
globalFilter: "housing",
|
|
308
|
+
sort: [
|
|
309
|
+
{ id: "publicName", direction: "desc" },
|
|
310
|
+
{ id: "createdAt", direction: "asc" }
|
|
311
|
+
]
|
|
312
|
+
}
|
|
313
|
+
]
|
|
314
|
+
});
|
|
315
|
+
var QueryStandard = Schema5.toStandardSchemaV1(Query);
|
|
316
|
+
var PaginationMeta = Schema5.Struct({
|
|
317
|
+
page: Schema5.Int,
|
|
318
|
+
pageSize: Schema5.Int,
|
|
319
|
+
total: Schema5.Int,
|
|
320
|
+
pageCount: Schema5.Int
|
|
321
|
+
}).pipe(Schema5.annotate({
|
|
322
|
+
identifier: "PaginationMeta",
|
|
323
|
+
title: "Pagination Metadata",
|
|
324
|
+
description: "Pagination metadata returned with a paginated list response.",
|
|
325
|
+
examples: [{ page: 0, pageSize: 20, total: 125, pageCount: 7 }]
|
|
326
|
+
}));
|
|
327
|
+
|
|
328
|
+
// ../../src/services/events/schema.ts
|
|
329
|
+
var EventUuid = Schema6.String.check(Schema6.isUUID());
|
|
330
|
+
var EventId = Schema6.NonEmptyString.check(Schema6.isMaxLength(100));
|
|
331
|
+
var BrowserEventPath = Schema6.String.check(Schema6.isMaxLength(2048), Schema6.isPattern(/^\/(?!\/)[^?#]*$/));
|
|
332
|
+
var EventIdentity = Schema6.Struct({
|
|
333
|
+
userId: Schema6.optional(Schema6.NonEmptyString),
|
|
334
|
+
organizationId: Schema6.optional(Schema6.NonEmptyString)
|
|
335
|
+
}).annotate({ identifier: "EventIdentity" });
|
|
336
|
+
var EventIpAddress = Schema6.String.check(Schema6.makeFilter((value) => Option3.isSome(Schema6.decodeUnknownOption(Schema6.IpAddressFromString)(value)) || "Invalid IP address")).annotate({ identifier: "EventIpAddress" });
|
|
337
|
+
var EventCountry = Schema6.String.check(Schema6.isPattern(/^[A-Z]{2}$/), Schema6.makeFilter((value) => !["XX", "T1"].includes(value) || "Unknown country")).annotate({ identifier: "EventCountry" });
|
|
338
|
+
var EventRegion = Schema6.String.check(Schema6.isPattern(/^[A-Z0-9]{1,3}$/)).annotate({ identifier: "EventRegion" });
|
|
339
|
+
var EventCity = Schema6.NonEmptyString.check(Schema6.isMaxLength(128)).annotate({ identifier: "EventCity" });
|
|
340
|
+
var EventGeolocation = Schema6.Struct({
|
|
341
|
+
ip: Schema6.optional(EventIpAddress),
|
|
342
|
+
country: Schema6.optional(EventCountry),
|
|
343
|
+
region: Schema6.optional(EventRegion),
|
|
344
|
+
city: Schema6.optional(EventCity)
|
|
345
|
+
}).annotate({ identifier: "EventGeolocation" });
|
|
346
|
+
|
|
347
|
+
class EventGeolocationError extends Schema6.TaggedError()("EventGeolocationError", {}) {
|
|
348
|
+
}
|
|
349
|
+
var BrowserEventOptions = Schema6.Struct({
|
|
350
|
+
messageId: Schema6.optional(EventId),
|
|
351
|
+
timestamp: Schema6.optional(Schema6.DateTimeUtc),
|
|
352
|
+
context: Schema6.optional(EventAttributesSchema)
|
|
353
|
+
}).annotate({ identifier: "BrowserEventOptions" });
|
|
354
|
+
var BrowserPage = Schema6.Struct({
|
|
355
|
+
name: Schema6.optional(Schema6.NonEmptyString),
|
|
356
|
+
category: Schema6.optional(Schema6.NonEmptyString),
|
|
357
|
+
path: Schema6.optional(Schema6.NonEmptyString),
|
|
358
|
+
properties: Schema6.optional(EventAttributesSchema),
|
|
359
|
+
options: Schema6.optional(BrowserEventOptions)
|
|
360
|
+
}).annotate({ identifier: "BrowserPage" });
|
|
361
|
+
var AuditTarget = Schema6.Struct({
|
|
362
|
+
id: Schema6.NonEmptyString.check(Schema6.isMaxLength(256)),
|
|
363
|
+
name: Schema6.NonEmptyString.check(Schema6.isMaxLength(2048)),
|
|
364
|
+
type: Schema6.NonEmptyString.check(Schema6.isMaxLength(128))
|
|
365
|
+
}).annotate({ identifier: "AuditTarget" });
|
|
366
|
+
var trackEventFields = {
|
|
367
|
+
eventId: Schema6.optional(EventId),
|
|
368
|
+
name: Schema6.NonEmptyString.check(Schema6.isMaxLength(128)),
|
|
369
|
+
properties: Schema6.optional(EventAttributesSchema),
|
|
370
|
+
identity: Schema6.optional(EventIdentity),
|
|
371
|
+
timestamp: Schema6.optional(Schema6.DateTimeUtc)
|
|
372
|
+
};
|
|
373
|
+
var TrackEvent = Schema6.Union([
|
|
374
|
+
Schema6.Struct({
|
|
375
|
+
...trackEventFields,
|
|
376
|
+
category: Schema6.optional(Schema6.Literal("analytics"))
|
|
377
|
+
}),
|
|
378
|
+
Schema6.Struct({
|
|
379
|
+
...trackEventFields,
|
|
380
|
+
category: Schema6.Literal("audit"),
|
|
381
|
+
target: AuditTarget
|
|
382
|
+
})
|
|
383
|
+
]).annotate({ identifier: "TrackEvent" });
|
|
384
|
+
var ListAudit = Schema6.Struct({
|
|
385
|
+
organizationId: Schema6.NonEmptyString,
|
|
386
|
+
...Query.fields
|
|
387
|
+
}).annotate({ identifier: "ListAudit" });
|
|
388
|
+
var AuditSortId = Schema6.Literals([
|
|
389
|
+
"time",
|
|
390
|
+
"eventName",
|
|
391
|
+
"recordType",
|
|
392
|
+
"record",
|
|
393
|
+
"actorType",
|
|
394
|
+
"actorId"
|
|
395
|
+
]).annotate({ identifier: "AuditSortId" });
|
|
396
|
+
var AuditCount = Schema6.Struct({ total: Schema6.Int }).annotate({
|
|
397
|
+
identifier: "AuditCount"
|
|
398
|
+
});
|
|
399
|
+
var AuditAttribution = Schema6.Struct({
|
|
400
|
+
"app.actor.type": Schema6.NonEmptyString,
|
|
401
|
+
"app.actor.id": Schema6.NonEmptyString
|
|
402
|
+
}).annotate({ identifier: "AuditAttribution" });
|
|
403
|
+
var RequestActorAttribution = Schema6.Struct({
|
|
404
|
+
...AuditAttribution.fields,
|
|
405
|
+
"app.auth.method": Schema6.optional(Schema6.NonEmptyString),
|
|
406
|
+
"app.auth.credential.id": Schema6.optional(Schema6.NonEmptyString),
|
|
407
|
+
"app.auth.impersonator.id": Schema6.optional(Schema6.NonEmptyString),
|
|
408
|
+
"user.roles": Schema6.optional(Schema6.Array(Schema6.String))
|
|
409
|
+
}).annotate({ identifier: "RequestActorAttribution" });
|
|
410
|
+
|
|
411
|
+
class EventsPersistenceError extends Schema6.TaggedError()("EventsPersistenceError", { operation: Schema6.String }) {
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
class EventConflictError extends Schema6.TaggedError()("EventConflictError", { eventId: EventId }) {
|
|
415
|
+
}
|
|
416
|
+
var EventSource = Schema6.Literals(["browser", "server"]).annotate({
|
|
417
|
+
identifier: "EventSource"
|
|
418
|
+
});
|
|
419
|
+
var ExistingEventRequest = Schema6.Struct({
|
|
420
|
+
eventId: EventId,
|
|
421
|
+
source: EventSource
|
|
422
|
+
}).annotate({ identifier: "ExistingEventRequest" });
|
|
423
|
+
var StoredEventRequest = Schema6.Struct({
|
|
424
|
+
source: EventSource,
|
|
425
|
+
event_id: EventId,
|
|
426
|
+
event_name: Schema6.NonEmptyString,
|
|
427
|
+
event_type: Schema6.Literals(["page", "track"]),
|
|
428
|
+
occurred_at: Schema6.Finite,
|
|
429
|
+
received_at: Schema6.Finite,
|
|
430
|
+
organization_id: Schema6.NullOr(Schema6.NonEmptyString),
|
|
431
|
+
user_id: Schema6.NullOr(Schema6.NonEmptyString),
|
|
432
|
+
session_id: Schema6.NullOr(Schema6.NonEmptyString),
|
|
433
|
+
anonymous_id: Schema6.NullOr(Schema6.NonEmptyString),
|
|
434
|
+
payload_json: Schema6.String
|
|
435
|
+
}).annotate({ identifier: "StoredEventRequest" });
|
|
436
|
+
var StoredEventId = Schema6.Struct({
|
|
437
|
+
event_id: EventId
|
|
438
|
+
}).annotate({ identifier: "StoredEventId" });
|
|
439
|
+
var PrimitiveValue = Schema6.Union([
|
|
440
|
+
Schema6.Struct({ stringValue: Schema6.String.check(Schema6.isMaxLength(2048)) }),
|
|
441
|
+
Schema6.Struct({
|
|
442
|
+
intValue: Schema6.Union([
|
|
443
|
+
Schema6.String.check(Schema6.isPattern(/^-?\d{1,20}$/)),
|
|
444
|
+
Schema6.Int
|
|
445
|
+
])
|
|
446
|
+
}),
|
|
447
|
+
Schema6.Struct({ doubleValue: Schema6.Finite }),
|
|
448
|
+
Schema6.Struct({ boolValue: Schema6.Boolean })
|
|
449
|
+
]);
|
|
450
|
+
var AttributeValue = Schema6.Union([
|
|
451
|
+
PrimitiveValue,
|
|
452
|
+
Schema6.Struct({
|
|
453
|
+
arrayValue: Schema6.Struct({
|
|
454
|
+
values: Schema6.Array(PrimitiveValue).check(Schema6.isMaxLength(32))
|
|
455
|
+
})
|
|
456
|
+
})
|
|
457
|
+
]);
|
|
458
|
+
var EventAttribute = Schema6.Struct({
|
|
459
|
+
key: Schema6.NonEmptyString.check(Schema6.isMaxLength(128)),
|
|
460
|
+
value: AttributeValue
|
|
461
|
+
}).annotate({ identifier: "EventAttribute" });
|
|
462
|
+
var EventLogRecord = Schema6.Struct({
|
|
463
|
+
eventName: Schema6.NonEmptyString.check(Schema6.isMaxLength(128), Schema6.isPattern(/^[^\r\n]+$/)),
|
|
464
|
+
timeUnixNano: Schema6.String.check(Schema6.isPattern(/^\d{1,20}$/)),
|
|
465
|
+
observedTimeUnixNano: Schema6.optional(Schema6.String.check(Schema6.isPattern(/^\d{1,20}$/))),
|
|
466
|
+
severityNumber: Schema6.optional(Schema6.Int),
|
|
467
|
+
traceId: Schema6.optional(Schema6.String.check(Schema6.isPattern(/^[a-f0-9]{32}$/))),
|
|
468
|
+
spanId: Schema6.optional(Schema6.String.check(Schema6.isPattern(/^[a-f0-9]{16}$/))),
|
|
469
|
+
attributes: Schema6.Array(EventAttribute).check(Schema6.isMaxLength(64), Schema6.makeFilter((values) => new Set(values.map(({ key }) => key)).size === values.length || "Duplicate attribute keys"))
|
|
470
|
+
}).annotate({ identifier: "EventLogRecord" });
|
|
471
|
+
var extensions = Schema6.Record(Schema6.String, Schema6.Unknown);
|
|
472
|
+
var OtlpLogs = Schema6.StructWithRest(Schema6.Struct({
|
|
473
|
+
resourceLogs: Schema6.Array(Schema6.StructWithRest(Schema6.Struct({
|
|
474
|
+
scopeLogs: Schema6.Array(Schema6.StructWithRest(Schema6.Struct({
|
|
475
|
+
scope: Schema6.optional(Schema6.StructWithRest(Schema6.Struct({ name: Schema6.optional(Schema6.String) }), [extensions])),
|
|
476
|
+
logRecords: Schema6.Array(Schema6.Unknown).pipe(Schema6.withDecodingDefaultKey(Effect5.succeed([])))
|
|
477
|
+
}), [extensions])).pipe(Schema6.withDecodingDefaultKey(Effect5.succeed([])))
|
|
478
|
+
}), [extensions])).pipe(Schema6.withDecodingDefaultKey(Effect5.succeed([])))
|
|
479
|
+
}), [extensions]).annotate({ identifier: "EventsOtlpLogs" });
|
|
480
|
+
var StoredEventPayload = Schema6.Struct({
|
|
481
|
+
payload_json: Schema6.Union([OtlpLogs, Schema6.fromJsonString(OtlpLogs)])
|
|
482
|
+
}).annotate({ identifier: "StoredEventPayload" });
|
|
483
|
+
var VisitorEventsRequest = Schema6.Struct({
|
|
484
|
+
visitorId: Schema6.NonEmptyString
|
|
485
|
+
}).annotate({ identifier: "VisitorEventsRequest" });
|
|
486
|
+
var VisitorEventSession = Schema6.Struct({
|
|
487
|
+
event_id: EventId,
|
|
488
|
+
session_id: Schema6.NullOr(Schema6.NonEmptyString),
|
|
489
|
+
received_at: Schema6.Finite
|
|
490
|
+
}).annotate({ identifier: "VisitorEventSession" });
|
|
491
|
+
|
|
492
|
+
// ../../src/services/events/request-context.ts
|
|
493
|
+
var cloudflareGeolocation = (headers) => ({
|
|
494
|
+
ip: Option4.getOrUndefined(Schema7.decodeUnknownOption(EventIpAddress)(headers["cf-connecting-ip"])),
|
|
495
|
+
country: Option4.getOrUndefined(Schema7.decodeUnknownOption(EventCountry)(headers["cf-ipcountry"])),
|
|
496
|
+
region: Option4.getOrUndefined(Schema7.decodeUnknownOption(EventRegion)(headers["cf-region-code"])),
|
|
497
|
+
city: Option4.getOrUndefined(Schema7.decodeUnknownOption(EventCity)(headers["cf-ipcity"]))
|
|
498
|
+
});
|
|
499
|
+
var geolocationAttributes = (location) => {
|
|
500
|
+
const attributes = {};
|
|
501
|
+
if (location?.country) {
|
|
502
|
+
attributes["geo.country.iso_code"] = location.country;
|
|
503
|
+
if (location.region)
|
|
504
|
+
attributes["geo.region.iso_code"] = `${location.country}-${location.region}`;
|
|
505
|
+
}
|
|
506
|
+
if (location?.city)
|
|
507
|
+
attributes["geo.locality.name"] = location.city;
|
|
508
|
+
return attributes;
|
|
509
|
+
};
|
|
510
|
+
var deviceContext = (userAgent) => {
|
|
511
|
+
const parsed = userAgent ? Bowser.parse(userAgent) : undefined;
|
|
512
|
+
return {
|
|
513
|
+
"browser.name": parsed?.browser.name ?? "unknown",
|
|
514
|
+
"os.name": parsed?.os.name ?? "unknown",
|
|
515
|
+
"device.type": parsed?.platform.type ?? "unknown"
|
|
516
|
+
};
|
|
517
|
+
};
|
|
518
|
+
|
|
519
|
+
// ../../src/services/events/migrations.ts
|
|
520
|
+
import { Effect as Effect6 } from "effect";
|
|
521
|
+
import { Migrator, SqlClient } from "effect/sql";
|
|
522
|
+
var eventsMigrations = Migrator.fromRecord({
|
|
523
|
+
"1_events_initial": Effect6.gen(function* () {
|
|
524
|
+
const sql = yield* SqlClient.SqlClient;
|
|
525
|
+
const payloadType = sql.onDialectOrElse({
|
|
526
|
+
pg: () => sql.literal("jsonb"),
|
|
527
|
+
orElse: () => sql.literal("text")
|
|
528
|
+
});
|
|
529
|
+
yield* sql`CREATE TABLE events (
|
|
530
|
+
service_name text NOT NULL,
|
|
531
|
+
source text NOT NULL CHECK (source IN ('browser', 'server')),
|
|
532
|
+
event_id text NOT NULL,
|
|
533
|
+
event_name text NOT NULL,
|
|
534
|
+
event_type text NOT NULL,
|
|
535
|
+
occurred_at double precision NOT NULL,
|
|
536
|
+
received_at double precision NOT NULL,
|
|
537
|
+
organization_id text,
|
|
538
|
+
user_id text,
|
|
539
|
+
session_id text,
|
|
540
|
+
anonymous_id text,
|
|
541
|
+
payload_json ${payloadType} NOT NULL,
|
|
542
|
+
PRIMARY KEY (service_name, source, event_id)
|
|
543
|
+
)`;
|
|
544
|
+
yield* sql`CREATE INDEX events_organization_time ON events (service_name, organization_id, occurred_at)`;
|
|
545
|
+
yield* sql`CREATE INDEX events_visitor_time ON events (service_name, anonymous_id, received_at DESC, event_id DESC)`;
|
|
546
|
+
yield* sql`CREATE INDEX events_session_time ON events (service_name, session_id, occurred_at, event_id)`;
|
|
547
|
+
yield* sql.onDialectOrElse({
|
|
548
|
+
pg: () => sql`CREATE INDEX events_payload ON events USING gin (payload_json jsonb_path_ops)`,
|
|
549
|
+
orElse: () => Effect6.void
|
|
550
|
+
});
|
|
551
|
+
})
|
|
552
|
+
});
|
|
553
|
+
var migrateEvents = Migrator.make({})({
|
|
554
|
+
loader: eventsMigrations,
|
|
555
|
+
table: "events_migrations"
|
|
556
|
+
});
|
|
557
|
+
|
|
558
|
+
// ../../src/services/events/index.ts
|
|
559
|
+
var SESSION_TIMEOUT_MS = 30 * 60 * 1000;
|
|
560
|
+
var identityAttributes = (identity) => {
|
|
561
|
+
const attributes = {};
|
|
562
|
+
if (identity?.userId)
|
|
563
|
+
attributes["user.id"] = identity.userId;
|
|
564
|
+
if (identity?.organizationId)
|
|
565
|
+
attributes["organization.id"] = identity.organizationId;
|
|
566
|
+
return attributes;
|
|
567
|
+
};
|
|
568
|
+
var actorAttributeKeys = [
|
|
569
|
+
"app.actor.type",
|
|
570
|
+
"app.actor.id",
|
|
571
|
+
"app.auth.method",
|
|
572
|
+
"app.auth.credential.id",
|
|
573
|
+
"app.auth.impersonator.id",
|
|
574
|
+
"user.roles"
|
|
575
|
+
];
|
|
576
|
+
var reservedBrowserAttribute = (key) => key.startsWith("app.user.") || key.startsWith("user.") || key.startsWith("app.actor.") || key.startsWith("app.auth.") || key.startsWith("app.audit.") || key.startsWith("app.executor.") || key === "app.access.channel";
|
|
577
|
+
var Configuration = Schema8.Struct({
|
|
578
|
+
serviceName: Schema8.NonEmptyString,
|
|
579
|
+
origin: Schema8.URLFromString.check(Schema8.makeFilter((url) => (url.protocol === "https:" || url.protocol === "http:") && !url.username && !url.password && url.pathname === "/" && !url.search && !url.hash || "Expected an HTTP origin")),
|
|
580
|
+
geolocation: Schema8.optional(Schema8.Union([
|
|
581
|
+
Schema8.Literal("cloudflare"),
|
|
582
|
+
Schema8.declare((value) => Predicate.isFunction(value))
|
|
583
|
+
])),
|
|
584
|
+
secret: Schema8.String.check(Schema8.isMinLength(32))
|
|
585
|
+
}).annotate({ identifier: "EventsConfiguration" });
|
|
586
|
+
|
|
587
|
+
class EventsConfigurationError extends Schema8.TaggedError()("EventsConfigurationError", { message: Schema8.String }) {
|
|
588
|
+
}
|
|
589
|
+
var codec = Schema8.fromJsonString(OtlpLogs);
|
|
590
|
+
var textAttribute = (record, key) => {
|
|
591
|
+
const value = record.attributes.find((attribute) => attribute.key === key)?.value;
|
|
592
|
+
return value && "stringValue" in value ? value.stringValue : undefined;
|
|
593
|
+
};
|
|
594
|
+
var contextKeys = new Set([
|
|
595
|
+
"url.path",
|
|
596
|
+
"url.referrer",
|
|
597
|
+
"browser.language",
|
|
598
|
+
"analytics.locale",
|
|
599
|
+
"analytics.page_view.id",
|
|
600
|
+
"log.record.uid",
|
|
601
|
+
"app.event.schema.version",
|
|
602
|
+
"analytics.page.name",
|
|
603
|
+
"analytics.page.category",
|
|
604
|
+
"utm.source",
|
|
605
|
+
"utm.medium",
|
|
606
|
+
"utm.campaign",
|
|
607
|
+
"utm.content",
|
|
608
|
+
"utm.term"
|
|
609
|
+
]);
|
|
610
|
+
var eventContent = (record, source, compareTimestamp = source === "browser") => JSON.stringify({
|
|
611
|
+
name: record.eventName,
|
|
612
|
+
timestamp: compareTimestamp ? record.timeUnixNano : undefined,
|
|
613
|
+
attributes: record.attributes.filter(({ key }) => source === "browser" ? (contextKeys.has(key) || key.startsWith("app.")) && !reservedBrowserAttribute(key) && !key.startsWith("app.event.") : key.startsWith("app.") && ![
|
|
614
|
+
"app.event.type",
|
|
615
|
+
"app.event.source",
|
|
616
|
+
"app.event.schema.version"
|
|
617
|
+
].includes(key) || key === "user.id" || key === "organization.id").sort((a, b) => a.key.localeCompare(b.key))
|
|
618
|
+
});
|
|
619
|
+
var dailyVisitorId = (input) => createHmac("sha256", Redacted.value(input.secret)).update(JSON.stringify([
|
|
620
|
+
"analytics.visitor.v1",
|
|
621
|
+
input.serviceName,
|
|
622
|
+
input.day,
|
|
623
|
+
input.ip,
|
|
624
|
+
input.userAgent
|
|
625
|
+
])).digest("hex");
|
|
626
|
+
|
|
627
|
+
class Events extends Context4.Service()("krakstack/events/Events", {
|
|
628
|
+
make: (options) => Effect7.gen(function* () {
|
|
629
|
+
const telemetry = yield* Otlp;
|
|
630
|
+
const resource = options.serviceName ? yield* OtlpResource3.fromConfig({ serviceName: options.serviceName }) : yield* telemetry.resource;
|
|
631
|
+
const configuration = yield* Schema8.decodeUnknownEffect(Configuration)({
|
|
632
|
+
...options,
|
|
633
|
+
serviceName: OtlpResource3.serviceNameUnsafe(resource),
|
|
634
|
+
secret: Redacted.value(options.secret)
|
|
635
|
+
}).pipe(Effect7.mapError(() => new EventsConfigurationError({
|
|
636
|
+
message: "Events requires an OTel service name, HTTP origin, and server secret of at least 32 characters"
|
|
637
|
+
})));
|
|
638
|
+
const client = yield* Effect7.serviceOption(SqlClient2.SqlClient);
|
|
639
|
+
const storage = Option5.isSome(client) ? yield* Effect7.gen(function* () {
|
|
640
|
+
const sql = client.value.withoutTransforms();
|
|
641
|
+
if (!sql.onDialectOrElse({
|
|
642
|
+
pg: () => true,
|
|
643
|
+
sqlite: () => true,
|
|
644
|
+
orElse: () => false
|
|
645
|
+
})) {
|
|
646
|
+
return yield* new EventsConfigurationError({
|
|
647
|
+
message: "Events supports PostgreSQL and SQLite"
|
|
648
|
+
});
|
|
649
|
+
}
|
|
650
|
+
const latestSession = SqlSchema.findOneOption({
|
|
651
|
+
Request: VisitorEventsRequest,
|
|
652
|
+
Result: VisitorEventSession,
|
|
653
|
+
execute: ({ visitorId }) => sql`
|
|
654
|
+
SELECT event_id, session_id, received_at FROM events
|
|
655
|
+
WHERE service_name = ${configuration.serviceName} AND anonymous_id = ${visitorId}
|
|
656
|
+
AND session_id IS NOT NULL
|
|
657
|
+
ORDER BY received_at DESC, event_id DESC LIMIT 1
|
|
658
|
+
`
|
|
659
|
+
});
|
|
660
|
+
const existingEvent = SqlSchema.findOne({
|
|
661
|
+
Request: ExistingEventRequest,
|
|
662
|
+
Result: StoredEventPayload,
|
|
663
|
+
execute: ({ source, eventId }) => sql`
|
|
664
|
+
SELECT payload_json FROM events
|
|
665
|
+
WHERE service_name = ${configuration.serviceName} AND source = ${source} AND event_id = ${eventId}
|
|
666
|
+
`
|
|
667
|
+
});
|
|
668
|
+
const lockVisitor = (visitorId) => sql.onDialectOrElse({
|
|
669
|
+
pg: () => sql`SELECT pg_advisory_xact_lock(hashtextextended(${JSON.stringify(["analytics.visit.v1", configuration.serviceName, visitorId])}, 0))`,
|
|
670
|
+
orElse: () => sql`UPDATE events SET received_at = received_at WHERE 1 = 0`
|
|
671
|
+
});
|
|
672
|
+
const insertEvent = SqlSchema.findOneOption({
|
|
673
|
+
Request: StoredEventRequest,
|
|
674
|
+
Result: StoredEventId,
|
|
675
|
+
execute: (event) => sql`
|
|
676
|
+
INSERT INTO events ${sql.insert({ service_name: configuration.serviceName, ...event })}
|
|
677
|
+
ON CONFLICT (service_name, source, event_id) DO NOTHING RETURNING event_id
|
|
678
|
+
`
|
|
679
|
+
});
|
|
680
|
+
const persist = Effect7.fnUntraced(function* (input) {
|
|
681
|
+
const { record, payload, now, source } = input;
|
|
682
|
+
const eventId = textAttribute(record, "log.record.uid");
|
|
683
|
+
const payloadJson = yield* Schema8.encodeEffect(codec)(payload);
|
|
684
|
+
const inserted = yield* insertEvent({
|
|
685
|
+
source,
|
|
686
|
+
event_id: eventId,
|
|
687
|
+
event_name: record.eventName,
|
|
688
|
+
event_type: record.eventName === "browser.page_view" ? "page" : "track",
|
|
689
|
+
occurred_at: Number(BigInt(record.timeUnixNano) / 1000000n),
|
|
690
|
+
received_at: now,
|
|
691
|
+
organization_id: textAttribute(record, "organization.id") ?? null,
|
|
692
|
+
user_id: textAttribute(record, "user.id") ?? null,
|
|
693
|
+
session_id: textAttribute(record, "session.id") ?? null,
|
|
694
|
+
anonymous_id: textAttribute(record, "analytics.anonymous_id") ?? null,
|
|
695
|
+
payload_json: payloadJson
|
|
696
|
+
});
|
|
697
|
+
if (Option5.isSome(inserted))
|
|
698
|
+
return { eventId, inserted: true, record };
|
|
699
|
+
const existing = yield* existingEvent({ source, eventId });
|
|
700
|
+
const original = yield* Schema8.decodeUnknownEffect(EventLogRecord)(existing.payload_json.resourceLogs[0]?.scopeLogs[0]?.logRecords[0]);
|
|
701
|
+
const identityChanged = source === "browser" && ["user.id", "organization.id"].some((key) => textAttribute(original, key) !== textAttribute(record, key));
|
|
702
|
+
if (identityChanged || eventContent(original, source, input.compareTimestamp) !== eventContent(record, source, input.compareTimestamp)) {
|
|
703
|
+
return yield* new EventConflictError({ eventId });
|
|
704
|
+
}
|
|
705
|
+
return { eventId, inserted: false, record: original };
|
|
706
|
+
});
|
|
707
|
+
return {
|
|
708
|
+
sql,
|
|
709
|
+
persist,
|
|
710
|
+
latestSession,
|
|
711
|
+
lockVisitor
|
|
712
|
+
};
|
|
713
|
+
}) : undefined;
|
|
714
|
+
const resolveGeolocation = Effect7.fnUntraced(function* (request) {
|
|
715
|
+
const location = configuration.geolocation === "cloudflare" ? cloudflareGeolocation(request.headers) : configuration.geolocation ? yield* configuration.geolocation(request) : null;
|
|
716
|
+
return yield* Schema8.decodeUnknownEffect(Schema8.NullOr(EventGeolocation))(location);
|
|
717
|
+
}, Effect7.mapError(() => new EventGeolocationError({})));
|
|
718
|
+
const resolveRequestContext = Effect7.fnUntraced(function* (request, now, location) {
|
|
719
|
+
const userAgent = request.headers["user-agent"]?.slice(0, 2048) ?? "";
|
|
720
|
+
const visitorId = location?.ip && userAgent ? dailyVisitorId({
|
|
721
|
+
serviceName: configuration.serviceName,
|
|
722
|
+
secret: options.secret,
|
|
723
|
+
ip: location.ip,
|
|
724
|
+
userAgent,
|
|
725
|
+
day: DateTime2.formatIsoDate(now)
|
|
726
|
+
}) : undefined;
|
|
727
|
+
let sessionId;
|
|
728
|
+
if (visitorId && storage) {
|
|
729
|
+
yield* storage.lockVisitor(visitorId);
|
|
730
|
+
const latest = yield* storage.latestSession({ visitorId });
|
|
731
|
+
sessionId = Option5.isSome(latest) && latest.value.received_at > DateTime2.toEpochMillis(now) - SESSION_TIMEOUT_MS ? latest.value.session_id : randomUUID();
|
|
732
|
+
}
|
|
733
|
+
const identity = {};
|
|
734
|
+
if (visitorId)
|
|
735
|
+
identity["analytics.anonymous_id"] = visitorId;
|
|
736
|
+
if (sessionId)
|
|
737
|
+
identity["session.id"] = sessionId;
|
|
738
|
+
return {
|
|
739
|
+
...deviceContext(userAgent),
|
|
740
|
+
...geolocationAttributes(location),
|
|
741
|
+
"analytics.identity.mode": visitorId ? "daily" : "unattributed",
|
|
742
|
+
...identity
|
|
743
|
+
};
|
|
744
|
+
});
|
|
745
|
+
const track = Effect7.fn("Events.track")(function* (input) {
|
|
746
|
+
const event = yield* Schema8.decodeUnknownEffect(TrackEvent)(input);
|
|
747
|
+
const eventId = event.eventId ?? randomUUID();
|
|
748
|
+
const category = event.category ?? "analytics";
|
|
749
|
+
if (!storage)
|
|
750
|
+
return yield* new EventsPersistenceError({
|
|
751
|
+
operation: "persistence-disabled"
|
|
752
|
+
});
|
|
753
|
+
const receivedAt = yield* DateTime2.now;
|
|
754
|
+
const now = DateTime2.toEpochMillis(receivedAt);
|
|
755
|
+
const request = yield* Effect7.serviceOption(HttpServerRequest.HttpServerRequest);
|
|
756
|
+
const annotations = yield* References2.CurrentLogAnnotations;
|
|
757
|
+
const hasIdentity = [
|
|
758
|
+
"user.id",
|
|
759
|
+
"organization.id",
|
|
760
|
+
...actorAttributeKeys
|
|
761
|
+
].some((key) => annotations[key] !== undefined);
|
|
762
|
+
const identity = hasIdentity ? yield* Schema8.decodeUnknownEffect(EventIdentity)({
|
|
763
|
+
userId: annotations["user.id"],
|
|
764
|
+
organizationId: annotations["organization.id"]
|
|
765
|
+
}) : event.identity;
|
|
766
|
+
if (category === "audit") {
|
|
767
|
+
yield* Schema8.decodeUnknownEffect(AuditAttribution)(annotations);
|
|
768
|
+
}
|
|
769
|
+
const attributes = {};
|
|
770
|
+
for (const [key, value] of Object.entries(event.properties ?? {})) {
|
|
771
|
+
const name = key.startsWith("app.") ? key : `app.${key}`;
|
|
772
|
+
if (!reservedBrowserAttribute(name))
|
|
773
|
+
attributes[name] = value;
|
|
774
|
+
}
|
|
775
|
+
Object.assign(attributes, identityAttributes(identity));
|
|
776
|
+
Object.assign(attributes, Object.fromEntries(Object.entries(annotations).filter(([key]) => key !== "user.full_name" && key !== "user.name" && key !== "user.image" && key !== "app.user.image")));
|
|
777
|
+
attributes["log.record.uid"] = eventId;
|
|
778
|
+
if (event.category === "audit") {
|
|
779
|
+
attributes["app.audit.target.id"] = event.target.id;
|
|
780
|
+
attributes["app.audit.target.name"] = event.target.name;
|
|
781
|
+
attributes["app.audit.target.type"] = event.target.type;
|
|
782
|
+
}
|
|
783
|
+
attributes["app.event.schema.version"] = "1";
|
|
784
|
+
attributes["app.event.type"] = "track";
|
|
785
|
+
attributes["app.event.source"] = "server";
|
|
786
|
+
attributes["app.event.category"] = category;
|
|
787
|
+
const span = yield* Effect7.currentSpan.pipe(Effect7.option);
|
|
788
|
+
const location = Option5.isSome(request) ? yield* resolveGeolocation(request.value).pipe(Effect7.mapError(() => new EventsPersistenceError({ operation: "geolocation" }))) : null;
|
|
789
|
+
const entry = {
|
|
790
|
+
eventName: event.name,
|
|
791
|
+
timeUnixNano: (BigInt(event.timestamp ? DateTime2.toEpochMillis(event.timestamp) : now) * 1000000n).toString(),
|
|
792
|
+
observedTimeUnixNano: (BigInt(now) * 1000000n).toString()
|
|
793
|
+
};
|
|
794
|
+
return yield* Effect7.gen(function* () {
|
|
795
|
+
const requestContext = Option5.isSome(request) ? yield* resolveRequestContext(request.value, receivedAt, location) : {};
|
|
796
|
+
const validated = yield* Schema8.decodeUnknownEffect(EventLogRecord)({
|
|
797
|
+
...entry,
|
|
798
|
+
attributes: OtlpResource3.entriesToAttributes(Object.entries({ ...requestContext, ...attributes })),
|
|
799
|
+
traceId: Option5.isSome(span) ? span.value.traceId : undefined,
|
|
800
|
+
spanId: Option5.isSome(span) ? span.value.spanId : undefined
|
|
801
|
+
});
|
|
802
|
+
return yield* storage.persist({
|
|
803
|
+
source: "server",
|
|
804
|
+
compareTimestamp: event.timestamp !== undefined,
|
|
805
|
+
record: validated,
|
|
806
|
+
now,
|
|
807
|
+
payload: {
|
|
808
|
+
resourceLogs: [
|
|
809
|
+
{
|
|
810
|
+
resource,
|
|
811
|
+
scopeLogs: [
|
|
812
|
+
{
|
|
813
|
+
scope: { name: "krakstack.application.events" },
|
|
814
|
+
logRecords: [validated]
|
|
815
|
+
}
|
|
816
|
+
]
|
|
817
|
+
}
|
|
818
|
+
]
|
|
819
|
+
}
|
|
820
|
+
});
|
|
821
|
+
}).pipe(storage.sql.withTransaction, Effect7.map(({ eventId, inserted }) => ({ eventId, inserted })), Effect7.mapError((error) => error._tag === "EventConflictError" ? error : new EventsPersistenceError({
|
|
822
|
+
operation: "track"
|
|
823
|
+
})));
|
|
824
|
+
});
|
|
825
|
+
const listAudit = Effect7.fn("Events.listAudit")(function* (input) {
|
|
826
|
+
const request = yield* Schema8.decodeUnknownEffect(ListAudit)(input);
|
|
827
|
+
if (!storage)
|
|
828
|
+
return yield* new EventsPersistenceError({
|
|
829
|
+
operation: "persistence-disabled"
|
|
830
|
+
});
|
|
831
|
+
const sql = storage.sql;
|
|
832
|
+
const text = (key) => sql.onDialectOrElse({
|
|
833
|
+
pg: () => sql`jsonb_path_query_first(payload_json, ${`$.resourceLogs[*].scopeLogs[*].logRecords[*].attributes[*] ? (@.key == ${JSON.stringify(key)}).value.stringValue`}::jsonpath) #>> '{}'`,
|
|
834
|
+
orElse: () => sql`(SELECT json_extract(attribute.value, '$.value.stringValue')
|
|
835
|
+
FROM json_each(payload_json, '$.resourceLogs') AS resource,
|
|
836
|
+
json_each(resource.value, '$.scopeLogs') AS scope,
|
|
837
|
+
json_each(scope.value, '$.logRecords') AS record,
|
|
838
|
+
json_each(record.value, '$.attributes') AS attribute
|
|
839
|
+
WHERE json_extract(attribute.value, '$.key') = ${key} LIMIT 1)`
|
|
840
|
+
});
|
|
841
|
+
const sortColumns = {
|
|
842
|
+
time: sql`occurred_at`,
|
|
843
|
+
eventName: sql`event_name`,
|
|
844
|
+
recordType: text("app.audit.target.type"),
|
|
845
|
+
record: text("app.audit.target.name"),
|
|
846
|
+
actorType: text("app.actor.type"),
|
|
847
|
+
actorId: text("app.actor.id")
|
|
848
|
+
};
|
|
849
|
+
const sort = yield* Effect7.forEach(request.sort ?? [], (part) => Effect7.gen(function* () {
|
|
850
|
+
const id = yield* Schema8.decodeUnknownEffect(AuditSortId)(part.id);
|
|
851
|
+
return sql`${sortColumns[id]} ${sql.literal(part.direction === "desc" ? "DESC" : "ASC")}`;
|
|
852
|
+
}));
|
|
853
|
+
const category = sql.onDialectOrElse({
|
|
854
|
+
pg: () => sql`jsonb_path_exists(payload_json, '$.resourceLogs[*].scopeLogs[*].logRecords[*].attributes[*] ? (@.key == "app.event.category" && @.value.stringValue == "audit")')`,
|
|
855
|
+
orElse: () => sql`EXISTS (
|
|
856
|
+
SELECT 1 FROM json_each(payload_json, '$.resourceLogs') AS resource,
|
|
857
|
+
json_each(resource.value, '$.scopeLogs') AS scope,
|
|
858
|
+
json_each(scope.value, '$.logRecords') AS record,
|
|
859
|
+
json_each(record.value, '$.attributes') AS attribute
|
|
860
|
+
WHERE json_extract(attribute.value, '$.key') = 'app.event.category'
|
|
861
|
+
AND json_extract(attribute.value, '$.value.stringValue') = 'audit'
|
|
862
|
+
)`
|
|
863
|
+
});
|
|
864
|
+
const search = request.globalFilter?.trim();
|
|
865
|
+
const filter = search ? sql`AND ${sql.or([
|
|
866
|
+
sql`LOWER(event_name) LIKE ${`%${search.toLowerCase()}%`}`,
|
|
867
|
+
...[
|
|
868
|
+
"app.audit.target.id",
|
|
869
|
+
"app.audit.target.name",
|
|
870
|
+
"app.audit.target.type",
|
|
871
|
+
"app.actor.id",
|
|
872
|
+
"app.actor.type",
|
|
873
|
+
"user.id"
|
|
874
|
+
].map((key) => sql`LOWER(${text(key)}) LIKE ${`%${search.toLowerCase()}%`}`)
|
|
875
|
+
])}` : sql``;
|
|
876
|
+
const predicate = sql`service_name = ${configuration.serviceName} AND organization_id = ${request.organizationId}
|
|
877
|
+
AND source = 'server' AND ${category} ${filter}`;
|
|
878
|
+
const total = yield* SqlSchema.findOne({
|
|
879
|
+
Request: ListAudit,
|
|
880
|
+
Result: AuditCount,
|
|
881
|
+
execute: () => sql`SELECT CAST(COUNT(*) AS INTEGER) AS total FROM events WHERE ${predicate}`
|
|
882
|
+
})(request);
|
|
883
|
+
const find = SqlSchema.findAll({
|
|
884
|
+
Request: ListAudit,
|
|
885
|
+
Result: StoredEventPayload,
|
|
886
|
+
execute: () => sql`
|
|
887
|
+
SELECT payload_json FROM events
|
|
888
|
+
WHERE ${predicate}
|
|
889
|
+
ORDER BY ${sql.join(", ", false)(sort.length ? [...sort, sql`event_id DESC`] : [sql`occurred_at DESC`, sql`event_id DESC`])}
|
|
890
|
+
LIMIT ${request.pageSize} OFFSET ${request.page * request.pageSize}
|
|
891
|
+
`
|
|
892
|
+
});
|
|
893
|
+
const rows = yield* find(request);
|
|
894
|
+
const data = yield* Effect7.forEach(rows, (row) => Schema8.decodeUnknownEffect(EventLogRecord)(row.payload_json.resourceLogs.flatMap((resource) => resource.scopeLogs.flatMap((scope) => scope.logRecords))[0]));
|
|
895
|
+
return {
|
|
896
|
+
data,
|
|
897
|
+
meta: {
|
|
898
|
+
page: request.page,
|
|
899
|
+
pageSize: request.pageSize,
|
|
900
|
+
total: total.total,
|
|
901
|
+
pageCount: Math.ceil(total.total / request.pageSize)
|
|
902
|
+
}
|
|
903
|
+
};
|
|
904
|
+
});
|
|
905
|
+
const process = Effect7.fnUntraced(function* (body) {
|
|
906
|
+
const request = yield* HttpServerRequest.HttpServerRequest;
|
|
907
|
+
const payload = yield* Schema8.decodeUnknownEffect(codec)(new TextDecoder().decode(body)).pipe(Effect7.mapError(() => new OtlpProcessingError({ status: 400 })));
|
|
908
|
+
const analyticsScopes = payload.resourceLogs.flatMap((resource) => resource.scopeLogs).filter((scope) => scope.scope?.name === "krakstack.application.events");
|
|
909
|
+
if (analyticsScopes.length === 0)
|
|
910
|
+
return { body, persisted: false };
|
|
911
|
+
if (request.headers.origin !== configuration.origin.origin || request.headers["sec-fetch-site"] === "cross-site") {
|
|
912
|
+
return yield* new OtlpProcessingError({ status: 403 });
|
|
913
|
+
}
|
|
914
|
+
const rawRecords = analyticsScopes.flatMap((scope) => scope.logRecords);
|
|
915
|
+
const records = yield* Schema8.decodeUnknownEffect(Schema8.Array(EventLogRecord).check(Schema8.isMinLength(1), Schema8.isMaxLength(100)))(rawRecords).pipe(Effect7.mapError(() => new OtlpProcessingError({ status: 400 })));
|
|
916
|
+
const now = yield* DateTime2.now;
|
|
917
|
+
const nowMillis = DateTime2.toEpochMillis(now);
|
|
918
|
+
for (const record of records) {
|
|
919
|
+
const timestamp = BigInt(record.timeUnixNano) / 1000000n;
|
|
920
|
+
if (timestamp < BigInt(nowMillis - 60 * 60 * 1000) || timestamp > BigInt(nowMillis + 60000) || textAttribute(record, "app.event.schema.version") !== "1" || Option5.isNone(Schema8.decodeUnknownOption(EventUuid)(textAttribute(record, "analytics.page_view.id"))) || Option5.isNone(Schema8.decodeUnknownOption(EventId)(textAttribute(record, "log.record.uid"))) || Option5.isNone(Schema8.decodeUnknownOption(BrowserEventPath)(textAttribute(record, "url.path")))) {
|
|
921
|
+
return yield* new OtlpProcessingError({ status: 400 });
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
const annotations = yield* References2.CurrentLogAnnotations;
|
|
925
|
+
const hasIdentity = [
|
|
926
|
+
"user.id",
|
|
927
|
+
"organization.id",
|
|
928
|
+
...actorAttributeKeys
|
|
929
|
+
].some((key) => annotations[key] !== undefined);
|
|
930
|
+
const trustedIdentity = yield* (hasIdentity ? Schema8.decodeUnknownEffect(EventIdentity)({
|
|
931
|
+
userId: annotations["user.id"],
|
|
932
|
+
organizationId: annotations["organization.id"]
|
|
933
|
+
}) : options.identity ? options.identity(request).pipe(Effect7.flatMap(Schema8.decodeUnknownEffect(Schema8.NullOr(EventIdentity)))) : Effect7.succeed(null)).pipe(Effect7.mapError(() => new OtlpProcessingError({ status: 503 })));
|
|
934
|
+
const trustedActor = actorAttributeKeys.some((key) => annotations[key] !== undefined) ? yield* Schema8.decodeUnknownEffect(RequestActorAttribution)(Object.fromEntries(actorAttributeKeys.filter((key) => annotations[key] !== undefined).map((key) => [key, annotations[key]]))).pipe(Effect7.mapError(() => new OtlpProcessingError({ status: 503 }))) : {};
|
|
935
|
+
const trustedAttributes = {
|
|
936
|
+
...identityAttributes(trustedIdentity),
|
|
937
|
+
...trustedActor
|
|
938
|
+
};
|
|
939
|
+
const location = yield* resolveGeolocation(request).pipe(Effect7.mapError(() => new OtlpProcessingError({ status: 503 })));
|
|
940
|
+
const ingest = Effect7.gen(function* () {
|
|
941
|
+
const requestContext = yield* resolveRequestContext(request, now, location);
|
|
942
|
+
let index = 0;
|
|
943
|
+
const resourceLogs = payload.resourceLogs.map((resource) => ({
|
|
944
|
+
...resource,
|
|
945
|
+
scopeLogs: resource.scopeLogs.map((scope) => scope.scope?.name !== "krakstack.application.events" ? scope : {
|
|
946
|
+
...scope,
|
|
947
|
+
logRecords: scope.logRecords.map(() => {
|
|
948
|
+
const record = records[index++];
|
|
949
|
+
return {
|
|
950
|
+
...record,
|
|
951
|
+
observedTimeUnixNano: (BigInt(nowMillis) * 1000000n).toString(),
|
|
952
|
+
attributes: [
|
|
953
|
+
...record.attributes.filter(({ key }) => (contextKeys.has(key) || key.startsWith("app.")) && !reservedBrowserAttribute(key) && !key.startsWith("app.event.")),
|
|
954
|
+
{
|
|
955
|
+
key: "app.event.type",
|
|
956
|
+
value: {
|
|
957
|
+
stringValue: record.eventName === "browser.page_view" ? "page" : "track"
|
|
958
|
+
}
|
|
959
|
+
},
|
|
960
|
+
...OtlpResource3.entriesToAttributes(Object.entries({
|
|
961
|
+
...requestContext,
|
|
962
|
+
...trustedAttributes,
|
|
963
|
+
"app.event.category": "analytics",
|
|
964
|
+
"app.event.source": "browser",
|
|
965
|
+
"app.event.schema.version": "1"
|
|
966
|
+
}))
|
|
967
|
+
]
|
|
968
|
+
};
|
|
969
|
+
})
|
|
970
|
+
})
|
|
971
|
+
}));
|
|
972
|
+
const persistedRecords = new Map;
|
|
973
|
+
if (storage) {
|
|
974
|
+
for (const resource of resourceLogs) {
|
|
975
|
+
for (const scope of resource.scopeLogs) {
|
|
976
|
+
if (scope.scope?.name !== "krakstack.application.events")
|
|
977
|
+
continue;
|
|
978
|
+
for (const raw of scope.logRecords) {
|
|
979
|
+
const record = yield* Schema8.decodeUnknownEffect(EventLogRecord)(raw);
|
|
980
|
+
const persisted = yield* storage.persist({
|
|
981
|
+
source: "browser",
|
|
982
|
+
record,
|
|
983
|
+
now: nowMillis,
|
|
984
|
+
payload: {
|
|
985
|
+
...payload,
|
|
986
|
+
resourceLogs: [
|
|
987
|
+
{
|
|
988
|
+
...resource,
|
|
989
|
+
scopeLogs: [{ ...scope, logRecords: [record] }]
|
|
990
|
+
}
|
|
991
|
+
]
|
|
992
|
+
}
|
|
993
|
+
});
|
|
994
|
+
persistedRecords.set(raw, persisted.record);
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
const encoded = yield* Schema8.encodeEffect(codec)({
|
|
1000
|
+
...payload,
|
|
1001
|
+
resourceLogs: resourceLogs.map((resource) => ({
|
|
1002
|
+
...resource,
|
|
1003
|
+
scopeLogs: resource.scopeLogs.map((scope) => ({
|
|
1004
|
+
...scope,
|
|
1005
|
+
logRecords: scope.logRecords.map((raw) => persistedRecords.get(raw) ?? raw)
|
|
1006
|
+
}))
|
|
1007
|
+
}))
|
|
1008
|
+
});
|
|
1009
|
+
const persisted = Boolean(storage) && payload.resourceLogs.every((resource) => resource.scopeLogs.every((scope) => scope.scope?.name === "krakstack.application.events" || scope.logRecords.length === 0));
|
|
1010
|
+
return { body: new TextEncoder().encode(encoded), persisted };
|
|
1011
|
+
});
|
|
1012
|
+
return yield* (storage ? ingest.pipe(storage.sql.withTransaction) : ingest).pipe(Effect7.mapError((error) => new OtlpProcessingError({
|
|
1013
|
+
status: error._tag === "EventConflictError" ? 409 : 503
|
|
1014
|
+
})));
|
|
1015
|
+
});
|
|
1016
|
+
return { process, track, listAudit };
|
|
1017
|
+
})
|
|
1018
|
+
}) {
|
|
1019
|
+
static baseLayer = (options) => Layer3.effect(this, this.make(options));
|
|
1020
|
+
static layer = (options) => this.baseLayer(options).pipe(Layer3.provide(Layer3.effectDiscard(Effect7.gen(function* () {
|
|
1021
|
+
const client = yield* Effect7.serviceOption(SqlClient2.SqlClient);
|
|
1022
|
+
if (Option5.isNone(client))
|
|
1023
|
+
return;
|
|
1024
|
+
if (!client.value.onDialectOrElse({
|
|
1025
|
+
pg: () => true,
|
|
1026
|
+
sqlite: () => true,
|
|
1027
|
+
orElse: () => false
|
|
1028
|
+
})) {
|
|
1029
|
+
return yield* new EventsConfigurationError({
|
|
1030
|
+
message: "Events supports PostgreSQL and SQLite"
|
|
1031
|
+
});
|
|
1032
|
+
}
|
|
1033
|
+
yield* migrateEvents.pipe(Effect7.provideService(SqlClient2.SqlClient, client.value));
|
|
1034
|
+
}))));
|
|
1035
|
+
static ingestionLayer = Layer3.effect(OtlpLogsProcessor, Events);
|
|
1036
|
+
}
|
|
1037
|
+
export {
|
|
1038
|
+
AuditTarget,
|
|
1039
|
+
EventLogRecord,
|
|
1040
|
+
Events,
|
|
1041
|
+
EventsConfigurationError,
|
|
1042
|
+
ListAudit,
|
|
1043
|
+
SESSION_TIMEOUT_MS,
|
|
1044
|
+
TrackEvent,
|
|
1045
|
+
dailyVisitorId
|
|
1046
|
+
};
|