@krak-stack/registry 0.1.52 → 0.1.54
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 +21 -0
- package/dist/services/events/browser.d.ts +5 -1
- package/dist/services/events/browser.js +287 -172
- package/dist/services/events/client/tracking-notice.d.ts +24 -0
- package/dist/services/events/client/tracking-notice.js +480 -0
- package/dist/services/events/index.d.ts +13 -7
- package/dist/services/events/index.js +175 -90
- package/dist/services/events/schema.js +10 -0
- package/dist/services/opentelemetry/api.js +13 -1
- package/dist/services/opentelemetry/browser.d.ts +8 -0
- package/dist/services/opentelemetry/browser.js +36 -11
- package/dist/services/opentelemetry/consent.d.ts +21 -0
- package/dist/services/opentelemetry/events.d.ts +2 -0
- package/dist/services/opentelemetry/index.js +13 -1
- package/dist/services/opentelemetry/schema.d.ts +11 -0
- package/dist/services/opentelemetry/web-vitals.d.ts +3 -2
- package/dist/services/opentelemetry/web-vitals.js +161 -58
- package/package.json +5 -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 Effect8,
|
|
7
8
|
Layer as Layer3,
|
|
8
|
-
Option as
|
|
9
|
+
Option as Option6,
|
|
9
10
|
Predicate,
|
|
10
11
|
Redacted,
|
|
11
12
|
References as References2,
|
|
12
|
-
Schema as
|
|
13
|
+
Schema as Schema9
|
|
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";
|
|
@@ -55,6 +57,16 @@ import {
|
|
|
55
57
|
|
|
56
58
|
// ../../src/services/opentelemetry/schema.ts
|
|
57
59
|
import { Schema as Schema2 } from "effect";
|
|
60
|
+
var BrowserAnalyticsPreference = Schema2.Struct({
|
|
61
|
+
version: Schema2.String,
|
|
62
|
+
choice: Schema2.Literals(["accepted", "declined"]),
|
|
63
|
+
revision: Schema2.String,
|
|
64
|
+
issuedAt: Schema2.Finite,
|
|
65
|
+
expiresAt: Schema2.Finite
|
|
66
|
+
}).annotate({ identifier: "BrowserAnalyticsPreference" });
|
|
67
|
+
var BrowserPrivacySignals = Schema2.Struct({
|
|
68
|
+
globalPrivacyControl: Schema2.optional(Schema2.Boolean)
|
|
69
|
+
}).annotate({ identifier: "BrowserPrivacySignals" });
|
|
58
70
|
var BrowserWebVital = Schema2.Struct({
|
|
59
71
|
name: Schema2.Literals(["LCP", "INP", "CLS", "FCP", "TTFB"]),
|
|
60
72
|
id: Schema2.NonEmptyString.check(Schema2.isMaxLength(64)),
|
|
@@ -104,7 +116,9 @@ class OtlpEvents extends Context2.Service()("krakstack/opentelemetry/Events") {
|
|
|
104
116
|
label: "OtlpEvents",
|
|
105
117
|
body: (logRecords) => {
|
|
106
118
|
const scopes = new Map;
|
|
107
|
-
for (const { scopeName, ...record } of logRecords) {
|
|
119
|
+
for (const { scopeName, canExport, ...record } of logRecords) {
|
|
120
|
+
if (canExport && !canExport())
|
|
121
|
+
continue;
|
|
108
122
|
const name = scopeName ?? options.scopeName ?? "krakstack.events";
|
|
109
123
|
const records = scopes.get(name);
|
|
110
124
|
if (records)
|
|
@@ -496,15 +510,15 @@ var cloudflareGeolocation = (headers) => ({
|
|
|
496
510
|
region: Option4.getOrUndefined(Schema7.decodeUnknownOption(EventRegion)(headers["cf-region-code"])),
|
|
497
511
|
city: Option4.getOrUndefined(Schema7.decodeUnknownOption(EventCity)(headers["cf-ipcity"]))
|
|
498
512
|
});
|
|
499
|
-
var geolocationAttributes = (
|
|
513
|
+
var geolocationAttributes = (location2) => {
|
|
500
514
|
const attributes = {};
|
|
501
|
-
if (
|
|
502
|
-
attributes["geo.country.iso_code"] =
|
|
503
|
-
if (
|
|
504
|
-
attributes["geo.region.iso_code"] = `${
|
|
515
|
+
if (location2?.country) {
|
|
516
|
+
attributes["geo.country.iso_code"] = location2.country;
|
|
517
|
+
if (location2.region)
|
|
518
|
+
attributes["geo.region.iso_code"] = `${location2.country}-${location2.region}`;
|
|
505
519
|
}
|
|
506
|
-
if (
|
|
507
|
-
attributes["geo.locality.name"] =
|
|
520
|
+
if (location2?.city)
|
|
521
|
+
attributes["geo.locality.name"] = location2.city;
|
|
508
522
|
return attributes;
|
|
509
523
|
};
|
|
510
524
|
var deviceContext = (userAgent) => {
|
|
@@ -555,6 +569,25 @@ var migrateEvents = Migrator.make({})({
|
|
|
555
569
|
table: "events_migrations"
|
|
556
570
|
});
|
|
557
571
|
|
|
572
|
+
// ../../src/services/opentelemetry/consent.ts
|
|
573
|
+
import { Effect as Effect7, Option as Option5, Schema as Schema8 } from "effect";
|
|
574
|
+
var ANALYTICS_CONSENT_COOKIE = "krakstack_analytics_consent";
|
|
575
|
+
var ANALYTICS_NOTICE_VERSION = "1";
|
|
576
|
+
var lifetime = 180 * 24 * 60 * 60 * 1000;
|
|
577
|
+
var codec = Schema8.StringFromUriComponent.pipe(Schema8.decodeTo(Schema8.fromJsonString(BrowserAnalyticsPreference)));
|
|
578
|
+
var readCookie = (cookie) => cookie.split(";").map((part) => part.trim()).find((part) => part.startsWith(`${ANALYTICS_CONSENT_COOKIE}=`))?.slice(ANALYTICS_CONSENT_COOKIE.length + 1);
|
|
579
|
+
var analyticsPreference = (cookie, now = Date.now()) => {
|
|
580
|
+
const value = readCookie(cookie);
|
|
581
|
+
if (!value)
|
|
582
|
+
return;
|
|
583
|
+
const decoded = Schema8.decodeUnknownOption(codec)(value);
|
|
584
|
+
if (Option5.isNone(decoded))
|
|
585
|
+
return;
|
|
586
|
+
const preference = decoded.value;
|
|
587
|
+
return preference.version === ANALYTICS_NOTICE_VERSION && preference.issuedAt <= now && preference.expiresAt > now && preference.expiresAt - preference.issuedAt <= lifetime ? preference : undefined;
|
|
588
|
+
};
|
|
589
|
+
var hasAnalyticsConsent = (cookie, headers = {}) => analyticsPreference(cookie)?.choice === "accepted" && headers.dnt !== "1" && headers.dnt !== "yes" && headers["sec-gpc"] !== "1";
|
|
590
|
+
|
|
558
591
|
// ../../src/services/events/index.ts
|
|
559
592
|
var SESSION_TIMEOUT_MS = 30 * 60 * 1000;
|
|
560
593
|
var identityAttributes = (identity) => {
|
|
@@ -574,19 +607,19 @@ var actorAttributeKeys = [
|
|
|
574
607
|
"user.roles"
|
|
575
608
|
];
|
|
576
609
|
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 =
|
|
578
|
-
serviceName:
|
|
579
|
-
origin:
|
|
580
|
-
geolocation:
|
|
581
|
-
|
|
582
|
-
|
|
610
|
+
var Configuration = Schema9.Struct({
|
|
611
|
+
serviceName: Schema9.NonEmptyString,
|
|
612
|
+
origin: Schema9.URLFromString.check(Schema9.makeFilter((url) => (url.protocol === "https:" || url.protocol === "http:") && !url.username && !url.password && url.pathname === "/" && !url.search && !url.hash || "Expected an HTTP origin")),
|
|
613
|
+
geolocation: Schema9.optional(Schema9.Union([
|
|
614
|
+
Schema9.Literal("cloudflare"),
|
|
615
|
+
Schema9.declare((value) => Predicate.isFunction(value))
|
|
583
616
|
])),
|
|
584
|
-
secret:
|
|
617
|
+
secret: Schema9.String.check(Schema9.isMinLength(32))
|
|
585
618
|
}).annotate({ identifier: "EventsConfiguration" });
|
|
586
619
|
|
|
587
|
-
class EventsConfigurationError extends
|
|
620
|
+
class EventsConfigurationError extends Schema9.TaggedError()("EventsConfigurationError", { message: Schema9.String }) {
|
|
588
621
|
}
|
|
589
|
-
var
|
|
622
|
+
var codec2 = Schema9.fromJsonString(OtlpLogs);
|
|
590
623
|
var textAttribute = (record, key) => {
|
|
591
624
|
const value = record.attributes.find((attribute) => attribute.key === key)?.value;
|
|
592
625
|
return value && "stringValue" in value ? value.stringValue : undefined;
|
|
@@ -616,27 +649,41 @@ var eventContent = (record, source, compareTimestamp = source === "browser") =>
|
|
|
616
649
|
"app.event.schema.version"
|
|
617
650
|
].includes(key) || key === "user.id" || key === "organization.id").sort((a, b) => a.key.localeCompare(b.key))
|
|
618
651
|
});
|
|
619
|
-
var dailyVisitorId = (
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
652
|
+
var dailyVisitorId = Effect8.fnUntraced(function* (input) {
|
|
653
|
+
const crypto2 = yield* Crypto.Crypto;
|
|
654
|
+
const encoder = new TextEncoder;
|
|
655
|
+
const salt = yield* crypto2.digest("SHA-256", encoder.encode(JSON.stringify([
|
|
656
|
+
"analytics.visitor.salt.v2",
|
|
657
|
+
Redacted.value(input.secret),
|
|
658
|
+
input.serviceName,
|
|
659
|
+
input.day
|
|
660
|
+
])));
|
|
661
|
+
const digest = yield* crypto2.digest("SHA-256", encoder.encode(JSON.stringify([
|
|
662
|
+
"analytics.visitor.v2",
|
|
663
|
+
input.serviceName,
|
|
664
|
+
input.day,
|
|
665
|
+
input.ip,
|
|
666
|
+
input.userAgent,
|
|
667
|
+
Hex.encode(salt)
|
|
668
|
+
])));
|
|
669
|
+
return Hex.encode(digest);
|
|
670
|
+
});
|
|
626
671
|
|
|
627
672
|
class Events extends Context4.Service()("krakstack/events/Events", {
|
|
628
|
-
make: (options) =>
|
|
673
|
+
make: (options) => Effect8.gen(function* () {
|
|
674
|
+
const crypto2 = yield* Crypto.Crypto;
|
|
629
675
|
const telemetry = yield* Otlp;
|
|
676
|
+
const exporter = yield* OtlpEvents;
|
|
630
677
|
const resource = options.serviceName ? yield* OtlpResource3.fromConfig({ serviceName: options.serviceName }) : yield* telemetry.resource;
|
|
631
|
-
const configuration = yield*
|
|
678
|
+
const configuration = yield* Schema9.decodeUnknownEffect(Configuration)({
|
|
632
679
|
...options,
|
|
633
680
|
serviceName: OtlpResource3.serviceNameUnsafe(resource),
|
|
634
681
|
secret: Redacted.value(options.secret)
|
|
635
|
-
}).pipe(
|
|
682
|
+
}).pipe(Effect8.mapError(() => new EventsConfigurationError({
|
|
636
683
|
message: "Events requires an OTel service name, HTTP origin, and server secret of at least 32 characters"
|
|
637
684
|
})));
|
|
638
|
-
const client = yield*
|
|
639
|
-
const storage =
|
|
685
|
+
const client = yield* Effect8.serviceOption(SqlClient2.SqlClient);
|
|
686
|
+
const storage = Option6.isSome(client) ? yield* Effect8.gen(function* () {
|
|
640
687
|
const sql = client.value.withoutTransforms();
|
|
641
688
|
if (!sql.onDialectOrElse({
|
|
642
689
|
pg: () => true,
|
|
@@ -677,10 +724,10 @@ class Events extends Context4.Service()("krakstack/events/Events", {
|
|
|
677
724
|
ON CONFLICT (service_name, source, event_id) DO NOTHING RETURNING event_id
|
|
678
725
|
`
|
|
679
726
|
});
|
|
680
|
-
const persist =
|
|
727
|
+
const persist = Effect8.fnUntraced(function* (input) {
|
|
681
728
|
const { record, payload, now, source } = input;
|
|
682
729
|
const eventId = textAttribute(record, "log.record.uid");
|
|
683
|
-
const payloadJson = yield*
|
|
730
|
+
const payloadJson = yield* Schema9.encodeEffect(codec2)(payload);
|
|
684
731
|
const inserted = yield* insertEvent({
|
|
685
732
|
source,
|
|
686
733
|
event_id: eventId,
|
|
@@ -694,10 +741,10 @@ class Events extends Context4.Service()("krakstack/events/Events", {
|
|
|
694
741
|
anonymous_id: textAttribute(record, "analytics.anonymous_id") ?? null,
|
|
695
742
|
payload_json: payloadJson
|
|
696
743
|
});
|
|
697
|
-
if (
|
|
744
|
+
if (Option6.isSome(inserted))
|
|
698
745
|
return { eventId, inserted: true, record };
|
|
699
746
|
const existing = yield* existingEvent({ source, eventId });
|
|
700
|
-
const original = yield*
|
|
747
|
+
const original = yield* Schema9.decodeUnknownEffect(EventLogRecord)(existing.payload_json.resourceLogs[0]?.scopeLogs[0]?.logRecords[0]);
|
|
701
748
|
const identityChanged = source === "browser" && ["user.id", "organization.id"].some((key) => textAttribute(original, key) !== textAttribute(record, key));
|
|
702
749
|
if (identityChanged || eventContent(original, source, input.compareTimestamp) !== eventContent(record, source, input.compareTimestamp)) {
|
|
703
750
|
return yield* new EventConflictError({ eventId });
|
|
@@ -711,24 +758,24 @@ class Events extends Context4.Service()("krakstack/events/Events", {
|
|
|
711
758
|
lockVisitor
|
|
712
759
|
};
|
|
713
760
|
}) : undefined;
|
|
714
|
-
const resolveGeolocation =
|
|
715
|
-
const
|
|
716
|
-
return yield*
|
|
717
|
-
},
|
|
718
|
-
const resolveRequestContext =
|
|
761
|
+
const resolveGeolocation = Effect8.fnUntraced(function* (request) {
|
|
762
|
+
const location2 = configuration.geolocation === "cloudflare" ? cloudflareGeolocation(request.headers) : configuration.geolocation ? yield* configuration.geolocation(request) : null;
|
|
763
|
+
return yield* Schema9.decodeUnknownEffect(Schema9.NullOr(EventGeolocation))(location2);
|
|
764
|
+
}, Effect8.mapError(() => new EventGeolocationError({})));
|
|
765
|
+
const resolveRequestContext = Effect8.fnUntraced(function* (request, now, location2) {
|
|
719
766
|
const userAgent = request.headers["user-agent"]?.slice(0, 2048) ?? "";
|
|
720
|
-
const visitorId =
|
|
767
|
+
const visitorId = location2?.ip && userAgent ? yield* dailyVisitorId({
|
|
721
768
|
serviceName: configuration.serviceName,
|
|
722
769
|
secret: options.secret,
|
|
723
|
-
ip:
|
|
770
|
+
ip: location2.ip,
|
|
724
771
|
userAgent,
|
|
725
772
|
day: DateTime2.formatIsoDate(now)
|
|
726
|
-
}) : undefined;
|
|
773
|
+
}).pipe(Effect8.provideService(Crypto.Crypto, crypto2)) : undefined;
|
|
727
774
|
let sessionId;
|
|
728
775
|
if (visitorId && storage) {
|
|
729
776
|
yield* storage.lockVisitor(visitorId);
|
|
730
777
|
const latest = yield* storage.latestSession({ visitorId });
|
|
731
|
-
sessionId =
|
|
778
|
+
sessionId = Option6.isSome(latest) && latest.value.received_at > DateTime2.toEpochMillis(now) - SESSION_TIMEOUT_MS ? latest.value.session_id : yield* crypto2.randomUUIDv7;
|
|
732
779
|
}
|
|
733
780
|
const identity = {};
|
|
734
781
|
if (visitorId)
|
|
@@ -737,34 +784,33 @@ class Events extends Context4.Service()("krakstack/events/Events", {
|
|
|
737
784
|
identity["session.id"] = sessionId;
|
|
738
785
|
return {
|
|
739
786
|
...deviceContext(userAgent),
|
|
740
|
-
...geolocationAttributes(
|
|
787
|
+
...geolocationAttributes(location2),
|
|
741
788
|
"analytics.identity.mode": visitorId ? "daily" : "unattributed",
|
|
742
789
|
...identity
|
|
743
790
|
};
|
|
744
791
|
});
|
|
745
|
-
const track =
|
|
746
|
-
const event = yield*
|
|
747
|
-
const eventId = event.eventId ??
|
|
792
|
+
const track = Effect8.fn("Events.track")(function* (input) {
|
|
793
|
+
const event = yield* Schema9.decodeUnknownEffect(TrackEvent)(input);
|
|
794
|
+
const eventId = event.eventId ?? (yield* crypto2.randomUUIDv7);
|
|
748
795
|
const category = event.category ?? "analytics";
|
|
749
|
-
if (!storage)
|
|
750
|
-
return yield* new EventsPersistenceError({
|
|
751
|
-
operation: "persistence-disabled"
|
|
752
|
-
});
|
|
753
796
|
const receivedAt = yield* DateTime2.now;
|
|
754
797
|
const now = DateTime2.toEpochMillis(receivedAt);
|
|
755
|
-
const request = yield*
|
|
798
|
+
const request = yield* Effect8.serviceOption(HttpServerRequest.HttpServerRequest);
|
|
756
799
|
const annotations = yield* References2.CurrentLogAnnotations;
|
|
800
|
+
if (category === "analytics" && options.requireConsent && (Option6.isNone(request) || !hasAnalyticsConsent(request.value.headers.cookie ?? "", request.value.headers))) {
|
|
801
|
+
return { eventId, inserted: false };
|
|
802
|
+
}
|
|
757
803
|
const hasIdentity = [
|
|
758
804
|
"user.id",
|
|
759
805
|
"organization.id",
|
|
760
806
|
...actorAttributeKeys
|
|
761
807
|
].some((key) => annotations[key] !== undefined);
|
|
762
|
-
const identity = hasIdentity ? yield*
|
|
808
|
+
const identity = hasIdentity ? yield* Schema9.decodeUnknownEffect(EventIdentity)({
|
|
763
809
|
userId: annotations["user.id"],
|
|
764
810
|
organizationId: annotations["organization.id"]
|
|
765
811
|
}) : event.identity;
|
|
766
812
|
if (category === "audit") {
|
|
767
|
-
yield*
|
|
813
|
+
yield* Schema9.decodeUnknownEffect(AuditAttribution)(annotations);
|
|
768
814
|
}
|
|
769
815
|
const attributes = {};
|
|
770
816
|
for (const [key, value] of Object.entries(event.properties ?? {})) {
|
|
@@ -784,22 +830,22 @@ class Events extends Context4.Service()("krakstack/events/Events", {
|
|
|
784
830
|
attributes["app.event.type"] = "track";
|
|
785
831
|
attributes["app.event.source"] = "server";
|
|
786
832
|
attributes["app.event.category"] = category;
|
|
787
|
-
const span = yield*
|
|
788
|
-
const
|
|
833
|
+
const span = yield* Effect8.currentSpan.pipe(Effect8.option);
|
|
834
|
+
const location2 = Option6.isSome(request) && (!options.requireConsent || hasAnalyticsConsent(request.value.headers.cookie ?? "", request.value.headers)) ? yield* resolveGeolocation(request.value).pipe(Effect8.mapError(() => new EventsPersistenceError({ operation: "geolocation" }))) : null;
|
|
789
835
|
const entry = {
|
|
790
836
|
eventName: event.name,
|
|
791
837
|
timeUnixNano: (BigInt(event.timestamp ? DateTime2.toEpochMillis(event.timestamp) : now) * 1000000n).toString(),
|
|
792
838
|
observedTimeUnixNano: (BigInt(now) * 1000000n).toString()
|
|
793
839
|
};
|
|
794
|
-
return yield*
|
|
795
|
-
const requestContext =
|
|
796
|
-
const validated = yield*
|
|
840
|
+
return yield* Effect8.gen(function* () {
|
|
841
|
+
const requestContext = Option6.isSome(request) && (!options.requireConsent || hasAnalyticsConsent(request.value.headers.cookie ?? "", request.value.headers)) ? yield* resolveRequestContext(request.value, receivedAt, location2) : {};
|
|
842
|
+
const validated = yield* Schema9.decodeUnknownEffect(EventLogRecord)({
|
|
797
843
|
...entry,
|
|
798
844
|
attributes: OtlpResource3.entriesToAttributes(Object.entries({ ...requestContext, ...attributes })),
|
|
799
|
-
traceId:
|
|
800
|
-
spanId:
|
|
845
|
+
traceId: Option6.isSome(span) ? span.value.traceId : undefined,
|
|
846
|
+
spanId: Option6.isSome(span) ? span.value.spanId : undefined
|
|
801
847
|
});
|
|
802
|
-
|
|
848
|
+
const result = storage ? yield* storage.persist({
|
|
803
849
|
source: "server",
|
|
804
850
|
compareTimestamp: event.timestamp !== undefined,
|
|
805
851
|
record: validated,
|
|
@@ -817,13 +863,25 @@ class Events extends Context4.Service()("krakstack/events/Events", {
|
|
|
817
863
|
}
|
|
818
864
|
]
|
|
819
865
|
}
|
|
820
|
-
});
|
|
821
|
-
|
|
866
|
+
}) : { eventId, inserted: false };
|
|
867
|
+
return {
|
|
868
|
+
...result,
|
|
869
|
+
attributes: { ...requestContext, ...attributes }
|
|
870
|
+
};
|
|
871
|
+
}).pipe((effect) => storage ? storage.sql.withTransaction(effect) : effect, Effect8.tap((result) => !storage || result.inserted ? Otlp.event(event.name, result.attributes, {
|
|
872
|
+
messageId: result.eventId,
|
|
873
|
+
timestamp: event.timestamp ?? receivedAt
|
|
874
|
+
}).pipe(Effect8.provideService(OtlpEvents, {
|
|
875
|
+
push: (record) => exporter.push({
|
|
876
|
+
...record,
|
|
877
|
+
scopeName: "krakstack.application.events"
|
|
878
|
+
})
|
|
879
|
+
}), Effect8.provideService(References2.CurrentLogAnnotations, {})) : Effect8.void), Effect8.map(({ eventId, inserted }) => ({ eventId, inserted })), Effect8.mapError((error) => error._tag === "EventConflictError" ? error : new EventsPersistenceError({
|
|
822
880
|
operation: "track"
|
|
823
881
|
})));
|
|
824
882
|
});
|
|
825
|
-
const listAudit =
|
|
826
|
-
const request = yield*
|
|
883
|
+
const listAudit = Effect8.fn("Events.listAudit")(function* (input) {
|
|
884
|
+
const request = yield* Schema9.decodeUnknownEffect(ListAudit)(input);
|
|
827
885
|
if (!storage)
|
|
828
886
|
return yield* new EventsPersistenceError({
|
|
829
887
|
operation: "persistence-disabled"
|
|
@@ -846,8 +904,8 @@ class Events extends Context4.Service()("krakstack/events/Events", {
|
|
|
846
904
|
actorType: text("app.actor.type"),
|
|
847
905
|
actorId: text("app.actor.id")
|
|
848
906
|
};
|
|
849
|
-
const sort = yield*
|
|
850
|
-
const id = yield*
|
|
907
|
+
const sort = yield* Effect8.forEach(request.sort ?? [], (part) => Effect8.gen(function* () {
|
|
908
|
+
const id = yield* Schema9.decodeUnknownEffect(AuditSortId)(part.id);
|
|
851
909
|
return sql`${sortColumns[id]} ${sql.literal(part.direction === "desc" ? "DESC" : "ASC")}`;
|
|
852
910
|
}));
|
|
853
911
|
const category = sql.onDialectOrElse({
|
|
@@ -891,7 +949,7 @@ class Events extends Context4.Service()("krakstack/events/Events", {
|
|
|
891
949
|
`
|
|
892
950
|
});
|
|
893
951
|
const rows = yield* find(request);
|
|
894
|
-
const data = yield*
|
|
952
|
+
const data = yield* Effect8.forEach(rows, (row) => Schema9.decodeUnknownEffect(EventLogRecord)(row.payload_json.resourceLogs.flatMap((resource) => resource.scopeLogs.flatMap((scope) => scope.logRecords))[0]));
|
|
895
953
|
return {
|
|
896
954
|
data,
|
|
897
955
|
meta: {
|
|
@@ -902,9 +960,30 @@ class Events extends Context4.Service()("krakstack/events/Events", {
|
|
|
902
960
|
}
|
|
903
961
|
};
|
|
904
962
|
});
|
|
905
|
-
const process =
|
|
963
|
+
const process = Effect8.fnUntraced(function* (body) {
|
|
906
964
|
const request = yield* HttpServerRequest.HttpServerRequest;
|
|
907
|
-
|
|
965
|
+
let payload = yield* Schema9.decodeUnknownEffect(codec2)(new TextDecoder().decode(body)).pipe(Effect8.mapError(() => new OtlpProcessingError({ status: 400 })));
|
|
966
|
+
if (options.requireConsent && !hasAnalyticsConsent(request.headers.cookie ?? "", request.headers)) {
|
|
967
|
+
payload = {
|
|
968
|
+
...payload,
|
|
969
|
+
resourceLogs: payload.resourceLogs.map((resource) => ({
|
|
970
|
+
...resource,
|
|
971
|
+
scopeLogs: resource.scopeLogs.filter((scope) => scope.scope?.name !== "krakstack.application.events").map((scope) => ({
|
|
972
|
+
...scope,
|
|
973
|
+
logRecords: scope.logRecords.filter((record) => {
|
|
974
|
+
const parsed = Schema9.decodeUnknownOption(Schema9.Struct({
|
|
975
|
+
eventName: Schema9.optional(Schema9.String)
|
|
976
|
+
}))(record);
|
|
977
|
+
return Option6.isNone(parsed) || parsed.value.eventName !== "browser.web_vital";
|
|
978
|
+
})
|
|
979
|
+
}))
|
|
980
|
+
}))
|
|
981
|
+
};
|
|
982
|
+
return {
|
|
983
|
+
body: new TextEncoder().encode(yield* Schema9.encodeEffect(codec2)(payload).pipe(Effect8.mapError(() => new OtlpProcessingError({ status: 503 })))),
|
|
984
|
+
persisted: false
|
|
985
|
+
};
|
|
986
|
+
}
|
|
908
987
|
const analyticsScopes = payload.resourceLogs.flatMap((resource) => resource.scopeLogs).filter((scope) => scope.scope?.name === "krakstack.application.events");
|
|
909
988
|
if (analyticsScopes.length === 0)
|
|
910
989
|
return { body, persisted: false };
|
|
@@ -912,12 +991,12 @@ class Events extends Context4.Service()("krakstack/events/Events", {
|
|
|
912
991
|
return yield* new OtlpProcessingError({ status: 403 });
|
|
913
992
|
}
|
|
914
993
|
const rawRecords = analyticsScopes.flatMap((scope) => scope.logRecords);
|
|
915
|
-
const records = yield*
|
|
994
|
+
const records = yield* Schema9.decodeUnknownEffect(Schema9.Array(EventLogRecord).check(Schema9.isMinLength(1), Schema9.isMaxLength(100)))(rawRecords).pipe(Effect8.mapError(() => new OtlpProcessingError({ status: 400 })));
|
|
916
995
|
const now = yield* DateTime2.now;
|
|
917
996
|
const nowMillis = DateTime2.toEpochMillis(now);
|
|
918
997
|
for (const record of records) {
|
|
919
998
|
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" ||
|
|
999
|
+
if (timestamp < BigInt(nowMillis - 60 * 60 * 1000) || timestamp > BigInt(nowMillis + 60000) || textAttribute(record, "app.event.schema.version") !== "1" || Option6.isNone(Schema9.decodeUnknownOption(EventUuid)(textAttribute(record, "analytics.page_view.id"))) || Option6.isNone(Schema9.decodeUnknownOption(EventId)(textAttribute(record, "log.record.uid"))) || Option6.isNone(Schema9.decodeUnknownOption(BrowserEventPath)(textAttribute(record, "url.path")))) {
|
|
921
1000
|
return yield* new OtlpProcessingError({ status: 400 });
|
|
922
1001
|
}
|
|
923
1002
|
}
|
|
@@ -927,18 +1006,18 @@ class Events extends Context4.Service()("krakstack/events/Events", {
|
|
|
927
1006
|
"organization.id",
|
|
928
1007
|
...actorAttributeKeys
|
|
929
1008
|
].some((key) => annotations[key] !== undefined);
|
|
930
|
-
const trustedIdentity = yield* (hasIdentity ?
|
|
1009
|
+
const trustedIdentity = yield* (hasIdentity ? Schema9.decodeUnknownEffect(EventIdentity)({
|
|
931
1010
|
userId: annotations["user.id"],
|
|
932
1011
|
organizationId: annotations["organization.id"]
|
|
933
|
-
}) : options.identity ? options.identity(request).pipe(
|
|
934
|
-
const trustedActor = actorAttributeKeys.some((key) => annotations[key] !== undefined) ? yield*
|
|
1012
|
+
}) : options.identity ? options.identity(request).pipe(Effect8.flatMap(Schema9.decodeUnknownEffect(Schema9.NullOr(EventIdentity)))) : Effect8.succeed(null)).pipe(Effect8.mapError(() => new OtlpProcessingError({ status: 503 })));
|
|
1013
|
+
const trustedActor = actorAttributeKeys.some((key) => annotations[key] !== undefined) ? yield* Schema9.decodeUnknownEffect(RequestActorAttribution)(Object.fromEntries(actorAttributeKeys.filter((key) => annotations[key] !== undefined).map((key) => [key, annotations[key]]))).pipe(Effect8.mapError(() => new OtlpProcessingError({ status: 503 }))) : {};
|
|
935
1014
|
const trustedAttributes = {
|
|
936
1015
|
...identityAttributes(trustedIdentity),
|
|
937
1016
|
...trustedActor
|
|
938
1017
|
};
|
|
939
|
-
const
|
|
940
|
-
const ingest =
|
|
941
|
-
const requestContext = yield* resolveRequestContext(request, now,
|
|
1018
|
+
const location2 = yield* resolveGeolocation(request).pipe(Effect8.mapError(() => new OtlpProcessingError({ status: 503 })));
|
|
1019
|
+
const ingest = Effect8.gen(function* () {
|
|
1020
|
+
const requestContext = yield* resolveRequestContext(request, now, location2);
|
|
942
1021
|
let index = 0;
|
|
943
1022
|
const resourceLogs = payload.resourceLogs.map((resource) => ({
|
|
944
1023
|
...resource,
|
|
@@ -976,7 +1055,7 @@ class Events extends Context4.Service()("krakstack/events/Events", {
|
|
|
976
1055
|
if (scope.scope?.name !== "krakstack.application.events")
|
|
977
1056
|
continue;
|
|
978
1057
|
for (const raw of scope.logRecords) {
|
|
979
|
-
const record = yield*
|
|
1058
|
+
const record = yield* Schema9.decodeUnknownEffect(EventLogRecord)(raw);
|
|
980
1059
|
const persisted = yield* storage.persist({
|
|
981
1060
|
source: "browser",
|
|
982
1061
|
record,
|
|
@@ -996,7 +1075,7 @@ class Events extends Context4.Service()("krakstack/events/Events", {
|
|
|
996
1075
|
}
|
|
997
1076
|
}
|
|
998
1077
|
}
|
|
999
|
-
const encoded = yield*
|
|
1078
|
+
const encoded = yield* Schema9.encodeEffect(codec2)({
|
|
1000
1079
|
...payload,
|
|
1001
1080
|
resourceLogs: resourceLogs.map((resource) => ({
|
|
1002
1081
|
...resource,
|
|
@@ -1009,17 +1088,22 @@ class Events extends Context4.Service()("krakstack/events/Events", {
|
|
|
1009
1088
|
const persisted = Boolean(storage) && payload.resourceLogs.every((resource) => resource.scopeLogs.every((scope) => scope.scope?.name === "krakstack.application.events" || scope.logRecords.length === 0));
|
|
1010
1089
|
return { body: new TextEncoder().encode(encoded), persisted };
|
|
1011
1090
|
});
|
|
1012
|
-
return yield* (storage ? ingest.pipe(storage.sql.withTransaction) : ingest).pipe(
|
|
1091
|
+
return yield* (storage ? ingest.pipe(storage.sql.withTransaction) : ingest).pipe(Effect8.mapError((error) => new OtlpProcessingError({
|
|
1013
1092
|
status: error._tag === "EventConflictError" ? 409 : 503
|
|
1014
1093
|
})));
|
|
1015
1094
|
});
|
|
1016
1095
|
return { process, track, listAudit };
|
|
1017
1096
|
})
|
|
1018
1097
|
}) {
|
|
1019
|
-
static
|
|
1020
|
-
|
|
1021
|
-
const
|
|
1022
|
-
|
|
1098
|
+
static baseLayerWith = (options = {}) => Layer3.effect(this, Effect8.gen(function* () {
|
|
1099
|
+
const origin = options.origin ?? (yield* Config2.URL("VITE_SITE_URL").pipe(Config2.map((url) => url.origin)));
|
|
1100
|
+
const secret = options.secret ?? (yield* Config2.Redacted("APP_SECRET"));
|
|
1101
|
+
return yield* Events.make({ ...options, origin, secret });
|
|
1102
|
+
}));
|
|
1103
|
+
static baseLayer = this.baseLayerWith();
|
|
1104
|
+
static layerWith = (options = {}) => this.baseLayerWith(options).pipe(Layer3.provide(Layer3.effectDiscard(Effect8.gen(function* () {
|
|
1105
|
+
const client = yield* Effect8.serviceOption(SqlClient2.SqlClient);
|
|
1106
|
+
if (Option6.isNone(client))
|
|
1023
1107
|
return;
|
|
1024
1108
|
if (!client.value.onDialectOrElse({
|
|
1025
1109
|
pg: () => true,
|
|
@@ -1030,8 +1114,9 @@ class Events extends Context4.Service()("krakstack/events/Events", {
|
|
|
1030
1114
|
message: "Events supports PostgreSQL and SQLite"
|
|
1031
1115
|
});
|
|
1032
1116
|
}
|
|
1033
|
-
yield* migrateEvents.pipe(
|
|
1117
|
+
yield* migrateEvents.pipe(Effect8.provideService(SqlClient2.SqlClient, client.value));
|
|
1034
1118
|
}))));
|
|
1119
|
+
static layer = this.layerWith();
|
|
1035
1120
|
static ingestionLayer = Layer3.effect(OtlpLogsProcessor, Events);
|
|
1036
1121
|
}
|
|
1037
1122
|
export {
|
|
@@ -3,6 +3,16 @@ import { Effect as Effect2, Option as Option2, Schema as Schema3 } from "effect"
|
|
|
3
3
|
|
|
4
4
|
// ../../src/services/opentelemetry/schema.ts
|
|
5
5
|
import { Schema } from "effect";
|
|
6
|
+
var BrowserAnalyticsPreference = Schema.Struct({
|
|
7
|
+
version: Schema.String,
|
|
8
|
+
choice: Schema.Literals(["accepted", "declined"]),
|
|
9
|
+
revision: Schema.String,
|
|
10
|
+
issuedAt: Schema.Finite,
|
|
11
|
+
expiresAt: Schema.Finite
|
|
12
|
+
}).annotate({ identifier: "BrowserAnalyticsPreference" });
|
|
13
|
+
var BrowserPrivacySignals = Schema.Struct({
|
|
14
|
+
globalPrivacyControl: Schema.optional(Schema.Boolean)
|
|
15
|
+
}).annotate({ identifier: "BrowserPrivacySignals" });
|
|
6
16
|
var BrowserWebVital = Schema.Struct({
|
|
7
17
|
name: Schema.Literals(["LCP", "INP", "CLS", "FCP", "TTFB"]),
|
|
8
18
|
id: Schema.NonEmptyString.check(Schema.isMaxLength(64)),
|
|
@@ -40,6 +40,16 @@ import {
|
|
|
40
40
|
|
|
41
41
|
// ../../src/services/opentelemetry/schema.ts
|
|
42
42
|
import { Schema } from "effect";
|
|
43
|
+
var BrowserAnalyticsPreference = Schema.Struct({
|
|
44
|
+
version: Schema.String,
|
|
45
|
+
choice: Schema.Literals(["accepted", "declined"]),
|
|
46
|
+
revision: Schema.String,
|
|
47
|
+
issuedAt: Schema.Finite,
|
|
48
|
+
expiresAt: Schema.Finite
|
|
49
|
+
}).annotate({ identifier: "BrowserAnalyticsPreference" });
|
|
50
|
+
var BrowserPrivacySignals = Schema.Struct({
|
|
51
|
+
globalPrivacyControl: Schema.optional(Schema.Boolean)
|
|
52
|
+
}).annotate({ identifier: "BrowserPrivacySignals" });
|
|
43
53
|
var BrowserWebVital = Schema.Struct({
|
|
44
54
|
name: Schema.Literals(["LCP", "INP", "CLS", "FCP", "TTFB"]),
|
|
45
55
|
id: Schema.NonEmptyString.check(Schema.isMaxLength(64)),
|
|
@@ -89,7 +99,9 @@ class OtlpEvents extends Context.Service()("krakstack/opentelemetry/Events") {
|
|
|
89
99
|
label: "OtlpEvents",
|
|
90
100
|
body: (logRecords) => {
|
|
91
101
|
const scopes = new Map;
|
|
92
|
-
for (const { scopeName, ...record } of logRecords) {
|
|
102
|
+
for (const { scopeName, canExport, ...record } of logRecords) {
|
|
103
|
+
if (canExport && !canExport())
|
|
104
|
+
continue;
|
|
93
105
|
const name = scopeName ?? options.scopeName ?? "krakstack.events";
|
|
94
106
|
const records = scopes.get(name);
|
|
95
107
|
if (records)
|
|
@@ -2,6 +2,14 @@ import { Effect, Layer, Schema } from "effect";
|
|
|
2
2
|
import { type Otlp, OtlpExporter, OtlpLogger, OtlpMetrics, OtlpTracer } from "effect/observability";
|
|
3
3
|
import { OtlpEvents, type EventExportOptions } from "./events.js";
|
|
4
4
|
export type { EventAttributes, EventOptions } from "./schema.js";
|
|
5
|
+
/** Essential diagnostics omit arbitrary messages, functions, URL queries and directories. */
|
|
6
|
+
export declare const sanitizeBrowserException: (input: {
|
|
7
|
+
readonly type: string;
|
|
8
|
+
readonly stack?: string;
|
|
9
|
+
}) => {
|
|
10
|
+
message: string;
|
|
11
|
+
stack: string | undefined;
|
|
12
|
+
};
|
|
5
13
|
type OtlpOptions = Parameters<typeof Otlp.layerJson>[0];
|
|
6
14
|
type SignalOptions<Options> = Omit<Options, "url" | "resource" | "headers">;
|
|
7
15
|
export interface BrowserOtlpOptions {
|
|
@@ -28,6 +28,16 @@ import {
|
|
|
28
28
|
|
|
29
29
|
// ../../src/services/opentelemetry/schema.ts
|
|
30
30
|
import { Schema } from "effect";
|
|
31
|
+
var BrowserAnalyticsPreference = Schema.Struct({
|
|
32
|
+
version: Schema.String,
|
|
33
|
+
choice: Schema.Literals(["accepted", "declined"]),
|
|
34
|
+
revision: Schema.String,
|
|
35
|
+
issuedAt: Schema.Finite,
|
|
36
|
+
expiresAt: Schema.Finite
|
|
37
|
+
}).annotate({ identifier: "BrowserAnalyticsPreference" });
|
|
38
|
+
var BrowserPrivacySignals = Schema.Struct({
|
|
39
|
+
globalPrivacyControl: Schema.optional(Schema.Boolean)
|
|
40
|
+
}).annotate({ identifier: "BrowserPrivacySignals" });
|
|
31
41
|
var BrowserWebVital = Schema.Struct({
|
|
32
42
|
name: Schema.Literals(["LCP", "INP", "CLS", "FCP", "TTFB"]),
|
|
33
43
|
id: Schema.NonEmptyString.check(Schema.isMaxLength(64)),
|
|
@@ -77,7 +87,9 @@ class OtlpEvents extends Context.Service()("krakstack/opentelemetry/Events") {
|
|
|
77
87
|
label: "OtlpEvents",
|
|
78
88
|
body: (logRecords) => {
|
|
79
89
|
const scopes = new Map;
|
|
80
|
-
for (const { scopeName, ...record } of logRecords) {
|
|
90
|
+
for (const { scopeName, canExport, ...record } of logRecords) {
|
|
91
|
+
if (canExport && !canExport())
|
|
92
|
+
continue;
|
|
81
93
|
const name = scopeName ?? options.scopeName ?? "krakstack.events";
|
|
82
94
|
const records = scopes.get(name);
|
|
83
95
|
if (records)
|
|
@@ -146,15 +158,27 @@ class BrowserReportedError extends Schema3.TaggedError()("BrowserReportedError",
|
|
|
146
158
|
stack: Schema3.optional(Schema3.String)
|
|
147
159
|
}) {
|
|
148
160
|
}
|
|
149
|
-
var reportBrowserException = (exception) =>
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
161
|
+
var reportBrowserException = (exception) => {
|
|
162
|
+
const sanitized = sanitizeBrowserException(exception);
|
|
163
|
+
return Effect2.fail(new BrowserReportedError({ type: exception.type, ...sanitized })).pipe(Effect2.withSpan("browser.exception", {
|
|
164
|
+
root: true,
|
|
165
|
+
sampled: true,
|
|
166
|
+
attributes: {
|
|
167
|
+
"exception.type": exception.type,
|
|
168
|
+
"exception.message": sanitized.message,
|
|
169
|
+
"exception.stacktrace": sanitized.stack ?? ""
|
|
170
|
+
}
|
|
171
|
+
}), Effect2.ignoreCause);
|
|
172
|
+
};
|
|
173
|
+
var sanitizeBrowserException = (input) => ({
|
|
174
|
+
message: input.type === "window.error" ? "Browser error" : "Unhandled promise rejection",
|
|
175
|
+
stack: input.stack?.split(`
|
|
176
|
+
`).slice(1, 21).flatMap((line) => {
|
|
177
|
+
const match = line.match(/([a-zA-Z0-9_.-]+\.(?:m?js|tsx?)):(\d+):(\d+)/);
|
|
178
|
+
return match ? [`${match[1]}:${match[2]}:${match[3]}`] : [];
|
|
179
|
+
}).join(`
|
|
180
|
+
`)
|
|
181
|
+
});
|
|
158
182
|
var BrowserExceptionTrackingLive = Layer2.effectDiscard(Stream.merge(Stream.fromEventListener(globalThis, "error", {
|
|
159
183
|
bufferSize: 100
|
|
160
184
|
}).pipe(Stream.map((event) => {
|
|
@@ -246,5 +270,6 @@ class BrowserOtlp {
|
|
|
246
270
|
};
|
|
247
271
|
}
|
|
248
272
|
export {
|
|
249
|
-
BrowserOtlp
|
|
273
|
+
BrowserOtlp,
|
|
274
|
+
sanitizeBrowserException
|
|
250
275
|
};
|