Open History to see the last commit
1import * as SecureRandom from "effect/crypto/SecureRandom";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4import * as Option from "effect/Option";
5import * as PlatformError from "effect/PlatformError";
6import * as Schema from "effect/Schema";
7
8import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
9import { hashTelemetryId } from "@t3tools/shared/telemetryId";
10import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
11import { CLOUD_LINKED_USER_ID } from "../cloud/config.ts";
12import * as ServerConfig from "../config.ts";
13
14/**
15 * Who an install belongs to, from strongest to weakest. `connect` is the T3
16 * Connect account. `device` is a client device that connected.
17 */
18export const TelemetryOwnerSource = Schema.Literals(["connect", "device"]);
19export type TelemetryOwnerSource = typeof TelemetryOwnerSource.Type;
20
21export interface TelemetryOwner {
22 readonly source: TelemetryOwnerSource;
23 /** `hashTelemetryId` of the source's raw id. */
24 readonly ownerId: string;
25}
26
27class TelemetryIdentityReadError extends Schema.TaggedError<TelemetryIdentityReadError>()(
28 "TelemetryIdentityReadError",
29 {
30 filePath: Schema.String,
31 cause: Schema.Defect(),
32 },
33) {
34 override get message(): string {
35 return `Failed to read anonymous telemetry identity at '${this.filePath}'.`;
36 }
37}
38
39export class TelemetryAnonymousIdGenerationError extends Schema.TaggedError<TelemetryAnonymousIdGenerationError>()(
40 "TelemetryAnonymousIdGenerationError",
41 {
42 filePath: Schema.String,
43 cause: Schema.Defect(),
44 },
45) {
46 override get message(): string {
47 return `Failed to generate anonymous telemetry identity for '${this.filePath}'.`;
48 }
49}
50
51export class TelemetryAnonymousIdPersistenceError extends Schema.TaggedError<TelemetryAnonymousIdPersistenceError>()(
52 "TelemetryAnonymousIdPersistenceError",
53 {
54 filePath: Schema.String,
55 cause: Schema.Defect(),
56 },
57) {
58 override get message(): string {
59 return `Failed to persist anonymous telemetry identity at '${this.filePath}'.`;
60 }
61}
62
63type TelemetryIdentityError =
64 | TelemetryIdentityReadError
65 | TelemetryAnonymousIdGenerationError
66 | TelemetryAnonymousIdPersistenceError;
67
68function isNotFoundError(error: PlatformError.PlatformError): boolean {
69 return error.reason._tag === "NotFound";
70}
71
72const getTelemetryIdentityCauseAnnotations = (cause: unknown) => {
73 if (cause instanceof PlatformError.PlatformError) {
74 return {
75 causeKind: "platform",
76 platformReason: cause.reason._tag,
77 };
78 }
79 return { causeKind: "other" };
80};
81
82const logTelemetryIdentityError = (error: TelemetryIdentityError) =>
83 Effect.logWarning(error.message).pipe(
84 Effect.annotateLogs({
85 errorTag: error._tag,
86 filePath: error.filePath,
87 ...getTelemetryIdentityCauseAnnotations(error.cause),
88 ...(error.stack === undefined ? {} : { errorStack: error.stack }),
89 }),
90 );
91
92const readIdentityFile = (fileSystem: FileSystem.FileSystem, filePath: string) =>
93 fileSystem.readFileString(filePath).pipe(
94 Effect.asSome,
95 Effect.catchTags({
96 PlatformError: (cause) =>
97 isNotFoundError(cause)
98 ? Effect.succeed(Option.none<string>())
99 : Effect.fail(new TelemetryIdentityReadError({ filePath, cause })),
100 }),
101 );
102
103const upsertAnonymousId = Effect.gen(function* () {
104 const fileSystem = yield* FileSystem.FileSystem;
105 const { anonymousIdPath } = yield* ServerConfig.ServerConfig;
106
107 const existing = yield* readIdentityFile(fileSystem, anonymousIdPath);
108 if (Option.isSome(existing)) {
109 return existing.value;
110 }
111
112 const anonymousId = yield* SecureRandom.SecureRandom.pipe(
113 Effect.flatMap((crypto) => crypto.uuidV4()),
114 Effect.mapError(
115 (cause) =>
116 new TelemetryAnonymousIdGenerationError({
117 filePath: anonymousIdPath,
118 cause,
119 }),
120 ),
121 );
122 yield* writeFileStringAtomically({ filePath: anonymousIdPath, contents: anonymousId }).pipe(
123 Effect.mapError(
124 (cause) =>
125 new TelemetryAnonymousIdPersistenceError({
126 filePath: anonymousIdPath,
127 cause,
128 }),
129 ),
130 );
131
132 return anonymousId;
133});
134
135/**
136 * `distinctId` and `installId` are the same hash of a random id kept in the state
137 * directory. Identity never comes from a provider's sign-in files or account. Both
138 * names are sent because the ingest side reads each. Null disables telemetry.
139 */
140export const getTelemetryIdentity = upsertAnonymousId.pipe(
141 Effect.map(hashTelemetryId),
142 Effect.catch((error) => logTelemetryIdentityError(error).pipe(Effect.as(null))),
143 Effect.map((installId) => ({ distinctId: installId, installId })),
144 Effect.withSpan("getTelemetryIdentity"),
145);
146
147/**
148 * The owner the server can read without a client: the linked T3 Connect
149 * account. Clients add `connect` and `device` owners when they connect.
150 */
151export const getServerOwners = Effect.gen(function* () {
152 const secrets = yield* ServerSecretStore.ServerSecretStore;
153 const connectUser = yield* secrets.get(CLOUD_LINKED_USER_ID).pipe(
154 Effect.map(Option.map((bytes) => new TextDecoder().decode(bytes))),
155 Effect.catch((cause) =>
156 Effect.logWarning("Failed to read the linked T3 Connect account for telemetry", {
157 errorTag: cause._tag,
158 }).pipe(Effect.as(Option.none<string>())),
159 ),
160 );
161 return Option.isSome(connectUser) && connectUser.value.trim() !== ""
162 ? [{ source: "connect", ownerId: hashTelemetryId(connectUser.value) } satisfies TelemetryOwner]
163 : [];
164}).pipe(Effect.withSpan("getServerOwners"));