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