Skip to content
TypeScript

feat(mobile): report crashes to Axiom with symbolicated stacks (#19093)

Gabriel De Andrade570d4b03eef8
diff --git a/.github/workflows/mobile-eas-production.yml b/.github/workflows/mobile-eas-production.yml
index b6581e0e8ea..4dd434a956e 100644
--- a/.github/workflows/mobile-eas-production.yml
+++ b/.github/workflows/mobile-eas-production.yml
@@ -275,6 +275,7 @@ jobs:
--environment production \
--platform ${{ inputs.platform }} \
--message "$OTA_MESSAGE" \
+ --emit-metadata \
--non-interactive
# Reconcile each version separately because the major is in the fingerprint.
@@ -313,8 +314,11 @@ jobs:
--environment production \
--platform "$platform" \
--message "$message" \
+ --emit-metadata \
--non-interactive; then
echo ":white_check_mark: $platform/$profile: OTA published to production (fingerprint \`$hash\`)" >> "$GITHUB_STEP_SUMMARY"
+ # The next target's export replaces dist; keep this one for the map upload.
+ rm -rf "dist-$platform-$profile" && mv dist "dist-$platform-$profile"
else
failed=1
echo ":x: $platform/$profile: OTA publish failed (fingerprint \`$hash\`)" >> "$GITHUB_STEP_SUMMARY"
@@ -354,3 +358,18 @@ jobs:
fi
done
exit "$failed"
+
+ # Lets the relay symbolicate crash stacks from the updates published
+ # above. A step of its own so the R2 credentials reach only this script,
+ # not `eas update` and the dependencies it runs. Never fails the job.
+ - name: Upload OTA source maps
+ if: ${{ !cancelled() && steps.expo-token.outputs.present == 'true' }}
+ working-directory: apps/mobile
+ env:
+ MOBILE_SOURCEMAPS_R2: ${{ secrets.MOBILE_SOURCEMAPS_R2 }}
+ run: |
+ for dir in dist dist-*; do
+ if [ -f "$dir/eas-update-metadata.json" ]; then
+ node scripts/upload-sourcemaps.mts ota "$dir"
+ fi
+ done
diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.ts
index 92e587f171c..980da9c83c3 100644
--- a/apps/mobile/app.config.ts
+++ b/apps/mobile/app.config.ts
@@ -17,6 +17,12 @@ const runtimeVersionPolicy =
const personalTeamBundleIdentifier = repoEnv.T3CODE_IOS_PERSONAL_TEAM_BUNDLE_ID?.trim();
const IOS_BUNDLE_IDENTIFIER_PATTERN = /^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/;
+// Compiled into the native project. Without a relay, Observe's native side could dispatch to
+// Expo's own ingest before observe.ts turns it off; `.invalid` never resolves (RFC 6761).
+const observeEndpointUrl = repoEnv.T3CODE_RELAY_URL?.trim()
+ ? new URL("/v1/mobile/observe", repoEnv.T3CODE_RELAY_URL.trim()).toString()
+ : "https://observe.invalid";
+
const fromRepoRoot = (relativePath: string) => `../../${relativePath}`;
const androidAdaptiveForeground = "./assets/android-icon-foreground.png";
@@ -450,6 +456,7 @@ const config: ExpoConfig = {
},
eas: {
projectId: "d763fcb8-d37c-41ea-a773-b54a0ab4a454",
+ observe: { endpointUrl: observeEndpointUrl },
},
},
owner: "pingdotgg",
diff --git a/apps/mobile/eas.json b/apps/mobile/eas.json
index f694fc8d6ef..f773c2c5bbc 100644
--- a/apps/mobile/eas.json
+++ b/apps/mobile/eas.json
@@ -66,7 +66,8 @@
"corepack": true,
"env": {
"APP_VARIANT": "production",
- "NODE_OPTIONS": "--max-old-space-size=4096"
+ "NODE_OPTIONS": "--max-old-space-size=4096",
+ "SOURCEMAP_FILE": "/tmp/t3code-ios-main.jsbundle.map"
},
"channel": "production",
"environment": "production",
diff --git a/apps/mobile/index.ts b/apps/mobile/index.ts
index 6aac4869d97..169d5cc4048 100644
--- a/apps/mobile/index.ts
+++ b/apps/mobile/index.ts
@@ -1,5 +1,7 @@
// Must stay first: the render counter wraps the DevTools hook before any React commit.
import "./src/features/development/render-counter-entry";
+// Next, so errors thrown while the rest of the app loads are recorded too.
+import "./src/features/observability/observe";
import { registerRootComponent } from "expo";
import "react-native-gesture-handler";
import { LogBox } from "react-native";
diff --git a/apps/mobile/package.json b/apps/mobile/package.json
index f5e817165b9..42d81c8adad 100644
--- a/apps/mobile/package.json
+++ b/apps/mobile/package.json
@@ -46,6 +46,7 @@
"measure-renders": "node scripts/measure-renders.mts",
"generate": "node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON scripts/generate-uniwind-themes.mts",
"generate:highlights": "node scripts/generate-highlights.mts",
+ "eas-build-on-success": "node scripts/upload-sourcemaps.mts build",
"test": "vp test run --project unit --project react",
"typecheck": "tsc --noEmit"
},
@@ -103,6 +104,7 @@
"expo-linking": "~58.0.13",
"expo-network": "~58.0.3",
"expo-notifications": "~58.1.5",
+ "expo-observe": "~58.0.15",
"expo-paste-input": "^0.1.15",
"expo-quick-actions": "^6.0.2",
"expo-secure-store": "~58.0.2",
@@ -145,6 +147,7 @@
"@types/mdast": "^4.0.4",
"@types/react": "catalog:",
"@types/react-dom": "catalog:",
+ "aws4fetch": "1.0.20",
"babel-preset-expo": "~58.0.17",
"jsdom": "^30.0.1",
"tailwindcss": "^4.0.0",
diff --git a/apps/mobile/scripts/sourcemap-upload.mts b/apps/mobile/scripts/sourcemap-upload.mts
new file mode 100644
index 00000000000..a962f98a378
--- /dev/null
+++ b/apps/mobile/scripts/sourcemap-upload.mts
@@ -0,0 +1,165 @@
+import * as NodeFS from "node:fs";
+import * as NodePath from "node:path";
+import { mobileSourceMapKey, type MobilePlatform } from "@t3tools/shared/mobileSourceMaps";
+import { AwsClient } from "aws4fetch";
+
+export interface SourceMapUpload {
+ readonly key: string;
+ readonly path: string;
+}
+
+/** The `MOBILE_SOURCEMAPS_R2` secret: the relay stack's `mobileSourceMapsUploadCredentials`. */
+interface UploadCredentials {
+ readonly endpoint: string;
+ readonly bucketName: string;
+ readonly accessKeyId: string;
+ readonly secretAccessKey: string;
+}
+
+const isPlatform = (value: unknown): value is MobilePlatform =>
+ value === "ios" || value === "android";
+
+const readJson = (path: string): unknown => JSON.parse(NodeFS.readFileSync(path, "utf8"));
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === "object" && value !== null && !Array.isArray(value);
+
+export function parseCredentials(value: string | undefined): UploadCredentials | undefined {
+ if (!value?.trim()) return undefined;
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(value);
+ } catch {
+ // JSON.parse's message quotes the input, which here is the secret.
+ throw new Error("MOBILE_SOURCEMAPS_R2 is not valid JSON.");
+ }
+ if (!isRecord(parsed)) throw new Error("MOBILE_SOURCEMAPS_R2 is not a JSON object.");
+ const { endpoint, bucketName, accessKeyId, secretAccessKey } = parsed;
+ if (
+ typeof endpoint !== "string" ||
+ typeof bucketName !== "string" ||
+ typeof accessKeyId !== "string" ||
+ typeof secretAccessKey !== "string"
+ ) {
+ throw new Error(
+ "MOBILE_SOURCEMAPS_R2 needs endpoint, bucketName, accessKeyId and secretAccessKey.",
+ );
+ }
+ return { endpoint, bucketName, accessKeyId, secretAccessKey };
+}
+
+/** One map per update `eas update --emit-metadata` published, next to the bundle `metadata.json` names. */
+export function otaSourceMapUploads(distDir: string): ReadonlyArray<SourceMapUpload> {
+ const metadata = readJson(NodePath.join(distDir, "metadata.json"));
+ const easMetadata = readJson(NodePath.join(distDir, "eas-update-metadata.json"));
+ const fileMetadata = isRecord(metadata) ? metadata.fileMetadata : undefined;
+ const updates = isRecord(easMetadata) ? easMetadata.updates : undefined;
+ if (!isRecord(fileMetadata) || !Array.isArray(updates)) {
+ throw new Error(`${distDir} is missing Expo export or EAS update metadata.`);
+ }
+ return updates.flatMap((update): Array<SourceMapUpload> => {
+ if (!isRecord(update) || !isPlatform(update.platform) || typeof update.id !== "string") {
+ return [];
+ }
+ const platformFiles = fileMetadata[update.platform];
+ const bundle = isRecord(platformFiles) ? platformFiles.bundle : undefined;
+ if (typeof bundle !== "string") return [];
+ return [
+ {
+ key: mobileSourceMapKey(update.platform, "ota", update.id),
+ path: NodePath.join(distDir, `${bundle}.map`),
+ },
+ ];
+ });
+}
+
+/** Android's Gradle plugin writes the map under the release variant; iOS to `SOURCEMAP_FILE` (eas.json). */
+export function buildSourceMapUpload(
+ env: Readonly<Record<string, string | undefined>>,
+ projectDir: string,
+): SourceMapUpload {
+ const platform = env.EAS_BUILD_PLATFORM;
+ const buildId = env.EAS_BUILD_ID;
+ if (!isPlatform(platform) || !buildId) {
+ throw new Error("EAS_BUILD_PLATFORM and EAS_BUILD_ID are only set on EAS Build.");
+ }
+ if (platform === "ios") {
+ if (!env.SOURCEMAP_FILE) throw new Error("SOURCEMAP_FILE is not set for this iOS build.");
+ return { key: mobileSourceMapKey("ios", "build", buildId), path: env.SOURCEMAP_FILE };
+ }
+ const variantsDir = NodePath.join(projectDir, "android/app/build/generated/sourcemaps/react");
+ const variant = NodeFS.existsSync(variantsDir)
+ ? NodeFS.readdirSync(variantsDir).find((name) => /release$/iu.test(name))
+ : undefined;
+ if (!variant) throw new Error(`No release source map under ${variantsDir}.`);
+ return {
+ key: mobileSourceMapKey("android", "build", buildId),
+ path: NodePath.join(variantsDir, variant, "index.android.bundle.map"),
+ };
+}
+
+/**
+ * EAS writes the app's debug symbols next to the `.ipa`, so native frames in iOS crash
+ * reports can be read with `atos`. Undefined when the build left none.
+ */
+export function buildDsymUpload(
+ env: Readonly<Record<string, string | undefined>>,
+ projectDir: string,
+): SourceMapUpload | undefined {
+ if (env.EAS_BUILD_PLATFORM !== "ios" || !env.EAS_BUILD_ID) return undefined;
+ const buildDir = NodePath.join(projectDir, "ios/build");
+ const dsym = NodeFS.existsSync(buildDir)
+ ? NodeFS.readdirSync(buildDir).find((name) => name.endsWith(".app.dSYM.zip"))
+ : undefined;
+ if (!dsym) return undefined;
+ return { key: `ios/dsym/${env.EAS_BUILD_ID}.zip`, path: NodePath.join(buildDir, dsym) };
+}
+
+/** Only what the relay reads: source text stays out of the bucket, and the rest is dead weight. */
+function stripToMappings(text: string): string {
+ const map: unknown = JSON.parse(text);
+ if (!isRecord(map)) throw new Error("Source map is not a JSON object.");
+ const { version, sources, sourceRoot, mappings } = map;
+ return JSON.stringify({ version, sources, sourceRoot, mappings });
+}
+
+export function uploadSourceMap(
+ credentials: UploadCredentials,
+ upload: SourceMapUpload,
+): Promise<number> {
+ return putObject(
+ credentials,
+ upload.key,
+ stripToMappings(NodeFS.readFileSync(upload.path, "utf8")),
+ "application/json",
+ );
+}
+
+export function uploadDsym(credentials: UploadCredentials, upload: SourceMapUpload) {
+ const body = new Uint8Array(NodeFS.readFileSync(upload.path));
+ return putObject(credentials, upload.key, body, "application/zip");
+}
+
+async function putObject(
+ credentials: UploadCredentials,
+ key: string,
+ body: string | Uint8Array<ArrayBuffer>,
+ contentType: string,
+): Promise<number> {
+ const client = new AwsClient({
+ accessKeyId: credentials.accessKeyId,
+ secretAccessKey: credentials.secretAccessKey,
+ service: "s3",
+ region: "auto",
+ });
+ const url = `${credentials.endpoint.replace(/\/$/u, "")}/${credentials.bucketName}/${key}`;
+ const response = await client.fetch(url, {
+ method: "PUT",
+ body,
+ headers: { "content-type": contentType },
+ });
+ if (!response.ok) {
+ throw new Error(`R2 answered ${response.status}: ${(await response.text()).slice(0, 500)}`);
+ }
+ return body.length;
+}
diff --git a/apps/mobile/scripts/sourcemap-upload.test.ts b/apps/mobile/scripts/sourcemap-upload.test.ts
new file mode 100644
index 00000000000..ee8ae57d690
--- /dev/null
+++ b/apps/mobile/scripts/sourcemap-upload.test.ts
@@ -0,0 +1,136 @@
+import * as NodeFS from "node:fs";
+import * as NodeHttp from "node:http";
+import type * as NodeNet from "node:net";
+import * as NodeOS from "node:os";
+import * as NodePath from "node:path";
+import { afterEach, describe, expect, it } from "vite-plus/test";
+
+import {
+ buildDsymUpload,
+ buildSourceMapUpload,
+ otaSourceMapUploads,
+ uploadSourceMap,
+} from "./sourcemap-upload.mts";
+
+const directories: Array<string> = [];
+const tempDir = () => {
+ const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "sourcemap-upload-"));
+ directories.push(dir);
+ return dir;
+};
+const writeFile = (path: string, contents: string) => {
+ NodeFS.mkdirSync(NodePath.dirname(path), { recursive: true });
+ NodeFS.writeFileSync(path, contents);
+};
+
+afterEach(() => {
+ for (const dir of directories.splice(0)) NodeFS.rmSync(dir, { recursive: true, force: true });
+});
+
+describe("uploadSourceMap", () => {
+ it("PUTs each published update's map, only what the relay reads, under its update id", async () => {
+ const dist = tempDir();
+ writeFile(
+ NodePath.join(dist, "metadata.json"),
+ JSON.stringify({
+ fileMetadata: {
+ android: { bundle: "_expo/static/js/android/index-abc.hbc" },
+ ios: { bundle: "_expo/static/js/ios/index-def.hbc" },
+ },
+ }),
+ );
+ writeFile(
+ NodePath.join(dist, "eas-update-metadata.json"),
+ JSON.stringify({
+ updates: [
+ { id: "update-android", platform: "android" },
+ { id: "update-ios", platform: "ios" },
+ { id: "update-web", platform: "web" },
+ ],
+ }),
+ );
+ for (const platform of ["android", "ios"]) {
+ writeFile(
+ NodePath.join(
+ dist,
+ `_expo/static/js/${platform}/index-${platform === "ios" ? "def" : "abc"}.hbc.map`,
+ ),
+ JSON.stringify({
+ version: 3,
+ sources: [`${platform}.ts`],
+ sourcesContent: ["secret"],
+ names: ["render"],
+ x_facebook_sources: [[null]],
+ mappings: "",
+ }),
+ );
+ }
+
+ const requests: Array<{ method?: string; url?: string; auth?: string; body: string }> = [];
+ const server = NodeHttp.createServer((request, response) => {
+ let body = "";
+ request.on("data", (chunk) => (body += chunk));
+ request.on("end", () => {
+ requests.push({
+ method: request.method,
+ url: request.url,
+ auth: request.headers.authorization,
+ body,
+ });
+ response.end();
+ });
+ });
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ try {
+ const address = server.address() as NodeNet.AddressInfo;
+ const credentials = {
+ endpoint: `http://127.0.0.1:${address.port}`,
+ bucketName: "maps",
+ accessKeyId: "key-id",
+ secretAccessKey: "secret-key",
+ };
+ for (const upload of otaSourceMapUploads(dist)) {
+ await uploadSourceMap(credentials, upload);
+ }
+ expect(requests).toEqual(
+ ["android", "ios"].map((platform) => ({
+ method: "PUT",
+ url: `/maps/${platform}/ota/update-${platform}.map`,
+ auth: expect.stringMatching(/^AWS4-HMAC-SHA256 Credential=key-id\/\d{8}\/auto\/s3\//),
+ body: JSON.stringify({ version: 3, sources: [`${platform}.ts`], mappings: "" }),
+ })),
+ );
+ } finally {
+ server.close();
+ }
+ });
+});
+
+describe("buildSourceMapUpload", () => {
+ it("names the EAS build's embedded bundle map under its build id", () => {
+ const project = tempDir();
+ const androidMap = NodePath.join(
+ project,
+ "android/app/build/generated/sourcemaps/react/release/index.android.bundle.map",
+ );
+ writeFile(androidMap, "{}");
+ expect(
+ buildSourceMapUpload({ EAS_BUILD_PLATFORM: "android", EAS_BUILD_ID: "build-1" }, project),
+ ).toEqual({ key: "android/build/build-1.map", path: androidMap });
+ expect(
+ buildSourceMapUpload(
+ { EAS_BUILD_PLATFORM: "ios", EAS_BUILD_ID: "build-2", SOURCEMAP_FILE: "/tmp/main.map" },
+ project,
+ ),
+ ).toEqual({ key: "ios/build/build-2.map", path: "/tmp/main.map" });
+ });
+
+ it("names an iOS build's dSYMs under its build id", () => {
+ const project = tempDir();
+ const dsym = NodePath.join(project, "ios/build/T3Code.app.dSYM.zip");
+ writeFile(dsym, "zip");
+ expect(
+ buildDsymUpload({ EAS_BUILD_PLATFORM: "ios", EAS_BUILD_ID: "build-3" }, project),
+ ).toEqual({ key: "ios/dsym/build-3.zip", path: dsym });
+ });
+});
diff --git a/apps/mobile/scripts/upload-sourcemaps.mts b/apps/mobile/scripts/upload-sourcemaps.mts
new file mode 100644
index 00000000000..1656035906e
--- /dev/null
+++ b/apps/mobile/scripts/upload-sourcemaps.mts
@@ -0,0 +1,61 @@
+#!/usr/bin/env node
+// Usage: `ota <dist>` after `eas update --emit-metadata`, or `build` from eas-build-on-success.
+// Problems are warnings, never failures: an unreadable stack is not worth failing a release over.
+import {
+ buildDsymUpload,
+ buildSourceMapUpload,
+ otaSourceMapUploads,
+ parseCredentials,
+ uploadDsym,
+ uploadSourceMap,
+ type SourceMapUpload,
+} from "./sourcemap-upload.mts";
+
+const warn = (message: string) => {
+ // GitHub Actions shows this as an annotation; elsewhere it is a log line.
+ console.warn(process.env.GITHUB_ACTIONS ? `::warning::${message}` : `warning: ${message}`);
+};
+
+const errorMessage = (error: unknown) => (error instanceof Error ? error.message : String(error));
+
+async function main() {
+ const [mode, distDir] = process.argv.slice(2);
+ const credentials = parseCredentials(process.env.MOBILE_SOURCEMAPS_R2);
+ if (!credentials) {
+ warn("MOBILE_SOURCEMAPS_R2 is not set; crash stacks from this bundle stay minified.");
+ return;
+ }
+ let uploads: ReadonlyArray<SourceMapUpload>;
+ if (mode === "ota" && distDir) {
+ uploads = otaSourceMapUploads(distDir);
+ } else if (mode === "build") {
+ uploads = [buildSourceMapUpload(process.env, process.cwd())];
+ } else {
+ throw new Error("Usage: upload-sourcemaps.mts ota <dist-dir> | build");
+ }
+ if (uploads.length === 0) warn("Found no source maps to upload.");
+ for (const upload of uploads) {
+ try {
+ const bytes = await uploadSourceMap(credentials, upload);
+ console.log(`Uploaded ${upload.key} (${(bytes / 1e6).toFixed(1)} MB)`);
+ } catch (error) {
+ warn(`Could not upload ${upload.key}: ${errorMessage(error)}`);
+ }
+ }
+ if (mode !== "build" || process.env.EAS_BUILD_PLATFORM !== "ios") return;
+ const dsym = buildDsymUpload(process.env, process.cwd());
+ if (!dsym) {
+ warn("Found no dSYM under ios/build; native iOS frames from this build stay unreadable.");
+ return;
+ }
+ try {
+ const bytes = await uploadDsym(credentials, dsym);
+ console.log(`Uploaded ${dsym.key} (${(bytes / 1e6).toFixed(1)} MB)`);
+ } catch (error) {
+ warn(`Could not upload ${dsym.key}: ${errorMessage(error)}`);
+ }
+}
+
+await main().catch((error: unknown) => {
+ warn(`Source map upload skipped: ${errorMessage(error)}`);
+});
diff --git a/apps/mobile/src/components/RenderErrorBoundary.tsx b/apps/mobile/src/components/RenderErrorBoundary.tsx
index 16f9439a2cd..f4a6035b097 100644
--- a/apps/mobile/src/components/RenderErrorBoundary.tsx
+++ b/apps/mobile/src/components/RenderErrorBoundary.tsx
@@ -1,3 +1,4 @@
+import { Observe } from "expo-observe";
import { Component, type ReactNode } from "react";
import { ScrollView, View } from "react-native";
@@ -60,7 +61,9 @@ export class RenderErrorBoundary extends Component<
return { failed: true, error };
}
- override componentDidCatch(_error: unknown, info: { componentStack?: string }) {
+ override componentDidCatch(error: unknown, info: { componentStack?: string }) {
+ // A caught render error never reaches Observe's global handler.
+ Observe.reportError(error);
this.setState({ componentStack: info.componentStack });
}
diff --git a/apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx b/apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx
index 41872729346..8c0cbff3352 100644
--- a/apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx
+++ b/apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx
@@ -3,8 +3,9 @@ import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScroll
import * as Application from "expo-application";
import Constants from "expo-constants";
import * as Updates from "expo-updates";
-import { useAtomValue } from "@effect/atom-react";
+import { useAtomSet, useAtomValue } from "@effect/atom-react";
import * as Effect from "effect/Effect";
+import * as Exit from "effect/Exit";
import { AsyncResult, Atom } from "effect/reactivity";
import { useState } from "react";
import { View } from "react-native";
@@ -13,9 +14,12 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
import { SymbolView } from "../../components/ui/AppSymbol";
import { AppText as Text } from "../../components/ui/AppText";
import { tryCopyTextWithHaptic } from "../../lib/copyTextWithHaptic";
+import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
+import { crashReportingAvailable, setCrashReportsEnabled } from "../observability/observe";
import { SettingsActionRow } from "../settings/components/SettingsActionRow";
import { SettingsScreen } from "../settings/components/SettingsScreen";
import { SettingsSection } from "../settings/components/SettingsSection";
+import { SettingsSwitchRow } from "../settings/components/SettingsSwitchRow";
import {
formatStartupCrashReport,
parseStartupCrashRecords,
@@ -86,6 +90,8 @@ export function SettingsDiagnosticsRouteScreen() {
className="flex-1"
contentContainerClassName="gap-6 px-5 pt-4 pb-[18px]"
>
+ {crashReportingAvailable ? <CrashReportsSetting /> : null}
+
<SettingsSection title="Startup crashes">
{state.status === "loading" ? (
<View className="items-center gap-3 px-6 py-8">
@@ -131,6 +137,54 @@ export function SettingsDiagnosticsRouteScreen() {
);
}
+function CrashReportsSetting() {
+ const preferences = useAtomValue(mobilePreferencesAtom);
+ const savePreferences = useAtomSet(updateMobilePreferencesAtom, { mode: "promiseExit" });
+ // One change at a time, so a slow save never turns sending back on after a later opt-out.
+ const [saving, setSaving] = useState(false);
+ const ready = AsyncResult.isSuccess(preferences) && !preferences.waiting;
+ const enabled = AsyncResult.isSuccess(preferences)
+ ? preferences.value.crashReportsEnabled !== false
+ : true;
+
+ const change = (value: boolean) => {
+ setSaving(true);
+ // Sending stops before the save and starts only after it.
+ if (!value) void setCrashReportsEnabled(false);
+ savePreferences({ crashReportsEnabled: value })
+ .then((exit) => {
+ if (Exit.isFailure(exit)) {
+ console.warn("[diagnostics] could not save the crash report setting", exit.cause);
+ return value ? undefined : setCrashReportsEnabled(true);
+ }
+ return value ? setCrashReportsEnabled(true) : undefined;
+ })
+ .catch((error: unknown) => {
+ console.warn("[diagnostics] could not apply the crash report setting", error);
+ })
+ .finally(() => setSaving(false));
+ };
+
+ return (
+ <View className="gap-3">
+ <SettingsSection title="Crash reports">
+ <SettingsSwitchRow
+ icon="tray.and.arrow.up"
+ label="Send crash reports"
+ disabled={!ready || saving}
+ value={enabled}
+ onValueChange={change}
+ />
+ </SettingsSection>
+ <Text className="px-2 text-sm leading-normal text-foreground-muted">
+ When the app crashes or hits an error, it sends the error message, the stack trace, the app
+ version, and the device model and OS version to the T3 Code team. Each launch also sends
+ startup timings. Reports carry a random ID for this install.
+ </Text>
+ </View>
+ );
+}
+
function EmptyState(props: {
readonly icon: "exclamationmark.triangle" | "checkmark.circle";
readonly title: string;
diff --git a/apps/mobile/src/features/observability/observe.ts b/apps/mobile/src/features/observability/observe.ts
new file mode 100644
index 00000000000..fbbb5e22b83
--- /dev/null
+++ b/apps/mobile/src/features/observability/observe.ts
@@ -0,0 +1,63 @@
+import Constants from "expo-constants";
+import { Observe } from "expo-observe";
+
+// Importing expo-observe installs its global JS error handler; reports leave only through the relay.
+const relayUrl: unknown = Constants.expoConfig?.extra?.relay?.url;
+const appVariant: unknown = Constants.expoConfig?.extra?.appVariant;
+
+export const crashReportingAvailable = typeof relayUrl === "string" && relayUrl.trim() !== "";
+
+interface PromiseRejectionTracker {
+ readonly enablePromiseRejectionTracker?: (options: {
+ readonly allRejections: boolean;
+ readonly onUnhandled: (id: number, rejection: unknown) => void;
+ }) => void;
+}
+
+// React Native tracks unhandled rejections only in development, for LogBox; Observe has no hook.
+if (!__DEV__) {
+ const hermes: PromiseRejectionTracker | undefined = Reflect.get(globalThis, "HermesInternal");
+ hermes?.enablePromiseRejectionTracker?.({
+ allRejections: true,
+ onUnhandled: (_id, rejection) => Observe.reportError(rejection),
+ });
+}
+
+let latestConfiguration = 0;
+
+// While sending is off, a dispatch pass drops what it finds, so one runs before turning it back on.
+// Best effort: Observe skips the pass while it is backing off from a failed send.
+export async function setCrashReportsEnabled(enabled: boolean) {
+ const configuration = ++latestConfiguration;
+ const dispatchingEnabled = crashReportingAvailable && enabled;
+ if (dispatchingEnabled) {
+ await Observe.dispatchEvents();
+ if (configuration !== latestConfiguration) return;
+ }
+ Observe.configure({
+ dispatchingEnabled,
+ ...(typeof appVariant === "string" ? { environment: appVariant } : {}),
+ });
+}
+
+if (!crashReportingAvailable) {
+ void setCrashReportsEnabled(false);
+} else {
+ // Observe keeps its last configuration across launches; configuring it off while the setting
+ // loads would drop the last session's native crash. Imported lazily so the persistence graph
+ // never runs ahead of the imports `index.ts` orders first.
+ const changedSinceLoad = () => latestConfiguration !== 0;
+ void import("../../persistence/imperative")
+ .then(({ loadPreferences }) => loadPreferences())
+ .then(
+ (preferences) =>
+ changedSinceLoad()
+ ? undefined
+ : setCrashReportsEnabled(preferences.crashReportsEnabled !== false),
+ // Observe keeps the last choice it was given, which stands in for the unreadable one.
+ (error: unknown) => console.warn("[observe] could not read the crash report setting", error),
+ )
+ .catch((error: unknown) => {
+ console.warn("[observe] could not apply the crash report setting", error);
+ });
+}
diff --git a/apps/mobile/src/persistence/mobile-preferences.ts b/apps/mobile/src/persistence/mobile-preferences.ts
index 3a79a73ee3c..b38e65c0f25 100644
--- a/apps/mobile/src/persistence/mobile-preferences.ts
+++ b/apps/mobile/src/persistence/mobile-preferences.ts
@@ -103,6 +103,8 @@ export interface Preferences {
readonly codeFontSize?: number | null;
readonly codeWordBreak?: boolean;
readonly mathRenderingEnabled?: boolean;
+ /** Unset means on: crash reports are sent unless the user turns them off. */
+ readonly crashReportsEnabled?: boolean;
readonly connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
readonly collapsedProjectGroups?: readonly string[];
readonly dismissedDatabaseStorageNotices?: readonly string[];
@@ -183,6 +185,7 @@ function sanitizePreferences(parsed: Preferences): Preferences {
codeFontSize?: number | null;
codeWordBreak?: boolean;
mathRenderingEnabled?: boolean;
+ crashReportsEnabled?: boolean;
connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
collapsedProjectGroups?: readonly string[];
dismissedDatabaseStorageNotices?: readonly string[];
@@ -272,6 +275,9 @@ function sanitizePreferences(parsed: Preferences): Preferences {
if (typeof parsed.codeWordBreak === "boolean") preferences.codeWordBreak = parsed.codeWordBreak;
if (typeof parsed.mathRenderingEnabled === "boolean")
preferences.mathRenderingEnabled = parsed.mathRenderingEnabled;
+ if (typeof parsed.crashReportsEnabled === "boolean") {
+ preferences.crashReportsEnabled = parsed.crashReportsEnabled;
+ }
if (Array.isArray(parsed.connectOnboardingOptOutAccounts)) {
preferences.connectOnboardingOptOutAccounts = parsed.connectOnboardingOptOutAccounts.filter(
(account): account is string => typeof account === "string",
diff --git a/docs/operations/relay-observability.md b/docs/operations/relay-observability.md
index f2cd94e333b..a64ac6cdb3e 100644
--- a/docs/operations/relay-observability.md
+++ b/docs/operations/relay-observability.md
@@ -10,6 +10,11 @@ The relay Alchemy stack owns a shared Axiom trace setup:
- `t3-code-mobile-otel-ingest-prod`, the dataset-scoped mobile ingest token
- `t3-code-relay-client-otel-ingest-prod`, the dataset-scoped first-party relay-client ingest token
- `t3-code-relay-recent-spans-prod`, a view of recent request and endpoint spans
+- `t3-code-mobile-logs-prod` and `t3-code-mobile-metrics-prod`, the mobile app's crash, error, and
+ startup data from `expo-observe` (see [Mobile crashes and errors](#mobile-crashes-and-errors))
+- `t3-code-mobile-telemetry-ingest-prod`, the ingest token the Worker forwards that data with
+- `t3-code-mobile-sourcemaps-prod`, the R2 bucket of mobile JavaScript source maps, and
+ `t3-code-mobile-sourcemaps-upload-prod`, a Cloudflare token that can only write objects to it
Alchemy stages append their sanitized stage name to isolate resources, for example
`t3-code-relay-traces-dev-julius` for a personal stage.
@@ -159,3 +164,91 @@ see [Managed tunnel cleanup rollout](release.md#managed-tunnel-cleanup-rollout).
**Links degraded / database slow.** Warnings for slow degradation. Link failures above 20% over six
hours have so far meant provisioning running into the 9 s deadline, with Postgres latency as the
usual cause.
+
+## Mobile crashes and errors
+
+The mobile app reports through [`expo-observe`](https://docs.expo.dev/eas/observe/). Its
+`endpointUrl` points at the relay (`/v1/mobile/observe`, set in `apps/mobile/app.config.ts` from
+`T3CODE_RELAY_URL`), because Observe cannot send auth headers and prefixes every path with the EAS
+project id. The relay forwards each request to Axiom with its own token: logs (JavaScript errors,
+native crashes, log events) to `t3-code-mobile-logs-*`, metrics to `t3-code-mobile-metrics-*`, and
+spans to the shared traces dataset. Expo's Observe dashboard receives nothing. The endpoint URL is
+compiled into the native app, so pointing it elsewhere takes a store build.
+
+Hermes stacks from release builds are minified bytecode offsets. On the way through, the relay
+rewrites each JavaScript exception's `exception.stacktrace` with the bundle's source map from R2
+and records the outcome on the log record:
+
+- `relay.symbolication.status`: `symbolicated`, or why not. `no_bundle_id` is a development or
+ local build. `source_map_missing` means no map was uploaded for the bundle;
+ `source_map_too_large`, `source_map_invalid` and `source_map_unavailable` (R2 unreadable, retried
+ shortly) mean one was. `source_map_limit` is a request naming more bundles than the relay decodes
+ at once, and `no_bundle_frames` a stack with no frames from the bundle.
+- `relay.symbolication.source_map`: the R2 key used
+- `relay.symbolication.raw_stacktrace`: the original stack, when it was rewritten
+
+iOS frames lose their install path (`/private/var/containers/Bundle/Application/<uuid>/...`), which
+differs per install, so `exception.stacktrace` groups across users.
+
+A fatal JavaScript error ends in a native abort, which Observe reports as a second crash with a
+generic React Native stack. The relay marks that one `relay.crash.js_fatal` when both arrive in one
+request, as they do on the next launch. Leave it out to count real native crashes:
+
+```apl
+['t3-code-mobile-logs-prod']
+| where ['attributes.expo.error.source'] == 'nativeCrash'
+| where isnull(['attributes.relay.crash.js_fatal'])
+| summarize count() by ['attributes.exception.type'], ['attributes.exception.message']
+```
+
+Native crash stacks (`expo.error.source == 'nativeCrash'`) are not symbolicated. On iOS, app frames
+read like `main (T3Code + 19476)`: the offset into the app binary. The build hook uploads that
+build's dSYMs to `ios/dsym/<easBuildId>.zip`; download it with an account R2 token, then:
+
+```sh
+unzip <easBuildId>.zip
+atos -arch arm64 -o T3Code.app.dSYM/Contents/Resources/DWARF/T3Code -l 0x100000000 \
+ $(printf '0x%x' $((0x100000000 + 19476)))
+```
+
+Maps are keyed by the bundle that crashed: `<platform>/ota/<updateId>.map` for OTA updates and
+`<platform>/build/<easBuildId>.map` for the bundle embedded in a store build. The production
+mobile workflow uploads OTA maps after `eas update`, and the `eas-build-on-success` hook in
+`apps/mobile/package.json` uploads a build's map, both with `apps/mobile/scripts/upload-sourcemaps.mts`.
+They need the `MOBILE_SOURCEMAPS_R2` secret, a JSON value the stack outputs as
+`mobileSourceMapsUploadCredentials` from a token that can only write to the bucket. Creating that
+token needs **Account API Tokens: Edit** on the deploy token. Deploy output shows it redacted; read
+it from state, where it is under `__redacted__`:
+
+```sh
+cd infra/relay && vp exec alchemy state read T3CodeRelay/prod/output
+```
+
+Set it as a GitHub Actions secret, for OTA updates, and as an EAS environment variable with
+`secret` visibility in the `production` environment only, for builds. Keep it out of `preview`:
+PR preview builds run the PR's code in that environment. In CI only the upload step gets it, not
+`eas update` and the dependencies it runs. If the deploy replaces the token, update both.
+
+The `t3-code-mobile-health` dashboard is the place to look every few days: crash and handled
+error counts, top crashes with the installs and app versions they hit, crashes by version, whether
+stacks are symbolicated, and whether reports reach the relay at all. A crash counts once: the
+native abort after a JS crash (`relay.crash.js_fatal`) is left out. Startup times are metrics, so
+they are not on it; query `t3-code-mobile-metrics-*` with MPL. Prod and PR previews get the
+dashboard, and deployments with `RELAY_ALERT_NOTIFIER_ID` get these monitors
+([`infra/relay/src/mobileTelemetry/monitoring.ts`](../../infra/relay/src/mobileTelemetry/monitoring.ts)):
+
+- **crash spike** (pages): crashes per 15 min well above the same time over the last 7 days. Until
+ a week of data exists it has no baseline. A spike right after a release usually means a bad OTA
+ update; roll it back in EAS.
+- **one crash hitting many installs** (pages): a single crash on 25 installs within an hour.
+- **reports stopped** (warning): no startup metrics forwarded for an hour, so crashes are not
+ arriving either.
+- **crash stacks not symbolicated** (warning): over half of release JS stacks stayed minified for
+ 6 h. `relay.symbolication.status` names the cause.
+
+Thresholds are starting points, not measured baselines; revisit them after two weeks of
+production data.
+
+Without it, uploads are skipped with a warning and stacks stay minified. Each ingest request is one
+`relay.mobile_telemetry.ingest` span; `relay.mobile_telemetry.outcome` is `forwarded`,
+`rate_limited`, `body_too_large`, `upstream_unavailable`, or `upstream_timeout`.
diff --git a/docs/user/telemetry.md b/docs/user/telemetry.md
index 5b224b4ba14..aeec380e8dd 100644
--- a/docs/user/telemetry.md
+++ b/docs/user/telemetry.md
@@ -21,6 +21,16 @@ environment before starting it. Relay tracing also stops when `T3CODE_OTEL_SDK_D
The desktop app reads `T3CODE_TELEMETRY_ENABLED` from your shell profile (for example `~/.zshrc`) on macOS and
Linux, so export it there and restart the app. On Windows, set it as a user environment variable.
+## Mobile app crash reports
+
+When the iOS or Android app crashes or hits an error, it sends a report to T3 Code: the error
+message, the stack trace, the app version, and the device model and OS version. Each launch also
+sends startup timings, and every report carries a random ID for the install. Reports go through
+the T3 Connect relay to Axiom. They do not include your threads, prompts, or connection details,
+but an error message can quote a value the app was handling.
+
+To stop sending them, turn off **Send crash reports** in **Settings > About T3 Code > Diagnostics**.
+
## Export diagnostics to your own receiver
To send traces, metrics, or logs to an OpenTelemetry receiver, open
diff --git a/infra/relay/alchemy.run.ts b/infra/relay/alchemy.run.ts
index 7bca2b1c0e3..b203d518107 100644
--- a/infra/relay/alchemy.run.ts
+++ b/infra/relay/alchemy.run.ts
@@ -10,7 +10,7 @@ import * as Planetscale from "@alchemy.run/planetscale";
import { PublishClientConfig, tokenDigest } from "./src/clientConfig.ts";
import * as RelayDb from "./src/db.ts";
-import { RelayObservability } from "./src/observability.ts";
+import { MobileSourceMapsUploadCredentials, RelayObservability } from "./src/observability.ts";
import { isPreviewStage } from "./src/previewStages.ts";
import { PreviewTunnelSweep, PreviewTunnelSweepProvider } from "./src/previewTunnelSweep.ts";
import { ManagedEndpointZone, RelayApiZone, RelayDeploymentConfig } from "./src/zone.ts";
@@ -35,6 +35,7 @@ export default Alchemy.Stack(
const managedEndpointZone = yield* ManagedEndpointZone.pipe(Effect.orDie);
const relayApiZone = yield* RelayApiZone.pipe(Effect.orDie);
const observability = yield* RelayObservability;
+ const mobileSourceMapsUploadCredentials = yield* MobileSourceMapsUploadCredentials;
const api = yield* RelayWorker.Api;
if (isPreviewStage(stage)) {
const { managedEndpointZoneName } = yield* RelayDeploymentConfig;
@@ -72,6 +73,11 @@ export default Alchemy.Stack(
clientTracingUrl: observability.traces.otelTracesEndpoint,
clientTracingDataset: observability.traces.name,
clientTracingToken: observability.clientIngestToken.token,
+ mobileLogsDataset: observability.mobileLogs.name,
+ mobileMetricsDataset: observability.mobileMetrics.name,
+ mobileSourceMapsBucket: observability.mobileSourceMaps.bucketName,
+ // The MOBILE_SOURCEMAPS_R2 secret for GitHub Actions and EAS Build.
+ mobileSourceMapsUploadCredentials,
};
}).pipe(Effect.provide(RelayWorker.layer)),
);
diff --git a/infra/relay/src/mobileTelemetry/MobileTelemetry.test.ts b/infra/relay/src/mobileTelemetry/MobileTelemetry.test.ts
new file mode 100644
index 00000000000..1adea38b2ab
--- /dev/null
+++ b/infra/relay/src/mobileTelemetry/MobileTelemetry.test.ts
@@ -0,0 +1,382 @@
+import * as NodeHttpPlatform from "@effect/platform-node/NodeHttpPlatform";
+import * as NodeServices from "@effect/platform-node/NodeServices";
+import { describe, expect, it } from "@effect/vitest";
+import { RelayApi } from "@t3tools/contracts/relay";
+import * as Deferred from "effect/Deferred";
+import * as Effect from "effect/Effect";
+import * as Fiber from "effect/Fiber";
+import * as Layer from "effect/Layer";
+import * as Redacted from "effect/Redacted";
+import * as Schema from "effect/Schema";
+import * as Etag from "effect/http/Etag";
+import * as HttpClient from "effect/http/HttpClient";
+import type * as HttpClientError from "effect/http/HttpClientError";
+import type * as HttpClientRequest from "effect/http/HttpClientRequest";
+import * as HttpClientResponse from "effect/http/HttpClientResponse";
+import * as HttpEffect from "effect/http/HttpEffect";
+import * as HttpRouter from "effect/http/HttpRouter";
+import * as HttpServerRequest from "effect/http/HttpServerRequest";
+import * as HttpServerResponse from "effect/http/HttpServerResponse";
+import * as HttpApi from "effect/http-api/HttpApi";
+import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
+
+import { RELAY_HTTP_ROUTER_CONFIG } from "../http/Api.ts";
+import * as RelayHttpApi from "../http/Api.ts";
+import * as MobileTelemetry from "./MobileTelemetry.ts";
+
+const PROJECT_ID = "d763fcb8-d37c-41ea-a773-b54a0ab4a454";
+const UPDATE_ID = "0198e8a4-1111-7000-8000-000000000001";
+const BUILD_ID = "0198e8a4-2222-7000-8000-000000000002";
+const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
+const decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
+
+const destinations = {
+ traces: { url: "https://axiom.test/v1/traces", dataset: "mobile-traces" },
+ logs: { url: "https://axiom.test/v1/logs", dataset: "mobile-logs" },
+ metrics: { url: "https://axiom.test/v1/metrics", dataset: "mobile-metrics" },
+} as const;
+
+/** Maps generated column 12 of the one-line bundle to `src/App.tsx` 1:2. */
+const SOURCE_MAP = encodeJson({ version: 3, sources: ["src/App.tsx"], mappings: "AAAA,UAAE" });
+const STACK = "Error: x\n at render (address at index.android.bundle:1:12)";
+
+interface Harness {
+ readonly execute?: (
+ request: HttpClientRequest.HttpClientRequest,
+ ) => Effect.Effect<HttpClientResponse.HttpClientResponse, HttpClientError.HttpClientError>;
+ /** The source maps bucket, by key. */
+ readonly objects?: Readonly<Record<string, string>>;
+}
+
+const makeHarness = (options: Harness = {}) => {
+ const sent: Array<HttpClientRequest.HttpClientRequest> = [];
+ const execute =
+ options.execute ??
+ ((request: HttpClientRequest.HttpClientRequest) =>
+ Effect.succeed(
+ HttpClientResponse.fromWeb(
+ request,
+ new Response("{}", { status: 200, headers: { "content-type": "application/json" } }),
+ ),
+ ));
+ const layerTelemetry = MobileTelemetry.layer.pipe(
+ Layer.provide(
+ Layer.mergeAll(
+ Layer.succeed(MobileTelemetry.MobileTelemetrySettings, {
+ axiomToken: Redacted.make("axiom-ingest-token"),
+ destinations,
+ }),
+ Layer.succeed(MobileTelemetry.MobileTelemetryRateLimiter, {
+ allow: () => Effect.succeed(true),
+ }),
+ MobileTelemetry.layerSourceMaps.pipe(
+ Layer.provide(
+ Layer.succeed(MobileTelemetry.SourceMapObjects, {
+ get: (key) =>
+ Effect.sync(() => {
+ const object = options.objects?.[key];
+ return object === undefined
+ ? undefined
+ : { size: object.length, text: Effect.succeed(object) };
+ }),
+ }),
+ ),
+ ),
+ Layer.succeed(
+ HttpClient.HttpClient,
+ HttpClient.make((request) => {
+ sent.push(request);
+ return execute(request);
+ }),
+ ),
+ ),
+ ),
+ );
+ const httpEffect = HttpRouter.toHttpEffect(
+ Layer.mergeAll(
+ HttpApiBuilder.layer(HttpApi.make("RelayApi").add(RelayApi.groups.mobileTelemetry)).pipe(
+ Layer.provide(MobileTelemetry.layerApi.pipe(Layer.provide(layerTelemetry))),
+ Layer.provide([NodeServices.layer, NodeHttpPlatform.layer, Etag.layerWeak]),
+ ),
+ RelayHttpApi.layerNotFoundRoute,
+ ),
+ ).pipe(Effect.provideService(HttpRouter.RouterConfig, RELAY_HTTP_ROUTER_CONFIG));
+ const send = (request: Request) =>
+ Effect.gen(function* () {
+ const handler = yield* httpEffect;
+ const response = yield* Deferred.make<HttpServerResponse.HttpServerResponse>();
+ yield* HttpEffect.toHandled(handler, (_request, value) =>
+ Deferred.succeed(response, value),
+ ).pipe(
+ Effect.provideService(
+ HttpServerRequest.HttpServerRequest,
+ HttpServerRequest.fromWeb(request),
+ ),
+ );
+ return yield* Deferred.await(response);
+ });
+ return { sent, send };
+};
+
+const ingest = (signal: string, body: string) =>
+ new Request(`https://relay.test/v1/mobile/observe/${PROJECT_ID}/v1/${signal}`, {
+ method: "POST",
+ headers: { "content-type": "application/json", "cf-connecting-ip": "203.0.113.7" },
+ body,
+ });
+
+const sentText = (request: HttpClientRequest.HttpClientRequest) =>
+ request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "";
+
+const str = (key: string, value: string) => ({ key, value: { stringValue: value } });
+
+/** One resource's JS exception, as Observe reports it from the app's bundle. */
+const exceptionResource = (resource: ReadonlyArray<ReturnType<typeof str>>) => ({
+ resource: { attributes: resource },
+ scopeLogs: [
+ {
+ logRecords: [
+ {
+ attributes: [str("expo.error.source", "global"), str("exception.stacktrace", STACK)],
+ },
+ ],
+ },
+ ],
+});
+
+/** Each forwarded exception record's string attributes. */
+const forwardedExceptions = (request: HttpClientRequest.HttpClientRequest) => {
+ const payload = decodeJson(sentText(request)) as {
+ resourceLogs: Array<{
+ scopeLogs: Array<{
+ logRecords: Array<{ attributes: Array<{ key: string; value: { stringValue: string } }> }>;
+ }>;
+ }>;
+ };
+ return payload.resourceLogs.map((resourceLogs) =>
+ Object.fromEntries(
+ resourceLogs.scopeLogs[0]!.logRecords[0]!.attributes.map(({ key, value }) => [
+ key,
+ value.stringValue,
+ ]),
+ ),
+ );
+};
+
+describe("MobileTelemetry", () => {
+ it.effect("forwards each signal to its Axiom dataset with the relay's token", () =>
+ Effect.gen(function* () {
+ const harness = makeHarness();
+ const body = encodeJson({ resourceMetrics: [] });
+ for (const signal of ["metrics", "traces", "logs"] as const) {
+ const response = yield* harness.send(ingest(signal, body));
+ expect(response.status).toBe(200);
+ }
+ expect(
+ harness.sent.map((request) => ({
+ url: request.url,
+ authorization: request.headers.authorization,
+ dataset: request.headers["x-axiom-dataset"],
+ body: sentText(request),
+ })),
+ ).toEqual(
+ (["metrics", "traces", "logs"] as const).map((signal) => ({
+ url: destinations[signal].url,
+ authorization: "Bearer axiom-ingest-token",
+ dataset: destinations[signal].dataset,
+ body,
+ })),
+ );
+ }),
+ );
+
+ it.effect("passes Axiom's status and Retry-After back for Observe's retries", () =>
+ Effect.gen(function* () {
+ const harness = makeHarness({
+ execute: (request) =>
+ Effect.succeed(
+ HttpClientResponse.fromWeb(
+ request,
+ new Response('{"message":"slow down"}', {
+ status: 429,
+ headers: { "content-type": "application/json", "retry-after": "30" },
+ }),
+ ),
+ ),
+ });
+ const response = yield* harness.send(ingest("metrics", "{}"));
+ expect(response.status).toBe(429);
+ expect(response.headers["retry-after"]).toBe("30");
+ }),
+ );
+
+ it.effect("symbolicates JS exceptions with the OTA update's map, else the build's", () =>
+ Effect.gen(function* () {
+ const harness = makeHarness({
+ objects: {
+ [`android/ota/${UPDATE_ID}.map`]: SOURCE_MAP,
+ [`ios/build/${BUILD_ID}.map`]: SOURCE_MAP,
+ },
+ });
+ const body = encodeJson({
+ resourceLogs: [
+ exceptionResource([
+ str("os.type", "linux"),
+ str("expo.app.update_id", UPDATE_ID),
+ str("expo.eas_build.id", BUILD_ID),
+ ]),
+ exceptionResource([str("os.type", "darwin"), str("expo.eas_build.id", BUILD_ID)]),
+ ],
+ });
+ expect((yield* harness.send(ingest("logs", body))).status).toBe(200);
+ const symbolicated = (key: string) => ({
+ "expo.error.source": "global",
+ "exception.stacktrace": "Error: x\n at render (src/App.tsx:1:3)",
+ "relay.symbolication.source_map": key,
+ "relay.symbolication.status": "symbolicated",
+ "relay.symbolication.raw_stacktrace": STACK,
+ });
+ expect(forwardedExceptions(harness.sent[0]!)).toEqual([
+ symbolicated(`android/ota/${UPDATE_ID}.map`),
+ symbolicated(`ios/build/${BUILD_ID}.map`),
+ ]);
+ }),
+ );
+
+ it.effect("forwards the stack untouched when the OTA update's map is missing", () =>
+ Effect.gen(function* () {
+ // The build's map describes the embedded bundle, not the update that threw.
+ const harness = makeHarness({
+ objects: { [`android/build/${BUILD_ID}.map`]: SOURCE_MAP },
+ });
+ const body = encodeJson({
+ resourceLogs: [
+ exceptionResource([
+ str("os.type", "linux"),
+ str("expo.app.update_id", UPDATE_ID),
+ str("expo.eas_build.id", BUILD_ID),
+ ]),
+ ],
+ });
+ expect((yield* harness.send(ingest("logs", body))).status).toBe(200);
+ expect(forwardedExceptions(harness.sent[0]!)).toEqual([
+ {
+ "expo.error.source": "global",
+ "exception.stacktrace": STACK,
+ "relay.symbolication.status": "source_map_missing",
+ },
+ ]);
+ }),
+ );
+
+ it.effect("says why a stack stayed minified, without the iOS install path", () =>
+ Effect.gen(function* () {
+ const harness = makeHarness({ objects: { [`ios/build/${BUILD_ID}.map`]: "{}" } });
+ const iosStack =
+ "Error: x\n at render (address at /private/var/containers/Bundle/Application/" +
+ "0C1D/T3Code.app/main.jsbundle:1:12)";
+ const record = (stack: string) => ({
+ scopeLogs: [{ logRecords: [{ attributes: [str("exception.stacktrace", stack)] }] }],
+ });
+ const body = encodeJson({
+ resourceLogs: [
+ { resource: { attributes: [str("os.type", "linux")] }, ...record(STACK) },
+ {
+ resource: {
+ attributes: [str("os.type", "darwin"), str("expo.eas_build.id", BUILD_ID)],
+ },
+ ...record(iosStack),
+ },
+ ],
+ });
+ expect((yield* harness.send(ingest("logs", body))).status).toBe(200);
+ expect(forwardedExceptions(harness.sent[0]!)).toEqual([
+ { "exception.stacktrace": STACK, "relay.symbolication.status": "no_bundle_id" },
+ {
+ "exception.stacktrace": "Error: x\n at render (address at main.jsbundle:1:12)",
+ "relay.symbolication.status": "source_map_invalid",
+ },
+ ]);
+ }),
+ );
+
+ it.effect("marks the native abort that follows a fatal JS error in the same session", () =>
+ Effect.gen(function* () {
+ const harness = makeHarness();
+ const fatal = { key: "expo.error.is_fatal", value: { boolValue: true } };
+ const crash = (session: string, source: string) => ({
+ attributes: [str("expo.error.source", source), str("session.id", session), fatal],
+ });
+ const body = encodeJson({
+ resourceLogs: [
+ {
+ resource: { attributes: [str("os.type", "darwin")] },
+ scopeLogs: [
+ {
+ logRecords: [
+ crash("a", "global"),
+ crash("a", "nativeCrash"),
+ crash("b", "nativeCrash"),
+ ],
+ },
+ ],
+ },
+ ],
+ });
+ expect((yield* harness.send(ingest("logs", body))).status).toBe(200);
+ const records = (
+ decodeJson(sentText(harness.sent[0]!)) as {
+ resourceLogs: Array<{
+ scopeLogs: Array<{ logRecords: Array<{ attributes: Array<{ key: string }> }> }>;
+ }>;
+ }
+ ).resourceLogs[0]!.scopeLogs[0]!.logRecords;
+ expect(
+ records.map((record) =>
+ record.attributes.some((attribute) => attribute.key === "relay.crash.js_fatal"),
+ ),
+ ).toEqual([false, true, false]);
+ }),
+ );
+
+ it.effect("answers 413 for a body over the cap without forwarding it", () =>
+ Effect.gen(function* () {
+ const harness = makeHarness();
+ const tooLarge = "x".repeat(MobileTelemetry.MOBILE_TELEMETRY_MAX_BODY_BYTES + 1);
+ expect((yield* harness.send(ingest("logs", tooLarge))).status).toBe(413);
+ expect(harness.sent).toEqual([]);
+ }),
+ );
+
+ it.effect("decodes one source map at a time", () =>
+ Effect.gen(function* () {
+ const releaseFirst = yield* Deferred.make<void>();
+ const firstStarted = yield* Deferred.make<void>();
+ let firstDone = false;
+ let secondSawFirstDone: boolean | undefined;
+ const sourceMaps = yield* MobileTelemetry.SourceMaps.pipe(
+ Effect.provide(MobileTelemetry.layerSourceMaps),
+ Effect.provideService(MobileTelemetry.SourceMapObjects, {
+ get: (key) =>
+ key === "first"
+ ? Deferred.succeed(firstStarted, undefined).pipe(
+ Effect.andThen(Deferred.await(releaseFirst)),
+ Effect.as({ size: SOURCE_MAP.length, text: Effect.succeed(SOURCE_MAP) }),
+ Effect.ensuring(Effect.sync(() => (firstDone = true))),
+ )
+ : Effect.sync(() => {
+ secondSawFirstDone = firstDone;
+ return { size: SOURCE_MAP.length, text: Effect.succeed(SOURCE_MAP) };
+ }),
+ }),
+ );
+ const first = yield* Effect.forkChild(sourceMaps.find("first"));
+ yield* Deferred.await(firstStarted);
+ const second = yield* Effect.forkChild(sourceMaps.find("second"), { startImmediately: true });
+ yield* Deferred.succeed(releaseFirst, undefined);
+ yield* Fiber.join(first);
+ expect(yield* Fiber.join(second)).toMatchObject({ key: "second" });
+ expect(secondSawFirstDone).toBe(true);
+ }),
+ );
+});
diff --git a/infra/relay/src/mobileTelemetry/MobileTelemetry.ts b/infra/relay/src/mobileTelemetry/MobileTelemetry.ts
new file mode 100644
index 00000000000..88a6ba1e4de
--- /dev/null
+++ b/infra/relay/src/mobileTelemetry/MobileTelemetry.ts
@@ -0,0 +1,339 @@
+import * as Cache from "effect/Cache";
+import * as Context from "effect/Context";
+import * as Duration from "effect/Duration";
+import * as Effect from "effect/Effect";
+import * as Exit from "effect/Exit";
+import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
+import * as Redacted from "effect/Redacted";
+import * as Result from "effect/Result";
+import * as Schema from "effect/Schema";
+import * as Semaphore from "effect/Semaphore";
+import * as Stream from "effect/Stream";
+import * as HttpClient from "effect/http/HttpClient";
+import * as HttpClientRequest from "effect/http/HttpClientRequest";
+import type * as HttpServerRequest from "effect/http/HttpServerRequest";
+import * as HttpServerResponse from "effect/http/HttpServerResponse";
+import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
+import { RelayApi, type RelayMobileTelemetrySignal } from "@t3tools/contracts/relay";
+
+import {
+ applySymbolication,
+ bundleSourceMapKey,
+ collectJsExceptions,
+ markJsFatalCrashes,
+ type SourceMapMiss,
+} from "./otlpLogs.ts";
+import { decodeSourceMap, type CompactSourceMap } from "./sourceMap.ts";
+
+/** Observe splits batches the endpoint answers 413 for, so this only bounds one request. */
+export const MOBILE_TELEMETRY_MAX_BODY_BYTES = 2 * 1024 * 1024;
+/** Per client IP. An app flushes a few batches per launch and background. */
+export const MOBILE_TELEMETRY_RATE_LIMIT = { limit: 120, periodSeconds: 60 } as const;
+/** Inside the relay's 9 s request deadline, so a slow Axiom answers as `upstream_timeout`. */
+const UPSTREAM_TIMEOUT = Duration.seconds(7);
+const MAX_UPSTREAM_RESPONSE_BYTES = 64 * 1024;
+/** A decoded production map is about 20 MB; two fit an isolate and cover iOS and Android. */
+const SOURCE_MAP_CACHE_CAPACITY = 2;
+/** Our iOS map is about 12 MB once uploads drop what the relay never reads; larger is skipped unread. */
+const MAX_SOURCE_MAP_BYTES = 16 * 1024 * 1024;
+/** A request can carry thousands of frames, each rewritten to a longer source path. */
+const MAX_SYMBOLICATION_GROWTH = 1024 * 1024;
+/** One app names one bundle, or two across an OTA update; more would evict cached maps. */
+const MAX_SOURCE_MAPS_PER_REQUEST = 2;
+/** A map can land in R2 a moment after its update ships, so a miss is retried. */
+const MISSING_SOURCE_MAP_TTL = Duration.minutes(5);
+const FAILED_SOURCE_MAP_TTL = Duration.seconds(30);
+
+const UnknownFromJsonString = Schema.fromJsonString(Schema.Unknown);
+const decodeJson = Schema.decodeUnknownOption(UnknownFromJsonString);
+const encodeJson = Schema.encodeSync(UnknownFromJsonString);
+const parseJson = (text: string): unknown => Option.getOrUndefined(decodeJson(text));
+
+interface AxiomDestination {
+ /** Axiom's OTLP/HTTP endpoint for the signal, such as `.../v1/logs`. */
+ readonly url: string;
+ readonly dataset: string;
+}
+
+export class MobileTelemetrySettings extends Context.Service<
+ MobileTelemetrySettings,
+ {
+ readonly axiomToken: Redacted.Redacted<string>;
+ readonly destinations: Readonly<Record<RelayMobileTelemetrySignal, AxiomDestination>>;
+ }
+>()("t3code-relay/mobileTelemetry/MobileTelemetry/MobileTelemetrySettings") {}
+
+export class MobileTelemetryRateLimiter extends Context.Service<
+ MobileTelemetryRateLimiter,
+ { readonly allow: (key: string) => Effect.Effect<boolean> }
+>()("t3code-relay/mobileTelemetry/MobileTelemetry/MobileTelemetryRateLimiter") {}
+
+export class SourceMapObjectError extends Schema.TaggedError<SourceMapObjectError>()(
+ "SourceMapObjectError",
+ { key: Schema.String, cause: Schema.Defect() },
+) {}
+
+/** An object in the source maps bucket, read only once its size is known to fit. */
+interface StoredSourceMap {
+ readonly size: number;
+ readonly text: Effect.Effect<string, SourceMapObjectError>;
+}
+
+interface FoundSourceMap {
+ readonly key: string;
+ readonly map: CompactSourceMap;
+}
+
+export class SourceMaps extends Context.Service<
+ SourceMaps,
+ {
+ readonly find: (key: string) => Effect.Effect<FoundSourceMap | SourceMapMiss>;
+ }
+>()("t3code-relay/mobileTelemetry/MobileTelemetry/SourceMaps") {}
+
+export class SourceMapObjects extends Context.Service<
+ SourceMapObjects,
+ {
+ readonly get: (key: string) => Effect.Effect<StoredSourceMap | undefined, SourceMapObjectError>;
+ }
+>()("t3code-relay/mobileTelemetry/MobileTelemetry/SourceMapObjects") {}
+
+const makeSourceMaps = Effect.gen(function* () {
+ const objects = yield* SourceMapObjects;
+ // The cache only joins lookups of one key; a decode holds ~40 MB, so different keys take turns.
+ const decoding = yield* Semaphore.make(1);
+ const cache = yield* Cache.makeWith(
+ (key: string) =>
+ Effect.gen(function* () {
+ const stored = yield* objects.get(key);
+ if (stored === undefined) return "source_map_missing" as const;
+ if (stored.size > MAX_SOURCE_MAP_BYTES) {
+ yield* Effect.logWarning("Stored mobile source map is too large", {
+ key,
+ size: stored.size,
+ });
+ return "source_map_too_large" as const;
+ }
+ const map = decodeSourceMap(parseJson(yield* stored.text));
+ if (typeof map !== "string") return { key, map } satisfies FoundSourceMap;
+ yield* Effect.logWarning("Stored mobile source map could not be decoded", { key, map });
+ return map === "too_large"
+ ? ("source_map_too_large" as const)
+ : ("source_map_invalid" as const);
+ }).pipe(Semaphore.withPermit(decoding)),
+ {
+ capacity: SOURCE_MAP_CACHE_CAPACITY,
+ timeToLive: (exit) =>
+ Exit.isFailure(exit)
+ ? FAILED_SOURCE_MAP_TTL
+ : typeof exit.value === "string"
+ ? MISSING_SOURCE_MAP_TTL
+ : Duration.infinity,
+ },
+ );
+ return SourceMaps.of({
+ find: Effect.fn("MobileTelemetry.findSourceMap")(function* (key: string) {
+ return yield* Cache.get(cache, key).pipe(
+ Effect.catch((error) =>
+ Effect.logWarning("Mobile source map lookup failed", { key: error.key }).pipe(
+ Effect.as("source_map_unavailable" as const),
+ ),
+ ),
+ );
+ }),
+ });
+});
+
+/** Build once per Worker isolate, not per request: decoding a production map costs ~150 ms. */
+export const layerSourceMaps = Layer.effect(SourceMaps, makeSourceMaps);
+
+export class MobileTelemetry extends Context.Service<
+ MobileTelemetry,
+ {
+ readonly handle: (
+ request: HttpServerRequest.HttpServerRequest,
+ params: { readonly projectId: string; readonly signal: RelayMobileTelemetrySignal },
+ ) => Effect.Effect<HttpServerResponse.HttpServerResponse>;
+ }
+>()("t3code-relay/mobileTelemetry/MobileTelemetry") {}
+
+class BodyTooLarge extends Schema.TaggedError<BodyTooLarge>()("BodyTooLarge", {}) {}
+
+const errorResponse = (status: number, error: string, headers?: Record<string, string>) =>
+ HttpServerResponse.jsonUnsafe({ error }, { status, ...(headers ? { headers } : {}) });
+
+const readCapped = <E>(stream: Stream.Stream<Uint8Array, E>, maxBytes: number) =>
+ Effect.suspend(() => {
+ const chunks: Array<Uint8Array> = [];
+ let total = 0;
+ return stream.pipe(
+ Stream.runForEach((chunk) => {
+ total += chunk.length;
+ if (total > maxBytes) return Effect.fail(new BodyTooLarge());
+ chunks.push(chunk);
+ return Effect.void;
+ }),
+ Effect.map(() => {
+ const body = new Uint8Array(total);
+ let offset = 0;
+ for (const chunk of chunks) {
+ body.set(chunk, offset);
+ offset += chunk.length;
+ }
+ return body;
+ }),
+ );
+ });
+
+const hasNoBody = (request: HttpServerRequest.HttpServerRequest) =>
+ request.source instanceof Request && request.source.body === null;
+
+const make = Effect.gen(function* () {
+ const settings = yield* MobileTelemetrySettings;
+ const rateLimiter = yield* MobileTelemetryRateLimiter;
+ const sourceMaps = yield* SourceMaps;
+ const httpClient = yield* HttpClient.HttpClient;
+
+ const symbolicateLogs = Effect.fn("relay.mobile_telemetry.symbolicate")(function* (
+ body: Uint8Array,
+ ) {
+ const payload = parseJson(new TextDecoder().decode(body));
+ const exceptions = collectJsExceptions(payload);
+ const jsFatalCrashes = markJsFatalCrashes(payload);
+ if (exceptions.length === 0 && jsFatalCrashes === 0) return undefined;
+ let symbolicated = 0;
+ let growthLeft = MAX_SYMBOLICATION_GROWTH;
+ const keys = new Set<string>();
+ for (const exception of exceptions) {
+ const key = bundleSourceMapKey(exception.identity);
+ if (key !== undefined && keys.size < MAX_SOURCE_MAPS_PER_REQUEST) keys.add(key);
+ const outcome = applySymbolication(
+ exception,
+ key === undefined
+ ? "no_bundle_id"
+ : keys.has(key)
+ ? yield* sourceMaps.find(key)
+ : "source_map_limit",
+ growthLeft,
+ );
+ growthLeft -= outcome.growth;
+ if (outcome.symbolicated) symbolicated += 1;
+ }
+ yield* Effect.annotateCurrentSpan({
+ "relay.mobile_telemetry.exceptions": exceptions.length,
+ "relay.mobile_telemetry.symbolicated": symbolicated,
+ "relay.mobile_telemetry.js_fatal_crashes": jsFatalCrashes,
+ });
+ return new TextEncoder().encode(encodeJson(payload));
+ });
+
+ const forward = Effect.fn("relay.mobile_telemetry.forward")(function* (
+ destination: AxiomDestination,
+ body: Uint8Array,
+ ) {
+ const response = yield* httpClient.execute(
+ HttpClientRequest.post(destination.url, {
+ headers: {
+ authorization: `Bearer ${Redacted.value(settings.axiomToken)}`,
+ "x-axiom-dataset": destination.dataset,
+ },
+ }).pipe(HttpClientRequest.bodyUint8Array(body, "application/json")),
+ );
+ const responseBody = yield* readCapped(response.stream, MAX_UPSTREAM_RESPONSE_BYTES).pipe(
+ Effect.catchIf(
+ (error) => error._tag === "HttpClientError" && error.reason._tag === "EmptyBodyError",
+ () => Effect.succeed(new Uint8Array(0)),
+ ),
+ );
+ return { response, body: responseBody };
+ }, Effect.timeoutOption(UPSTREAM_TIMEOUT));
+
+ const handle = Effect.fn("relay.mobile_telemetry.ingest")(function* (
+ request: HttpServerRequest.HttpServerRequest,
+ {
+ projectId,
+ signal,
+ }: { readonly projectId: string; readonly signal: RelayMobileTelemetrySignal },
+ ) {
+ const outcome = (value: string) =>
+ Effect.annotateCurrentSpan({ "relay.mobile_telemetry.outcome": value });
+ yield* Effect.annotateCurrentSpan({
+ "relay.mobile_telemetry.project_id": projectId,
+ "relay.mobile_telemetry.signal": signal,
+ });
+
+ const clientIp = request.headers["cf-connecting-ip"] ?? "unknown";
+ if (!(yield* rateLimiter.allow(clientIp))) {
+ yield* outcome("rate_limited");
+ return errorResponse(429, "rate_limited", {
+ "retry-after": String(MOBILE_TELEMETRY_RATE_LIMIT.periodSeconds),
+ });
+ }
+
+ const read = yield* (
+ hasNoBody(request)
+ ? Effect.succeed(new Uint8Array(0))
+ : readCapped(request.stream, MOBILE_TELEMETRY_MAX_BODY_BYTES)
+ ).pipe(Effect.result);
+ if (Result.isFailure(read)) {
+ const tooLarge = read.failure._tag === "BodyTooLarge";
+ yield* outcome(tooLarge ? "body_too_large" : "body_unreadable");
+ return errorResponse(tooLarge ? 413 : 400, tooLarge ? "body_too_large" : "invalid_body");
+ }
+ yield* Effect.annotateCurrentSpan({ "relay.mobile_telemetry.bytes": read.success.length });
+
+ // Forwarding matters more than symbolication: on any defect the payload goes through as sent.
+ const body =
+ signal === "logs"
+ ? ((yield* symbolicateLogs(read.success).pipe(
+ Effect.catchCause((cause) =>
+ Effect.logWarning("Mobile stack symbolication failed", { cause }).pipe(
+ Effect.as(undefined),
+ ),
+ ),
+ )) ?? read.success)
+ : read.success;
+
+ const upstream = yield* forward(settings.destinations[signal], body).pipe(Effect.result);
+ if (Result.isFailure(upstream)) {
+ yield* outcome("upstream_unavailable");
+ return errorResponse(502, "upstream_unavailable");
+ }
+ if (Option.isNone(upstream.success)) {
+ yield* outcome("upstream_timeout");
+ return errorResponse(504, "upstream_timeout");
+ }
+ const { response, body: responseBody } = upstream.success.value;
+ yield* outcome("forwarded");
+ yield* Effect.annotateCurrentSpan({
+ "relay.mobile_telemetry.upstream_status": response.status,
+ });
+ // Observe's retry and partial-success handling reads only these from Axiom's answer.
+ const contentType = response.headers["content-type"];
+ const retryAfter = response.headers["retry-after"];
+ const headers = retryAfter === undefined ? undefined : { "retry-after": retryAfter };
+ if (responseBody.length === 0) {
+ return HttpServerResponse.empty({ status: response.status, ...(headers ? { headers } : {}) });
+ }
+ return HttpServerResponse.uint8Array(responseBody, {
+ status: response.status,
+ ...(headers ? { headers } : {}),
+ ...(contentType ? { contentType } : {}),
+ });
+ });
+
+ return MobileTelemetry.of({ handle });
+});
+
+export const layer = Layer.effect(MobileTelemetry, make);
+
+/** Raw so the body is read once, capped. */
+export const layerApi = HttpApiBuilder.group(
+ RelayApi,
+ "mobileTelemetry",
+ Effect.fnUntraced(function* (handlers) {
+ const telemetry = yield* MobileTelemetry;
+ return handlers.handleRaw("ingest", ({ request, params }) => telemetry.handle(request, params));
+ }),
+);
diff --git a/infra/relay/src/mobileTelemetry/monitoring.ts b/infra/relay/src/mobileTelemetry/monitoring.ts
new file mode 100644
index 00000000000..119c4269aff
--- /dev/null
+++ b/infra/relay/src/mobileTelemetry/monitoring.ts
@@ -0,0 +1,297 @@
+import * as Alchemy from "alchemy";
+import * as Axiom from "@alchemy.run/axiom";
+import * as Output from "alchemy/Output";
+import * as Effect from "effect/Effect";
+import * as Option from "effect/Option";
+
+import { relayResourceNameForStage } from "../deploymentConfig.ts";
+import { notifierConfig } from "../monitoring.ts";
+import { isPreviewStage } from "../previewStages.ts";
+
+const RUNBOOK_URL =
+ "https://github.com/pingdotgg/t3code/blob/main/docs/operations/relay-observability.md#mobile-crashes-and-errors";
+
+// A new dataset has none of these fields until a report carries them, and an
+// unknown field fails the whole query, so every one has a default.
+const field = (name: string, fallback: string) => `column_ifexists('${name}', ${fallback})`;
+const reports = (dataset: string) =>
+ [
+ `['${dataset}']`,
+ `| extend source = tostring(${field("attributes.expo.error.source", "''")}),`,
+ ` fatal = tobool(${field("attributes.expo.error.is_fatal", "false")}),`,
+ ` js_fatal = tobool(${field("attributes.relay.crash.js_fatal", "false")}),`,
+ ` platform = tostring(${field("resource.os.name", "''")}),`,
+ ` install = tostring(${field("resource.expo.eas_client.id", "''")}),`,
+ ` error_type = tostring(${field("attributes.exception.type", "''")}),`,
+ ` message = substring(tostring(${field("attributes.exception.message", "''")}), 0, 140),`,
+ ` version = strcat(tostring(${field("service.version", "''")}), ' (', tostring(${field("resource.expo.app.build_number", "''")}), ')')`,
+ `| where isnotempty(source) and isnotempty(platform)`,
+ // A fatal JS error also ends in a native abort; counting both would double every JS crash.
+ `| extend kind = case(source == 'nativeCrash' and js_fatal, 'abort after JS crash', source == 'nativeCrash', 'native crash', fatal, 'JS crash', 'handled error')`,
+ ].join("\n");
+const crashes = (dataset: string) =>
+ `${reports(dataset)}\n| where kind in ('JS crash', 'native crash')`;
+const handledErrors = (dataset: string) => `${reports(dataset)}\n| where kind == 'handled error'`;
+const ingest = (traces: string) =>
+ `['${traces}']\n| where name == 'relay.mobile_telemetry.ingest'\n| extend signal = tostring(['attributes.custom']['relay.mobile_telemetry.signal']), outcome = tostring(['attributes.custom']['relay.mobile_telemetry.outcome'])`;
+
+type Severity = "page" | "warn";
+
+interface Datasets {
+ readonly logs: string;
+ readonly traces: string;
+}
+
+interface MobileMonitor {
+ readonly id: string;
+ readonly severity: Severity;
+ readonly name: string;
+ /** Why it fires. The runbook link is appended. */
+ readonly description: string;
+ readonly query: (datasets: Datasets) => string;
+ readonly props: Pick<
+ Axiom.MonitorProps,
+ | "type"
+ | "operator"
+ | "threshold"
+ | "rangeMinutes"
+ | "intervalMinutes"
+ | "compareDays"
+ | "tolerance"
+ | "alertOnNoData"
+ | "triggerFromNRuns"
+ >;
+}
+
+// No production baseline exists yet: the spike monitor learns its own, and the
+// thresholds below are starting points to tune after two weeks of data.
+const mobileMonitors: ReadonlyArray<MobileMonitor> = [
+ {
+ id: "MobileCrashSpikeMonitor",
+ severity: "page",
+ name: "T3 Code mobile: crash spike",
+ description:
+ "Crashes (JS and native, each counted once) per 15 min well above the same time over the last 7 days. Usually a bad OTA update or store build: compare app versions on the dashboard.",
+ query: ({ logs }) => `${crashes(logs)}\n| summarize crashes = count() by bin_auto(_time)`,
+ props: {
+ type: "AnomalyDetection",
+ operator: "Above",
+ compareDays: 7,
+ tolerance: 50,
+ rangeMinutes: 15,
+ intervalMinutes: 15,
+ },
+ },
+ {
+ id: "MobileCrashSpreadMonitor",
+ severity: "page",
+ name: "T3 Code mobile: one crash hitting many installs",
+ description:
+ "The most widespread crash reached this many installs in an hour. Its message and versions are at the top of the dashboard's Top crashes table.",
+ query: ({ logs }) =>
+ `${crashes(logs)}\n| summarize installs = dcount(install) by platform, error_type, message\n| summarize worst = max(installs)`,
+ props: {
+ type: "Threshold",
+ operator: "AboveOrEqual",
+ threshold: 25,
+ rangeMinutes: 60,
+ intervalMinutes: 15,
+ },
+ },
+ {
+ id: "MobileTelemetryStoppedMonitor",
+ severity: "warn",
+ name: "T3 Code mobile: reports stopped",
+ description:
+ "No startup metrics forwarded in an hour. Every launch sends some, so the relay route, the Axiom token, or the app's endpoint is broken, and crashes go unseen too.",
+ query: ({ traces }) =>
+ `${ingest(traces)}\n| where signal == 'metrics' and outcome == 'forwarded'\n| summarize forwarded = count()`,
+ props: {
+ type: "Threshold",
+ operator: "Below",
+ threshold: 1,
+ rangeMinutes: 60,
+ intervalMinutes: 15,
+ alertOnNoData: true,
+ triggerFromNRuns: 2,
+ },
+ },
+ {
+ id: "MobileSymbolicationFailingMonitor",
+ severity: "warn",
+ name: "T3 Code mobile: crash stacks not symbolicated",
+ description:
+ "Share of release JS exceptions over 6 h whose stack stayed minified. Map uploads are failing or the relay cannot read them; relay.symbolication.status says which.",
+ query: ({ logs }) =>
+ [
+ `['${logs}']`,
+ `| extend status = tostring(${field("attributes.relay.symbolication.status", "''")})`,
+ `| where isnotempty(status) and status !in ('no_bundle_id', 'no_bundle_frames')`,
+ `| summarize total = count(), minified = countif(status != 'symbolicated')`,
+ `| project minified_pct = iff(total >= 20, 100.0 * minified / total, 0.0)`,
+ ].join("\n"),
+ props: {
+ type: "Threshold",
+ operator: "Above",
+ threshold: 50,
+ rangeMinutes: 360,
+ intervalMinutes: 60,
+ },
+ },
+];
+
+interface QueryChart {
+ readonly id: string;
+ readonly name: string;
+ readonly type: "TimeSeries" | "Table" | "Statistic";
+ readonly query: { readonly apl: string };
+ /** Grid columns out of 12. */
+ readonly width: 4 | 6 | 12;
+}
+
+const chart = (
+ type: QueryChart["type"],
+ width: QueryChart["width"],
+ id: string,
+ name: string,
+ apl: string,
+): QueryChart => ({ id, name, type, width, query: { apl } });
+
+const mobileDashboardCharts = ({ logs, traces }: Datasets): ReadonlyArray<QueryChart> => [
+ chart("Statistic", 4, "crashes", "Crashes", `${crashes(logs)}\n| summarize count()`),
+ chart(
+ "Statistic",
+ 4,
+ "crashed-installs",
+ "Installs that crashed",
+ `${crashes(logs)}\n| summarize dcount(install)`,
+ ),
+ chart(
+ "Statistic",
+ 4,
+ "handled-errors",
+ "Handled errors",
+ `${handledErrors(logs)}\n| summarize count()`,
+ ),
+ chart(
+ "TimeSeries",
+ 6,
+ "crashes-over-time",
+ "Crashes by platform",
+ `${crashes(logs)}\n| summarize count() by bin_auto(_time), series = strcat(platform, ' ', kind)`,
+ ),
+ chart(
+ "TimeSeries",
+ 6,
+ "handled-over-time",
+ "Handled errors by platform",
+ `${handledErrors(logs)}\n| summarize count() by bin_auto(_time), platform`,
+ ),
+ chart(
+ "Table",
+ 12,
+ "top-crashes",
+ "Top crashes",
+ `${crashes(logs)}\n| summarize installs = dcount(install), crashes = count(), first_seen = min(_time), last_seen = max(_time), versions = make_set(version, 3) by platform, kind, error_type, message\n| order by installs desc, crashes desc\n| take 15`,
+ ),
+ chart(
+ "Table",
+ 12,
+ "top-handled",
+ "Top handled errors",
+ `${handledErrors(logs)}\n| summarize installs = dcount(install), errors = count(), last_seen = max(_time), versions = make_set(version, 3) by platform, error_type, message\n| order by installs desc, errors desc\n| take 15`,
+ ),
+ chart(
+ "Table",
+ 6,
+ "by-version",
+ "Crashes by app version",
+ `${crashes(logs)}\n| summarize crashes = count(), installs = dcount(install) by platform, version\n| order by crashes desc\n| take 10`,
+ ),
+ chart(
+ "TimeSeries",
+ 6,
+ "symbolication",
+ "JS stacks by symbolication outcome",
+ `['${logs}']\n| extend status = tostring(${field("attributes.relay.symbolication.status", "''")})\n| where isnotempty(status)\n| summarize count() by bin_auto(_time), status`,
+ ),
+ chart(
+ "TimeSeries",
+ 12,
+ "ingest",
+ "Reports reaching the relay",
+ `${ingest(traces)}\n| summarize count() by bin_auto(_time), series = strcat(signal, ' ', outcome)`,
+ ),
+];
+
+/** Lays charts left to right, wrapping at Axiom's 12-column grid. */
+function layout(charts: ReadonlyArray<QueryChart>) {
+ let x = 0;
+ let y = 0;
+ let rowHeight = 0;
+ return charts.map((chart) => {
+ const h = chart.type === "Statistic" ? 3 : 6;
+ if (x + chart.width > 12) {
+ x = 0;
+ y += rowHeight;
+ rowHeight = 0;
+ }
+ const cell = { i: chart.id, x, y, w: chart.width, h };
+ x += chart.width;
+ rowHeight = Math.max(rowHeight, h);
+ return cell;
+ });
+}
+
+/**
+ * Monitors follow the relay's: a deployment opts in by naming its paging notifier. The
+ * dashboard also comes up on PR previews, so a change to mobile telemetry can be checked
+ * there; the preview's teardown removes it.
+ */
+export const MobileMonitoring = Effect.fn("MobileMonitoring")(function* (
+ logs: Axiom.Dataset,
+ traces: Axiom.Dataset,
+) {
+ const { stage } = yield* Alchemy.Stack;
+ const page = yield* notifierConfig("RELAY_ALERT_NOTIFIER_ID");
+ if (Option.isNone(page) && !isPreviewStage(stage)) return;
+ const datasets = Output.map(Output.all(logs.name, traces.name), ([logs, traces]) => ({
+ logs,
+ traces,
+ }));
+
+ if (Option.isSome(page)) {
+ const notifiers: Record<Severity, Option.Option<string>> = {
+ page,
+ warn: yield* notifierConfig("RELAY_WARNING_NOTIFIER_ID"),
+ };
+ for (const monitor of mobileMonitors) {
+ yield* Axiom.Monitor(monitor.id, {
+ ...monitor.props,
+ name: stage === "prod" ? monitor.name : `[${stage}] ${monitor.name}`,
+ description: `${monitor.description} Runbook: ${RUNBOOK_URL}`,
+ aplQuery: Output.map(datasets, monitor.query),
+ triggerFromNRuns: monitor.props.triggerFromNRuns ?? 1,
+ alertOnNoData: monitor.props.alertOnNoData ?? false,
+ notifierIds: Option.toArray(notifiers[monitor.severity]),
+ });
+ }
+ }
+
+ yield* Axiom.Dashboard("MobileHealthDashboard", {
+ dashboard: Output.map(datasets, (names) => {
+ const charts = mobileDashboardCharts(names);
+ return {
+ name: relayResourceNameForStage("t3-code-mobile-health", stage),
+ owner: "X-AXIOM-EVERYONE",
+ description: `T3 Code mobile app crashes and errors. Crashes count JS and native once each. Runbook: ${RUNBOOK_URL}`,
+ refreshTime: 300,
+ schemaVersion: 2,
+ timeWindowStart: "qr-now-7d",
+ timeWindowEnd: "qr-now",
+ charts: charts.map(({ width: _width, ...chart }) => chart),
+ layout: layout(charts),
+ };
+ }),
+ });
+});
diff --git a/infra/relay/src/mobileTelemetry/otlpLogs.ts b/infra/relay/src/mobileTelemetry/otlpLogs.ts
new file mode 100644
index 00000000000..18f797f6fc1
--- /dev/null
+++ b/infra/relay/src/mobileTelemetry/otlpLogs.ts
@@ -0,0 +1,178 @@
+import { mobileSourceMapKey, type MobilePlatform } from "@t3tools/shared/mobileSourceMaps";
+
+import { stripBundlePaths, symbolicateStack, type CompactSourceMap } from "./sourceMap.ts";
+
+/** The JS bundle a record came from, read from its OTLP resource. */
+interface BundleIdentity {
+ readonly platform: MobilePlatform;
+ /** Observe reports one only for an OTA launch. */
+ readonly updateId: string | undefined;
+ readonly easBuildId: string | undefined;
+}
+
+const BUNDLE_ID_PATTERN = /^[A-Za-z0-9-]{1,64}$/u;
+
+/**
+ * The map for the bundle that threw. A build map never stands in for a
+ * missing OTA map: its offsets belong to a different bundle.
+ */
+export function bundleSourceMapKey(identity: BundleIdentity): string | undefined {
+ if (identity.updateId !== undefined) {
+ return BUNDLE_ID_PATTERN.test(identity.updateId)
+ ? mobileSourceMapKey(identity.platform, "ota", identity.updateId)
+ : undefined;
+ }
+ if (identity.easBuildId !== undefined && BUNDLE_ID_PATTERN.test(identity.easBuildId)) {
+ return mobileSourceMapKey(identity.platform, "build", identity.easBuildId);
+ }
+ return undefined;
+}
+
+interface JsException {
+ readonly identity: BundleIdentity;
+ readonly stack: string;
+ /** The record's attribute list, updated in place by `applySymbolication`. */
+ readonly attributes: Array<unknown>;
+}
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === "object" && value !== null && !Array.isArray(value);
+
+const arrayAt = (value: unknown, key: string): Array<unknown> | undefined => {
+ const child = isRecord(value) ? value[key] : undefined;
+ return Array.isArray(child) ? child : undefined;
+};
+
+const stringAttribute = (attributes: ReadonlyArray<unknown>, key: string): string | undefined => {
+ for (const attribute of attributes) {
+ if (!isRecord(attribute) || attribute.key !== key) continue;
+ const value = isRecord(attribute.value) ? attribute.value.stringValue : undefined;
+ return typeof value === "string" ? value : undefined;
+ }
+ return undefined;
+};
+
+const platformOf = (attributes: ReadonlyArray<unknown>): MobilePlatform | undefined => {
+ const osType = stringAttribute(attributes, "os.type");
+ if (osType === "darwin") return "ios";
+ if (osType === "linux") return "android";
+ return undefined;
+};
+
+/** JavaScript exception records with a stack; native crash frames are not in the bundle. */
+export function collectJsExceptions(payload: unknown): ReadonlyArray<JsException> {
+ const exceptions: Array<JsException> = [];
+ for (const resourceLogs of arrayAt(payload, "resourceLogs") ?? []) {
+ const resourceAttributes =
+ arrayAt(isRecord(resourceLogs) ? resourceLogs.resource : undefined, "attributes") ?? [];
+ const platform = platformOf(resourceAttributes);
+ if (platform === undefined) continue;
+ const identity: BundleIdentity = {
+ platform,
+ updateId:
+ stringAttribute(resourceAttributes, "expo.app.updates.id") ??
+ stringAttribute(resourceAttributes, "expo.app.update_id"),
+ easBuildId: stringAttribute(resourceAttributes, "expo.eas_build.id"),
+ };
+ for (const scopeLogs of arrayAt(resourceLogs, "scopeLogs") ?? []) {
+ for (const logRecord of arrayAt(scopeLogs, "logRecords") ?? []) {
+ const attributes = arrayAt(logRecord, "attributes");
+ if (!attributes) continue;
+ const stack = stringAttribute(attributes, "exception.stacktrace");
+ if (stack === undefined) continue;
+ if (stringAttribute(attributes, "expo.error.source") === "nativeCrash") continue;
+ exceptions.push({ identity, stack, attributes });
+ }
+ }
+ }
+ return exceptions;
+}
+
+const stringValue = (key: string, value: string) => ({ key, value: { stringValue: value } });
+
+const setAttribute = (attributes: Array<unknown>, key: string, value: string) => {
+ const index = attributes.findIndex((attribute) => isRecord(attribute) && attribute.key === key);
+ if (index === -1) attributes.push(stringValue(key, value));
+ else attributes[index] = stringValue(key, value);
+};
+
+/** Why a stack stayed minified, recorded as `relay.symbolication.status`. */
+export type SourceMapMiss =
+ /** A development or local build: no update or EAS build to name a map. */
+ | "no_bundle_id"
+ | "source_map_missing"
+ | "source_map_too_large"
+ | "source_map_invalid"
+ /** The bucket could not be read; retried shortly. */
+ | "source_map_unavailable"
+ /** The request named more bundles than the relay decodes for one request. */
+ | "source_map_limit";
+
+/**
+ * Rewrites one exception's stack, growing it by at most `maxGrowth`, and
+ * records the outcome on the record so a stack still minified in Axiom
+ * explains itself.
+ */
+export function applySymbolication(
+ exception: JsException,
+ found: { readonly key: string; readonly map: CompactSourceMap } | SourceMapMiss,
+ maxGrowth: number,
+): { readonly symbolicated: boolean; readonly growth: number } {
+ const stack = stripBundlePaths(exception.stack);
+ if (stack !== exception.stack) setAttribute(exception.attributes, "exception.stacktrace", stack);
+ if (typeof found === "string") {
+ setAttribute(exception.attributes, "relay.symbolication.status", found);
+ return { symbolicated: false, growth: 0 };
+ }
+ const result = symbolicateStack(stack, found.map, maxGrowth);
+ setAttribute(exception.attributes, "relay.symbolication.source_map", found.key);
+ if (result.mappedFrames === 0) {
+ setAttribute(exception.attributes, "relay.symbolication.status", "no_bundle_frames");
+ return { symbolicated: false, growth: 0 };
+ }
+ setAttribute(exception.attributes, "relay.symbolication.status", "symbolicated");
+ setAttribute(exception.attributes, "relay.symbolication.raw_stacktrace", stack);
+ setAttribute(exception.attributes, "exception.stacktrace", result.stack);
+ return { symbolicated: true, growth: result.growth };
+}
+
+const isFatal = (attributes: ReadonlyArray<unknown>) =>
+ attributes.some(
+ (attribute) =>
+ isRecord(attribute) &&
+ attribute.key === "expo.error.is_fatal" &&
+ isRecord(attribute.value) &&
+ attribute.value.boolValue === true,
+ );
+
+/**
+ * A fatal JS error ends in a native abort, which Observe reports as a second crash with the
+ * same generic stack in the same session. Marks those `relay.crash.js_fatal` so they don't
+ * bury real native crashes. Both arrive together on the next launch.
+ */
+export function markJsFatalCrashes(payload: unknown): number {
+ const records: Array<Array<unknown>> = [];
+ const fatalSessions = new Set<string>();
+ for (const resourceLogs of arrayAt(payload, "resourceLogs") ?? []) {
+ for (const scopeLogs of arrayAt(resourceLogs, "scopeLogs") ?? []) {
+ for (const logRecord of arrayAt(scopeLogs, "logRecords") ?? []) {
+ const attributes = arrayAt(logRecord, "attributes");
+ if (!attributes || !isFatal(attributes)) continue;
+ const session = stringAttribute(attributes, "session.id");
+ if (session === undefined) continue;
+ if (stringAttribute(attributes, "expo.error.source") === "nativeCrash") {
+ records.push(attributes);
+ } else {
+ fatalSessions.add(session);
+ }
+ }
+ }
+ }
+ let marked = 0;
+ for (const attributes of records) {
+ if (!fatalSessions.has(stringAttribute(attributes, "session.id")!)) continue;
+ attributes.push({ key: "relay.crash.js_fatal", value: { boolValue: true } });
+ marked += 1;
+ }
+ return marked;
+}
diff --git a/infra/relay/src/mobileTelemetry/sourceMap.test.ts b/infra/relay/src/mobileTelemetry/sourceMap.test.ts
new file mode 100644
index 00000000000..971b62afff7
--- /dev/null
+++ b/infra/relay/src/mobileTelemetry/sourceMap.test.ts
@@ -0,0 +1,60 @@
+import { describe, expect, it } from "@effect/vitest";
+
+import { decodeSourceMap, symbolicateStack, type CompactSourceMap } from "./sourceMap.ts";
+
+// Real `hermesc -O -output-source-map` output and the stack its VM printed: a frame's column is the
+// map's 0-based generated column. In `t.js`, alpha throws at 2:18, beta calls it at 5:19, gamma calls
+// beta at 8:13, and the top level calls gamma at 10:6.
+const HERMES_MAP = {
+ version: 3,
+ sources: ["t.js"],
+ mappings:
+ "AAAA,iBAAA,OAAA,MAAA,KAAA,MAAA,KAAA,MASA,OAAK,IAAE,EATP,EACY,MAAK,KAAA,WAAA,IAAA,IAAf,EAEF,EACa,OAAK,OAAT,IAAP,EAEF,AACE,EAAM,OAAI,IAAI,EAAE,IAAY,MAAO,OAAF,KAAW,EAC9C;",
+ x_hermes_function_offsets: { "0": [0, 65, 99, 121] },
+};
+const HERMES_STACK = [
+ "Error: boom",
+ " at alpha (address at t.hbc:1:89)",
+ " at beta (address at t.hbc:1:108)",
+ " at gamma (address at t.hbc:1:130)",
+ " at global (address at t.hbc:1:59)",
+].join("\n");
+
+describe("symbolicateStack", () => {
+ it("rewrites Hermes bundle frames to their original locations and keeps the rest", () => {
+ const map = decodeSourceMap(HERMES_MAP) as CompactSourceMap;
+ const result = symbolicateStack(
+ `${HERMES_STACK}\n at apply (native)\n at tryCallOne (address at InternalBytecode.js:1:89)`,
+ map,
+ Number.POSITIVE_INFINITY,
+ );
+ expect(result).toEqual({
+ stack: [
+ "Error: boom",
+ " at alpha (t.js:2:18)",
+ " at beta (t.js:5:19)",
+ " at gamma (t.js:8:13)",
+ " at global (t.js:10:6)",
+ " at apply (native)",
+ " at tryCallOne (address at InternalBytecode.js:1:89)",
+ ].join("\n"),
+ bundleFrames: 4,
+ mappedFrames: 4,
+ growth: -50,
+ });
+ });
+});
+
+describe("decodeSourceMap", () => {
+ it("fits a map as large as our iOS release map, read from an OTA bundle's path", () => {
+ // 2.1M segments, every other one repeating its predecessor's position, like Hermes output.
+ const mappings = `AAAA,${"CAAC,CAAA,".repeat(1_050_000)}CAAC`;
+ const map = decodeSourceMap({ version: 3, sources: ["src/App.tsx"], mappings });
+ const frame =
+ " at render (address at /var/mobile/Containers/Data/Application/A1/Library/" +
+ "Application Support/.expo-internal/bundle:1:4)";
+ expect(symbolicateStack(frame, map as CompactSourceMap, Number.POSITIVE_INFINITY).stack).toBe(
+ " at render (src/App.tsx:1:3)",
+ );
+ });
+});
diff --git a/infra/relay/src/mobileTelemetry/sourceMap.ts b/infra/relay/src/mobileTelemetry/sourceMap.ts
new file mode 100644
index 00000000000..b55c64b2a27
--- /dev/null
+++ b/infra/relay/src/mobileTelemetry/sourceMap.ts
@@ -0,0 +1,287 @@
+// A production Hermes map has over a million segments. General-purpose decoders hold
+// each as its own array, past a Worker isolate's memory budget; typed arrays fit.
+
+const BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+const BASE64_VALUES = new Int8Array(128).fill(-1);
+for (let index = 0; index < BASE64.length; index += 1) {
+ BASE64_VALUES[BASE64.charCodeAt(index)] = index;
+}
+const COMMA = 44;
+const SEMICOLON = 59;
+/** The relay caches two decoded maps in a 128 MB isolate. */
+const MAX_DECODED_BYTES = 32 * 1024 * 1024;
+
+export interface CompactSourceMap {
+ readonly sources: ReadonlyArray<string>;
+ /** Segment index where each generated line starts, plus one past the last line. */
+ readonly lineStarts: Int32Array;
+ readonly generatedColumns: Int32Array;
+ /** -1 for segments that map to no source. */
+ readonly sourceIndexes: Int32Array;
+ readonly originalLines: Int32Array;
+ readonly originalColumns: Int32Array;
+}
+
+interface OriginalPosition {
+ readonly source: string;
+ /** 1-based. */
+ readonly line: number;
+ /** 0-based, as source maps store it. */
+ readonly column: number;
+}
+
+const isStringArray = (value: unknown): value is ReadonlyArray<string> =>
+ Array.isArray(value) && value.every((item) => typeof item === "string");
+
+/**
+ * Calls `visit` per segment in order; `sourceIndex` is -1 for a segment that maps to no source.
+ * False if a segment is malformed.
+ */
+function walkSegments(
+ mappings: string,
+ visit: (
+ line: number,
+ generatedColumn: number,
+ sourceIndex: number,
+ originalLine: number,
+ originalColumn: number,
+ ) => void,
+): boolean {
+ // Names keep the running offsets right but are not stored: they name an identifier, not the function.
+ const fields = [0, 0, 0, 0, 0];
+ let line = 0;
+ let generatedColumn = 0;
+ let sourceIndex = 0;
+ let originalLine = 0;
+ let originalColumn = 0;
+ let index = 0;
+
+ while (index < mappings.length) {
+ const code = mappings.charCodeAt(index);
+ if (code === SEMICOLON) {
+ line += 1;
+ generatedColumn = 0;
+ index += 1;
+ continue;
+ }
+ if (code === COMMA) {
+ index += 1;
+ continue;
+ }
+
+ let fieldCount = 0;
+ while (index < mappings.length) {
+ const next = mappings.charCodeAt(index);
+ if (next === COMMA || next === SEMICOLON) break;
+ let value = 0;
+ let shift = 0;
+ let digit: number;
+ do {
+ const char = mappings.charCodeAt(index);
+ digit = char < 128 ? BASE64_VALUES[char]! : -1;
+ if (digit === -1) return false;
+ value += (digit & 31) * 2 ** shift;
+ shift += 5;
+ index += 1;
+ } while (digit & 32);
+ const negative = value % 2 === 1;
+ value = Math.floor(value / 2);
+ if (fieldCount < fields.length) fields[fieldCount] = negative ? -value : value;
+ fieldCount += 1;
+ }
+ if (fieldCount !== 1 && fieldCount !== 4 && fieldCount !== 5) return false;
+
+ generatedColumn += fields[0]!;
+ if (fieldCount === 1) {
+ visit(line, generatedColumn, -1, 0, 0);
+ } else {
+ sourceIndex += fields[1]!;
+ originalLine += fields[2]!;
+ originalColumn += fields[3]!;
+ visit(line, generatedColumn, sourceIndex, originalLine, originalColumn);
+ }
+ }
+ return true;
+}
+
+/**
+ * `too_large` past the decode budget; `invalid` for anything but a version 3 map, including
+ * index maps, which React Native never emits.
+ */
+export function decodeSourceMap(raw: unknown): CompactSourceMap | "too_large" | "invalid" {
+ if (typeof raw !== "object" || raw === null) return "invalid";
+ const version = Reflect.get(raw, "version");
+ const mappings = Reflect.get(raw, "mappings");
+ const sources = Reflect.get(raw, "sources");
+ const sourceRoot = Reflect.get(raw, "sourceRoot");
+ if (version !== 3 || typeof mappings !== "string" || !isStringArray(sources)) return "invalid";
+
+ // Hermes maps most bytecode instructions to the same position as the one before; a lookup
+ // lands on the earlier segment instead with the same answer. Dropping them shrinks our iOS
+ // map from 2.1M segments to 1.2M, so the first pass counts what the second keeps.
+ let lineCount = 1;
+ for (let index = 0; index < mappings.length; index += 1) {
+ if (mappings.charCodeAt(index) === SEMICOLON) lineCount += 1;
+ }
+ let kept = 0;
+ let lastLine = -1;
+ let lastSource = -2;
+ let lastOriginalLine = 0;
+ let lastOriginalColumn = 0;
+ const repeats = (line: number, source: number, originalLine: number, originalColumn: number) => {
+ const same =
+ line === lastLine &&
+ source === lastSource &&
+ (source === -1 ||
+ (originalLine === lastOriginalLine && originalColumn === lastOriginalColumn));
+ lastLine = line;
+ lastSource = source;
+ lastOriginalLine = originalLine;
+ lastOriginalColumn = originalColumn;
+ return same;
+ };
+ const counted = walkSegments(mappings, (line, _column, source, originalLine, originalColumn) => {
+ if (!repeats(line, source, originalLine, originalColumn)) kept += 1;
+ });
+ if (!counted) return "invalid";
+
+ const prefixLength = typeof sourceRoot === "string" ? sourceRoot.length + 1 : 0;
+ let sourceChars = 0;
+ for (const source of sources) sourceChars += source.length + prefixLength;
+ // A path takes up to two bytes a character, plus its string header and array slot.
+ const decodedBytes = kept * 16 + (lineCount + 1) * 4 + sourceChars * 2 + sources.length * 32;
+ if (decodedBytes > MAX_DECODED_BYTES) return "too_large";
+
+ const lineStarts = new Int32Array(lineCount + 1);
+ const generatedColumns = new Int32Array(kept);
+ const sourceIndexes = new Int32Array(kept);
+ const originalLines = new Int32Array(kept);
+ const originalColumns = new Int32Array(kept);
+ let segment = 0;
+ let currentLine = 0;
+ lastLine = -1;
+ lastSource = -2;
+ walkSegments(mappings, (line, generatedColumn, source, originalLine, originalColumn) => {
+ if (repeats(line, source, originalLine, originalColumn)) return;
+ while (currentLine < line) {
+ currentLine += 1;
+ lineStarts[currentLine] = segment;
+ }
+ generatedColumns[segment] = generatedColumn;
+ sourceIndexes[segment] = source;
+ originalLines[segment] = originalLine;
+ originalColumns[segment] = originalColumn;
+ segment += 1;
+ });
+ while (currentLine < lineCount) {
+ currentLine += 1;
+ lineStarts[currentLine] = segment;
+ }
+
+ const prefix = typeof sourceRoot === "string" && sourceRoot !== "" ? sourceRoot : undefined;
+ return {
+ sources: prefix ? sources.map((source) => `${prefix.replace(/\/?$/u, "/")}${source}`) : sources,
+ lineStarts,
+ generatedColumns,
+ sourceIndexes,
+ originalLines,
+ originalColumns,
+ };
+}
+
+/** `line` is 1-based and `column` 0-based, as in `@jridgewell/trace-mapping`. */
+function originalPositionFor(
+ map: CompactSourceMap,
+ line: number,
+ column: number,
+): OriginalPosition | undefined {
+ const lineIndex = line - 1;
+ if (lineIndex < 0 || lineIndex >= map.lineStarts.length - 1) return undefined;
+ const lineStart = map.lineStarts[lineIndex]!;
+ // An exact hit takes the first segment at `column`: Hermes maps a function's first
+ // instruction twice (declaration, then first statement), and other libraries take the first.
+ let low = lineStart;
+ let high = map.lineStarts[lineIndex + 1]!;
+ while (low < high) {
+ const middle = (low + high) >>> 1;
+ if (map.generatedColumns[middle]! < column) low = middle + 1;
+ else high = middle;
+ }
+ const exact = low < map.lineStarts[lineIndex + 1]! && map.generatedColumns[low] === column;
+ const found = exact ? low : low - 1;
+ if (found < lineStart) return undefined;
+ const sourceIndex = map.sourceIndexes[found]!;
+ const source = sourceIndex === -1 ? undefined : map.sources[sourceIndex];
+ if (source === undefined) return undefined;
+ return {
+ source,
+ line: map.originalLines[found]! + 1,
+ column: map.originalColumns[found]!,
+ };
+}
+
+/**
+ * `at render (address at index.android.bundle:1:48213)`: Hermes prints the bytecode offset,
+ * the composed map's generated column. On iOS the path is absolute, and an OTA bundle's
+ * contains a space (`Application Support`).
+ */
+const BUNDLE_FRAME = /address at (.+?):(\d+):(\d+)(?=\)?$)/u;
+/** Hermes's own runtime, not in the map. */
+const HERMES_RUNTIME = "InternalBytecode.js";
+
+const baseName = (path: string) => path.slice(path.lastIndexOf("/") + 1);
+
+/** iOS bundle paths carry per-install container UUIDs, which split one crash into many groups. */
+export function stripBundlePaths(stack: string): string {
+ return stack
+ .split("\n")
+ .map((line) => {
+ const match = BUNDLE_FRAME.exec(line);
+ if (!match || !match[1]!.includes("/")) return line;
+ const start = match.index + "address at ".length;
+ return line.slice(0, start) + baseName(match[1]!) + line.slice(start + match[1]!.length);
+ })
+ .join("\n");
+}
+
+interface SymbolicatedStack {
+ readonly stack: string;
+ /** Frames in the app bundle. */
+ readonly bundleFrames: number;
+ /** Bundle frames the map resolved. */
+ readonly mappedFrames: number;
+ /** How much longer the stack got. */
+ readonly growth: number;
+}
+
+/** Once the stack would grow by more than `maxGrowth`, the remaining frames keep their offsets. */
+export function symbolicateStack(
+ stack: string,
+ map: CompactSourceMap,
+ maxGrowth: number,
+): SymbolicatedStack {
+ let bundleFrames = 0;
+ let mappedFrames = 0;
+ let growth = 0;
+ let exhausted = false;
+ const lines = stack.split("\n").map((line) => {
+ const match = BUNDLE_FRAME.exec(line);
+ if (!match || baseName(match[1]!) === HERMES_RUNTIME) return line;
+ bundleFrames += 1;
+ if (exhausted) return line;
+ const position = originalPositionFor(map, Number(match[2]), Number(match[3]));
+ if (!position) return line;
+ const lineAndColumn = `:${position.line}:${position.column + 1}`;
+ const added = position.source.length + lineAndColumn.length - match[0].length;
+ if (growth + added > maxGrowth) {
+ exhausted = true;
+ return line;
+ }
+ growth += added;
+ mappedFrames += 1;
+ // Spliced, not `replace`d: a replacement string would expand `$&` and `$'` in the path.
+ const end = match.index + match[0].length;
+ return line.slice(0, match.index) + position.source + lineAndColumn + line.slice(end);
+ });
+ return { stack: lines.join("\n"), bundleFrames, mappedFrames, growth };
+}
diff --git a/infra/relay/src/monitoring.ts b/infra/relay/src/monitoring.ts
index 46127a02430..2d9bd8f6dc3 100644
--- a/infra/relay/src/monitoring.ts
+++ b/infra/relay/src/monitoring.ts
@@ -343,7 +343,7 @@ const relayDashboardCharts = (dataset: string): ReadonlyArray<QueryChart> => {
];
};
-const notifierConfig = (name: string) =>
+export const notifierConfig = (name: string) =>
Config.String(name).pipe(
Config.option,
Config.map(Option.flatMap((value) => Option.liftPredicate(value.trim(), Boolean))),
diff --git a/infra/relay/src/observability.ts b/infra/relay/src/observability.ts
index 1238224d913..d0586ce8bff 100644
--- a/infra/relay/src/observability.ts
+++ b/infra/relay/src/observability.ts
@@ -1,14 +1,20 @@
+// @effect-diagnostics nodeBuiltinImport:off - one sha256 inside a synchronous Output.map.
+import * as NodeCrypto from "node:crypto";
+
import * as Alchemy from "alchemy";
import * as Axiom from "@alchemy.run/axiom";
+import * as Cloudflare from "@alchemy.run/cloudflare";
import * as Output from "alchemy/Output";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Option from "effect/Option";
+import * as Redacted from "effect/Redacted";
import * as Schema from "effect/Schema";
import * as Tracer from "effect/Tracer";
import { relayResourceNameForStage } from "./deploymentConfig.ts";
+import { MobileMonitoring } from "./mobileTelemetry/monitoring.ts";
import { RelayMonitoring } from "./monitoring.ts";
const relayRecentSpansQuery = (dataset: string) =>
@@ -56,6 +62,37 @@ export const RelayObservability = Effect.gen(function* () {
})),
});
+ // expo-observe data, forwarded by src/mobileTelemetry. Mobile spans share the traces dataset.
+ const mobileLogs = yield* Axiom.Dataset("MobileLogsDataset", {
+ name: relayResourceNameForStage("t3-code-mobile-logs", stage),
+ kind: "otel:logs:v1",
+ description: "T3 Code mobile app errors, crashes, and log events from expo-observe.",
+ retentionDays: 30,
+ useRetentionPeriod: true,
+ });
+ const mobileMetrics = yield* Axiom.Dataset("MobileMetricsDataset", {
+ name: relayResourceNameForStage("t3-code-mobile-metrics", stage),
+ kind: "otel:metrics:v1",
+ description: "T3 Code mobile app startup and update metrics from expo-observe.",
+ retentionDays: 30,
+ useRetentionPeriod: true,
+ });
+ const mobileTelemetryIngestToken = yield* Axiom.ApiToken("MobileTelemetryAxiomIngestToken", {
+ name: relayResourceNameForStage("t3-code-mobile-telemetry-ingest", stage),
+ description: "Owned by Alchemy. Scoped ingest token the relay forwards mobile telemetry with.",
+ datasetCapabilities: Output.map(
+ Output.all(traces.name, mobileLogs.name, mobileMetrics.name),
+ (datasets) =>
+ Object.fromEntries(datasets.map((dataset) => [dataset, { ingest: ["create" as const] }])),
+ ),
+ });
+
+ const mobileSourceMaps = yield* Cloudflare.R2.Bucket("MobileSourceMapsBucket", {
+ name: mobileSourceMapsBucketName(stage),
+ // R2 refuses to delete a non-empty bucket, which would half tear down every non-prod stage.
+ forceDestroy: stage !== "prod",
+ });
+
yield* Axiom.View("RelayRecentSpansView", {
name: relayResourceNameForStage("t3-code-relay-recent-spans", stage),
description: "Recent relay HTTP request spans.",
@@ -64,8 +101,53 @@ export const RelayObservability = Effect.gen(function* () {
});
yield* RelayMonitoring(traces);
+ yield* MobileMonitoring(mobileLogs, traces);
+
+ return {
+ traces,
+ workerIngestToken,
+ mobileIngestToken,
+ clientIngestToken,
+ mobileLogs,
+ mobileMetrics,
+ mobileTelemetryIngestToken,
+ mobileSourceMaps,
+ } as const;
+});
- return { traces, workerIngestToken, mobileIngestToken, clientIngestToken } as const;
+const mobileSourceMapsBucketName = (stage: string) =>
+ relayResourceNameForStage("t3-code-mobile-sourcemaps", stage);
+
+/**
+ * Write-only S3 credentials for the source maps bucket: the `MOBILE_SOURCEMAPS_R2` secret.
+ * R2's S3 access key id is the API token's id and the secret the SHA-256 of its value.
+ */
+export const MobileSourceMapsUploadCredentials = Effect.gen(function* () {
+ const { stage } = yield* Alchemy.Stack;
+ const { accountId } = yield* yield* Cloudflare.CloudflareEnvironment;
+ const bucketName = mobileSourceMapsBucketName(stage);
+ const token = yield* Cloudflare.ApiToken.AccountApiToken("MobileSourceMapsUploadToken", {
+ name: relayResourceNameForStage("t3-code-mobile-sourcemaps-upload", stage),
+ policies: [
+ {
+ effect: "allow",
+ permissionGroups: ["Workers R2 Storage Bucket Item Write"],
+ resources: { [`com.cloudflare.edge.r2.bucket.${accountId}_default_${bucketName}`]: "*" },
+ },
+ ],
+ });
+ return Output.map(Output.all(token.tokenId, token.value), ([tokenId, value]) =>
+ Redacted.make(
+ JSON.stringify({
+ endpoint: `https://${accountId}.r2.cloudflarestorage.com`,
+ bucketName,
+ accessKeyId: tokenId,
+ secretAccessKey: NodeCrypto.createHash("sha256")
+ .update(Redacted.value(value))
+ .digest("hex"),
+ }),
+ ),
+ );
});
export const withSpanAttributes =
diff --git a/infra/relay/src/worker.ts b/infra/relay/src/worker.ts
index 2b9d1e7842a..e8f1dae91bd 100644
--- a/infra/relay/src/worker.ts
+++ b/infra/relay/src/worker.ts
@@ -69,6 +69,7 @@ import * as HookForwarder from "./hooks/HookForwarder.ts";
import * as HeldHooks from "./hooks/HeldHooks.ts";
import * as HookInbox from "./hooks/HookInbox.ts";
import * as HookInboxObject from "./hooks/HookInboxObject.ts";
+import * as MobileTelemetry from "./mobileTelemetry/MobileTelemetry.ts";
const layerWebcrypto = Layer.succeed(
Crypto.Crypto,
@@ -140,7 +141,7 @@ export const layer = Api.make(
const relayApiZone = yield* RelayApiZone;
const managedEndpointZone = yield* ManagedEndpointZone;
const randomApnsDeliveryJobSigningSecret = yield* ApnsDeliveryJobSigningSecret;
- yield* RelayObservability;
+ const observability = yield* RelayObservability;
const apnsEnabled = yield* Config.Boolean("APNS_ENABLED").pipe(Config.withDefault(true));
const apnsCredentials = apnsEnabled
@@ -201,6 +202,21 @@ export const layer = Api.make(
},
});
const hookInboxes = yield* HookInboxObject.HookInboxObject;
+ const mobileTelemetryRateLimit = yield* Cloudflare.RateLimit("MOBILE_TELEMETRY_RATE_LIMIT", {
+ namespaceId: 1003,
+ simple: {
+ limit: MobileTelemetry.MOBILE_TELEMETRY_RATE_LIMIT.limit,
+ period: MobileTelemetry.MOBILE_TELEMETRY_RATE_LIMIT.periodSeconds,
+ },
+ });
+ const mobileSourceMaps = yield* Cloudflare.R2.ReadBucket(observability.mobileSourceMaps);
+ const mobileTelemetryToken = yield* observability.mobileTelemetryIngestToken.token;
+ const mobileTracesUrl = yield* observability.traces.otelTracesEndpoint;
+ const mobileTracesDataset = yield* observability.traces.name;
+ const mobileLogsUrl = yield* observability.mobileLogs.otelLogsEndpoint;
+ const mobileLogsDataset = yield* observability.mobileLogs.name;
+ const mobileMetricsUrl = yield* observability.mobileMetrics.otelMetricsEndpoint;
+ const mobileMetricsDataset = yield* observability.mobileMetrics.name;
const alchemyRuntimeContext: Alchemy.BaseRuntimeContext = yield* Cloudflare.Worker;
@@ -325,18 +341,19 @@ export const layer = Api.make(
Layer.provideMerge(layerWebcrypto),
);
- // Fails open: a limiter outage must not drop webhooks the environment would accept.
+ // Fails open: a limiter outage must not drop webhooks or app telemetry.
const allowWith =
- (limiter: typeof hookRateLimit) =>
+ (
+ limiter: typeof hookRateLimit,
+ failedOpenAttribute = "relay.hook.rate_limiter_failed_open",
+ ) =>
(key: string): Effect.Effect<boolean> =>
limiter.limit({ key }).pipe(
Effect.map((result) => result.success),
Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
Effect.catch((error) =>
- Effect.logWarning("Hook rate limiter unavailable", { error: error.message }).pipe(
- Effect.andThen(
- Effect.annotateCurrentSpan({ "relay.hook.rate_limiter_failed_open": true }),
- ),
+ Effect.logWarning("Rate limiter unavailable", { error: error.message }).pipe(
+ Effect.andThen(Effect.annotateCurrentSpan({ [failedOpenAttribute]: true })),
Effect.as(true),
),
),
@@ -346,12 +363,64 @@ export const layer = Api.make(
allowEndpoint: allowWith(hookEndpointRateLimit),
});
- const layerApp = Layer.merge(
+ // `fetch` rebuilds its layers per request; the source map cache must outlive one.
+ const mobileSourceMapLookups = yield* MobileTelemetry.SourceMaps.pipe(
+ Effect.provide(MobileTelemetry.layerSourceMaps),
+ Effect.provideService(MobileTelemetry.SourceMapObjects, {
+ get: (key) =>
+ mobileSourceMaps.get(key).pipe(
+ Effect.map((object) =>
+ object === null
+ ? undefined
+ : {
+ size: object.size,
+ text: object.text().pipe(
+ Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
+ Effect.mapError(
+ (cause) => new MobileTelemetry.SourceMapObjectError({ key, cause }),
+ ),
+ ),
+ },
+ ),
+ Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
+ Effect.mapError((cause) => new MobileTelemetry.SourceMapObjectError({ key, cause })),
+ ),
+ }),
+ );
+ const layerMobileTelemetry = MobileTelemetry.layer.pipe(
+ Layer.provide(
+ Layer.mergeAll(
+ Layer.effect(
+ MobileTelemetry.MobileTelemetrySettings,
+ Effect.gen(function* () {
+ return MobileTelemetry.MobileTelemetrySettings.of({
+ axiomToken: yield* mobileTelemetryToken,
+ destinations: {
+ traces: { url: yield* mobileTracesUrl, dataset: yield* mobileTracesDataset },
+ logs: { url: yield* mobileLogsUrl, dataset: yield* mobileLogsDataset },
+ metrics: { url: yield* mobileMetricsUrl, dataset: yield* mobileMetricsDataset },
+ },
+ });
+ }),
+ ),
+ Layer.succeed(MobileTelemetry.MobileTelemetryRateLimiter, {
+ allow: allowWith(
+ mobileTelemetryRateLimit,
+ "relay.mobile_telemetry.rate_limiter_failed_open",
+ ),
+ }),
+ Layer.succeed(MobileTelemetry.SourceMaps, mobileSourceMapLookups),
+ ),
+ ),
+ );
+
+ const layerApp = Layer.mergeAll(
layerRelayApi,
HookForwarder.layerApi.pipe(
Layer.provide(HookForwarder.layer),
Layer.provide(layerHookRateLimiter),
),
+ MobileTelemetry.layerApi.pipe(Layer.provide(layerMobileTelemetry)),
).pipe(
Layer.provideMerge(RelayHttpApi.layerClientAuth),
Layer.provideMerge(RelayHttpApi.layerDpopClientAuth),
@@ -481,6 +550,7 @@ export const layer = Api.make(
Layer.provideMerge(Cloudflare.Tunnel.ReadWriteTunnelBinding),
Layer.provideMerge(Cloudflare.DNS.ReadWriteDnsHttp),
Layer.provideMerge(Cloudflare.Workers.RateLimitBinding),
+ Layer.provideMerge(Cloudflare.R2.ReadBucketBinding),
Layer.provideMerge(HookInboxObject.layer),
// Disable the duplicate runtime span; ours applies route/header/token redaction and rejects sender traceparent.
Layer.provideMerge(
diff --git a/packages/contracts/src/relay.ts b/packages/contracts/src/relay.ts
index d8409b6717a..59ec4f76101 100644
--- a/packages/contracts/src/relay.ts
+++ b/packages/contracts/src/relay.ts
@@ -1250,6 +1250,22 @@ const RelayHooksGroup = HttpApiGroup.make("hooks")
)
.annotate(OpenApi.Description, "Forward webhook requests to an environment.");
+export const RelayMobileTelemetrySignal = Schema.Literals(["logs", "metrics", "traces"]);
+export type RelayMobileTelemetrySignal = typeof RelayMobileTelemetrySignal.Type;
+
+// expo-observe appends `<easProjectId>/v1/<signal>` to its endpoint URL and cannot send credentials.
+const RelayMobileTelemetryParams = Schema.Struct({
+ projectId: Schema.String.check(Schema.isGUID()),
+ signal: RelayMobileTelemetrySignal,
+});
+const RelayMobileTelemetryGroup = HttpApiGroup.make("mobileTelemetry")
+ .add(
+ HttpApiEndpoint.post("ingest", "/v1/mobile/observe/:projectId/v1/:signal", {
+ params: RelayMobileTelemetryParams,
+ }),
+ )
+ .annotate(OpenApi.Description, "Receive mobile app telemetry from expo-observe.");
+
export const RelayApi = HttpApi.make("RelayApi")
.add(
RelayHealthGroup,
@@ -1260,6 +1276,7 @@ export const RelayApi = HttpApi.make("RelayApi")
RelayDpopClientGroup,
RelayServerGroup,
RelayHooksGroup,
+ RelayMobileTelemetryGroup,
)
.annotate(OpenApi.Title, "T3 Code Relay API")
.annotate(OpenApi.Version, "1.0.0")
diff --git a/packages/shared/package.json b/packages/shared/package.json
index 0bfb6cdf081..be5dbfe9ebd 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -35,6 +35,10 @@
"types": "./src/projectFavicon.ts",
"import": "./src/projectFavicon.ts"
},
+ "./mobileSourceMaps": {
+ "types": "./src/mobileSourceMaps.ts",
+ "import": "./src/mobileSourceMaps.ts"
+ },
"./model": {
"types": "./src/model.ts",
"import": "./src/model.ts"
diff --git a/packages/shared/src/mobileSourceMaps.ts b/packages/shared/src/mobileSourceMaps.ts
new file mode 100644
index 00000000000..b6dfe77869c
--- /dev/null
+++ b/packages/shared/src/mobileSourceMaps.ts
@@ -0,0 +1,10 @@
+export type MobilePlatform = "ios" | "android";
+
+export type MobileSourceMapKind = "ota" | "build";
+
+/** The relay's R2 key for a bundle's source map: an OTA update's, or an EAS build's embedded one. */
+export const mobileSourceMapKey = (
+ platform: MobilePlatform,
+ kind: MobileSourceMapKind,
+ id: string,
+) => `${platform}/${kind}/${id}.map`;
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index afa9d42e4ec..8ceba3cbcfd 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -680,6 +680,9 @@ importers:
expo-notifications:
specifier: ~58.1.5
+ expo-observe:
+ specifier: ~58.0.15
+ version: 58.0.16(677910f8cba89c74801637ca226a8913)
expo-paste-input:
specifier: ^0.1.15
@@ -801,6 +804,9 @@ importers:
'@types/react-dom':
specifier: 'catalog:'
version: 19.3.0(@types/[email protected])
+ aws4fetch:
+ specifier: 1.0.20
+ version: 1.0.20
babel-preset-expo:
specifier: ~58.0.17
@@ -8568,6 +8574,13 @@ packages:
resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==}
engines: {node: '>=12.0.0'}
+ resolution: {integrity: sha512-Bj/Bx3s5woOKThUcqucmDOdOAxmyHr232KbnOBD8SoA/iUo7E4RBWvRT8DwZOmLJ7H1wFK2ckFTiNoDFB+Ag+Q==}
+ peerDependencies:
+ expo: '*'
+ react: '*'
+ react-native: '*'
+
resolution: {integrity: sha512-WYFdNHGaxe/j69oYREhK0cKsKYszuIuz399WXYCP+M1grfO+FCWB/RbuMgaXJsLWlzqhNjA/zLgfJ+33FwrQvw==}
peerDependencies:
@@ -8779,6 +8792,23 @@ packages:
react: '*'
react-native: '*'
+ resolution: {integrity: sha512-STG1qp5VKA3f0jFQuf+waoO8QNIG6fpog8Hqi2UnklA08ec8a+w+hJm0wL4DgyO8dy5oDdiTVUnpqaloeUC2lQ==}
+ peerDependencies:
+ '@react-navigation/native': ^7.0.0
+ expo: '*'
+ expo-router: 58.0.20
+ react: '*'
+ react-native: '*'
+ react-native-reanimated: 4.7.1
+ peerDependenciesMeta:
+ '@react-navigation/native':
+ optional: true
+ expo-router:
+ optional: true
+ react-native-reanimated:
+ optional: true
+
resolution: {integrity: sha512-wV0z1s0/Q4MB+lNiSwbMfck+1Im6sDIcgyCi5Y0aF35n5kcM4FHSOjmRfzn3UbkMlvxmYfDiHeHvIqn22qatqA==}
peerDependencies:
@@ -17192,8 +17222,7 @@ snapshots:
- optional: true
@@ -18201,6 +18230,13 @@ snapshots:
+ dependencies:
+ expo: 58.0.14(277a83826bb26ba15256633fefeb0bc2)
+ expo-updates-interface: 58.0.1([email protected])
+ react: 19.3.0
+
dependencies:
expo: 58.0.14(277a83826bb26ba15256633fefeb0bc2)
@@ -18436,6 +18472,17 @@ snapshots:
- supports-color
- typescript
+ [email protected](677910f8cba89c74801637ca226a8913):
+ dependencies:
+ expo: 58.0.14(277a83826bb26ba15256633fefeb0bc2)
+ expo-eas-client: 58.0.2
+ react: 19.3.0
+ optionalDependencies:
+
dependencies:
expo: 58.0.14(277a83826bb26ba15256633fefeb0bc2)