Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

6.3 KB
Raw Blame
import {
  type SelfDescribingJson,
  newTracker,
  trackSelfDescribingEvent,
} from "@snowplow/browser-tracker";
import { version as reactVersion } from "react";

import type { SdkStoreState } from "embedding-sdk-bundle/store/types";
import { ANALYTICS_PROXY_PATH } from "embedding-sdk-shared/constants/analytics";
import { EMBEDDING_SDK_CONFIG } from "metabase/embedding-sdk/config";
import { isEmbedPreviewRequest } from "metabase/embedding/lib/auth/set-embed-preview-header";
import { getSettings } from "metabase/settings";
import { trackMetaplowEvent } from "metabase/utils/metaplow";
import type { SimpleEventSchema } from "metabase-types/analytics/event";

const SIMPLE_EVENT_SCHEMA_URI =
  "iglu:com.metabase/simple_event/jsonschema/1-0-0";

type ValidateEvent<
  T extends SimpleEventSchema &
    Record<Exclude<keyof T, keyof SimpleEventSchema>, never>,
> = T;

type EmbeddingSdkInitializedEvent = ValidateEvent<{
  event: "embedding_sdk_initialized";
  event_detail: string;
}>;

type EmbeddingSdkComponentRenderedEvent = ValidateEvent<{
  event: "embedding_sdk_component_rendered";
  event_detail: string;
}>;

type EmbeddingSdkEvent =
  | EmbeddingSdkInitializedEvent
  | EmbeddingSdkComponentRenderedEvent;

// The SDK runs inside the customer's app. A direct POST to the Snowplow
// collector (`sp.metabase.com`) is cross-origin and blocked by a strict
// `connect-src` CSP. We instead point the tracker at the customer's own
// Metabase instance, which proxies the payload to the collector server-side.
// `connect-src` matches host (not path), so the instance origin — already
// allowlisted for the SDK's data calls — passes with no extra customer config.

// Named tracker, isolated from the main-app tracker ("sp").
const SDK_TRACKER_NAME = "sdk";

export type SdkAuthMethod = "guest" | "api_key" | "sso";

// true = tracker initialized for the first time; false = already running (idempotent call)
type WasJustInitialized = boolean;

let trackerInitialized = false;
let sdkAuthMethod: SdkAuthMethod;
let sdkLocaleUsed: boolean = false;
let sdkMetaplowEnabled: boolean = false;

// Initialize the SDK's Snowplow tracker. Idempotent — safe under StrictMode double-mount.
export function initSdkTracker({
  metabaseInstanceUrl,
  authMethod,
  localeUsed = false,
  store,
}: {
  metabaseInstanceUrl: string;
  authMethod: SdkAuthMethod;
  localeUsed?: boolean;
  store: { getState: () => SdkStoreState };
}): WasJustInitialized {
  if (trackerInitialized) {
    return false;
  }
  trackerInitialized = true;
  sdkAuthMethod = authMethod;
  sdkLocaleUsed = localeUsed;

  const settingValues = getSettings(store.getState());
  sdkMetaplowEnabled = !!settingValues?.["metaplow-tracking-enabled"];

  newTracker(SDK_TRACKER_NAME, metabaseInstanceUrl, {
    appId: "metabase",
    platform: "web",
    eventMethod: "post",
    contexts: { webPage: true },
    // Plain JSON on the wire. The main-app tracker keeps base64 on;
    // the SDK tracker is new, so there's no legacy format to preserve.
    encodeBase64: false,
    // Deliver through the instance proxy, not the collector's tp2 path.
    postPath: ANALYTICS_PROXY_PATH,
    // No cookies / localStorage: the SDK must not touch the host page's storage.
    stateStorageStrategy: "none",
    // v4 defaults this to true, and the test-cookie probe ignores stateStorageStrategy.
    discoverRootDomain: false,
    // Server-side anonymisation: strip IP + network_userid, send the SP-Anonymous header.
    anonymousTracking: { withServerAnonymisation: true },
    // The proxy endpoint uses `Access-Control-Allow-Origin: *`. Wildcard CORS rejects
    // credentialed requests, so credentials must be omitted.
    credentials: "omit",
    plugins: [createSdkInstanceContextPlugin(store)],
  });
  return true;
}

export function getSdkAuthMethod(): SdkAuthMethod | undefined {
  return sdkAuthMethod;
}

export function getSdkLocaleUsed(): boolean {
  return sdkLocaleUsed;
}

export function getHostReactVersion(): string {
  // `undefined` would get removed by the serialization,
  // explicit `unknown` to differentiate old data from real unknown
  return reactVersion ?? "unknown";
}

type SdkClientHeader =
  (typeof EMBEDDING_SDK_CONFIG)["metabaseClientRequestHeader"];

export type SdkClient = SdkClientHeader | `${SdkClientHeader}-preview`;

// Same value the backend records as embedding_client for SDK requests,
// including the -preview suffix added when the preview header is sent
// (not all clients have a `-preview` variant, but the type allows for it).
export function getSdkClient(): SdkClient {
  const client = EMBEDDING_SDK_CONFIG.metabaseClientRequestHeader;
  return isEmbedPreviewRequest() ? `${client}-preview` : client;
}

// Attaches the instance context to every SDK event. Omits userId — unlike the
// main-app tracker, SDK component usage is tracked at instance granularity;
// the analytics-uuid already identifies the account.
function createSdkInstanceContextPlugin(store: {
  getState: () => SdkStoreState;
}) {
  return {
    contexts(): SelfDescribingJson[] {
      // Settings are guaranteed present: initSdkTracker is only called after
      // isTrackingEnabled, which requires anon-tracking-enabled to be loaded.
      const settings = getSettings(store.getState());
      const version = settings?.["version"] ?? {};

      return [
        {
          schema: "iglu:com.metabase/instance/jsonschema/1-1-0",
          data: {
            id: settings?.["analytics-uuid"],
            version: {
              tag: version.tag,
            },
            created_at: settings?.["instance-creation"],
            token_features: settings?.["token-features"],
          },
        },
      ];
    },
  };
}

// Send a self-describing event through the SDK tracker. Schema-agnostic: the caller
// supplies the Iglu schema + data, so the transport stays decoupled from the event shape.
function trackSdkEvent(event: SelfDescribingJson): void {
  trackSelfDescribingEvent({ event }, [SDK_TRACKER_NAME]);
}

// Use instead of trackSimpleEvent in the SDK: the main-app "sp" tracker is not
// initialized in the customer's page, so trackSimpleEvent's Snowplow leg is a no-op.
export function trackSdkSimpleEvent(event: EmbeddingSdkEvent): void {
  trackSdkEvent({ schema: SIMPLE_EVENT_SCHEMA_URI, data: event });

  if (sdkMetaplowEnabled) {
    const { event: name, ...data } = event;
    trackMetaplowEvent(name, data);
  }
}