diff --git a/.changeset/config.json b/.changeset/config.json index 66c1704..2be13d4 100644 --- a/.changeset/config.json +++ b/.changeset/config.json @@ -1,10 +1,10 @@ { "$schema": "https://unpkg.com/@changesets/config@3.1.1/schema.json", "changelog": "@changesets/cli/changelog", - "commit": true, + "commit": false, "fixed": [], "linked": [], - "access": "restricted", + "access": "public", "baseBranch": "main", "updateInternalDependencies": "patch", "ignore": [] diff --git a/.changeset/v0-tracing-rewrite.md b/.changeset/v0-tracing-rewrite.md new file mode 100644 index 0000000..48500c6 --- /dev/null +++ b/.changeset/v0-tracing-rewrite.md @@ -0,0 +1,8 @@ +--- +"react-native-open-telemetry": minor +--- + +v0: a rewrite around one trace across JS and native. Native-first init (`RNOtel.start` on Android and iOS) with a JS +fallback (`startReactNativeSdk`), a context patch that carries the active span through `await`, promises and timers, +and a `withOtel` helper for Metro. Removed (breaking): metrics, fetch instrumentation, session tagging and +the `openTelemetrySDK` init. See MIGRATION.md. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3aa5d0e..4d69474 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -459,8 +459,49 @@ jobs: if-no-files-found: ignore include-hidden-files: true # verify/e2e/.e2e is a dot dir + # Task 30: replays every raw request the e2e jobs captured (protobuf and JSON) and every verify/expected file into + # the official OpenTelemetry Collector (pinned; bump deliberately). Fails on a non-2xx or an error log line. + # Needs docker, so it is not part of `bun verify`. + compliance: + needs: [e2e-android-bare, e2e-ios-bare, e2e-android-expo, e2e-ios-expo, e2e-web] + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + - uses: oven-sh/setup-bun@v2 + with: + bun-version: 1.2.19 + - uses: actions/download-artifact@v4 + with: + pattern: verify-artifacts-e2e-* + path: e2e-artifacts # one subdirectory per job + - name: Start the Collector + run: | + docker run -d --name otelcol -p 4318:4318 \ + -v "$PWD/verify/compliance/collector.yaml:/etc/otelcol/config.yaml:ro" \ + otel/opentelemetry-collector:0.165.0 --config /etc/otelcol/config.yaml + for i in $(seq 30); do + code=$(curl -s -o /dev/null -w '%{http_code}' -X POST localhost:4318/v1/traces || true) + [ "$code" != 000 ] && break + sleep 1 + done + [ "$code" != 000 ] || { docker logs otelcol; exit 1; } + - name: Replay + run: bun verify/compliance/replay.ts --url http://localhost:4318 --dirs e2e-artifacts + - name: Collector log has no errors + if: always() + run: | + docker logs otelcol > collector.log 2>&1 + if grep -P '\terror\t' collector.log; then echo '::error::the Collector logged errors'; exit 1; fi + - uses: actions/upload-artifact@v4 + if: always() + with: + name: compliance-collector-log + path: collector.log + if-no-files-found: ignore + budget: - needs: [static-fast, fast-swift, e2e-android-bare, e2e-ios-bare, e2e-android-expo, e2e-ios-expo, e2e-web] # every other job; extend when jobs are added + needs: [static-fast, fast-swift, e2e-android-bare, e2e-ios-bare, e2e-android-expo, e2e-ios-expo, e2e-web, compliance] # every other job; extend when jobs are added if: always() runs-on: ubuntu-latest timeout-minutes: 5 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..f7555d8 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,161 @@ +name: Release + +# Two gates, both checked through the GitHub API by scripts/release-gate.js, which fails closed (red, pending, missing +# or an API error all stop the job): +# - publish-next: after CI completes on a `main` push, and only if that commit's CI is green. Changesets opens the +# "version packages" PR while changesets are pending; once it is merged (and CI is green on the merge), it runs +# `changeset publish --tag next` (npm publish --tag next). Nothing ever publishes to `latest` directly. +# - promote (manual, from `main`): moves a published version from `next` to `latest`, only if its release commit +# (tag v) has a green `nightly` status from a successful scheduled.yml run (mark-nightly), and the version +# is not lower than the current `latest`. Run the nightly on that commit first if needed: +# Actions -> Nightly -> Run workflow -> "Use workflow from" tag v. +# Both publishing jobs run in the `npm` environment, which holds NPM_TOKEN (a granular, publish-only token). Setup and +# caveats (the version PR gets no CI): CONTRIBUTING.md "Publishing to npm". +# Real publishing is first verified after merge to `main` (R28); until then only the dry run below has run (from the +# PR, Release run 45353782465). +on: + workflow_run: + workflows: [CI] + types: [completed] + branches: [main] + workflow_dispatch: + inputs: + promote: + description: 'Version to move from `next` to `latest` (e.g. 0.3.0). Empty: nothing to promote.' + type: string + default: '' + dry_run: + description: 'Dry run: evaluate the gates, version and pack; publish and promote nothing' + type: boolean + default: false + +permissions: + contents: read + +# per event: a dry run or a promote never queues behind or replaces a pending publish-next +concurrency: + group: release-${{ github.event_name }} + cancel-in-progress: false + +env: + PACKAGE: react-native-open-telemetry + # A commit whose CI is red (a v0-impl PR run): the dry run proves the CI gate refuses it, live against the API. + KNOWN_RED_SHA: 78482b19a4537be8f05306744729b5a6db8b0d10 + # A commit whose CI is green: the positive control, so the refusal above is not a gate that always fails. + KNOWN_GREEN_SHA: d6d1af161ea6a6a1ee587aa858304f3aa6f2e5b3 + +jobs: + dry-run: + if: github.event_name == 'workflow_dispatch' && inputs.dry_run + runs-on: ubuntu-latest + timeout-minutes: 20 + permissions: + contents: read + actions: read + statuses: read + env: + GH_TOKEN: ${{ github.token }} + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 # all branches: changeset status compares against origin/main + - uses: actions/setup-node@v4 + with: + node-version: '24' + - uses: oven-sh/setup-bun@v2 + with: + bun-version: 1.2.19 + - run: node scripts/release-gate.js --self-test + - name: The CI gate refuses a red commit and passes a green one + run: | + if node scripts/release-gate.js ci "$KNOWN_RED_SHA"; then echo "::error::CI gate passed a red commit"; exit 1; fi + node scripts/release-gate.js ci "$KNOWN_GREEN_SHA" + - name: The promote gate refuses a commit without a green nightly + run: | + if node scripts/release-gate.js nightly "$KNOWN_RED_SHA"; then echo "::error::nightly gate passed"; exit 1; fi + - run: bun install --frozen-lockfile + - run: bun run prepare + - run: bunx changeset status --verbose --since=origin/main + - name: Version (what the version PR would contain) + run: bun run version && git status --short && git diff -- package.json src/sdk/config.ts ios/RNOtel/RNOtel.swift + # `changeset publish` has no dry-run flag, so the dry run packs exactly what it would publish, with its dist-tag + - run: npm publish --dry-run --tag next --ignore-scripts + + publish-next: + if: >- + github.event_name == 'workflow_run' && github.event.workflow_run.event == 'push' && + github.event.workflow_run.conclusion == 'success' + runs-on: ubuntu-latest + timeout-minutes: 30 + environment: npm + permissions: + contents: write # the version PR branch and the v tag + pull-requests: write # the version PR + actions: read # the CI gate + id-token: write # npm provenance + env: + SHA: ${{ github.event.workflow_run.head_sha }} + GH_TOKEN: ${{ github.token }} + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.workflow_run.head_sha }} + fetch-depth: 0 + - uses: actions/setup-node@v4 + with: + node-version: '24' + # the event says success; re-check through the API so a re-run or a stale event cannot publish a red commit + - run: node scripts/release-gate.js ci "$SHA" + - uses: oven-sh/setup-bun@v2 + with: + bun-version: 1.2.19 + - run: bun install --frozen-lockfile + - uses: changesets/action@v1 + with: + version: bun run version + publish: bun run release + title: 'chore: version packages' + commit: 'chore: version packages' + createGithubReleases: false # `latest` is promote's call, not the publish's + env: + GITHUB_TOKEN: ${{ github.token }} + NPM_TOKEN: ${{ secrets.NPM_TOKEN }} + NPM_CONFIG_PROVENANCE: 'true' + + promote: + if: >- + github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' && + inputs.promote != '' && !inputs.dry_run + runs-on: ubuntu-latest + timeout-minutes: 10 + environment: npm + permissions: + contents: read + statuses: read # the nightly gate: the status + actions: read # the nightly gate: the scheduled.yml run it links + env: + VERSION: ${{ inputs.promote }} + GH_TOKEN: ${{ github.token }} + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - uses: actions/setup-node@v4 + with: + node-version: '24' + registry-url: https://registry.npmjs.org + - name: Resolve the release commit + run: | + # x.y.z only: a prerelease never becomes `latest`, and sort -V orders plain versions correctly + [[ "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || { echo "::error::not a release version: $VERSION"; exit 1; } + sha=$(git rev-list -n 1 "v$VERSION") # fails the step when the tag is missing + echo "SHA=$sha" >> "$GITHUB_ENV" + test "$(npm view "$PACKAGE@$VERSION" version)" = "$VERSION" + latest=$(npm view "$PACKAGE" dist-tags.latest) + if [ "$(printf '%s\n' "$latest" "$VERSION" | sort -V | tail -n 1)" != "$VERSION" ]; then + echo "::error::$VERSION is lower than latest $latest"; exit 1 + fi + - run: node scripts/release-gate.js nightly "$SHA" + - run: npm dist-tag add "$PACKAGE@$VERSION" latest + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} diff --git a/.github/workflows/scheduled.yml b/.github/workflows/scheduled.yml new file mode 100644 index 0000000..3126bc4 --- /dev/null +++ b/.github/workflows/scheduled.yml @@ -0,0 +1,207 @@ +name: Nightly + +# Spec §9.4/§9.5 (Task 31). Setup steps follow ci.yml; no native caches here: every nightly build is from scratch. +# `schedule` and `workflow_dispatch` only run workflow files from the default branch (main), so the real schedule is +# first verified after merge to main (R28). On success, `mark-nightly` marks the commit with a `nightly` status. +on: + schedule: + - cron: '0 2 * * *' + workflow_dispatch: + inputs: + dry_run: + description: 'Dry run: setup, app regeneration and packing only (no builds, no devices, no status)' + type: boolean + default: false + +permissions: + contents: read + +concurrency: + group: nightly-${{ github.ref }} + cancel-in-progress: false # never cancel a real nightly + +env: + E2E_TELEMETRY_DISABLED: '1' + DRY_RUN: ${{ inputs.dry_run == true }} + +jobs: + e2e: + name: ${{ matrix.name }} + runs-on: ${{ matrix.platform == 'ios' && 'xcode-27' || 'ubuntu-latest' }} + timeout-minutes: 90 + continue-on-error: ${{ matrix.experimental == true }} + strategy: + fail-fast: false + matrix: + # platform: android | ios. app: bare (example/, default) | expo (example-expo/). + # mode: e2e (Release, test mode, every scenario) | smoke (Release, test mode off, smoke-device) | + # dev (Debug + Metro, test mode, fast-refresh-idempotent). + # rn: regenerate example/ from the RN template at that version (verify/nightly/app.sh bare, X13). + # deps: @opentelemetry/*, otel-java (BOM) and opentelemetry-swift at their latest, plus the fast loop. + # pack: npm pack, install the tarball into that app instead of linking the source tree (app.sh pack). + include: + # oldest supported (peer range >=0.79) and newest React Native + - {name: rn-0.79-android, platform: android, rn: '0.79', mode: e2e} + # experimental (AUTHOR GATE, VERIFY.md "Nightly"): RN 0.79.7 iOS does not build on Xcode 27 (locally: the + # adapter podspec's module-map script phase collides with CocoaPods' own, then RN 0.79's fmt pod fails on + # consteval). Fix both or raise the minimum RN, then drop the flag. + - {name: rn-0.79-ios, platform: ios, rn: '0.79', mode: e2e, experimental: true} + - {name: rn-latest-android, platform: android, rn: latest, mode: e2e} + - {name: rn-latest-ios, platform: ios, rn: latest, mode: e2e} + - {name: deps-latest-android, platform: android, deps: true, mode: e2e} + - {name: deps-latest-ios, platform: ios, deps: true, mode: e2e} + # the published package: a fresh bare app (template at latest) and the Expo app (prebuild --clean), test mode + # off. The Expo entries are also the Expo smoke-device run (X11 interim: bare per PR, Expo here). + - {name: pack-bare-android, platform: android, rn: latest, pack: example, mode: smoke} + - {name: pack-bare-ios, platform: ios, rn: latest, pack: example, mode: smoke} + - {name: pack-expo-android, platform: android, app: expo, pack: example-expo, mode: smoke} + - {name: pack-expo-ios, platform: ios, app: expo, pack: example-expo, mode: smoke} + # Android process-name fallback below API 28 (/proc/self/cmdline, Task 24): native init must still run + - {name: api26-android-smoke, platform: android, api: 26, mode: smoke} + # fast-refresh-idempotent needs Debug builds and Metro, so it is not per PR (Task 27) + - {name: dev-android, platform: android, mode: dev} + - {name: dev-ios, platform: ios, mode: dev} + env: + APP_DIR: ${{ matrix.app == 'expo' && 'example-expo' || 'example' }} + SCHEME: ${{ matrix.app == 'expo' && 'OpenTelemetryExpo' || 'OpenTelemetryExample' }} + CONFIGURATION: ${{ matrix.mode == 'dev' && 'Debug' || 'Release' }} + OTEL_TEST_MODE: ${{ matrix.mode != 'smoke' && '1' || '' }} + E2E_SMOKE: ${{ matrix.mode == 'smoke' && '1' || '' }} + E2E_DEV: ${{ matrix.mode == 'dev' && '1' || '' }} + E2E_TARGET: ${{ format('{0}-{1}', matrix.platform, matrix.mode == 'dev' && 'dev' || matrix.app == 'expo' && 'expo' || 'bare') }} + AGENT_DEVICE_DAEMON_STARTUP_TIMEOUT_MS: '600000' # the first daemon start on a cold runner outlasts the default + steps: + - uses: actions/checkout@v4 + - if: matrix.platform == 'ios' + uses: maxim-lobanov/setup-xcode@v1 + with: + xcode-version: '27.0' + - uses: oven-sh/setup-bun@v2 + with: + bun-version: 1.2.19 + - uses: actions/setup-node@v4 # npm view / npm pack / the RN CLI in verify/nightly/app.sh + with: + node-version: '24' + - if: matrix.platform == 'android' + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '17' + + - name: Bump @opentelemetry/*, otel-java and opentelemetry-swift to latest + if: matrix.deps + run: | + jq -r '.dependencies | keys[] | select(startswith("@opentelemetry/")) + "@latest"' package.json | xargs bun add + java=$(curl -fsSL https://repo1.maven.org/maven2/io/opentelemetry/opentelemetry-bom/maven-metadata.xml | + sed -n 's:.*\(.*\).*:\1:p') + perl -pi -e "s/opentelemetry-bom:[\d.]+/opentelemetry-bom:$java/" android/build.gradle android/core-jvm/build.gradle.kts + for repo in opentelemetry-swift opentelemetry-swift-core; do + v=$(git ls-remote --tags --refs "https://github.com/open-telemetry/$repo" | sed 's:.*/::; s/^v//' | + grep -E '^[0-9]+\.[0-9]+\.[0-9]+$' | sort -V | tail -1) + perl -0pi -e "s|($repo\", \.upToNextMinor\(from: \")[\d.]+|\${1}$v|" Package.swift + perl -0pi -e "s|($repo',\s*requirement: \{ kind: 'upToNextMinorVersion', minimumVersion: ')[\d.]+|\${1}$v|" \ + ReactNativeOpenTelemetryCore.podspec + grep -qF "$repo\", .upToNextMinor(from: \"$v\")" Package.swift || { echo "::error::Package.swift: $repo not bumped"; exit 1; } + grep -qF "minimumVersion: '$v'" ReactNativeOpenTelemetryCore.podspec || { echo "::error::podspec: $repo not bumped"; exit 1; } + done + # resolve the bumped Swift packages afresh + rm -f example/ios/OpenTelemetryExample.xcworkspace/xcshareddata/swiftpm/Package.resolved + git diff -- package.json android/build.gradle android/core-jvm/build.gradle.kts Package.swift '*.podspec' + - run: bun install --frozen-lockfile + - name: Regenerate example/ at React Native ${{ matrix.rn }} + if: matrix.rn + run: verify/nightly/app.sh bare '${{ matrix.rn }}' + - name: Install ${{ env.APP_DIR }} + working-directory: ${{ env.APP_DIR }} + run: bun install ${{ !matrix.rn && '--frozen-lockfile' || '' }} + - run: bun run prepare # the apps bundle the package through exports -> lib/ (R4) + - name: npm pack into ${{ matrix.pack }} + if: matrix.pack + run: verify/nightly/app.sh pack '${{ matrix.pack }}' + - name: Fast loop + if: matrix.deps && env.DRY_RUN != 'true' + # every non-e2e stage on Linux (fast-swift skips there); fast-swift on macOS + run: bun verify ${{ matrix.platform == 'ios' && 'fast-swift' || '' }} + - name: expo prebuild + if: matrix.app == 'expo' + working-directory: example-expo + run: bunx expo prebuild --clean --no-install --platform ${{ matrix.platform }} + + - name: Build (${{ env.CONFIGURATION }}) + if: env.DRY_RUN != 'true' + run: | + if [ '${{ matrix.platform }}' = android ]; then + cd "$APP_DIR/android" + args=(":app:assemble$CONFIGURATION" -PreactNativeArchitectures=x86_64 ${OTEL_TEST_MODE:+-PotelTestMode=true}) + ./gradlew "${args[@]}" || ./gradlew "${args[@]}" # one retry: plugin and NDK downloads fail transiently + else + cd "$APP_DIR/ios" + pod install # OTEL_TEST_MODE (job env) adds the Swift compilation condition + xcodebuild -workspace "$SCHEME.xcworkspace" -scheme "$SCHEME" -configuration "$CONFIGURATION" \ + -sdk iphonesimulator -destination 'generic/platform=iOS Simulator' -derivedDataPath build ARCHS=arm64 build + fi + - name: Start Metro (dev builds load their bundle from it) + if: matrix.mode == 'dev' && env.DRY_RUN != 'true' + working-directory: example + run: nohup bunx react-native start > "$RUNNER_TEMP/metro.log" 2>&1 & + + - name: Enable KVM + if: matrix.platform == 'android' && env.DRY_RUN != 'true' + run: | + echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules + sudo udevadm control --reload-rules + sudo udevadm trigger --name-match=kvm + - name: e2e (${{ env.E2E_TARGET }}) + if: matrix.platform == 'android' && env.DRY_RUN != 'true' + uses: reactivecircus/android-emulator-runner@v2 + with: + api-level: ${{ matrix.api || 35 }} + arch: x86_64 + target: google_apis + emulator-options: -no-snapshot-save -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -camera-back none + disable-animations: true + # each line runs in its own shell + script: | + adb shell settings put global hide_error_dialogs 1 + adb reverse tcp:8081 tcp:8081 + if [ "$E2E_DEV" = 1 ]; then bunx e2e run --config verify/e2e/e2e.config.ts --target "$E2E_TARGET" fast-refresh-idempotent; else bun verify --e2e e2e; fi + - name: Pre-boot the simulator (a cold boot on the runner outlasts agent-device's boot timeout) + if: matrix.platform == 'ios' && env.DRY_RUN != 'true' + run: | + udid=$(xcrun simctl list devices available -j | jq -r '[.devices[][] | select(.name | startswith("iPhone"))][0].udid') + xcrun simctl boot "$udid" + xcrun simctl bootstatus "$udid" -b + - name: e2e (${{ env.E2E_TARGET }}) + if: matrix.platform == 'ios' && env.DRY_RUN != 'true' + run: | + if [ "$E2E_DEV" = 1 ]; then bunx e2e run --config verify/e2e/e2e.config.ts --target "$E2E_TARGET" fast-refresh-idempotent; else bun verify --e2e e2e; fi + + - name: Metro log + if: failure() && matrix.mode == 'dev' + run: tail -100 "$RUNNER_TEMP/metro.log" || true + - uses: actions/upload-artifact@v4 + if: always() + with: + name: nightly-${{ matrix.name }} + path: | + verify/artifacts/ + verify/e2e/.e2e/ + if-no-files-found: ignore + include-hidden-files: true # verify/e2e/.e2e is a dot dir + + # Marks the commit for the release gate (Task 32). A matrix entry with `experimental: true` does not block it. + mark-nightly: + needs: [e2e] + if: ${{ !inputs.dry_run }} + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + statuses: write + steps: + - name: Mark the commit with the `nightly` status + env: + GH_TOKEN: ${{ github.token }} + run: > + gh api 'repos/${{ github.repository }}/statuses/${{ github.sha }}' + -f state=success -f context=nightly -f description='Nightly matrix passed' + -f target_url='${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}' diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 32303fa..2bfec6c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -77,9 +77,34 @@ We follow the [conventional commits specification](https://www.conventionalcommi We use [TypeScript](https://www.typescriptlang.org/) for type checking and [OXLint](https://oxc.rs/docs/guide/usage/linter.html) for linting and formatting the code. -### Publishing to npm 🚧 - -We use [changesets](https://github.com/changesets/changesets) for managing versions, though this is a manual process for now in the experimental phase. +### Publishing to npm + +We use [changesets](https://github.com/changesets/changesets), automated by `.github/workflows/release.yml`. Never run +`changeset publish` or `npm publish` locally. + +1. Add a changeset (`bunx changeset`) in your PR. +2. When CI is green on a `main` push, `publish-next` re-checks that CI result through the API + (`scripts/release-gate.js`). It then opens or updates the "chore: version packages" PR. +3. After that PR is merged and CI is green on the merge, it publishes with `npm publish --tag next` and pushes the + `v` tag. It creates no GitHub Release. +4. To make a version `latest`: + - Run Nightly on its tag: Actions → Nightly → Run workflow, "Use workflow from" `v`. + - Then run Release from `main` with `promote=`. + - It refuses a commit without a green nightly run, and a version lower than the current `latest`. + +Setup and caveats: + +- **`npm` environment.** Create an environment named `npm` (Settings → Environments). Store `NPM_TOKEN` there as an + environment secret. Use a granular access token limited to publishing this package. Both publishing jobs run in this + environment, so required reviewers on it gate them too. +- **Allow the version PR.** Enable Settings → Actions → General → "Allow GitHub Actions to create and approve pull + requests". Without it, the version PR cannot be opened. +- **The version PR gets no CI.** Events from `GITHUB_TOKEN` don't trigger workflows, so CI does not run on the + version PR. To get CI on it: + - close and reopen the PR, or push an empty commit to its branch yourself; + - or give the action a GitHub App or fine-grained PAT token in place of `GITHUB_TOKEN`. + + The merge to `main` runs CI either way, and `publish-next` publishes only after that run is green. ### Scripts diff --git a/MIGRATION.md b/MIGRATION.md new file mode 100644 index 0000000..ba8c487 --- /dev/null +++ b/MIGRATION.md @@ -0,0 +1,103 @@ +# Migrating from 0.2 to v0 (0.3.0) + +v0 is a rewrite. It keeps tracing, and JS and native spans now share one trace. It removes everything else that 0.2 +had. The version stays in 0.x (0.2.0 → 0.3.0), but expect breaking changes. + +| 0.2 | v0 | +| --- | --- | +| `openTelemetrySDK(options)` (JS) | `startReactNativeSdk(config)`. See [Init](#init) | +| Android `com.opentelemetry.OpenTelemetry.init(this) { … }` | `com.callstack.otel.RNOtel.start(this) { … }` | +| iOS: JS only | `RNOtel.start { c in … }` in `AppDelegate` (native-first), or the JS init | +| Metrics (JS `sdk.metrics.getMeter`, Android `getMeter`) | **Removed.** Returns in v1 | +| Fetch instrumentation (automatic) | **Removed.** Network instrumentation returns in v1 | +| Session tagging (`features.session.getSessionId`) | **Removed.** Sessions return in v1. Interim: your own `SpanProcessor` (below) | +| `debug: true` (console exporters) | Pass a console exporter in `spanProcessors` (below) | +| W3C trace-context + baggage propagators registered globally | Not registered. Register one yourself if you inject headers | + +## New requirements + +- React Native 0.79+, New Architecture, Hermes, and the peer `react-native-nitro-modules` ~0.37. +- iOS: add `pod 'ReactNativeOpenTelemetryCore', :path => '../node_modules/react-native-open-telemetry'` to the + Podfile. On Expo, add the `"react-native-open-telemetry"` config plugin instead. See the [README](README.md#install). +- Android: minSdk 26. +- Metro: wrap the merged config with `withOtel` from `react-native-open-telemetry/metro`. It runs the context patch + before any app module. Without it, the patch installs at the package import, and only code that runs before that + import loses parents. +- Expo web: also lower `async` for the web platform in `babel.config.js` (see the + [README](README.md#metro-helper)). Without it, context is lost after a native `await`. + +## Init + +```ts +// 0.2 +import {openTelemetrySDK} from 'react-native-open-telemetry'; +const api = openTelemetrySDK({url, name: 'shop', version: '1.4.0', environment: 'prod', debug: true}); +const tracer = api.trace.getTracer('app'); + +// v0 +import {trace} from '@opentelemetry/api'; +import {startReactNativeSdk} from 'react-native-open-telemetry'; +const {forceFlush, shutdown} = startReactNativeSdk({ + serviceName: 'shop', + serviceVersion: '1.4.0', + resourceAttributes: {'deployment.environment.name': 'prod'}, + exportConfig: {url, headers: {}}, +}); +const tracer = trace.getTracer('app'); +``` + +| 0.2 option | v0 | +| --- | --- | +| `name` / `version` | `serviceName` / `serviceVersion` | +| `environment` | `resourceAttributes: {'deployment.environment.name': …}`. 0.2 JS defaulted it to `process.env.NODE_ENV`; v0 sets no default, so pass it yourself. 0.2 Android wrote it as `environment` (default `development`) | +| `url` | `exportConfig.url` (JS) or `export { url }` (native). It is the OTLP **HTTP** traces endpoint, used as given (usually `https://host:4318/v1/traces`). 0.2 Android exported gRPC (4317); v0 sends OTLP/HTTP protobuf everywhere | +| `native` | Gone. Init natively with `RNOtel.start` instead. JS then attaches to it | +| return value (the `@opentelemetry/api` module) | `{tracerProvider, forceFlush, shutdown}`. Import `@opentelemetry/api` yourself | + +0.2 also set `os.name`/`os.version` from `Platform`. On mobile, v0 builds the resource natively (service attributes, +your `resourceAttributes`, the otel SDK defaults and `telemetry.distro.*`). Pass anything else in +`resourceAttributes`. + +On Android, the native call changes shape: + +```kotlin +// 0.2 +OpenTelemetry.init(this) { url = "https://collector:4317"; name = "shop"; version = "1.0.0"; environment = "prod" } + +// v0 +RNOtel.start(this) { + serviceName = "shop"; serviceVersion = "1.0.0" + resourceAttributes = mapOf("deployment.environment.name" to "prod") + export { url = "https://collector:4318/v1/traces" } +} +``` + +v0 does not set `GlobalOpenTelemetry`. For native spans, use `RNOtel.tracer(name)`. 0.2's Android `debug` (on by +default, through otel-java's logging exporters) is gone, and v0 has no native console exporter. Use the JS console +processor below for JS spans, or point the export at a local Collector with the `debug` exporter. + +## Interim replacements + +These snippets use upstream OpenTelemetry APIs only. This package does not test them. + +**Console output** (was `debug: true`): + +```ts +import {SimpleSpanProcessor, ConsoleSpanExporter} from '@opentelemetry/sdk-trace'; +startReactNativeSdk({/* … */, spanProcessors: [new SimpleSpanProcessor(new ConsoleSpanExporter())]}); +``` + +**Session id** (was `features.session`). This covers JS spans only. Native spans get sessions in v1. + +```ts +const sessionProcessor = { + onStart: span => { const id = getSessionId(); if (id) span.setAttribute('session.id', id); }, + onEnd() {}, forceFlush: () => Promise.resolve(), shutdown: () => Promise.resolve(), +}; +startReactNativeSdk({/* … */, spanProcessors: [sessionProcessor]}); +``` + +**Fetch spans:** v1 brings network instrumentation for XHR and native OkHttp/URLSession. Until then, you can register +upstream `@opentelemetry/instrumentation-fetch` yourself against the global tracer provider. + +**Metrics:** v1. Until then, run `@opentelemetry/sdk-metrics` with its own exporter next to this SDK. diff --git a/README.md b/README.md index 12c0062..f955ab6 100644 --- a/README.md +++ b/README.md @@ -1,112 +1,229 @@ # react-native-open-telemetry -Best in class observability brought to React Native. +OpenTelemetry tracing for React Native (iOS, Android) and web. JS spans and native spans share one trace and +export together over OTLP/HTTP to any OTLP backend. -* **OpenTelemetry** is a collection of APIs, SDKs, and tools developed by [OpenTelemetry](https://github.com/open-telemetry) to instrument, generate, collect, and export telemetry data. See [What is OpenTelemetry](https://opentelemetry.io/docs/what-is-opentelemetry/) for more information. -* **react-native-open-telemetry** is a library that allows you to easily use **OpenTelemetry's** JS and Native bindings inside your React Native app. +v0 is tracing only. If you used 0.x, read [MIGRATION.md](MIGRATION.md) first. -## Features +## Requirements -* **Telemetry without lock-in**. Send to **any OTLP compliant backend** including [vendors](https://opentelemetry.io/ecosystem/vendors/) -* [**Tracing** API](https://opentelemetry.io/docs/specs/otel/trace/api/) -* [**Metrics** API](https://opentelemetry.io/docs/specs/otel/metrics/api/) -* **Web**, **Android** (experimental) support with **iOS** coming soon -* Automatic **fetch instrumentation** -* Automatic **session tagging** +- React Native **0.79+**, New Architecture, Hermes +- `react-native-nitro-modules` **~0.37** +- iOS: Xcode **27.0+** (verified; Xcode 16.4 fails on the Swift packages' tools versions, Xcode 26 is untested), with a + React Native version that builds on your Xcode (verified on Xcode 27: **0.88.1**). React Native 0.79 does not build + on Xcode 27: its `fmt` pod fails on the newer Clang (`consteval`). RN 0.79 on iOS needs an older Xcode, which is + untested here. +- Android: minSdk **26**, React Native 0.79+ (0.88.1 is verified per PR; 0.79 runs in the nightly) -## Platform support +## Install -| Platform | Support | -| --- | --- | -| **web** | ☑️ Stable | -| **android** | ☑️ Stable JS with experimental Native 🏗️ | -| **ios** | ☑️ Stable JS with planned Native 👀 | +```sh +npm install react-native-open-telemetry react-native-nitro-modules +``` -## Installation +### iOS (bare) -```sh -npm install react-native-open-telemetry +Autolinking links only the Nitro adapter pod. Add the core pod to your app target in `ios/Podfile` yourself, then run +`pod install`: + +```ruby +target 'MyApp' do + pod 'ReactNativeOpenTelemetryCore', :path => '../node_modules/react-native-open-telemetry' + # ... +end ``` -## Usage +### Expo (prebuild / CNG) -### 1. Start the JS SDK +Expo regenerates the Podfile, so the package ships a config plugin that adds that one line: -See OpenTelemetry's JS documentation on [Traces](https://opentelemetry.io/docs/languages/js/instrumentation/#acquiring-a-tracer) and [Metrics](https://opentelemetry.io/docs/languages/js/instrumentation/#acquiring-a-meter) for more information on available APIs. +```json +{ "expo": { "plugins": ["react-native-open-telemetry"] } } +``` -```js -import { openTelemetrySDK } from 'react-native-open-telemetry'; - -// Start the SDK -const sdk = openTelemetrySDK({ - debug: true, - url: "https://my-collector.com:4317", - name: "my-app", - version: "1.0.0-alpha", - environment: "development", -}); +That is all the plugin does. Expo apps usually init from JS (below). -// Use available APIs -const meter = sdk.metrics.getMeter("my-js-meter", "1.0"); +### Android -const promoCounter = meter.createCounter("my-promo-counter", { - description: "A counter metric for my promo section" -}); +Nothing to add. The library's R8 consumer rules ship with it and apply automatically. + +## Init + +### Native-first (preferred) + +Start the SDK in native code, before React Native, so you can trace from the very start of the app. On Android it +does nothing outside the main process. It never throws: on bad config it logs one error and telemetry stays off. -function App() { - function onPress() { - promoCounter.add(1); +```kotlin +// android: MainApplication.onCreate, before loadReactNative(this) +import com.callstack.otel.RNOtel + +RNOtel.start(this) { + serviceName = "shop" + serviceVersion = BuildConfig.VERSION_NAME + resourceAttributes = mapOf("deployment.environment.name" to "prod") + export { + url = "https://collector.example.com:4318/v1/traces" + headers = mapOf("x-api-key" to KEY) } +} +``` - return