railyard/apps/console/lib/product-analytics.ts
caelum0x 3dca41bef0 feat(analytics): the analytics slot reaches product analytics; /s.js page speed; web view (QY1.2, A26, A18, I7, P-Y12)
Product analytics (A26, contract 5.3)
- Bridge: new signed route product_analytics {scribase_org_id, app, days?,
  with_server_key?} -> host, public key (the site key), first product event,
  web view; the server key only when asked, only to the Scribase control plane.
- sites answers analytics_host and analytics_key next to the page-tag values
  (nothing of the Insights path removed); insights answers
  first_product_event_at; the analytics proof falls back to
  first_product_event when no page-tag event came.
- lib/product-analytics.ts: one-app, viewer-scoped org tokens for every call;
  PRODUCT_ANALYTICS_PUBLIC_URL (default the SDK default host).
- PA: POST /v1/server/{app_id}/batch with Authorization: Bearer ry_pak_<hex>
  (HMAC of the app id under PRODUCT_ANALYTICS_CONSOLE_SECRET, constant-time
  check) for server-side forwarders (QU1.4); the public key is refused there.
- Contract tests/contract/fixtures/scribase-bridge/contract.json stays
  version 2 with additive QY1.2 keys: product_analytics route and answer
  keys, analytics_host section (env names, capture paths, server door).

Web view (A18)
- PA src/web/query.ts: visitors, page views, visits, bounce, daily series,
  top pages, entry referrers ($direct), entry UTM, p75 page speed with
  ratings, from pa.events under RLS. Shapes follow PostHog web analytics
  stats_table (MIT, 7b13402a6350, nothing from ee/), NOTICE updated.
- Console: product-analytics/web screen (range picker, tables, page speed).

/s.js page speed (I7, P-Y12)
- The page tag sends LCP, INP, CLS, FCP and TTFB once per page view
  (hidden, pagehide, or before a route change) as a performance event;
  data-vitals="off" turns it off. Port of insights-web metrics.ts; metric
  definitions per GoogleChrome/web-vitals (Apache-2.0), NOTICE added.
  1,620 bytes gzip (budget 3,072).
- With PRODUCT_ANALYTICS_URL the edge collector also forwards every stored
  event to product analytics ($pageview, $web_vitals, custom events,
  $identify) with cookieless daily ids, no IP, retried on 5xx with the same
  uuids, so the web view reads the same store.

Also: lib/ship/ship.test.ts type errors from QY1.1 fixed (doneText helper).

Tests
- insights-edge 34/34 (19 existing + 11 vitals within 10% of
  chrome-page-loads.json and 3 KB gzip + 4 forwarding).
- console 135/135; contract 6/6; console tsc clean.
- product-analytics a1 52/52; test/qy 7/7 (web view hand counts, isolation,
  edge-shape events, server door, and an end-to-end bridge -> SDK event ->
  first_product_event proof: 31 ms against the 60 s target); tsc clean.

Note: performance events still count toward the collector's monthly cap,
as the insights-web ones already did.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 12:36:08 +03:00

77 lines
3.2 KiB
TypeScript

// Server-only: what the console asks of the product analytics service on
// behalf of the Scribase bridge (QY1.2, A26). Every call carries a fresh org
// token scoped to one app; the server key is derived here and handed only to
// the Scribase control plane over the signed bridge (Wave Q contract 5.3).
//
// Configuration: PRODUCT_ANALYTICS_URL (how the console reaches the service),
// PRODUCT_ANALYTICS_CONSOLE_SECRET (shared with the service, 32+ characters)
// and PRODUCT_ANALYTICS_PUBLIC_URL (the host apps send events to; defaults to
// DEFAULT_PA_PUBLIC_HOST, the same default the SDKs use).
import { paConfig, paFetch, type PaConfig } from "../app/(app)/product-analytics/_lib/http.ts";
import { hex, hmacSha256 } from "./crypto.ts";
export const DEFAULT_PA_PUBLIC_HOST = "https://pa.railyard.ereboslab.com";
export interface ProductFirstEvent {
event: string;
at: string;
}
export interface WebRow {
value: string;
visitors: number;
views: number;
}
export interface WebVital {
p75: number | null;
samples: number;
rating: "good" | "needs_improvement" | "poor" | null;
}
/** The service's web view (`PA/src/web/query.ts`). */
export interface WebOverview {
range: { from: string; to: string };
totals: { visitors: number; views: number; sessions: number; bounce_rate: number | null };
series: { day: string; visitors: number; views: number }[];
pages: WebRow[];
referrers: WebRow[];
utm: { source: WebRow[]; medium: WebRow[]; campaign: WebRow[] };
vitals: Record<"LCP" | "INP" | "CLS" | "FCP" | "TTFB", WebVital>;
}
export interface ProductAnalyticsClient {
/** Public host the app's SDK sends to (`*_ANALYTICS_HOST`). */
host: string;
firstEvent(orgId: string, appId: string): Promise<ProductFirstEvent | null>;
web(orgId: string, appId: string, days: number): Promise<WebOverview>;
/** `ry_pak_...` for server-side forwarders of one app; never shown in a page or a log. */
serverKey(appId: string): Promise<string>;
}
export function productAnalyticsClient(cfg: PaConfig, publicHost: string, fetchImpl: typeof fetch = fetch, now: () => Date = () => new Date()): ProductAnalyticsClient {
const scope = (orgId: string, appId: string) => ({ org_id: orgId, app_ids: [appId], role: "viewer" as const });
return {
host: publicHost.replace(/\/$/, ""),
async firstEvent(orgId, appId) {
const s = await paFetch<{ first_event: { event: string; at: string } | null }>(cfg, scope(orgId, appId), `/v1/projects/${appId}/status`, {}, fetchImpl, now());
return s.first_event ? { event: s.first_event.event, at: s.first_event.at } : null;
},
web(orgId, appId, days) {
return paFetch<WebOverview>(cfg, scope(orgId, appId), `/v1/projects/${appId}/web?days=${days}`, {}, fetchImpl, now());
},
async serverKey(appId) {
return `ry_pak_${hex(await hmacSha256(cfg.secret, `pa-server-key:v1:${appId}`))}`;
},
};
}
/** Null when the service is not connected on this deployment. */
export function productAnalyticsFromEnv(env: Record<string, string | undefined> = process.env): ProductAnalyticsClient | null {
const cfg = paConfig(env);
if (!cfg) return null;
const host = env.PRODUCT_ANALYTICS_PUBLIC_URL?.trim();
return productAnalyticsClient(cfg, host && /^https?:\/\//.test(host) ? host : DEFAULT_PA_PUBLIC_HOST);
}