134 lines · 7.0 KBRaw
| 1 | import { sha256 } from "./auth.ts"; |
| 2 | import type { Actor, Role } from "./contract/actor.ts"; |
| 3 | import type { Visibility } from "./contract/views.ts"; |
| 4 | |
| 5 | interface AnalyticsConfig { |
| 6 | readonly POSTHOG_ENABLED?: string; |
| 7 | readonly POSTHOG_PROJECT_TOKEN?: string; |
| 8 | readonly POSTHOG_HOST?: string; |
| 9 | } |
| 10 | |
| 11 | type AccountEvent = |
| 12 | | { readonly name: "account.signed_up"; readonly userId: string; readonly entryPath: "waitlist" | "admin" | "invitation" } |
| 13 | | { readonly name: "account.approved"; readonly userId: string; readonly approvalPath: "waitlist" | "admin" | "invitation" } |
| 14 | | { readonly name: "account.signed_in"; readonly userId: string } |
| 15 | | { readonly name: "member.joined"; readonly userId: string; readonly namespaceId: string; readonly role: Role; readonly joinPath: "new_account" | "existing_account" }; |
| 16 | |
| 17 | type RepositoryEvent = { |
| 18 | readonly namespaceId: string; |
| 19 | readonly namespaceKind: "user" | "org"; |
| 20 | readonly visibility: Visibility; |
| 21 | readonly entryPath: "new_project" | "import" | "fork"; |
| 22 | readonly importUrl?: string; |
| 23 | } & ( |
| 24 | | { readonly name: "repo.created" | "repo.imported" | "repo.forked"; readonly repoId: string } |
| 25 | | { readonly name: "repo.provision_failed"; readonly reason: "conflict" | "storage_unavailable" } |
| 26 | ); |
| 27 | |
| 28 | /** Work on a branch. The branch name itself never leaves the backend. */ |
| 29 | type Work = { readonly branch: string | null }; |
| 30 | |
| 31 | type WorkEvent = { readonly repoId: string; readonly namespaceId: string } & ( |
| 32 | | { readonly name: "agent.connected" } |
| 33 | | ({ readonly name: "task.taken" | "work.rejected" | "work.corrected" | "review.thread_resolved" | "agent.push_accepted" } & Work) |
| 34 | | ({ readonly name: "agent.directed"; readonly channel: "pull" | "thread"; readonly assigned: boolean } & Work) |
| 35 | | ({ readonly name: "commits.recorded"; readonly commitCount: number; readonly decisionCount: number } & Work) |
| 36 | | ({ readonly name: "work.landed"; readonly mergeMethod: "web" | "push" } & Work) |
| 37 | ); |
| 38 | |
| 39 | type EventName = AccountEvent["name"] | RepositoryEvent["name"] | WorkEvent["name"] | "$groupidentify"; |
| 40 | |
| 41 | const HOSTS = new Set(["https://us.i.posthog.com", "https://eu.i.posthog.com"]); |
| 42 | |
| 43 | export function captureAccountEvent(config: AnalyticsConfig, ctx: Pick<ExecutionContext, "waitUntil">, event: AccountEvent): void { |
| 44 | const properties = { |
| 45 | subject_kind: "human", |
| 46 | is_user_activity: event.name !== "account.approved", |
| 47 | ...(event.name === "account.signed_up" ? { entry_path: event.entryPath } : {}), |
| 48 | ...(event.name === "account.approved" ? { approval_path: event.approvalPath } : {}), |
| 49 | ...(event.name === "member.joined" ? { namespace_id: event.namespaceId, role: event.role, join_path: event.joinPath, $groups: { workspace: event.namespaceId } } : {}), |
| 50 | }; |
| 51 | if (!event.userId) return; |
| 52 | capture(config, ctx, `human:${event.userId}`, event.name, properties); |
| 53 | } |
| 54 | |
| 55 | export function captureRepositoryEvent(config: AnalyticsConfig, ctx: Pick<ExecutionContext, "waitUntil">, actor: Actor, event: RepositoryEvent): void { |
| 56 | if (event.name !== "repo.provision_failed") { |
| 57 | captureActorEvent(config, ctx, actor, "$groupidentify", event.namespaceId, { $group_type: "workspace", $group_key: event.namespaceId, $group_set: { kind: event.namespaceKind } }); |
| 58 | } |
| 59 | captureActorEvent(config, ctx, actor, event.name, event.namespaceId, { |
| 60 | namespace_id: event.namespaceId, |
| 61 | namespace_kind: event.namespaceKind, |
| 62 | visibility: event.visibility, |
| 63 | entry_path: event.entryPath, |
| 64 | ...(event.entryPath === "import" ? { import_provider: importProvider(event.importUrl) } : {}), |
| 65 | ...(event.name === "repo.provision_failed" ? { failure_reason: event.reason } : { repo_id: event.repoId }), |
| 66 | }); |
| 67 | } |
| 68 | |
| 69 | export function captureWorkEvent(config: AnalyticsConfig, ctx: Pick<ExecutionContext, "waitUntil">, actor: Actor, event: WorkEvent): void { |
| 70 | const base = { |
| 71 | namespace_id: event.namespaceId, |
| 72 | repo_id: event.repoId, |
| 73 | ...(event.name === "work.landed" ? { merge_method: event.mergeMethod } : {}), |
| 74 | ...(event.name === "agent.directed" ? { channel: event.channel, assigned: event.assigned } : {}), |
| 75 | ...(event.name === "commits.recorded" ? { commit_count: event.commitCount, decision_count: event.decisionCount } : {}), |
| 76 | }; |
| 77 | const properties = event.name === "agent.connected" ? base : workKey(event.repoId, event.branch).then((work_key) => ({ ...base, work_key })); |
| 78 | captureActorEvent(config, ctx, actor, event.name, event.namespaceId, properties); |
| 79 | } |
| 80 | |
| 81 | /** A stable key for the work on one branch of one repository, so a work cycle can be followed without its branch name. */ |
| 82 | export async function workKey(repoId: string, branch: string | null): Promise<string | null> { |
| 83 | return branch === null ? null : (await sha256(`${repoId}\n${branch}`)).slice(0, 16); |
| 84 | } |
| 85 | |
| 86 | function captureActorEvent(config: AnalyticsConfig, ctx: Pick<ExecutionContext, "waitUntil">, actor: Actor, name: EventName, workspaceId: string, pending: object | Promise<object>): void { |
| 87 | if (actor.kind === "anonymous") return; |
| 88 | const identity = actor.kind === "human" ? `human:${actor.person.id}` : `agent:${actor.sessionId}`; |
| 89 | const complete = (properties: object) => ({ |
| 90 | actor_kind: actor.kind, |
| 91 | subject_kind: actor.kind, |
| 92 | is_user_activity: actor.kind === "human", |
| 93 | auth_method: actor.kind === "human" ? actor.via : "agent", |
| 94 | ...properties, |
| 95 | $groups: { workspace: workspaceId }, |
| 96 | ...(actor.kind === "agent" ? { owner_id: `human:${actor.onBehalfOf.id}`, $process_person_profile: false } : {}), |
| 97 | }); |
| 98 | capture(config, ctx, identity, name, pending instanceof Promise ? pending.then(complete) : complete(pending)); |
| 99 | } |
| 100 | |
| 101 | function importProvider(url: string | undefined): "github" | "gitlab" | "bitbucket" | "other" { |
| 102 | try { |
| 103 | const hostname = new URL(url ?? "").hostname; |
| 104 | if (hostname === "github.com") return "github"; |
| 105 | if (hostname === "gitlab.com") return "gitlab"; |
| 106 | if (hostname === "bitbucket.org") return "bitbucket"; |
| 107 | } catch {} |
| 108 | return "other"; |
| 109 | } |
| 110 | |
| 111 | function capture(config: AnalyticsConfig, ctx: Pick<ExecutionContext, "waitUntil">, identity: string, name: EventName, properties: object | Promise<object>): void { |
| 112 | const host = config.POSTHOG_HOST; |
| 113 | const token = config.POSTHOG_PROJECT_TOKEN; |
| 114 | if (config.POSTHOG_ENABLED !== "true" || !token || !host || !HOSTS.has(host)) return; |
| 115 | const envelope = { api_key: token, distinct_id: identity, event: name, uuid: crypto.randomUUID(), timestamp: new Date().toISOString() }; |
| 116 | const send = (resolved: object) => deliver(`${host}/i/v0/e/`, { ...envelope, properties: { schema_version: 1, $geoip_disable: true, ...resolved } }); |
| 117 | ctx.waitUntil(properties instanceof Promise ? properties.then(send) : send(properties)); |
| 118 | } |
| 119 | |
| 120 | async function deliver(url: string, payload: object): Promise<void> { |
| 121 | try { |
| 122 | const response = await fetch(url, { |
| 123 | method: "POST", |
| 124 | headers: { "content-type": "application/json" }, |
| 125 | body: JSON.stringify(payload), |
| 126 | signal: AbortSignal.timeout(5000), |
| 127 | redirect: "manual", |
| 128 | }); |
| 129 | if (!response.ok) console.warn("posthog_delivery_failed", { status: response.status }); |
| 130 | await response.body?.cancel(); |
| 131 | } catch { |
| 132 | console.warn("posthog_delivery_failed", { reason: "transport" }); |
| 133 | } |
| 134 | } |