Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Add Open Telemetry support 🚀 (#14438)
Damian Legawiec66df498e6f83
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.ymlindex 25234c2d3f..bc732c8ceb 100644--- a/.github/workflows/tests.yml+++ b/.github/workflows/tests.yml@@ -56,7 +56,7 @@ jobs:- name: Install all project dependenciesrun: |- for project in core api emails providers/easypost providers/meilisearch dashboard; do+ for project in core api emails providers/easypost providers/meilisearch dashboard opentelemetry; doecho "--- Installing gems for $project ---"cd spree/$projectbundle config set --local path ${{ github.workspace }}/vendor/bundle@@ -101,7 +101,7 @@ jobs:- name: Install all project dependenciesrun: |- for project in core api emails providers/easypost providers/meilisearch dashboard; do+ for project in core api emails providers/easypost providers/meilisearch dashboard opentelemetry; doecho "--- Installing gems for $project ---"cd spree/$projectbundle config set --local path ${{ github.workspace }}/vendor/bundle@@ -136,6 +136,8 @@ jobs:- { project: providers, dirs: "providers/easypost providers/meilisearch", shard: 1, total_shards: 1, procs: 2 }# dashboard: 1 runner × 2 procs (tiny suite — SPA host)- { project: dashboard, shard: 1, total_shards: 1, procs: 2 }+ # opentelemetry: 1 runner × 2 procs (tiny suite — optional tracing gem)+ - { project: opentelemetry, shard: 1, total_shards: 1, procs: 2 }services:postgres:image: postgres:16@@ -294,6 +296,8 @@ jobs:- { project: providers, dirs: "providers/easypost providers/meilisearch", shard: 1, total_shards: 1, procs: 2 }# dashboard: 1 runner × 2 procs (tiny suite — SPA host)- { project: dashboard, shard: 1, total_shards: 1, procs: 2 }+ # opentelemetry: 1 runner × 2 procs (tiny suite — optional tracing gem)+ - { project: opentelemetry, shard: 1, total_shards: 1, procs: 2 }services:mysql:image: mysql:8.0diff --git a/CLAUDE.md b/CLAUDE.mdindex a15ce699b3..e2721a87e2 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -39,6 +39,7 @@ Active plans (6.0 target, work pending):- `6.0-extendable-validations.md` — Workflow `validate` hooks are THE validation extension surface; **no generic model-validation registry** (design finalized 2026-08-13 — decorators stay the documented additive path, relaxing core rules = store preferences/predicate overrides). Ships: `Carts::UpsertItems` graduated to a workflow absorbing every non-increment item mutation (bulk payloads, PATCH quantity, DELETE = quantity 0; per-item `validate` with `AddItem`-compatible readers, shared item-application steps, ONE recalculate per batch; **partial-success on the storefront** — rejected items skip onto the cart's existing `warnings` array on 2xx, while the **order twin fails the whole batch**; no whole-batch veto; `SetQuantity`/`RemoveLineItem` → deprecated shells), `Products::Create`/`Update`/`Destroy` workflows (all write paths route through: Admin API v3, CSV importer, seeds; no standalone variant workflow), **rejections carry `ActiveModel::Errors`** (`Workflow#errors` + argument-less `reject!` rendering via `render_validation_error`; `reject!(message)` bridges to `:base`), `Spree.hooks.validate!` wired into boot, Address polish (document `Spree.validators.addresses` + removal API, `require_company` store preference). Address and cart creation get NO workflow (plain CRUD); custom-field value validation deferred to its own plan (Shopify-style per-definition rules, new-writes-only; `required` stays advisory). **Constraints now:** new item mutations route through `AddItem`/`UpsertItems`, new product write paths call the `Products::*` workflows, no hardcoded error codes at hook-bearing `render_service_error` call sites, clients must check `warnings` on storefront bulk-item 2xx responses. **Shipped 2026-08-13** (all four phases).- `6.0-store-scoped-configuration.md` — Move eight commerce-behavior globals (`auto_capture` + `auto_capture_on_dispatch` → one `capture_method` string; `allow_checkout_on_gateway_error` dropped, not moved — nothing reads it; `track_inventory_levels`, `stock_reservations_enabled`, `track_price_history`, `show_products_without_price`, `address_requires_phone`, `disable_sku_validation`) from `Spree::Config` to `Spree::Store` preferences. Store preference is **authoritative — no runtime fallback** (a fallback chain is what made `default_stock_reservation_ttl_minutes` silently unreachable); upgrade carries values over via `spree:store_settings:backfill_from_config`; globals are deprecated shells until 6.1. Storeless readers (`Address`, the product availability scope) use `Spree::Current.store` with a default fallback. Seven dead settings (`products_per_page`, `storefront_*_path`, …) get shells then deletion. **Capture timing is one vocabulary (2026-08-13):** `Spree::CaptureMethod` = `checkout | on_dispatch | manual` — a Store preference, overridable by a nullable `capture_method` **column** on PaymentMethod (null = inherit; a column, not a preference, since the payment-method preferences blob is per-provider gateway credentials); read `resolved_capture_method`, write `capture_method`; dispatch capture is decided per payment so a `manual` method is never charged by a dispatch; `spree:migrate_capture_methods` carries `auto_capture` over. **Constraints now:** no new `Spree::Config` reads of the movers; no new code against `auto_capture`/`auto_capture_on_dispatch` (deprecated on both models); new behavior flags are born on Store, never global; jobs that validate addresses or query the catalog must set `Spree::Current.store`.- `6.0-store-scoped-custom-field-definitions.md` — Add `store_id` + persisted `filter_key` to `Spree::MetafieldDefinition` (today global and computed), making uniqueness `(store_id, resource_type, filter_key)` with a DB index. Deferred from the 5.6 custom-field search/sort/filter work (schema change, not patch-safe). **Until then:** `filter_key` is a computed method — no Ransack predicates or `where`/`order` against it; definitions are global; uniqueness rests on a `CONCAT` validation with no index behind it.+- `6.0-opentelemetry.md` — First-class OpenTelemetry support (design finalized 2026-08-12; **phases 1–3 implemented same day** — core notifications + `spree/opentelemetry` gem + telemetry docs page; remaining: fast-follow spans, spree-starter Gemfile mention, collector smoke test): core emits a documented `ActiveSupport::Notifications` surface (NO OpenTelemetry dependency in core) + new optional top-level `spree_opentelemetry` gem (`spree/opentelemetry`) that boots the SDK from standard `OTEL_*` env vars (Saleor-style, no host initializer; `OTEL_SDK_DISABLED` kill switch), installs Rails auto-instrumentation, and translates Spree notifications into spans. Traces only in 6.0 (Ruby metrics/logs SDKs experimental; RED metrics via collector spanmetrics). First cut = commerce core four: workflows (`external_step` marks `external: true` → CLIENT spans; `outcome` payload key set inside the instrumented block), events dispatch, webhook delivery (+ outbound W3C `traceparent`), payment gateway boundary; provider bases/Meilisearch/imports/OIDC fast-follow. **Constraints now:** outbound network calls in workflows are always `external_step`, never `step`; never `rescue StandardError` around workflow execution (`FailureSignal`/`Halted` inherit `Exception`); notification payload keys are public API (additive only) and must be PII-safe; telemetry config is env-var deployment config — never `Spree::Config`, store preferences, or admin UI.Multi-version plans (some phases shipped, some pending):- `6.0-6.1-split-adjustments.md` — Replace polymorphic Adjustment with TaxLine, Discount, Fee. **6.0 implementation fully shipped to main** (typed tables + models, `Spree::Adjusters::*` winner-only promotion adjuster, `Spree.tax_provider` seam, admin `/orders/:id/{tax_lines,discounts,fees}` API + SDK + dashboard cards, `spree:migrate_adjustments_to_typed_rows` in the upgrade manifest; legacy `Adjustment`/`AdjustmentSource` deleted). v6 developer docs shipped (`docs/v6/developer/` taxes-discounts-fees + promotions + custom-promotion). Remaining: 6.1 drops `spree_adjustments` + deprecated shells and adds `Promotion#combines_with` stacking.diff --git a/docs/developer/deployment/telemetry.mdx b/docs/developer/deployment/telemetry.mdxnew file mode 100644index 0000000000..a7d6ed5392--- /dev/null+++ b/docs/developer/deployment/telemetry.mdx@@ -0,0 +1,218 @@+---+title: Telemetry+description: Distributed tracing with OpenTelemetry — one gem, standard OTEL_* environment variables, and every checkout becomes a trace from HTTP request to gateway call to webhook delivery.+---++Spree supports [OpenTelemetry](https://opentelemetry.io), the open standard for+distributed tracing. Install the optional `spree_opentelemetry` gem, point it+at your collector with the same environment variables every other+OpenTelemetry service uses, and Spree exports traces — no code changes, no+vendor lock-in. Traces flow to any OpenTelemetry-compatible backend: Grafana+Tempo, Jaeger, Datadog, Honeycomb, New Relic, Dynatrace, and others.++## Setup++Add the gem to your application's Gemfile:++```ruby+gem 'spree_opentelemetry'+```++Then configure the exporter through the standard OpenTelemetry environment+variables:++```bash+OTEL_SERVICE_NAME=spree+OTEL_EXPORTER_OTLP_ENDPOINT=http://collector:4318+```++That is the entire setup. Without an exporter configured, the gem stays+dormant and adds no overhead. `OTEL_SDK_DISABLED=true` turns telemetry off+regardless of any other setting.++Other standard variables work as documented in the+[OpenTelemetry SDK configuration reference](https://opentelemetry.io/docs/languages/sdk-configuration/),+including sampling:++```bash+# Sample 10% of traces (children follow their parent's decision)+OTEL_TRACES_SAMPLER=parentbased_traceidratio+OTEL_TRACES_SAMPLER_ARG=0.1+```++## What gets traced++Two layers combine into one trace per request or job.++**Framework spans** come from the official Rails auto-instrumentation: HTTP+requests, controller actions, database queries, background job enqueues and+executions, mail deliveries, and outbound HTTP calls. Trace context carries+across the job boundary, so work that happens in a background job stays+connected to the request that caused it.++**Commerce spans** come from Spree itself:++| Span | Kind | What it covers |+|---|---|---|+| `carts.complete` (any workflow key) | internal | One span per workflow run, with its outcome |+| `carts.complete process_payments` (any step) | internal / client | One span per workflow step; steps declared as external I/O become client spans |+| `carts.add_item hooks validate` | internal | Extension hook dispatch, only when handlers are registered |+| `order.placed dispatch` | internal | Event delivery to each subscriber, showing whether it ran inline or was enqueued |+| `spree.webhook.deliver order.placed` | client | Each webhook POST, with the destination host and response code |+| `spree.gateway.purchase` (any gateway action) | client | Each payment gateway call — authorize, purchase, capture, void, credit, and payment session operations |++A completed checkout, for example, produces one trace containing the HTTP+request, the `carts.complete` workflow and its steps, the payment gateway+call, the database work, and — linked from it — the background jobs and+webhook deliveries the order triggered.++Spree also propagates+[W3C Trace Context](https://www.w3.org/TR/trace-context/) headers on outbound+webhooks, so a system receiving your webhooks can join its own spans to the+trace that produced the event.++## Span attributes and personal data++Span attributes never contain personal or sensitive data. They are limited to+workflow and step names, gateway action names, payment method class names,+event names, webhook destination hosts, and HTTP status codes. Order contents,+customer emails, addresses, payment details, and webhook payloads are never+attached to spans.++## Metrics++Spree exports the trace signal. Request rates, error rates, and latency+percentiles per endpoint, workflow, or gateway are derived from spans in the+OpenTelemetry Collector with the+[span metrics connector](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/connector/spanmetricsconnector):++```yaml+# otel-collector config+connectors:+ spanmetrics:+ dimensions:+ - name: spree.workflow+ - name: spree.gateway.action++service:+ pipelines:+ traces:+ receivers: [otlp]+ exporters: [spanmetrics, otlp]+ metrics:+ receivers: [spanmetrics]+ exporters: [prometheusremotewrite]+```++## Using with Sentry++Sentry and OpenTelemetry are complementary — Sentry's error capture works+independently of tracing, so having both installed (as spree-starter does)+requires no special setup. For traces there are three arrangements:++**Sentry for errors, OpenTelemetry for traces (default).** Nothing to+configure. Just don't *also* enable Sentry's own performance tracing+(`traces_sample_rate`) — that would instrument every request twice and+produce two disconnected trace systems.++**Sentry as the trace backend.** Sentry ingests OpenTelemetry spans directly+through its [OTLP integration](https://docs.sentry.io/platforms/ruby/guides/rails/integrations/otlp/).+Order matters here: Sentry registers its span processor inside `Sentry.init`,+which only works if the OpenTelemetry SDK is already installed — so install+Spree's telemetry explicitly at the top of the same initializer:++```ruby+# Gemfile+gem 'sentry-opentelemetry'++# config/initializers/sentry.rb+SpreeOpenTelemetry.configure { |config| config.enabled = true }+SpreeOpenTelemetry.install!++Sentry.init do |config|+ config.dsn = ENV['SENTRY_DSN']+ config.otlp.enabled = true+ # Do not set traces_sample_rate or instrumenter — OpenTelemetry owns tracing.+end+```++```bash+# Sentry provides the exporter (derived from the DSN) — tell the SDK not to+# wire its own default OTLP exporter alongside it.+OTEL_TRACES_EXPORTER=none+```++A DSN alone does **not** enable tracing; `config.otlp.enabled` is the+explicit opt-in (Sentry bills for ingested spans, so error capture never+silently becomes span ingestion).++Spree's commerce spans — workflows, gateway calls, webhook deliveries — show+up in Sentry's trace view, and Sentry errors are linked automatically to the+span that was active when they were captured.++**Both, via the collector.** Point Spree at an OpenTelemetry Collector and+fan out from there — one pipeline exporting to your tracing backend and+another to Sentry's OTLP endpoint. This is the most flexible arrangement for+teams that want Grafana/Jaeger for latency work and Sentry for error triage+over the same traces.++## Correlating logs++To connect log lines to traces, tag your Rails logs with the current trace:++```ruby+# config/environments/production.rb+config.log_tags = [+ ->(_request) { "trace_id=#{OpenTelemetry::Trace.current_span.context.hex_trace_id}" }+]+```++## Trying it locally++Run Jaeger with an OTLP receiver and point Spree at it:++```bash+docker run --rm -p 16686:16686 -p 4318:4318 jaegertracing/jaeger:latest+```++```bash+OTEL_SERVICE_NAME=spree \+OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 \+bin/rails server+```++Place a test order and open [http://localhost:16686](http://localhost:16686)+to see the trace.++## Code-level configuration++Everything routine is controlled by environment variables. A+`SpreeOpenTelemetry.configure` block exists for the rest — adding+instrumentation for libraries your app uses, removing a default, or advanced+SDK tuning:++```ruby+# config/initializers/opentelemetry.rb+SpreeOpenTelemetry.configure do |config|+ config.use 'OpenTelemetry::Instrumentation::Redis' # add an instrumentation+ config.skip 'OpenTelemetry::Instrumentation::ActionMailer' # remove a default+ config.with_sdk { |otel| otel.add_span_processor(my_processor) }+end+```++## Instrumenting your own code++Spree's spans are built on `ActiveSupport::Notifications`, and yours can be+too — or use the OpenTelemetry API directly:++```ruby+tracer = OpenTelemetry.tracer_provider.tracer('my_app')++tracer.in_span('loyalty.award_points', attributes: { 'loyalty.points' => 50 }) do+ # your code+end+```++Custom workflows get traced automatically: every `Spree::Workflow` run, step,+and hook dispatch is instrumented by the framework, including workflows your+application or extensions define.diff --git a/docs/docs.json b/docs/docs.jsonindex b91f6dc932..f352b0567c 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -1252,7 +1252,8 @@"developer/deployment/cdn","developer/deployment/background_jobs","developer/deployment/caching",- "developer/deployment/database"+ "developer/deployment/database",+ "developer/deployment/telemetry"]},{@@ -2087,7 +2088,8 @@"developer/deployment/cdn","developer/deployment/background_jobs","developer/deployment/caching",- "developer/deployment/database"+ "developer/deployment/database",+ "developer/deployment/telemetry"]},{diff --git a/docs/plans/6.0-opentelemetry.md b/docs/plans/6.0-opentelemetry.mdnew file mode 100644index 0000000000..af55920316--- /dev/null+++ b/docs/plans/6.0-opentelemetry.md@@ -0,0 +1,285 @@+# OpenTelemetry Instrumentation++**Status:** In Progress — Phases 1–3 implemented 2026-08-12 (core notifications, `spree_opentelemetry` gem, telemetry docs page); remaining: fast-follow spans, spree-starter Gemfile mention, collector smoke test+**Target:** Spree 6.0+**Depends on:** `6.0-service-workflows.md` (workflow step instrumentation is the backbone)+**Author:** Damian Legawiec (design driven with Claude)+**Last updated:** 2026-08-12++## Summary++Enterprise buyers ask whether Spree supports OpenTelemetry the way Medusa,+Saleor and Vendure do, and today the answer is no — there is zero tracing,+metrics or APM code in any gem. This plan closes that gap with a two-layer+design: **core emits a rich, documented `ActiveSupport::Notifications`+surface** (and takes no OpenTelemetry dependency), and a **new optional+`spree_opentelemetry` gem** boots the OpenTelemetry SDK from standard `OTEL_*`+environment variables, installs the Rails auto-instrumentation suite, and+translates Spree's notifications into properly-attributed spans. The result+matches the competitor bar: HTTP → workflow → step → gateway/carrier call as+one distributed trace, configured the same way an SRE configures any other+OpenTelemetry service.++Ruby's OpenTelemetry implementation has **stable traces** but an+**experimental metrics SDK and logs SDK**, so this plan is traces-first;+metrics arrive via the collector (spanmetrics) now and via the metrics SDK+when it stabilizes.++## Key Decisions (do not deviate without discussion)++- **Packaging (2026-08-12): new top-level optional engine `spree/opentelemetry`,+ gem name `spree_opentelemetry`**, beside core/api/emails. Not under+ `spree/providers/` (that shelf means commerce providers with an+ `Integration` credential surface) and not an optional require inside+ `spree_core` (core's gemspec could not declare the OpenTelemetry+ dependencies, pushing version drift onto merchants).+- **Activation (2026-08-12): env vars only, Saleor-style.** Gem in the+ Gemfile + standard `OTEL_*` env vars = traces flow; without an exporter+ endpoint the SDK stays dormant, and `OTEL_SDK_DISABLED=true` is the kill+ switch. No mandatory host initializer. Accepted trade-off: activation via+ environment can surprise — mitigated by honoring `OTEL_SDK_DISABLED` and a+ boot-time log line stating telemetry is active and where it exports.+- **First-cut span scope (2026-08-12): the commerce core four** — workflows+ (with `external_step`/`outcome`), events dispatch, webhook delivery, and+ the payment gateway boundary. These cover what enterprise deals actually+ ask about (checkout traces, payment latency, webhook reliability);+ Rack/Active Record/Active Job/Net::HTTP spans come free from+ auto-instrumentation. Provider base classes (delivery rates, tax,+ fulfillment), Meilisearch, imports/exports and OIDC are a fast-follow (see+ Migration Path), not the first cut.+- **Metrics posture (2026-08-12): traces only in 6.0.** RED metrics+ (rate/errors/duration per endpoint, workflow, gateway) are derived from+ spans via the collector's spanmetrics connector and documented as such; no+ experimental Ruby metrics SDK ships. Accepted trade-off: no custom+ business counters (orders placed, payment failures) until the metrics SDK+ stabilizes — revisit in 6.1.+- **Core never depends on OpenTelemetry gems.** Spree's instrumentation+ contract is `ActiveSupport::Notifications` — the Rails-native bus that any+ APM (Scout, Datadog, AppSignal) can also consume. The OpenTelemetry+ translation lives entirely in the optional gem. This mirrors how Rails+ itself is instrumented and keeps core dependency-free.+- **Traces first.** Only the trace signal ships in 6.0. The Ruby metrics and+ logs SDKs are 0.x/experimental; RED metrics are derived in the collector+ (spanmetrics connector) and documented as such. Log correlation ships as+ trace/span IDs injected into Rails log tags, exported by the host's existing+ log pipeline — never the experimental logs SDK.+- **Telemetry is deployment configuration, never store data.** Standard+ `OTEL_*` environment variables (`OTEL_SERVICE_NAME`,+ `OTEL_EXPORTER_OTLP_ENDPOINT`, `OTEL_TRACES_SAMPLER`, `OTEL_SDK_DISABLED`)+ configure everything, exactly like Saleor. No `Spree::Config` preference, no+ store preference, no admin UI. A `SpreeOpenTelemetry.configure` block exists+ only for code-level needs (extra instrumentations, resource attributes,+ custom samplers).+- **No PII in span attributes — ever.** Attributes carry prefixed IDs+ (`spree.order.id = "order_86Rf07xd4z"`), workflow/step names, gateway+ action names, HTTP metadata. Never event payloads, customer emails,+ addresses, credentials, or webhook bodies. Any dynamic value passes through+ the same `ActiveSupport::ParameterFilter` that `Spree::EventLogSubscriber`+ already uses (`filter_parameters` + Spree's additions in `engine.rb`).+- **`external_step` self-identifies in the notification payload**+ (`external: true` on `step.spree_workflow`). One payload key marks all 11+ declared gateway/carrier boundaries as `CLIENT` spans; new `external_step`+ call sites get this for free.+- **Workflow failures must mark spans errored.** `FailureSignal` and `Halted`+ inherit `Exception` (deliberately, so a plain `rescue` can't swallow them),+ and a failure `Result` is detected *after* the instrumented block returns.+ The step instrumentation writes an `outcome` payload key inside the block;+ the span subscriber maps `failure`/`halted` outcomes and `:exception`+ payloads to span error status. Instrumentation code must never `rescue+ StandardError` around workflow execution.+- **Async trace continuity comes from the contrib ActiveJob+ instrumentation** (trace context injected into job metadata at enqueue,+ restored at perform), covering `Spree::Events::SubscriberJob`, webhook+ delivery jobs, search indexing and imports without any core change. Default+ `propagation_style: :link` (a checkout trace should not stretch until the+ last webhook retry finishes).+- **Outbound webhooks propagate W3C trace context.** `traceparent` /+ `tracestate` headers are injected into webhook POSTs (Saleor does the same),+ so a merchant's receiving system can join the trace. Core exposes a small+ header-decorator hook on `Spree::Webhooks::DeliverWebhook`; the gem+ registers the propagator there.+- **Span sources are hand-rolled notification subscribers**, following the+ `Spree::EventLogSubscriber` pattern (module-level subscription handle+ outside Zeitwerk, `detach` before every attach for reload safety), not the+ contrib `ActiveSupport.subscribe` helper — we need control over span kind+ (CLIENT for external steps), status mapping from `outcome`, and attribute+ filtering that the generic helper doesn't offer.++## Design Details++### Layer 1 — core notification surface (no new dependencies)++Today only two production `instrument` calls exist: `step.spree_workflow`+(`spree/core/lib/spree/workflow.rb`) and the events adapter's+`<event>.spree` (whose instrumented block is intentionally empty — fan-out+bookkeeping, not business work). Layer 1 hardens and extends this surface so+*any* consumer — the OpenTelemetry gem, an APM, a log subscriber — sees the+full picture:++| Notification | New/changed | Payload | Purpose |+|---|---|---|---|+| `perform.spree_workflow` | new | `workflow`, `outcome` | One span per workflow run (today only steps are visible) |+| `step.spree_workflow` | extended | + `external` (from `external_step`), + `outcome` (`success`/`failure`, set inside the block) | Step spans; external steps become CLIENT spans |+| `hooks.spree_workflow` | new | `workflow`, `hook`, `handler_count` | Extension handler dispatch, invisible today |+| `dispatch.spree_events` | new | `event_name`, `subscriber`, `async` | Per-subscriber dispatch (enqueue vs inline), uninstrumented today |+| `deliver.spree_webhooks` | new | `event_name`, `url_host`, `response_code`, `error_type` | Wraps the POST in `Webhooks::DeliverWebhook#call`, which already measures monotonic time and records these values |+| `gateway.spree_payments` | new | `action`, `payment_method_type` | Wraps `Payment::Processing#gateway_action`/`capture!`/`void_transaction!`, `Refund#process!`, and the payment-session methods (currently untraced controller-path network calls) |++Fast-follow notifications (same shape, after the first cut ships):+`estimate.spree_delivery_rates` / `<op>.spree_tax` / `<op>.spree_fulfillment`+instrumented in the provider base-class dispatch path (so third-party+providers are covered on arrival, and the per-line-item tax call in+`LineItem` becomes immediately visible as an N+1), Meilisearch client calls,+imports/exports continuation steps, and OIDC discovery/token exchange.++`<event>.spree` events stay as they are and surface as **span events** on the+current span (they wrap no work, so they must not become spans).++Existing consumers are unaffected: payload keys are only added, never renamed,+and `step.spree_workflow` semantics stay byte-compatible (the+`6.0-service-workflows.md` battery must pass unmodified).++### Layer 2 — the `spree_opentelemetry` gem++A new optional engine at `spree/opentelemetry` depending on:++- `opentelemetry-sdk` + `opentelemetry-exporter-otlp` (stable)+- `opentelemetry-instrumentation-rails` (umbrella: Rack, Action Pack, Active+ Record, Active Job, Action Mailer, Active Support, Concurrent Ruby)+- `opentelemetry-instrumentation-net_http` (covers webhook POSTs — the+ `SsrfFilter` path is Net::HTTP underneath — plus OIDC discovery/token+ calls and image downloads)++Responsibilities:++1. **SDK bootstrap** in an engine initializer: `OpenTelemetry::SDK.configure`+ reading standard env vars, installing the curated instrumentation list,+ setting service resource attributes (`service.name`, `spree.version`),+ and logging one boot-time line stating telemetry is active and its export+ endpoint. Dormant (no-op) when no exporter is configured; honors+ `OTEL_SDK_DISABLED`.+2. **Spree span subscribers** — one subscriber class per notification family+ above, producing spans named from a bounded vocabulary+ (`carts.add_item`, `carts.add_item validate_stock`,+ `spree.webhook.deliver`, `spree.gateway.capture`) with `spree.*`+ attributes. Reload-safe via the `EventLogSubscriber` handle pattern.+3. **ActiveJob propagation config** (`propagation_style: :link` default,+ overridable).+4. **Webhook `traceparent` injection** via the core header-decorator hook.+5. **`SpreeOpenTelemetry.configure`** for host-level extension.++### What auto-instrumentation already gives us for free++Rack/Action Pack server spans (every Store/Admin API request), Active Record+query spans, Active Job enqueue/perform spans with context propagation,+Action Mailer, Net::HTTP client spans. Spree's layer adds the *commerce*+semantics on top — which is exactly the split Medusa (`workflow:`/`step:`+spans) and Vendure (`@Instrument()` on services) ship.++### Testing++- Core: specs asserting notification names/payloads (including `external` and+ `outcome` keys, and that `FailureSignal` still propagates).+- Gem: specs with the in-memory span exporter+ (`opentelemetry-test-helpers`) asserting span hierarchy, kinds, error+ status mapping, and that filtered keys never appear in attributes.+- One end-to-end smoke: worktree Rails + OTLP collector (or Jaeger+ all-in-one) verifying a checkout produces the expected trace shape.++### Documentation++New `docs/developer/deployment/telemetry.mdx` (task-focused, mirroring the+competitor pages): install the gem, set env vars, point at a collector,+screenshot of a checkout trace, span catalog table, PII guarantees, sampling+guidance, log-correlation setup. The notification catalog also lands in the+customization docs since it doubles as the APM-agnostic instrumentation+contract.++## Migration Path++Purely additive — no schema changes, no behavior changes, no upgrade tasks.++1. **Phase 1 (core) — shipped 2026-08-12:** payload extensions + new+ notifications listed above (`Spree::Workflow`, events adapter,+ `DeliverWebhook` + header decorators, `Spree::InstrumentsGatewayCalls`+ in `Payment::Processing`/`Refund`/payment-session controllers).+2. **Phase 2 (gem) — shipped 2026-08-12:** `spree/opentelemetry`+ (`spree_opentelemetry`) with env-driven SDK bootstrap, one+ `SpanSubscriber` per notification family, domain events as span events,+ ActiveJob link propagation, webhook `traceparent` injection; wired into+ CI matrices and the release Rakefile.+3. **Phase 3 (docs) — shipped 2026-08-12:**+ `docs/developer/deployment/telemetry.mdx` in both v6 nav trees (including+ Sentry coexistence guidance). Still needs a spree-starter PR — and+ **amended 2026-08-12: the starter bundles the gem by default**, not+ commented out. The Docker image is built from the starter, so image users+ cannot edit the Gemfile; with the gem dormant until an `OTEL_*` exporter+ variable appears, bundling it makes tracing a pure env-var opt-in for+ container deployments at the cost of a few MB of image size. The starter+ already ships Sentry for errors — the docs page covers the three+ arrangements (independent, Sentry OTLP as trace backend, collector+ fan-out) and warns against enabling Sentry's own `traces_sample_rate`+ alongside. The Sentry-backend recipe requires explicit ordering+ (`SpreeOpenTelemetry.install!` before `Sentry.init`, with+ `OTEL_TRACES_EXPORTER=none`) — see decisions.md 2026-08-12; auto-detecting+ Sentry from the gem was reverted as unworkable.+4. **Fast-follow (can land within 6.0 after the first cut):** provider+ base-class spans (delivery rates, tax, fulfillment), Meilisearch client+ spans, imports/exports continuation-step spans, OIDC spans.+5. **6.1 (deferred):** metrics via the Ruby metrics SDK once stable+ (checkout conversion counters, payment failure counters, queue depth);+ provider-gem HTTP spans using native client hooks (EasyPost's response+ hook in `spree_easypost/engine.rb` is the template); storefront (Next.js)+ trace propagation guide.++## Constraints on Current Work++- **New `external_step` call sites need no extra work** — but never model an+ outbound network call as a plain `step`; the `external_step` distinction is+ now also the tracing contract, not just the transaction guard.+- **Never `rescue StandardError` around workflow execution** in+ instrumentation or middleware — `FailureSignal`/`Halted` inherit+ `Exception` and would be missed (failed work reported as OK).+- **Notification payload keys are public API** once this ships: additive+ changes only, same rule as workflow hook keys.+- **No telemetry configuration on `Spree::Store` or in admin UIs** — it is+ process-level deployment config.+- **Anything added to a notification payload must be PII-safe** or run+ through the parameter filter; assume every payload key becomes a span+ attribute on someone's dashboard.++## Open Questions++All four launch questions (packaging, activation, first-cut span scope,+metrics posture) were resolved 2026-08-12 — see Key Decisions. Genuinely+deferred items, each with its unblock condition:++- **Native metrics instruments** — unblocked when the Ruby metrics SDK+ reaches a stable release (track opentelemetry-ruby releases).+- **`Gateway#method_missing` forwarding** — arbitrary provider methods bypass+ the instrumented gateway boundary; decide whether to deprecate the escape+ hatch or instrument `method_missing` when the Stripe/Adyen provider gems+ land in the monorepo.+- **Span naming semantic conventions** — OpenTelemetry has no commerce+ semantic conventions yet; `spree.*` attribute names are our own vocabulary.+ Revisit if/when an upstream convention appears.++## References++- Codebase instrumentation inventory (2026-08-12): `step.spree_workflow` at+ `spree/core/lib/spree/workflow.rb:178`, events adapter at+ `spree/core/lib/spree/events/adapters/active_support_notifications.rb:32`,+ dispatch at `spree/core/lib/spree/events/adapters/base.rb:147`, log+ subscriber pattern at+ `spree/core/app/subscribers/spree/event_log_subscriber.rb`, webhook+ delivery at `spree/api/app/services/spree/webhooks/deliver_webhook.rb`,+ gateway boundary at `spree/core/app/models/spree/payment/processing.rb`.+- `docs/plans/6.0-service-workflows.md` — workflow tier, hook contracts,+ `step.spree_workflow` battery.+- Medusa instrumentation: https://docs.medusajs.com/learn/debugging-and-testing/instrumentation+- Saleor telemetry: https://docs.saleor.io/setup/telemetry+- Vendure telemetry: https://docs.vendure.io/current/core/how-to/telemetry+- opentelemetry-ruby: https://github.com/open-telemetry/opentelemetry-ruby+ (traces stable; metrics/logs SDKs experimental)+- opentelemetry-ruby-contrib (Rails umbrella, ActiveJob propagation):+ https://github.com/open-telemetry/opentelemetry-ruby-contribdiff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex 97aba7564f..0364b26136 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -2697,3 +2697,66 @@ newsletter subscriptions and any new resource route through the same seamwith no wiring; `/customers/me/*` endpoints stay owner-scoped by definition.Full B2B architecture: `6.1-channels-catalogs-b2b.md` → "Company roles andapprovals".++## 2026-08-12 — OpenTelemetry: notifications in core, spans in an optional gem, traces only++**Decision:** Spree ships first-class OpenTelemetry support+(`docs/plans/6.0-opentelemetry.md`) as two layers. Core's instrumentation+contract is `ActiveSupport::Notifications` — core takes **no** OpenTelemetry+dependency, and the notification catalog (workflow `perform`/`step`/`hooks`,+events dispatch, webhook delivery, payment gateway boundary) becomes public+API with the same additive-only rule as workflow hook keys. A new optional+top-level engine `spree/opentelemetry` (gem `spree_opentelemetry`, beside+core/api/emails — NOT under `spree/providers/`, which means commerce+providers with an `Integration` credential surface) boots the OpenTelemetry+SDK purely from standard `OTEL_*` env vars (Saleor-style; no host+initializer; `OTEL_SDK_DISABLED` honored), installs the Rails+auto-instrumentation umbrella, and translates Spree notifications into spans+via hand-rolled subscribers following the `Spree::EventLogSubscriber`+reload-safety pattern. 6.0 ships the trace signal only — the Ruby metrics and+logs SDKs are experimental, so RED metrics are collector-derived+(spanmetrics) and log correlation is trace IDs in log tags, never the logs+SDK.++**Consequences for other work:**+- An outbound network call inside a workflow is always an `external_step`,+ never a plain `step` — `external_step` now also marks the span as CLIENT+ (`external: true` in the `step.spree_workflow` payload), so the+ distinction is a tracing contract on top of the transaction guard.+- Never `rescue StandardError` around workflow execution in instrumentation+ or middleware: `FailureSignal`/`Halted` inherit `Exception` and would be+ silently missed.+- Anything added to an instrumented notification payload must be PII-safe+ (prefixed IDs, names, counts — never payloads, emails, addresses,+ credentials); assume every payload key ends up on someone's dashboard.+- Telemetry configuration is process-level deployment config (env vars) —+ never a `Spree::Config` preference, store preference, or admin UI surface.++## 2026-08-12 — spree-starter bundles spree_opentelemetry by default; Sentry keeps errors++**Decision:** spree-starter adds `spree_opentelemetry` to its Gemfile+installed, not commented out (amends the plan's original "commented in the+Gemfile"). The official Docker image is built from the starter, so image+users cannot edit the Gemfile — and since the gem is dormant until a standard+`OTEL_*` exporter variable is set, bundling it makes tracing a pure+environment-variable opt-in for container deployments. Sentry (already in the+starter) and OpenTelemetry divide cleanly: Sentry keeps error capture, the+OpenTelemetry stack owns tracing. The starter must NOT set Sentry's+`traces_sample_rate` — that would double-instrument every request into two+disconnected trace systems. Teams that want traces in Sentry use the+`sentry-opentelemetry` OTLP integration, and **ordering is load-bearing**+(2026-08-12 code review): Sentry registers its span processor synchronously+inside `Sentry.init` (`after(:configured)`), which requires the OpenTelemetry+SDK to already be installed — so the recipe is `SpreeOpenTelemetry.configure+{ |c| c.enabled = true }` + `SpreeOpenTelemetry.install!` at the top of the+Sentry initializer, before `Sentry.init` with `config.otlp.enabled = true`,+plus `OTEL_TRACES_EXPORTER=none` so the SDK wires no competing default+exporter (Sentry derives its endpoint from the DSN). Auto-detecting Sentry's+OTLP mode from `spree_opentelemetry` was tried and reverted — the gem+installs after `load_config_initializers` by design, so detection can never+run early enough. A bare SENTRY_DSN deliberately does NOT activate tracing:+Sentry bills for ingested spans, so error capture must never silently become+span ingestion. The starter's own sentry initializer encapsulates the whole+recipe behind an env var (e.g. `SENTRY_OTLP_ENABLED=true`) so container+users still flip it without code. Docs:+`docs/developer/deployment/telemetry.mdx`.diff --git a/spree/Rakefile b/spree/Rakefileindex b767205f85..ff9f3afcca 100644--- a/spree/Rakefile+++ b/spree/Rakefile@@ -8,7 +8,7 @@ rescue LoadErrorendSPREE_CORE_GEMS = %w(core api).freeze-SPREE_OPTIONAL_GEMS = %w(emails dashboard).freeze+SPREE_OPTIONAL_GEMS = %w(emails dashboard opentelemetry).freeze# Provider gems sit one directory deeper and their gem name doesn't match the# directory, so they carry the path explicitly.SPREE_PROVIDER_GEMS = {diff --git a/spree/api/app/services/spree/webhooks/deliver_webhook.rb b/spree/api/app/services/spree/webhooks/deliver_webhook.rbindex 1ed8e4cd00..d94052e347 100644--- a/spree/api/app/services/spree/webhooks/deliver_webhook.rb+++ b/spree/api/app/services/spree/webhooks/deliver_webhook.rb@@ -12,38 +12,66 @@ module Spreenew(delivery: delivery, secret_key: secret_key).callend+ # Callables invoked with (headers, delivery) before every webhook POST —+ # merge into the hash to add outbound headers (e.g. W3C trace context+ # propagation). Registrations live on a reloadable class: register from+ # a `config.to_prepare` block so they survive code reloads.+ #+ # @return [Array<#call>] the mutable decorator list+ def self.header_decorators+ @header_decorators ||= []+ end++ # @param delivery [Spree::WebhookDelivery] the pending delivery to send+ # @param secret_key [String] endpoint secret used to sign the payloaddef initialize(delivery:, secret_key:)@delivery = delivery@secret_key = secret_keyend+ # Sends the webhook and records the outcome on the delivery. Transport+ # failures are captured on the record rather than raised, so a broken+ # endpoint never breaks the caller.+ #+ # @return [Spree::WebhookDelivery] the completed deliverydef call- start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)-- response = make_request- execution_time = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - start_time) * 1000).round-- @delivery.complete!(- response_code: response.code.to_i,- execution_time: execution_time,- response_body: response.body.to_s.truncate(10_000)- )- rescue Net::OpenTimeout, Net::ReadTimeout => e- execution_time = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - start_time) * 1000).round- Rails.error.report(e, context: { webhook_delivery_id: @delivery.id, url: @delivery.url })- @delivery.complete!(- execution_time: execution_time,- error_type: 'timeout',- request_errors: e.message- )- rescue StandardError => e- execution_time = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - start_time) * 1000).round- Rails.error.report(e, context: { webhook_delivery_id: @delivery.id, url: @delivery.url })- @delivery.complete!(- execution_time: execution_time,- error_type: 'connection_error',- request_errors: e.message- )+ ActiveSupport::Notifications.instrument(+ 'deliver.spree_webhooks',+ event_name: @delivery.event_name,+ url_host: url_host+ ) do |payload|+ start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)++ begin+ response = make_request+ execution_time = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - start_time) * 1000).round++ payload[:response_code] = response.code.to_i+ @delivery.complete!(+ response_code: response.code.to_i,+ execution_time: execution_time,+ response_body: response.body.to_s.truncate(10_000)+ )+ rescue Net::OpenTimeout, Net::ReadTimeout => e+ execution_time = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - start_time) * 1000).round+ Rails.error.report(e, context: { webhook_delivery_id: @delivery.id, url: @delivery.url })+ payload[:error_type] = 'timeout'+ @delivery.complete!(+ execution_time: execution_time,+ error_type: 'timeout',+ request_errors: e.message+ )+ rescue StandardError => e+ execution_time = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - start_time) * 1000).round+ Rails.error.report(e, context: { webhook_delivery_id: @delivery.id, url: @delivery.url })+ payload[:error_type] = 'connection_error'+ @delivery.complete!(+ execution_time: execution_time,+ error_type: 'connection_error',+ request_errors: e.message+ )+ end+ endendprivate@@ -56,6 +84,8 @@ module Spree'X-Spree-Webhook-Timestamp' => webhook_timestamp.to_s,'X-Spree-Webhook-Event' => @delivery.event_name}+ self.class.header_decorators.each { |decorator| decorator.call(headers, @delivery) }+body = payload_jsonhttp_options = { open_timeout: TIMEOUT, read_timeout: TIMEOUT, verify_mode: ssl_verify_mode }@@ -89,6 +119,12 @@ module Spree@webhook_timestamp ||= Time.current.to_iend+ def url_host+ URI.parse(@delivery.url).host+ rescue URI::InvalidURIError+ nil+ end+def ssl_verify_modeif Spree::Api::Config.webhooks_verify_sslOpenSSL::SSL::VERIFY_PEERdiff --git a/spree/api/spec/services/spree/webhooks/deliver_webhook_spec.rb b/spree/api/spec/services/spree/webhooks/deliver_webhook_spec.rbindex cb18a6fa9a..008b2a00c6 100644--- a/spree/api/spec/services/spree/webhooks/deliver_webhook_spec.rb+++ b/spree/api/spec/services/spree/webhooks/deliver_webhook_spec.rb@@ -221,6 +221,62 @@ module Spreeendend+ context 'instrumentation' do+ def capture_delivery_notifications+ events = []+ subscriber = ActiveSupport::Notifications.subscribe('deliver.spree_webhooks') do |*, payload|+ events << payload+ end+ yield+ events+ ensure+ ActiveSupport::Notifications.unsubscribe(subscriber)+ end++ it 'instruments the delivery as deliver.spree_webhooks with the response code' do+ stub_request(:post, delivery.url).to_return(status: 200, body: '{}')++ notifications = capture_delivery_notifications do+ described_class.call(delivery: delivery, secret_key: secret_key)+ end++ expect(notifications.sole).to include(+ event_name: delivery.event_name,+ url_host: URI.parse(delivery.url).host,+ response_code: 200+ )+ end++ it 'records the error type instead of a response code on timeout' do+ stub_request(:post, delivery.url).to_timeout+ allow(Rails.error).to receive(:report)++ notifications = capture_delivery_notifications do+ described_class.call(delivery: delivery, secret_key: secret_key)+ end++ expect(notifications.sole).to include(error_type: 'timeout')+ expect(notifications.sole).not_to include(:response_code)+ end+ end++ context 'header decorators' do+ after { described_class.header_decorators.clear }++ it 'lets registered decorators add outbound headers' do+ described_class.header_decorators << lambda { |headers, decorated_delivery|+ headers['traceparent'] = "00-trace-#{decorated_delivery.id}-01"+ }+ stub_request(:post, delivery.url).to_return(status: 200, body: '{}')++ described_class.call(delivery: delivery, secret_key: secret_key)++ expect(WebMock).to have_requested(:post, delivery.url).with(+ headers: { 'traceparent' => "00-trace-#{delivery.id}-01" }+ )+ end+ end+context 'when URL resolves to private IP (SSRF)' dobefore dodeliverydiff --git a/spree/core/app/models/concerns/spree/instruments_gateway_calls.rb b/spree/core/app/models/concerns/spree/instruments_gateway_calls.rbnew file mode 100644index 0000000000..fc0e7c69f2--- /dev/null+++ b/spree/core/app/models/concerns/spree/instruments_gateway_calls.rb@@ -0,0 +1,20 @@+# frozen_string_literal: true++module Spree+ # Marks a payment-gateway network call for tracing subscribers via the+ # 'gateway.spree_payments' notification. The payload is PII-safe by+ # design — gateway action and payment method class only; never amounts,+ # sources, credentials, or gateway responses.+ module InstrumentsGatewayCalls+ private++ def instrument_gateway_call(action, payment_method, &block)+ ActiveSupport::Notifications.instrument(+ 'gateway.spree_payments',+ action: action.to_s,+ payment_method_type: payment_method&.type,+ &block+ )+ end+ end+enddiff --git a/spree/core/app/models/spree/payment/processing.rb b/spree/core/app/models/spree/payment/processing.rbindex d14cb636e0..1cda34328a 100644--- a/spree/core/app/models/spree/payment/processing.rb+++ b/spree/core/app/models/spree/payment/processing.rb@@ -4,6 +4,8 @@ module Spreeclass Payment < Spree.base_classmodule Processingextend ActiveSupport::Concern+ include Spree::InstrumentsGatewayCalls+included doclass_attribute :gateway_options_classself.gateway_options_class = Spree::Payment::GatewayOptions@@ -50,11 +52,13 @@ module Spreestarted_processing!protect_from_connection_error do# Capture the payment amount- response = payment_method.capture(- amount,- response_code,- gateway_options- )+ response = instrument_gateway_call(:capture, payment_method) do+ payment_method.capture(+ amount,+ response_code,+ gateway_options+ )+ endmoney = ::Money.new(amount, currency)capture_events.create!(amount: money.to_f)split_uncaptured_amount@@ -67,13 +71,15 @@ module Spreereturn void if response_code.blank?protect_from_connection_error do- if payment_method.payment_profiles_supported?- # Gateways supporting payment profiles will need access to credit card object because this stores the payment profile information- # so supply the authorization itself as well as the credit card, rather than just the authorization code- response = payment_method.void(response_code, source, gateway_options)- else- # Standard void usage- response = payment_method.void(response_code, gateway_options)+ response = instrument_gateway_call(:void, payment_method) do+ if payment_method.payment_profiles_supported?+ # Gateways supporting payment profiles will need access to credit card object because this stores the payment profile information+ # so supply the authorization itself as well as the credit card, rather than just the authorization code+ payment_method.void(response_code, source, gateway_options)+ else+ # Standard void usage+ payment_method.void(response_code, gateway_options)+ endendif response.success?@@ -86,7 +92,9 @@ module Spreeenddef cancel!- response = payment_method.cancel(response_code, self)+ response = instrument_gateway_call(:cancel, payment_method) do+ payment_method.cancel(response_code, self)+ endhandle_response(response, :void, :failure)end@@ -134,9 +142,11 @@ module Spreedef gateway_action(source, action, success_state)protect_from_connection_error do- response = payment_method.send(action, money.amount_in_cents,- source,- gateway_options)+ response = instrument_gateway_call(action, payment_method) do+ payment_method.send(action, money.amount_in_cents,+ source,+ gateway_options)+ endhandle_response(response, success_state, :failure)endenddiff --git a/spree/core/app/models/spree/payment_method.rb b/spree/core/app/models/spree/payment_method.rbindex 326e86415a..5d4447dbe4 100644--- a/spree/core/app/models/spree/payment_method.rb+++ b/spree/core/app/models/spree/payment_method.rb@@ -24,6 +24,17 @@ module Spreevalidates :capture_method, inclusion: { in: Spree::CaptureMethod::CAPTURE_METHODS }, allow_nil: true+ # Provider subclasses override the payment-session methods wholesale, so+ # tracing instrumentation must be prepended to each subclass — prepended+ # to this base class it would sit below the override and never run.+ #+ # @param subclass [Class] the inheriting payment method class+ # @return [void]+ def self.inherited(subclass)+ super+ subclass.prepend(Spree::PaymentMethod::SessionInstrumentation)+ end+scope :active, -> { where(active: true).order(position: :asc) }scope :available, -> { active.where(display_on: [:front_end, :back_end, :both]) }scope :store_credit, -> { where(type: 'Spree::PaymentMethod::StoreCredit') }diff --git a/spree/core/app/models/spree/payment_method/session_instrumentation.rb b/spree/core/app/models/spree/payment_method/session_instrumentation.rbnew file mode 100644index 0000000000..27d6832810--- /dev/null+++ b/spree/core/app/models/spree/payment_method/session_instrumentation.rb@@ -0,0 +1,34 @@+# frozen_string_literal: true++module Spree+ class PaymentMethod+ # Wraps the provider-implemented payment-session methods in the+ # 'gateway.spree_payments' notification so every caller — controllers,+ # workflows, extensions — gets the gateway span, not just known call+ # sites. Prepended to every subclass from PaymentMethod.inherited:+ # prepending only the base class would sit below a subclass override in+ # the ancestor chain and never run. If an implementation calls super into+ # another prepended copy, the nested (duplicate) span is accepted rather+ # than guarded against — the base implementations raise NotImplementedError,+ # so that chain does not occur in practice.+ module SessionInstrumentation+ SESSION_METHODS = %i[+ create_payment_session+ update_payment_session+ complete_payment_session+ create_payment_setup_session+ complete_payment_setup_session+ ].freeze++ SESSION_METHODS.each do |session_method|+ define_method(session_method) do |*args, **kwargs, &block|+ ActiveSupport::Notifications.instrument(+ 'gateway.spree_payments', action: session_method.to_s, payment_method_type: type+ ) do+ super(*args, **kwargs, &block)+ end+ end+ end+ end+ end+enddiff --git a/spree/core/app/models/spree/refund.rb b/spree/core/app/models/spree/refund.rbindex eb4af7eed8..83bc3378fe 100644--- a/spree/core/app/models/spree/refund.rb+++ b/spree/core/app/models/spree/refund.rb@@ -4,6 +4,7 @@ module Spreeinclude Spree::HasCustomFieldsinclude Spree::Metadata+ include Spree::InstrumentsGatewayCallsif defined?(Spree::Security::Refunds)include Spree::Security::Refundsend@@ -81,11 +82,13 @@ module Spreedef process!(credit_cents)refund_total_in_cents = calculate_refund_amount(credit_cents)- response = if payment.payment_method.payment_profiles_supported?- payment.payment_method.credit(refund_total_in_cents, payment.source, payment.transaction_id, originator: self)- else- payment.payment_method.credit(refund_total_in_cents, payment.transaction_id, originator: self)- end+ response = instrument_gateway_call(:credit, payment.payment_method) do+ if payment.payment_method.payment_profiles_supported?+ payment.payment_method.credit(refund_total_in_cents, payment.source, payment.transaction_id, originator: self)+ else+ payment.payment_method.credit(refund_total_in_cents, payment.transaction_id, originator: self)+ end+ endif response.success?track_order_as_refunded(refund_total_in_cents)diff --git a/spree/core/app/services/spree/sample_data/loader.rb b/spree/core/app/services/spree/sample_data/loader.rbindex 828198095d..c97149d9e9 100644--- a/spree/core/app/services/spree/sample_data/loader.rb+++ b/spree/core/app/services/spree/sample_data/loader.rb@@ -65,7 +65,7 @@ module Spreeprivatedef load_configuration_data- load_ruby_file('shipping_methods')+ load_ruby_file('fulfillment')load_ruby_file('payment_methods')load_ruby_file('promotions')enddiff --git a/spree/core/db/sample_data/fulfillment.rb b/spree/core/db/sample_data/fulfillment.rbnew file mode 100644index 0000000000..3d20d2bfd0--- /dev/null+++ b/spree/core/db/sample_data/fulfillment.rb@@ -0,0 +1,82 @@+# The whole demo fulfillment setup in one place: a rate-ready origin, a+# realistic parcel, and Shopify-style delivery methods on the seeded Domestic+# and International zones (Spree::Seeds::DeliveryZones). The free+# international method showcases delivery-method rules — free above a spend+# threshold, hidden below it.+store = Spree::Store.default++# Carrier rate providers (EasyPost) cannot quote without a complete origin+# address — a country-only stock location makes every carrier method silently+# disappear from checkout. Demo data only: the production seed deliberately+# leaves the address blank rather than invent an origin real rates would be+# quoted from.+stock_location = store.stock_locations.find_by(default: true) || store.stock_locations.first++# Any missing field leaves the origin unquotable, so completeness — not just a+# blank street — decides whether the demo address applies.+if stock_location&.country&.iso == 'US' &&+ [stock_location.address1, stock_location.city, stock_location.state_id, stock_location.zipcode].any?(&:blank?)+ stock_location.update!(+ address1: '417 Montgomery St',+ city: 'San Francisco',+ state: stock_location.country.states.find_by!(abbr: 'CA'),+ zipcode: '94104',+ phone: '415-555-0100'+ )+end++# A realistic shipping box (imperial units — the demo store is US): its weight+# rides on every parcel and its dimensions feed dimensional-weight pricing,+# without which carrier quotes under-price bulky-but-light items. Applied only+# when nothing is configured, so a half-filled box is never completed with+# values the merchant did not choose.+package_preferences = %i[+ preferred_default_package_weight+ preferred_default_package_length+ preferred_default_package_width+ preferred_default_package_height+]++if package_preferences.all? { |preference| store.public_send(preference).to_f.zero? }+ store.preferred_default_package_weight = 0.5+ store.preferred_default_package_length = 12+ store.preferred_default_package_width = 9+ store.preferred_default_package_height = 4+ store.save!+end++domestic = store.delivery_zones.find_by(name: 'Domestic')+international = store.delivery_zones.find_by(name: 'International')++if domestic.nil? || international.nil?+ # abort, not exit: exit reports success and would silently skip the payment+ # methods and promotions the loader still has to seed.+ abort "Couldn't find the Domestic/International delivery zones. Did you run `rake db:seed` first?"+end++currency = store.default_currency++delivery_methods = [+ { name: 'Standard', zone: domestic, amount: 5 },+ { name: 'Express', zone: domestic, amount: 15 },+ { name: 'International Shipping', zone: international, amount: 20 },+ { name: 'Free International Shipping', zone: international, amount: 0, minimum_item_total: 100 }+]++delivery_methods.each do |attributes|+ delivery_method = Spree::DeliveryMethod.where(name: attributes[:name], store: store).first_or_create! do |record|+ record.calculator = Spree::Calculator::Shipping::FlatRate.create!(+ preferences: { amount: attributes[:amount], currency: currency }+ )+ record.delivery_profile = attributes[:zone].delivery_profile+ record.delivery_zone = attributes[:zone]+ record.storefront_visible = true+ end++ next if attributes[:minimum_item_total].blank?++ Spree::DeliveryMethodRules::ItemTotalRule.where(delivery_method: delivery_method).first_or_create! do |rule|+ rule.active = true+ rule.preferred_minimum_amount = attributes[:minimum_item_total]+ end+enddiff --git a/spree/core/db/sample_data/shipping_methods.rb b/spree/core/db/sample_data/shipping_methods.rbdeleted file mode 100644index 0bfb62b40b..0000000000--- a/spree/core/db/sample_data/shipping_methods.rb+++ /dev/null@@ -1,40 +0,0 @@-# Shopify-style delivery setup: the seeded Domestic and International zones-# (Spree::Seeds::DeliveryZones) with a small set of realistic methods. The-# free international method showcases delivery-method rules — free above a-# spend threshold, hidden below it.-store = Spree::Store.default--domestic = store.delivery_zones.find_by(name: 'Domestic')-international = store.delivery_zones.find_by(name: 'International')--if domestic.nil? || international.nil?- puts "Couldn't find the Domestic/International delivery zones. Did you run `rake db:seed` first?"- exit-end--currency = store.default_currency--delivery_methods = [- { name: 'Standard', zone: domestic, amount: 5 },- { name: 'Express', zone: domestic, amount: 15 },- { name: 'International Shipping', zone: international, amount: 20 },- { name: 'Free International Shipping', zone: international, amount: 0, minimum_item_total: 100 }-]--delivery_methods.each do |attributes|- delivery_method = Spree::DeliveryMethod.where(name: attributes[:name], store: store).first_or_create! do |record|- record.calculator = Spree::Calculator::Shipping::FlatRate.create!(- preferences: { amount: attributes[:amount], currency: currency }- )- record.delivery_profile = attributes[:zone].delivery_profile- record.delivery_zone = attributes[:zone]- record.storefront_visible = true- end-- next if attributes[:minimum_item_total].blank?-- Spree::DeliveryMethodRules::ItemTotalRule.where(delivery_method: delivery_method).first_or_create! do |rule|- rule.active = true- rule.preferred_minimum_amount = attributes[:minimum_item_total]- end-enddiff --git a/spree/core/lib/spree/events/adapters/base.rb b/spree/core/lib/spree/events/adapters/base.rbindex 4d105c4b2d..620e27a995 100644--- a/spree/core/lib/spree/events/adapters/base.rb+++ b/spree/core/lib/spree/events/adapters/base.rb@@ -147,25 +147,52 @@ module Spreedef invoke_subscriber(subscriber, event, options)async = options.fetch(:async, true)- if subscriber.is_a?(Proc)- # Block subscribers run synchronously- subscriber.call(event)- elsif subscriber.respond_to?(:call)- # Callable objects (including subscriber instances)- if async && defined?(Spree::Events::SubscriberJob)- Spree::Events::SubscriberJob.perform_later(subscriber.name, event.to_h)- else+ ActiveSupport::Notifications.instrument(+ 'dispatch.spree_events',+ event_name: event.name,+ subscriber: subscriber_label(subscriber),+ async: async_dispatch?(subscriber, async)+ ) do+ if subscriber.is_a?(Proc)+ # Block subscribers run synchronouslysubscriber.call(event)- end- elsif subscriber.is_a?(Class) && subscriber < Spree::Subscriber- # Subscriber classes- if async && defined?(Spree::Events::SubscriberJob)- Spree::Events::SubscriberJob.perform_later(subscriber.name, event.to_h)+ elsif subscriber.respond_to?(:call)+ # Callable objects (including subscriber instances)+ if async && defined?(Spree::Events::SubscriberJob)+ Spree::Events::SubscriberJob.perform_later(subscriber.name, event.to_h)+ else+ subscriber.call(event)+ end+ elsif subscriber.is_a?(Class) && subscriber < Spree::Subscriber+ # Subscriber classes+ if async && defined?(Spree::Events::SubscriberJob)+ Spree::Events::SubscriberJob.perform_later(subscriber.name, event.to_h)+ else+ subscriber.new.call(event)+ endelse- subscriber.new.call(event)+ raise ArgumentError, "Invalid subscriber: #{subscriber.inspect}. Must be a Proc, callable, or Spree::Subscriber subclass."end+ end+ end++ # Whether this dispatch hops to ActiveJob rather than running inline —+ # mirrors the branching in {#invoke_subscriber}.+ def async_dispatch?(subscriber, async)+ return false if subscriber.is_a?(Proc)++ async && defined?(Spree::Events::SubscriberJob) ? true : false+ end++ # Stable, low-cardinality label for instrumentation payloads (a+ # Proc's #to_s embeds a memory address).+ def subscriber_label(subscriber)+ if subscriber.is_a?(Proc)+ 'Proc'+ elsif subscriber.respond_to?(:name) && subscriber.name+ subscriber.nameelse- raise ArgumentError, "Invalid subscriber: #{subscriber.inspect}. Must be a Proc, callable, or Spree::Subscriber subclass."+ subscriber.class.nameendenddiff --git a/spree/core/lib/spree/hooks.rb b/spree/core/lib/spree/hooks.rbindex f9ad850f05..f53b306180 100644--- a/spree/core/lib/spree/hooks.rb+++ b/spree/core/lib/spree/hooks.rb@@ -83,6 +83,13 @@ module Spreetrueend+ # @param key [String, Symbol] '<workflow key>.<hook name>'+ # @return [Integer] registered handler count for the key, without+ # constantizing anything (cheap enough for instrumentation payloads)+ def handler_count(key)+ @handlers.fetch(key.to_s) { [] }.size+ end+def keys@handlers.keysenddiff --git a/spree/core/lib/spree/workflow.rb b/spree/core/lib/spree/workflow.rbindex 8c79aedb4c..c6875fef30 100644--- a/spree/core/lib/spree/workflow.rb+++ b/spree/core/lib/spree/workflow.rb@@ -156,16 +156,26 @@ module Spreedef call(**kwargs)@undo_stack = []@outer_transaction_depth = ApplicationRecord.connection.open_transactions- outcome = perform(**kwargs)- outcome.is_a?(Spree::ServiceModule::Result) ? outcome : success(outcome)- rescue Halted => halted- success(halted.value)- rescue FailureSignal => signal- run_undo_stack!- signal.result- rescue StandardError- run_undo_stack!- raise++ ActiveSupport::Notifications.instrument(+ 'perform.spree_workflow', workflow: self.class.workflow_key+ ) do |payload|+ outcome = perform(**kwargs)+ result = outcome.is_a?(Spree::ServiceModule::Result) ? outcome : success(outcome)+ payload[:outcome] = result.success? ? 'success' : 'failure'+ result+ rescue Halted => halted+ payload[:outcome] = 'success'+ success(halted.value)+ rescue FailureSignal => signal+ payload[:outcome] = 'failure'+ run_undo_stack!+ signal.result+ rescue StandardError+ payload[:outcome] = 'error'+ run_undo_stack!+ raise+ endend# Successful early exit from anywhere — the caller receives@@ -219,11 +229,13 @@ module Spreeprivate- def step(name, with: nil, on_flow_failure: nil)+ def step(name, with: nil, on_flow_failure: nil, external: false)outcome = ActiveSupport::Notifications.instrument(- 'step.spree_workflow', workflow: self.class.workflow_key, step: name- ) do- with ? call_collaborator(instance_exec(&with)) : send(name)+ 'step.spree_workflow', workflow: self.class.workflow_key, step: name, external: external+ ) do |payload|+ result = with ? call_collaborator(instance_exec(&with)) : send(name)+ payload[:outcome] = result.is_a?(Spree::ServiceModule::Result) && result.failure? ? 'failure' : 'success'+ resultendraise FailureSignal.new(outcome) if outcome.is_a?(Spree::ServiceModule::Result) && outcome.failure?@@ -234,11 +246,12 @@ module Spree# Gateway/network I/O — must never share a database transaction the# workflow opened (a caller-level wrapping transaction is the caller's- # responsibility).+ # responsibility). Marks the notification payload `external: true` so+ # tracing subscribers render it as an outbound (client) call.def external_step(name, **options)raise ContractError, "external_step #{name} must not run inside a database transaction" if in_workflow_transaction?- step(name, **options)+ step(name, external: true, **options)end# Dispatches every handler registered for this extension point with@@ -253,7 +266,13 @@ module Spreeraise ContractError, "#{self.class.name} does not declare hook :#{name} — add `hooks :#{name}` to the class"end- Spree.hooks.dispatch("#{self.class.workflow_key}.#{name}", self)+ key = "#{self.class.workflow_key}.#{name}"+ ActiveSupport::Notifications.instrument(+ 'hooks.spree_workflow',+ workflow: self.class.workflow_key, hook: name.to_sym, handler_count: Spree.hooks.handler_count(key)+ ) do+ Spree.hooks.dispatch(key, self)+ endend# Undo methods arm when the workflow-opened transaction around theirdiff --git a/spree/core/spec/lib/spree/events_spec.rb b/spree/core/spec/lib/spree/events_spec.rbindex cee41eabc7..7dee97d43e 100644--- a/spree/core/spec/lib/spree/events_spec.rb+++ b/spree/core/spec/lib/spree/events_spec.rb@@ -98,6 +98,54 @@ RSpec.describe Spree::Events, events: true doendend+ describe 'dispatch instrumentation' do+ def capture_dispatch_notifications+ events = []+ subscriber = ActiveSupport::Notifications.subscribe('dispatch.spree_events') do |*, payload|+ events << payload+ end+ yield+ events+ ensure+ ActiveSupport::Notifications.unsubscribe(subscriber)+ end++ it 'instruments every subscriber dispatch as dispatch.spree_events' do+ handler_class = Class.new do+ def self.name = 'Spree::Testing::DispatchHandler'+ def self.call(_event) = nil+ end+ stub_const('Spree::Testing::DispatchHandler', handler_class)++ described_class.subscribe('order.placed', handler_class, async: false)+ described_class.activate!++ notifications = capture_dispatch_notifications do+ described_class.publish('order.placed', { id: 1 })+ end++ expect(notifications.sole).to include(+ event_name: 'order.placed',+ subscriber: 'Spree::Testing::DispatchHandler',+ async: false+ )+ end++ it 'labels block subscribers without leaking memory addresses' do+ # Options must be positional — subscribe has no keyword parameters, so+ # trailing keywords would land in (and be discarded from) the+ # subscriber slot when a block is given.+ described_class.subscribe('order.placed', nil, { async: false }) { |_event| nil }+ described_class.activate!++ notifications = capture_dispatch_notifications do+ described_class.publish('order.placed', {})+ end++ expect(notifications.sole).to include(subscriber: 'Proc', async: false)+ end+ end+describe '.unsubscribe' doit 'removes a subscriber' doreceived_events = []diff --git a/spree/core/spec/lib/spree/workflow_spec.rb b/spree/core/spec/lib/spree/workflow_spec.rbindex 28263c5be1..68a8d3ca21 100644--- a/spree/core/spec/lib/spree/workflow_spec.rb+++ b/spree/core/spec/lib/spree/workflow_spec.rb@@ -522,12 +522,18 @@ RSpec.describe Spree::Workflow doenddescribe 'observability' do- it 'instruments every step as step.spree_workflow' do+ def capture_notifications(name)events = []- subscriber = ActiveSupport::Notifications.subscribe('step.spree_workflow') do |*, payload|- events << payload.slice(:workflow, :step)+ subscriber = ActiveSupport::Notifications.subscribe(name) do |*, payload|+ events << payloadend+ yield+ events+ ensure+ ActiveSupport::Notifications.unsubscribe(subscriber)+ end+ it 'instruments every step as step.spree_workflow' doworkflow = build_workflow dodef perform(subject:)super@@ -541,14 +547,123 @@ RSpec.describe Spree::Workflow dodef one = nildef two = nilend- workflow.call(subject: 1)- expect(events).to eq([- { workflow: 'testing.sample_workflow', step: :one },- { workflow: 'testing.sample_workflow', step: :two }+ events = capture_notifications('step.spree_workflow') { workflow.call(subject: 1) }++ expect(events.map { |payload| payload.slice(:workflow, :step, :external, :outcome) }).to eq([+ { workflow: 'testing.sample_workflow', step: :one, external: false, outcome: 'success' },+ { workflow: 'testing.sample_workflow', step: :two, external: false, outcome: 'success' }])- ensure- ActiveSupport::Notifications.unsubscribe(subscriber)+ end++ it 'marks external_step payloads external: true' do+ workflow = build_workflow do+ def perform(subject:)+ super+ external_step :call_gateway+ success(subject)+ end++ private++ def call_gateway = nil+ end++ events = capture_notifications('step.spree_workflow') { workflow.call(subject: 1) }++ expect(events.sole).to include(step: :call_gateway, external: true)+ end++ it 'records a failure outcome when a collaborator step returns a failure result' do+ failing_collaborator = Class.new do+ def call = Spree::ServiceModule::Result.new(false, nil, 'nope')+ end.new++ workflow = build_workflow do+ define_method(:collaborator) { failing_collaborator }++ def perform(subject:)+ super+ step :delegated, with: -> { collaborator }+ success(subject)+ end+ end++ events = capture_notifications('step.spree_workflow') { workflow.call(subject: 1) }++ expect(events.sole).to include(step: :delegated, outcome: 'failure')+ end++ it 'records the FailureSignal as the exception when a step calls failure' do+ workflow = build_workflow do+ def perform(subject:)+ super+ step :explode+ success(subject)+ end++ private++ def explode = failure(:exploded, 'boom')+ end++ events = capture_notifications('step.spree_workflow') { workflow.call(subject: 1) }++ expect(events.sole[:exception]&.first).to eq('Spree::Workflow::FailureSignal')+ end++ it 'instruments the whole run as perform.spree_workflow with the outcome' do+ succeeding = build_workflow do+ def perform(subject:) = success(subject)+ end+ failing = build_workflow do+ def perform(subject:)+ super+ step :explode+ end++ private++ def explode = failure(:exploded, 'boom')+ end+ erroring = build_workflow do+ def perform(subject:) = raise(ArgumentError, 'broken')+ end+ halting = build_workflow do+ def perform(subject:)+ super+ halt!(subject)+ end+ end++ events = capture_notifications('perform.spree_workflow') do+ succeeding.call(subject: 1)+ failing.call(subject: 1)+ expect { erroring.call(subject: 1) }.to raise_error(ArgumentError)+ halting.call(subject: 1)+ end++ expect(events.map { |payload| payload[:outcome] }).to eq(%w[success failure error success])+ expect(events.map { |payload| payload[:workflow] }.uniq).to eq(['testing.sample_workflow'])+ end++ it 'instruments run_hooks as hooks.spree_workflow with the handler count' do+ workflow = build_workflow do+ hooks :after_thing++ def perform(subject:)+ super+ run_hooks :after_thing+ success(subject)+ end+ end+ Spree.hooks.register('testing.sample_workflow.after_thing') { |_context| nil }++ events = capture_notifications('hooks.spree_workflow') { workflow.call(subject: 1) }++ expect(events.sole).to include(+ workflow: 'testing.sample_workflow', hook: :after_thing, handler_count: 1+ )endendenddiff --git a/spree/core/spec/models/spree/payment_method_spec.rb b/spree/core/spec/models/spree/payment_method_spec.rbindex 2f29a1ae82..1b828ee52e 100644--- a/spree/core/spec/models/spree/payment_method_spec.rb+++ b/spree/core/spec/models/spree/payment_method_spec.rb@@ -270,6 +270,7 @@ describe Spree::PaymentMethod, type: :model doexpect(credit_card.reload.deleted_at).not_to be_nilendend+describe 'position scoping' doit 'numbers positions per store, not across the whole table' docreate(:payment_method, store: @default_store)@@ -280,4 +281,32 @@ describe Spree::PaymentMethod, type: :model doexpect(first_in_other_store.position).to eq(1)endend++ describe 'payment session instrumentation' do+ it 'instruments provider-implemented session methods as gateway.spree_payments, once per call' do+ gateway_class = Class.new(Spree::Gateway) do+ def self.name = 'Spree::Testing::SessionGateway'++ def create_payment_session(order:, amount: nil, external_data: {})+ :session+ end+ end+ stub_const('Spree::Testing::SessionGateway', gateway_class)++ notifications = []+ subscription = ActiveSupport::Notifications.subscribe('gateway.spree_payments') do |*, payload|+ notifications << payload+ end++ result = gateway_class.new.create_payment_session(order: nil)++ expect(result).to eq(:session)+ expect(notifications.sole).to include(+ action: 'create_payment_session',+ payment_method_type: 'Spree::Testing::SessionGateway'+ )+ ensure+ ActiveSupport::Notifications.unsubscribe(subscription)+ end+ endenddiff --git a/spree/core/spec/models/spree/payment_spec.rb b/spree/core/spec/models/spree/payment_spec.rbindex 56c6a5241e..319a97b364 100644--- a/spree/core/spec/models/spree/payment_spec.rb+++ b/spree/core/spec/models/spree/payment_spec.rb@@ -380,6 +380,37 @@ describe Spree::Payment, type: :model doendend+ describe 'gateway instrumentation' do+ def capture_gateway_notifications+ events = []+ subscriber = ActiveSupport::Notifications.subscribe('gateway.spree_payments') do |*, payload|+ events << payload+ end+ yield+ events+ ensure+ ActiveSupport::Notifications.unsubscribe(subscriber)+ end++ it 'instruments the purchase gateway call as gateway.spree_payments' do+ allow(gateway).to receive(:purchase).and_return(success_response)++ notifications = capture_gateway_notifications { payment.purchase! }++ expect(notifications.sole).to include(action: 'purchase', payment_method_type: 'Spree::Gateway::Bogus')+ end++ it 'instruments the capture gateway call' do+ payment.state = 'pending'+ payment.response_code = "BGS-#{SecureRandom.hex(6)}"+ allow(gateway).to receive(:capture).and_return(success_response)++ notifications = capture_gateway_notifications { payment.capture! }++ expect(notifications.sole).to include(action: 'capture', payment_method_type: 'Spree::Gateway::Bogus')+ end+ end+describe '#purchase!' doit 'calls purchase on the gateway with the payment amount' doexpect(gateway).to receive(:purchase).with(amount_in_cents, card, anything).and_return(success_response)diff --git a/spree/core/spec/models/spree/refund_spec.rb b/spree/core/spec/models/spree/refund_spec.rbindex 99fb0da98d..fc5f76c31e 100644--- a/spree/core/spec/models/spree/refund_spec.rb+++ b/spree/core/spec/models/spree/refund_spec.rb@@ -88,6 +88,19 @@ describe Spree::Refund, type: :model doexpect { subject }.to change { Spree::Refund.count }.by(1)end+ it 'instruments the credit gateway call as gateway.spree_payments' do+ notifications = []+ subscriber = ActiveSupport::Notifications.subscribe('gateway.spree_payments') do |*, payload|+ notifications << payload+ end++ subject++ expect(notifications.sole).to include(action: 'credit', payment_method_type: payment_method.type)+ ensure+ ActiveSupport::Notifications.unsubscribe(subscriber)+ end+it 'return the newly created refund' doexpect(subject).to be_a(Spree::Refund)enddiff --git a/spree/opentelemetry/Gemfile b/spree/opentelemetry/Gemfilenew file mode 100644index 0000000000..bcb6bab621--- /dev/null+++ b/spree/opentelemetry/Gemfile@@ -0,0 +1,5 @@+eval_gemfile('../common_spree_dependencies.rb')++gem 'spree', path: '../'++gemspecdiff --git a/spree/opentelemetry/README.md b/spree/opentelemetry/README.mdnew file mode 100644index 0000000000..9157d68601--- /dev/null+++ b/spree/opentelemetry/README.md@@ -0,0 +1,55 @@+# spree_opentelemetry++Distributed tracing for [Spree Commerce](https://spreecommerce.org) via+[OpenTelemetry](https://opentelemetry.io).++With this gem installed, Spree exports traces as soon as the standard+OpenTelemetry environment variables point at a collector — no code changes:++```ruby+# Gemfile+gem 'spree_opentelemetry'+```++```bash+OTEL_SERVICE_NAME=spree+OTEL_EXPORTER_OTLP_ENDPOINT=http://collector:4318+```++Without an exporter configured, the gem stays dormant. `OTEL_SDK_DISABLED=true`+is the kill switch.++## What gets traced++- **Framework layers** via the official Rails auto-instrumentation: HTTP+ requests (Rack/Action Pack), database queries (Active Record), background+ jobs (Active Job, with trace context carried across the enqueue → perform+ boundary), mail delivery, outbound HTTP (Net::HTTP).+- **Spree commerce layers** via Spree's own notification surface: workflow+ runs and steps (external steps become `client` spans), extension hook+ dispatch, event subscriber dispatch, webhook deliveries (with W3C+ `traceparent` propagated to the receiving system), and payment gateway+ calls.++Span attributes never contain personal data — prefixed IDs, workflow/step+names, gateway action names, and HTTP metadata only.++See the [telemetry guide](https://docs.spreecommerce.org/developer/deployment/telemetry)+for the full span catalog, collector examples, and sampling guidance.++## Code-level configuration++Only needed for what env vars can't express:++```ruby+# config/initializers/opentelemetry.rb+SpreeOpenTelemetry.configure do |config|+ config.use 'OpenTelemetry::Instrumentation::Redis' # extra instrumentation+ config.skip 'OpenTelemetry::Instrumentation::ActionMailer' # drop a default+ config.with_sdk { |otel| otel.add_span_processor(my_processor) }+end+```++## License++Spree is released under the [New BSD License](https://github.com/spree/spree/blob/main/license.md).diff --git a/spree/opentelemetry/Rakefile b/spree/opentelemetry/Rakefilenew file mode 100644index 0000000000..53447c24ff--- /dev/null+++ b/spree/opentelemetry/Rakefile@@ -0,0 +1,15 @@+require 'rubygems'+require 'rake'+require 'rake/testtask'+require 'rspec/core/rake_task'+require 'spree/testing_support/common_rake'++RSpec::Core::RakeTask.new++task default: :spec++desc "Generates a dummy app for testing"+task :test_app do+ ENV['LIB_NAME'] = 'spree_opentelemetry'+ Rake::Task['common:test_app'].invoke+enddiff --git a/spree/opentelemetry/lib/spree_opentelemetry.rb b/spree/opentelemetry/lib/spree_opentelemetry.rbnew file mode 100644index 0000000000..fbc6f0dc97--- /dev/null+++ b/spree/opentelemetry/lib/spree_opentelemetry.rb@@ -0,0 +1,120 @@+require 'spree_core'++require 'opentelemetry/sdk'+require 'opentelemetry-exporter-otlp'+require 'opentelemetry-instrumentation-rack'+require 'opentelemetry-instrumentation-action_pack'+require 'opentelemetry-instrumentation-action_mailer'+require 'opentelemetry-instrumentation-active_record'+require 'opentelemetry-instrumentation-active_support'+require 'opentelemetry-instrumentation-active_job'+require 'opentelemetry-instrumentation-concurrent_ruby'+require 'opentelemetry-instrumentation-net_http'++require 'spree_opentelemetry/configuration'+require 'spree_opentelemetry/span_subscriber'+require 'spree_opentelemetry/subscribers'+require 'spree_opentelemetry/webhook_trace_propagation'+require 'spree_opentelemetry/engine'++# Optional OpenTelemetry support for Spree (docs/plans/6.0-opentelemetry.md).+#+# Activation is environment-driven, the way an SRE configures any other+# OpenTelemetry service: with the gem installed, traces flow as soon as a+# standard OTEL_* exporter variable is set, and nothing happens without one.+# `SpreeOpenTelemetry.configure` exists only for code-level needs (extra+# instrumentations, custom samplers) — telemetry is deployment configuration,+# never store data.+module SpreeOpenTelemetry+ # Env vars whose presence opts this process into exporting traces —+ # signal-specific endpoint first, matching the SDK's own precedence.+ EXPORTER_ENV_KEYS = %w[+ OTEL_EXPORTER_OTLP_TRACES_ENDPOINT+ OTEL_EXPORTER_OTLP_ENDPOINT+ ].freeze++ class << self+ # @return [SpreeOpenTelemetry::Configuration] the process-wide configuration+ def configuration+ @configuration ||= Configuration.new+ end++ # @yieldparam configuration [SpreeOpenTelemetry::Configuration]+ # @return [SpreeOpenTelemetry::Configuration]+ def configure+ yield configuration+ configuration+ end++ # Whether telemetry should activate in this process. Dormant unless an+ # exporter is configured through the standard OpenTelemetry env vars (or+ # forced on via `configure { |c| c.enabled = true }` — the path+ # integrations like Sentry's OTLP mode use, since they register their own+ # exporter); OTEL_SDK_DISABLED is the kill switch and always wins.+ #+ # @return [Boolean]+ def enabled?+ # OpenTelemetry booleans are case-insensitive, so OTEL_SDK_DISABLED=TRUE+ # must silence telemetry exactly like the lowercase spelling.+ return false if ENV['OTEL_SDK_DISABLED'].to_s.casecmp?('true')+ return configuration.enabled unless configuration.enabled.nil?+ return true if EXPORTER_ENV_KEYS.any? { |key| !ENV[key].to_s.empty? }++ exporter = ENV['OTEL_TRACES_EXPORTER'].to_s+ !exporter.empty? && exporter != 'none'+ end++ # @return [Boolean] whether {#install!} has already run in this process+ def installed?+ @installed == true+ end++ # Boots the OpenTelemetry SDK and attaches the Spree span subscribers.+ # No-op when {#enabled?} is false — the opentelemetry-api layer stays a+ # zero-cost no-op in that case. Idempotent.+ #+ # @return [Boolean] whether telemetry is installed after the call+ def install!+ return true if installed?+ return false unless enabled?++ ::OpenTelemetry::SDK.configure do |otel_config|+ otel_config.service_name = configuration.service_name if configuration.service_name+ configuration.instrumentations.each do |instrumentation_name, instrumentation_config|+ otel_config.use(instrumentation_name, instrumentation_config)+ end+ configuration.sdk_hooks.each { |hook| hook.call(otel_config) }+ end++ Subscribers.attach!+ @installed = true+ log_activation+ true+ end++ # @return [OpenTelemetry::Trace::Tracer] the tracer Spree spans are created on+ def tracer+ version = defined?(Spree) && Spree.respond_to?(:version) ? Spree.version : nil+ ::OpenTelemetry.tracer_provider.tracer('spree', version)+ end++ # Test-only: forget installation state and configuration.+ #+ # @return [void]+ def reset!+ Subscribers.detach!+ @installed = nil+ @configuration = nil+ end++ private++ def log_activation+ return unless defined?(Rails) && Rails.logger++ exporter = ENV['OTEL_TRACES_EXPORTER'].to_s.empty? ? 'otlp' : ENV['OTEL_TRACES_EXPORTER']+ endpoint = EXPORTER_ENV_KEYS.filter_map { |key| ENV[key] unless ENV[key].to_s.empty? }.first || '(default)'+ Rails.logger.info "[Spree OpenTelemetry] traces active — exporter=#{exporter} endpoint=#{endpoint}"+ end+ end+enddiff --git a/spree/opentelemetry/lib/spree_opentelemetry/configuration.rb b/spree/opentelemetry/lib/spree_opentelemetry/configuration.rbnew file mode 100644index 0000000000..ac1a7d4f48--- /dev/null+++ b/spree/opentelemetry/lib/spree_opentelemetry/configuration.rb@@ -0,0 +1,61 @@+module SpreeOpenTelemetry+ # Code-level configuration, for the few things env vars can't express.+ # Set from a host initializer:+ #+ # SpreeOpenTelemetry.configure do |config|+ # config.service_name = 'storefront-api'+ # config.use 'OpenTelemetry::Instrumentation::Redis'+ # config.skip 'OpenTelemetry::Instrumentation::ActionMailer'+ # config.with_sdk { |otel| otel.add_span_processor(my_processor) }+ # end+ class Configuration+ DEFAULT_INSTRUMENTATIONS = {+ 'OpenTelemetry::Instrumentation::Rack' => {},+ 'OpenTelemetry::Instrumentation::ActionPack' => {},+ 'OpenTelemetry::Instrumentation::ActionMailer' => {},+ 'OpenTelemetry::Instrumentation::ActiveRecord' => {},+ 'OpenTelemetry::Instrumentation::ActiveSupport' => {},+ # :link keeps a checkout trace from stretching until the last webhook+ # retry finishes — background work links to the enqueuing trace instead+ # of continuing it.+ 'OpenTelemetry::Instrumentation::ActiveJob' => { propagation_style: :link },+ 'OpenTelemetry::Instrumentation::ConcurrentRuby' => {},+ 'OpenTelemetry::Instrumentation::Net::HTTP' => {},+ }.freeze++ # Force telemetry on/off regardless of exporter env vars; nil (default)+ # means env-driven activation.+ attr_accessor :enabled++ # Overrides OTEL_SERVICE_NAME when set.+ attr_accessor :service_name++ attr_reader :instrumentations, :sdk_hooks++ def initialize+ @enabled = nil+ @service_name = nil+ @instrumentations = DEFAULT_INSTRUMENTATIONS.transform_values(&:dup)+ @sdk_hooks = []+ end++ # Adds (or reconfigures) an instrumentation installed at SDK boot.+ #+ # @param name [String] instrumentation class name, e.g. 'OpenTelemetry::Instrumentation::Redis'+ # @param config [Hash] instrumentation-specific options+ def use(name, config = {})+ @instrumentations[name.to_s] = config+ end++ # Removes an instrumentation from the install list.+ def skip(name)+ @instrumentations.delete(name.to_s)+ end++ # Registers a block run inside OpenTelemetry::SDK.configure — the escape+ # hatch for samplers, extra span processors, resource attributes.+ def with_sdk(&block)+ @sdk_hooks << block+ end+ end+enddiff --git a/spree/opentelemetry/lib/spree_opentelemetry/engine.rb b/spree/opentelemetry/lib/spree_opentelemetry/engine.rbnew file mode 100644index 0000000000..3b62823562--- /dev/null+++ b/spree/opentelemetry/lib/spree_opentelemetry/engine.rb@@ -0,0 +1,22 @@+require 'rails/engine'++module SpreeOpenTelemetry+ class Engine < Rails::Engine+ engine_name 'spree_opentelemetry'++ # After the host's initializers so a SpreeOpenTelemetry.configure block+ # is applied before the SDK boots.+ initializer 'spree_opentelemetry.install', after: :load_config_initializers do+ SpreeOpenTelemetry.install!+ end++ # DeliverWebhook is reloadable — its decorator list resets with the class+ # on every code reload, so registration must happen in to_prepare.+ config.to_prepare do+ if SpreeOpenTelemetry.installed? && defined?(Spree::Webhooks::DeliverWebhook)+ decorators = Spree::Webhooks::DeliverWebhook.header_decorators+ decorators << SpreeOpenTelemetry::WebhookTracePropagation unless decorators.include?(SpreeOpenTelemetry::WebhookTracePropagation)+ end+ end+ end+enddiff --git a/spree/opentelemetry/lib/spree_opentelemetry/span_subscriber.rb b/spree/opentelemetry/lib/spree_opentelemetry/span_subscriber.rbnew file mode 100644index 0000000000..92ec873348--- /dev/null+++ b/spree/opentelemetry/lib/spree_opentelemetry/span_subscriber.rb@@ -0,0 +1,89 @@+module SpreeOpenTelemetry+ # Turns one ActiveSupport::Notifications event into a span. Evented+ # (start/finish) rather than block-subscribed, so the span is current while+ # the instrumented work runs and children nest under it correctly. The span+ # handle rides in the notification payload — the same trick the upstream+ # ActiveSupport instrumentation uses.+ class SpanSubscriber+ PAYLOAD_KEY = :__spree_opentelemetry_span++ # Workflow control-flow signals inherit Exception by design (a plain+ # rescue must not swallow them). Halted is a successful early exit and+ # must not mark the span errored; FailureSignal is a real failure but is+ # not worth an exception event — the error status carries the verdict.+ HALT_EXCEPTIONS = %w[Spree::Workflow::Halted].freeze+ CONTROL_FLOW_EXCEPTIONS = %w[Spree::Workflow::FailureSignal Spree::Workflow::Halted].freeze++ # @param tracer [OpenTelemetry::Trace::Tracer]+ # @param name [Proc] payload -> span name+ # @param kind [Proc, nil] payload -> :internal/:client/…; defaults to :internal+ # @param attributes [Proc, nil] payload -> attribute hash (nil values dropped)+ # @param skip [Proc, nil] payload -> true suppresses the span entirely+ # @param error [Proc, nil] payload -> error message when the span failed+ # without an exception (e.g. a failure result), nil otherwise+ def initialize(tracer:, name:, kind: nil, attributes: nil, skip: nil, error: nil)+ @tracer = tracer+ @name = name+ @kind = kind+ @attributes = attributes+ @skip = skip+ @error = error+ end++ # Instrumentation must never break the instrumented work: a raising+ # name/kind/attributes proc is reported through the OpenTelemetry error+ # handler instead of propagating, and finish/detach always run so a bad+ # proc cannot leak an unfinished span or a stuck context onto the thread.+ # @param _event_name [String] notification name (unused)+ # @param _id [String] notification instrumenter id (unused)+ # @param payload [Hash] notification payload; the span handle is stored on it+ # @return [void]+ def start(_event_name, _id, payload)+ return if @skip&.call(payload)++ span = @tracer.start_span(+ @name.call(payload),+ kind: @kind ? @kind.call(payload) : :internal+ )+ token = ::OpenTelemetry::Context.attach(::OpenTelemetry::Trace.context_with_span(span))+ payload[PAYLOAD_KEY] = [span, token]+ rescue StandardError => error+ ::OpenTelemetry.handle_error(exception: error, message: "SpreeOpenTelemetry failed to start span #{@name.inspect}")+ span&.finish if payload[PAYLOAD_KEY].nil?+ end++ # @param _event_name [String] notification name (unused)+ # @param _id [String] notification instrumenter id (unused)+ # @param payload [Hash] notification payload; the span handle is removed from it+ # @return [void]+ def finish(_event_name, _id, payload)+ span, token = payload.delete(PAYLOAD_KEY)+ return unless span++ begin+ @attributes&.call(payload)&.each do |key, value|+ span.set_attribute(key, value) unless value.nil?+ end+ record_outcome(span, payload)+ rescue StandardError => error+ ::OpenTelemetry.handle_error(exception: error, message: 'SpreeOpenTelemetry failed to finalize span')+ ensure+ span.finish+ ::OpenTelemetry::Context.detach(token)+ end+ end++ private++ def record_outcome(span, payload)+ exception = payload[:exception_object]++ if exception && !HALT_EXCEPTIONS.include?(exception.class.name)+ span.record_exception(exception) unless CONTROL_FLOW_EXCEPTIONS.include?(exception.class.name)+ span.status = ::OpenTelemetry::Trace::Status.error(exception.message.to_s)+ elsif (message = @error&.call(payload))+ span.status = ::OpenTelemetry::Trace::Status.error(message.to_s)+ end+ end+ end+enddiff --git a/spree/opentelemetry/lib/spree_opentelemetry/subscribers.rb b/spree/opentelemetry/lib/spree_opentelemetry/subscribers.rbnew file mode 100644index 0000000000..9371486fed--- /dev/null+++ b/spree/opentelemetry/lib/spree_opentelemetry/subscribers.rb@@ -0,0 +1,145 @@+require 'active_support/notifications'++module SpreeOpenTelemetry+ # Attaches one SpanSubscriber per Spree notification family — the+ # commerce-domain layer on top of the framework auto-instrumentation.+ # Span names come from bounded vocabularies (workflow keys, step names,+ # gateway actions, event names); attributes are PII-safe by construction+ # because the core notification payloads are (see+ # docs/plans/6.0-opentelemetry.md).+ module Subscribers+ class << self+ # Subscribes one span source per Spree notification family. Idempotent,+ # so a code reload cannot double-subscribe.+ #+ # @return [void]+ def attach!+ return if attached?++ tracer = SpreeOpenTelemetry.tracer+ @subscriptions = definitions(tracer).map do |notification_name, span_subscriber|+ ActiveSupport::Notifications.subscribe(notification_name, span_subscriber)+ end+ @subscriptions << domain_event_subscription+ end++ # @return [void]+ def detach!+ Array(@subscriptions).each { |subscription| ActiveSupport::Notifications.unsubscribe(subscription) }+ @subscriptions = nil+ end++ # @return [Boolean] whether the span sources are currently subscribed+ def attached?+ end++ private++ def definitions(tracer)+ {+ 'perform.spree_workflow' => SpanSubscriber.new(+ tracer: tracer,+ name: ->(payload) { payload[:workflow] },+ attributes: lambda do |payload|+ {+ 'spree.workflow' => payload[:workflow],+ 'spree.workflow.outcome' => payload[:outcome]+ }+ end,+ error: ->(payload) { 'workflow failed' if %w[failure error].include?(payload[:outcome]) }+ ),++ 'step.spree_workflow' => SpanSubscriber.new(+ tracer: tracer,+ name: ->(payload) { "#{payload[:workflow]} #{payload[:step]}" },+ kind: ->(payload) { payload[:external] ? :client : :internal },+ attributes: lambda do |payload|+ {+ 'spree.workflow' => payload[:workflow],+ 'spree.workflow.step' => payload[:step].to_s,+ 'spree.workflow.step.external' => payload[:external] == true,+ 'spree.workflow.outcome' => payload[:outcome]+ }+ end,+ error: ->(payload) { 'step failed' if payload[:outcome] == 'failure' }+ ),++ 'hooks.spree_workflow' => SpanSubscriber.new(+ tracer: tracer,+ name: ->(payload) { "#{payload[:workflow]} hooks #{payload[:hook]}" },+ skip: ->(payload) { payload[:handler_count].to_i.zero? },+ attributes: lambda do |payload|+ {+ 'spree.workflow' => payload[:workflow],+ 'spree.hook' => payload[:hook].to_s,+ 'spree.hook.handler_count' => payload[:handler_count]+ }+ end+ ),++ 'dispatch.spree_events' => SpanSubscriber.new(+ tracer: tracer,+ name: ->(payload) { "#{payload[:event_name]} dispatch" },+ attributes: lambda do |payload|+ {+ 'spree.event.name' => payload[:event_name],+ 'spree.event.subscriber' => payload[:subscriber],+ 'spree.event.async' => payload[:async] == true+ }+ end+ ),++ 'deliver.spree_webhooks' => SpanSubscriber.new(+ tracer: tracer,+ name: ->(payload) { "spree.webhook.deliver #{payload[:event_name]}" },+ kind: ->(_payload) { :client },+ attributes: lambda do |payload|+ {+ 'spree.webhook.event' => payload[:event_name],+ 'server.address' => payload[:url_host],+ 'http.response.status_code' => payload[:response_code],+ 'spree.webhook.error_type' => payload[:error_type]+ }+ end,+ error: lambda do |payload|+ next payload[:error_type] if payload[:error_type]+ next "HTTP #{payload[:response_code]}" if payload[:response_code].to_i >= 400++ nil+ end+ ),++ 'gateway.spree_payments' => SpanSubscriber.new(+ tracer: tracer,+ name: ->(payload) { "spree.gateway.#{payload[:action]}" },+ kind: ->(_payload) { :client },+ attributes: lambda do |payload|+ {+ 'spree.gateway.action' => payload[:action],+ 'spree.gateway.payment_method_type' => payload[:payment_method_type]+ }+ end+ )+ }+ end++ # Spree domain events ('order.placed' and friends, published as+ # '<name>.spree' with an intentionally empty instrumented block) wrap no+ # work — they surface as span events on the current span, never as+ # spans. Payloads are deliberately excluded: only the name and event id+ # are attached.+ def domain_event_subscription+ ActiveSupport::Notifications.subscribe(/\.spree$/) do |*args|+ event = args.last[:event]+ next unless event++ ::OpenTelemetry::Trace.current_span.add_event(+ "spree.event #{event.name}",+ attributes: { 'spree.event.id' => event.id.to_s }+ )+ end+ end+ end+ end+enddiff --git a/spree/opentelemetry/lib/spree_opentelemetry/webhook_trace_propagation.rb b/spree/opentelemetry/lib/spree_opentelemetry/webhook_trace_propagation.rbnew file mode 100644index 0000000000..9aec794a23--- /dev/null+++ b/spree/opentelemetry/lib/spree_opentelemetry/webhook_trace_propagation.rb@@ -0,0 +1,19 @@+module SpreeOpenTelemetry+ # DeliverWebhook header decorator — injects W3C trace context+ # (traceparent/tracestate) into outbound webhook requests so the merchant's+ # receiving system can join the trace.+ module WebhookTracePropagation+ # Trace context only, never the process-global propagator: that one is a+ # composite that also injects W3C baggage, and baggage carries arbitrary+ # application context to whatever third-party endpoint the merchant+ # configured.+ #+ # @param headers [Hash] outbound request headers, mutated in place+ # @param _delivery [Spree::WebhookDelivery] unused; part of the decorator contract+ # @return [Hash] the same headers hash+ def self.call(headers, _delivery)+ ::OpenTelemetry::Trace::Propagation::TraceContext.text_map_propagator.inject(headers)+ headers+ end+ end+enddiff --git a/spree/opentelemetry/spec/lib/span_subscriber_spec.rb b/spree/opentelemetry/spec/lib/span_subscriber_spec.rbnew file mode 100644index 0000000000..0f2d0e434b--- /dev/null+++ b/spree/opentelemetry/spec/lib/span_subscriber_spec.rb@@ -0,0 +1,50 @@+# frozen_string_literal: true++require 'spec_helper'++RSpec.describe SpreeOpenTelemetry::SpanSubscriber do+ def with_subscriber(subscriber, event_name)+ subscription = ActiveSupport::Notifications.subscribe(event_name, subscriber)+ yield+ ensure+ ActiveSupport::Notifications.unsubscribe(subscription)+ end++ it 'finishes the span and detaches the context even when an attributes proc raises' do+ subscriber = described_class.new(+ tracer: SpreeOpenTelemetry.tracer,+ name: ->(_payload) { 'fragile' },+ attributes: ->(_payload) { raise 'attribute proc bug' }+ )+ handled = []+ allow(OpenTelemetry).to receive(:handle_error) { |**kwargs| handled << kwargs }++ result = nil+ with_subscriber(subscriber, 'fragile.test') do+ result = ActiveSupport::Notifications.instrument('fragile.test') { :ran }+ end++ expect(result).to eq(:ran)+ expect(handled).not_to be_empty+ span = SPREE_OTEL_TEST_EXPORTER.finished_spans.sole+ expect(span.name).to eq('fragile')+ expect(OpenTelemetry::Trace.current_span).to eq(OpenTelemetry::Trace::Span::INVALID)+ end++ it 'never lets a raising name proc break the instrumented work' do+ subscriber = described_class.new(+ tracer: SpreeOpenTelemetry.tracer,+ name: ->(_payload) { raise 'name proc bug' }+ )+ allow(OpenTelemetry).to receive(:handle_error)++ result = nil+ with_subscriber(subscriber, 'fragile.test') do+ result = ActiveSupport::Notifications.instrument('fragile.test') { :ran }+ end++ expect(result).to eq(:ran)+ expect(OpenTelemetry).to have_received(:handle_error)+ expect(OpenTelemetry::Trace.current_span).to eq(OpenTelemetry::Trace::Span::INVALID)+ end+enddiff --git a/spree/opentelemetry/spec/lib/spree_opentelemetry_spec.rb b/spree/opentelemetry/spec/lib/spree_opentelemetry_spec.rbnew file mode 100644index 0000000000..1058d9dd76--- /dev/null+++ b/spree/opentelemetry/spec/lib/spree_opentelemetry_spec.rb@@ -0,0 +1,105 @@+# frozen_string_literal: true++require 'spec_helper'++RSpec.describe SpreeOpenTelemetry do+ # enabled? reads ENV directly — manage the relevant keys per example and+ # restore them afterwards.+ MANAGED_ENV_KEYS = %w[+ OTEL_SDK_DISABLED+ OTEL_EXPORTER_OTLP_ENDPOINT+ OTEL_EXPORTER_OTLP_TRACES_ENDPOINT+ OTEL_TRACES_EXPORTER+ ].freeze++ around do |example|+ saved = MANAGED_ENV_KEYS.index_with { |key| ENV[key] }+ begin+ saved.each_key { |key| ENV.delete(key) }+ example.run+ ensure+ saved.each { |key, value| value.nil? ? ENV.delete(key) : ENV[key] = value }+ end+ end++ after { described_class.instance_variable_set(:@configuration, nil) }++ describe '.enabled?' do+ it 'is dormant when no exporter is configured' do+ expect(described_class.enabled?).to be false+ end++ it 'activates when an OTLP endpoint is set' do+ ENV['OTEL_EXPORTER_OTLP_ENDPOINT'] = 'http://collector:4318'++ expect(described_class.enabled?).to be true+ end++ it 'activates when a traces exporter is named' do+ ENV['OTEL_TRACES_EXPORTER'] = 'otlp'++ expect(described_class.enabled?).to be true+ end++ it 'stays dormant when the traces exporter is explicitly none' do+ ENV['OTEL_TRACES_EXPORTER'] = 'none'++ expect(described_class.enabled?).to be false+ end++ it 'honors the OTEL_SDK_DISABLED kill switch over everything else' do+ ENV['OTEL_EXPORTER_OTLP_ENDPOINT'] = 'http://collector:4318'+ ENV['OTEL_SDK_DISABLED'] = 'true'++ expect(described_class.enabled?).to be false+ end++ # OpenTelemetry booleans are case-insensitive — a kill switch that only+ # recognises one spelling is not a kill switch.+ it 'honors the kill switch whatever its casing' do+ ENV['OTEL_EXPORTER_OTLP_ENDPOINT'] = 'http://collector:4318'++ ['TRUE', 'True', 'tRuE'].each do |spelling|+ ENV['OTEL_SDK_DISABLED'] = spelling++ expect(described_class.enabled?).to be(false), "expected #{spelling.inspect} to disable telemetry"+ end+ end++ it 'can be forced on from configuration without any env vars — the Sentry-OTLP-mode path' do+ described_class.configure { |config| config.enabled = true }++ expect(described_class.enabled?).to be true+ end+ end++ describe '.install!' do+ it 'does nothing while dormant' do+ expect(described_class.install!).to be false+ expect(described_class.installed?).to be false+ end+ end++ describe SpreeOpenTelemetry::Configuration do+ it 'ships the Rails instrumentation set with linked ActiveJob propagation' do+ configuration = described_class.new++ expect(configuration.instrumentations).to include(+ 'OpenTelemetry::Instrumentation::Rack',+ 'OpenTelemetry::Instrumentation::ActiveRecord',+ 'OpenTelemetry::Instrumentation::Net::HTTP'+ )+ expect(configuration.instrumentations['OpenTelemetry::Instrumentation::ActiveJob'])+ .to eq(propagation_style: :link)+ end++ it 'supports adding and removing instrumentations' do+ configuration = described_class.new+ configuration.use 'OpenTelemetry::Instrumentation::Redis', peer_service: 'cache'+ configuration.skip 'OpenTelemetry::Instrumentation::ActionMailer'++ expect(configuration.instrumentations['OpenTelemetry::Instrumentation::Redis']).to eq(peer_service: 'cache')+ expect(configuration.instrumentations).not_to include('OpenTelemetry::Instrumentation::ActionMailer')+ end+ end+enddiff --git a/spree/opentelemetry/spec/lib/subscribers_spec.rb b/spree/opentelemetry/spec/lib/subscribers_spec.rbnew file mode 100644index 0000000000..ca2bf59ffe--- /dev/null+++ b/spree/opentelemetry/spec/lib/subscribers_spec.rb@@ -0,0 +1,233 @@+# frozen_string_literal: true++require 'spec_helper'++RSpec.describe SpreeOpenTelemetry::Subscribers do+ before(:all) { described_class.attach! }+ after(:all) { described_class.detach! }++ before { Spree.hooks.clear! }+ after { Spree.hooks.clear! }++ def finished_spans+ SPREE_OTEL_TEST_EXPORTER.finished_spans+ end++ def build_workflow(&block)+ workflow = Class.new(Spree::Workflow) do+ def self.name = 'Spree::Testing::TracedWorkflow'+ workflow_key 'testing.traced_workflow'+ class_eval(&block)+ end+ stub_const('Spree::Testing::TracedWorkflow', workflow)+ workflow+ end++ describe 'workflow spans' do+ it 'nests step spans under the workflow span, marking external steps as client calls' do+ workflow = build_workflow do+ def perform(subject:)+ super+ step :prepare+ external_step :call_carrier+ success(subject)+ end++ private++ def prepare = nil+ def call_carrier = nil+ end++ workflow.call(subject: 1)++ perform_span = finished_spans.find { |span| span.name == 'testing.traced_workflow' }+ prepare_span = finished_spans.find { |span| span.name == 'testing.traced_workflow prepare' }+ carrier_span = finished_spans.find { |span| span.name == 'testing.traced_workflow call_carrier' }++ expect(perform_span.attributes).to include('spree.workflow.outcome' => 'success')+ expect(prepare_span.parent_span_id).to eq(perform_span.span_id)+ expect(prepare_span.kind).to eq(:internal)+ expect(carrier_span.kind).to eq(:client)+ expect(carrier_span.attributes).to include('spree.workflow.step.external' => true)+ end++ it 'marks failed workflows and their failing step errored' do+ workflow = build_workflow do+ def perform(subject:)+ super+ step :explode+ success(subject)+ end++ private++ def explode = failure(:exploded, 'boom')+ end++ workflow.call(subject: 1)++ perform_span = finished_spans.find { |span| span.name == 'testing.traced_workflow' }+ step_span = finished_spans.find { |span| span.name == 'testing.traced_workflow explode' }++ expect(perform_span.attributes).to include('spree.workflow.outcome' => 'failure')+ expect(perform_span.status.code).to eq(OpenTelemetry::Trace::Status::ERROR)+ expect(step_span.status.code).to eq(OpenTelemetry::Trace::Status::ERROR)+ # Control-flow signal, not a real exception — no exception event.+ expect(step_span.events.to_a).to be_empty+ end++ it 'treats a halted workflow as successful' do+ workflow = build_workflow do+ def perform(subject:)+ super+ step :bail+ success(:never_reached)+ end++ private++ def bail = halt!(:early)+ end++ expect(workflow.call(subject: 1).value).to eq(:early)++ perform_span = finished_spans.find { |span| span.name == 'testing.traced_workflow' }+ step_span = finished_spans.find { |span| span.name == 'testing.traced_workflow bail' }++ expect(perform_span.attributes).to include('spree.workflow.outcome' => 'success')+ expect(perform_span.status.code).not_to eq(OpenTelemetry::Trace::Status::ERROR)+ expect(step_span.status.code).not_to eq(OpenTelemetry::Trace::Status::ERROR)+ end++ it 'records real step exceptions on the span' do+ workflow = build_workflow do+ def perform(subject:)+ super+ step :broken+ success(subject)+ end++ private++ def broken = raise(ArgumentError, 'bad input')+ end++ expect { workflow.call(subject: 1) }.to raise_error(ArgumentError)++ step_span = finished_spans.find { |span| span.name == 'testing.traced_workflow broken' }+ expect(step_span.status.code).to eq(OpenTelemetry::Trace::Status::ERROR)+ expect(step_span.events.map(&:name)).to include('exception')+ end++ it 'spans hook dispatch only when handlers are registered' do+ workflow = build_workflow do+ hooks :after_thing++ def perform(subject:)+ super+ run_hooks :after_thing+ success(subject)+ end+ end++ workflow.call(subject: 1)+ expect(finished_spans.map(&:name)).not_to include('testing.traced_workflow hooks after_thing')++ Spree.hooks.register('testing.traced_workflow.after_thing') { |_context| nil }+ workflow.call(subject: 2)++ hook_span = finished_spans.find { |span| span.name == 'testing.traced_workflow hooks after_thing' }+ expect(hook_span.attributes).to include('spree.hook' => 'after_thing', 'spree.hook.handler_count' => 1)+ end+ end++ describe 'webhook delivery spans' do+ it 'creates a client span carrying the response code' do+ ActiveSupport::Notifications.instrument(+ 'deliver.spree_webhooks', event_name: 'order.placed', url_host: 'hooks.example.com'+ ) do |payload|+ payload[:response_code] = 200+ end++ span = finished_spans.sole+ expect(span.name).to eq('spree.webhook.deliver order.placed')+ expect(span.kind).to eq(:client)+ expect(span.attributes).to include(+ 'spree.webhook.event' => 'order.placed',+ 'server.address' => 'hooks.example.com',+ 'http.response.status_code' => 200+ )+ expect(span.status.code).not_to eq(OpenTelemetry::Trace::Status::ERROR)+ end++ it 'marks failed deliveries errored' do+ ActiveSupport::Notifications.instrument(+ 'deliver.spree_webhooks', event_name: 'order.placed', url_host: 'hooks.example.com'+ ) do |payload|+ payload[:error_type] = 'timeout'+ end++ expect(finished_spans.sole.status.code).to eq(OpenTelemetry::Trace::Status::ERROR)+ end++ it 'marks 4xx/5xx responses errored' do+ ActiveSupport::Notifications.instrument(+ 'deliver.spree_webhooks', event_name: 'order.placed', url_host: 'hooks.example.com'+ ) do |payload|+ payload[:response_code] = 500+ end++ span = finished_spans.sole+ expect(span.status.code).to eq(OpenTelemetry::Trace::Status::ERROR)+ expect(span.status.description).to eq('HTTP 500')+ end+ end++ describe 'gateway spans' do+ it 'creates a client span named after the gateway action' do+ ActiveSupport::Notifications.instrument(+ 'gateway.spree_payments', action: 'purchase', payment_method_type: 'Spree::Gateway::Bogus'+ ) { nil }++ span = finished_spans.sole+ expect(span.name).to eq('spree.gateway.purchase')+ expect(span.kind).to eq(:client)+ expect(span.attributes).to include(+ 'spree.gateway.action' => 'purchase',+ 'spree.gateway.payment_method_type' => 'Spree::Gateway::Bogus'+ )+ end+ end++ describe 'events dispatch spans' do+ it 'creates an internal span per subscriber dispatch' do+ ActiveSupport::Notifications.instrument(+ 'dispatch.spree_events', event_name: 'order.placed', subscriber: 'MySubscriber', async: true+ ) { nil }++ span = finished_spans.sole+ expect(span.name).to eq('order.placed dispatch')+ expect(span.attributes).to include(+ 'spree.event.name' => 'order.placed',+ 'spree.event.subscriber' => 'MySubscriber',+ 'spree.event.async' => true+ )+ end+ end++ describe 'domain events' do+ it 'surfaces published Spree events as span events on the current span, without payloads' do+ event = Spree::Event.new(name: 'order.placed', payload: { 'email' => '[email protected]' })++ SpreeOpenTelemetry.tracer.in_span('outer') do+ ActiveSupport::Notifications.instrument('order.placed.spree', event: event) { nil }+ end++ outer = finished_spans.find { |span| span.name == 'outer' }+ span_event = outer.events.to_a.sole+ expect(span_event.name).to eq('spree.event order.placed')+ expect(span_event.attributes.keys).to eq(['spree.event.id'])+ end+ end+enddiff --git a/spree/opentelemetry/spec/lib/webhook_trace_propagation_spec.rb b/spree/opentelemetry/spec/lib/webhook_trace_propagation_spec.rbnew file mode 100644index 0000000000..e344c15bd3--- /dev/null+++ b/spree/opentelemetry/spec/lib/webhook_trace_propagation_spec.rb@@ -0,0 +1,39 @@+# frozen_string_literal: true++require 'spec_helper'++RSpec.describe SpreeOpenTelemetry::WebhookTracePropagation do+ it 'injects W3C trace context into outbound webhook headers' do+ headers = { 'Content-Type' => 'application/json' }++ SpreeOpenTelemetry.tracer.in_span('outer') do+ described_class.call(headers, nil)+ end++ expect(headers['traceparent']).to match(/\A00-\h{32}-\h{16}-\h{2}\z/)+ expect(headers['Content-Type']).to eq('application/json')+ end++ it 'is a no-op outside any trace' do+ headers = {}++ described_class.call(headers, nil)++ expect(headers).not_to have_key('traceparent')+ end++ # Baggage carries arbitrary application context; the merchant's webhook+ # endpoint is a third party and must never receive it.+ it 'never forwards baggage to the endpoint' do+ headers = {}+ context = OpenTelemetry::Baggage.set_value('customer_email', '[email protected]')++ OpenTelemetry::Context.with_current(context) do+ SpreeOpenTelemetry.tracer.in_span('outer') { described_class.call(headers, nil) }+ end++ expect(headers).to have_key('traceparent')+ expect(headers).not_to have_key('baggage')+ expect(headers.values.join).not_to include('[email protected]')+ end+enddiff --git a/spree/opentelemetry/spec/spec_helper.rb b/spree/opentelemetry/spec/spec_helper.rbnew file mode 100644index 0000000000..ad47d87bc9--- /dev/null+++ b/spree/opentelemetry/spec/spec_helper.rb@@ -0,0 +1,43 @@+# frozen_string_literal: true++ENV['RAILS_ENV'] ||= 'test'+# Keep the SDK from wiring the default OTLP exporter in tests — spans go to+# the in-memory exporter below.+ENV['OTEL_TRACES_EXPORTER'] ||= 'none'++begin+ require File.expand_path('../dummy/config/environment', __FILE__)+rescue LoadError+ puts 'Could not load dummy application. Please ensure you have run `bundle exec rake test_app`'+end++require 'rspec/rails'+require 'database_cleaner/active_record'++require 'spree/testing_support/factories'+require 'spree/testing_support/jobs'+require 'spree/testing_support/store'++SPREE_OTEL_TEST_EXPORTER = OpenTelemetry::SDK::Trace::Export::InMemorySpanExporter.new++OpenTelemetry::SDK.configure do |otel_config|+ otel_config.add_span_processor(+ OpenTelemetry::SDK::Trace::Export::SimpleSpanProcessor.new(SPREE_OTEL_TEST_EXPORTER)+ )+end++RSpec.configure do |config|+ config.color = true+ config.default_formatter = 'progress'+ config.infer_spec_type_from_file_location!+ config.mock_with :rspec+ config.raise_errors_for_deprecations!+ config.use_transactional_fixtures = true++ config.include FactoryBot::Syntax::Methods++ config.before { SPREE_OTEL_TEST_EXPORTER.reset }++ config.order = :random+ Kernel.srand config.seed+enddiff --git a/spree/opentelemetry/spree_opentelemetry.gemspec b/spree/opentelemetry/spree_opentelemetry.gemspecnew file mode 100644index 0000000000..77421cfc06--- /dev/null+++ b/spree/opentelemetry/spree_opentelemetry.gemspec@@ -0,0 +1,40 @@+# encoding: UTF-8++require_relative '../core/lib/spree/core/version.rb'++Gem::Specification.new do |s|+ s.platform = Gem::Platform::RUBY+ s.name = 'spree_opentelemetry'+ s.version = Spree.version+ s.authors = ['Spark Solutions Sp. z o.o.', 'Vendo Connect Inc.']+ s.email = '[email protected]'+ s.summary = 'OpenTelemetry instrumentation for Spree eCommerce platform'+ s.description = 'Distributed tracing for Spree — boots the OpenTelemetry SDK from standard OTEL_* environment variables and turns Spree workflow, event, webhook and payment-gateway instrumentation into spans'+ s.homepage = 'https://spreecommerce.org'+ s.license = 'BSD-3-Clause'++ s.metadata = {+ "bug_tracker_uri" => "https://github.com/spree/spree/issues",+ "changelog_uri" => "https://github.com/spree/spree/releases/tag/v#{s.version}",+ "documentation_uri" => "https://docs.spreecommerce.org/",+ "source_code_uri" => "https://github.com/spree/spree/tree/v#{s.version}",+ }++ s.required_ruby_version = '>= 3.2'++ s.files = Dir["{app,config,db,lib,vendor}/**/*", "Rakefile", "README.md"].reject { |f| f.match(/^spec/) && !f.match(/^spec\/fixtures/) }+ s.require_path = 'lib'++ s.add_dependency 'spree_core', ">= #{s.version}"++ s.add_dependency 'opentelemetry-sdk', '~> 1.0'+ s.add_dependency 'opentelemetry-exporter-otlp', '~> 0.26'+ s.add_dependency 'opentelemetry-instrumentation-rack'+ s.add_dependency 'opentelemetry-instrumentation-action_pack'+ s.add_dependency 'opentelemetry-instrumentation-action_mailer'+ s.add_dependency 'opentelemetry-instrumentation-active_record'+ s.add_dependency 'opentelemetry-instrumentation-active_support'+ s.add_dependency 'opentelemetry-instrumentation-active_job'+ s.add_dependency 'opentelemetry-instrumentation-concurrent_ruby'+ s.add_dependency 'opentelemetry-instrumentation-net_http'+enddiff --git a/spree/providers/easypost/app/models/spree_easypost/delivery_rate_provider.rb b/spree/providers/easypost/app/models/spree_easypost/delivery_rate_provider.rbindex 5775494675..67c0871417 100644--- a/spree/providers/easypost/app/models/spree_easypost/delivery_rate_provider.rb+++ b/spree/providers/easypost/app/models/spree_easypost/delivery_rate_provider.rb@@ -70,12 +70,16 @@ module SpreeEasyPostreturn [] if integration.nil?return [] if package.owner&.ship_address.nil?- rates = begin- easypost_shipment(package).rates+ shipment = begin+ easypost_shipment(package)rescue StandardError => eRails.error.report(e, context: { delivery_method_id: delivery_method.id }, source: 'spree_easypost.rating')- []+ nilend+ return [] if shipment.nil?++ rates = Array(shipment.rates)+ log_rating_failures(shipment) if rates.empty?rates.map do |rate|Spree::DeliveryRateProvider::Estimate.new(@@ -91,6 +95,26 @@ module SpreeEasyPostprivate+ # EasyPost answers 201 with an empty rate list and per-carrier rate_error+ # messages when it cannot quote (incomplete origin address, unsupported+ # lane, oversize parcel). Without surfacing them, the method silently+ # vanishing from checkout is undiagnosable from the outside.+ def log_rating_failures(shipment)+ # The carrier account is part of the identity: the same carrier can fail+ # differently per linked account, and deduplicating on carrier alone+ # would hide one of them.+ reasons = Array(shipment.messages).map do |message|+ carrier = [message.carrier, message.try(:carrier_account_id)].compact.join('/')+ "#{carrier}: #{message.message}"+ end.uniq+ reasons = ['no rates returned and no carrier messages given'] if reasons.empty?++ Rails.logger.warn(+ "[SpreeEasyPost] no rates for delivery method '#{delivery_method.name}' " \+ "(shipment #{shipment.id}): #{reasons.join(' | ')}"+ )+ end+# One shipment-create returns rates for every carrier and service, so all# delivery methods sharing this provider within a request reuse it.def easypost_shipment(package)diff --git a/spree/providers/easypost/spec/models/spree_easypost/delivery_rate_provider_spec.rb b/spree/providers/easypost/spec/models/spree_easypost/delivery_rate_provider_spec.rbindex a4c9091e4a..c9024a08a8 100644--- a/spree/providers/easypost/spec/models/spree_easypost/delivery_rate_provider_spec.rb+++ b/spree/providers/easypost/spec/models/spree_easypost/delivery_rate_provider_spec.rb@@ -146,6 +146,49 @@ RSpec.describe SpreeEasyPost::DeliveryRateProvider doexpect(provider.estimates(package)).to eq([])end+ # EasyPost accepts the shipment (201) but attaches rate_error messages+ # instead of rates when it cannot quote — without logging them, "no+ # delivery options" is undiagnosable (e.g. an origin with no zip code).+ it 'logs the carrier rate errors when the shipment comes back with no rates' do+ rate_error = double(+ carrier: 'USPS',+ carrier_account_id: 'ca_1',+ message: 'Unable to retrieve USPS rates without a valid origin zip code.'+ )+ empty_shipment = double(id: 'shp_empty', rates: [], messages: [rate_error, rate_error])+ allow(shipment_service).to receive(:create).and_return(empty_shipment)+ allow(Rails.logger).to receive(:warn)++ expect(provider.estimates(package)).to eq([])+ expect(Rails.logger).to have_received(:warn).with(+ a_string_including('no rates', delivery_method.name, 'shp_empty', 'valid origin zip code')+ )+ end++ # Two linked accounts for one carrier can fail for different reasons;+ # collapsing them on carrier alone would hide one.+ it 'keeps per-account rate errors distinct' do+ first_account = double(carrier: 'UPS', carrier_account_id: 'ca_1', message: 'Invalid origin zip')+ second_account = double(carrier: 'UPS', carrier_account_id: 'ca_2', message: 'Account not authorized')+ empty_shipment = double(id: 'shp_empty', rates: [], messages: [first_account, second_account])+ allow(shipment_service).to receive(:create).and_return(empty_shipment)+ allow(Rails.logger).to receive(:warn)++ expect(provider.estimates(package)).to eq([])+ expect(Rails.logger).to have_received(:warn).with(+ a_string_including('UPS/ca_1', 'Invalid origin zip', 'UPS/ca_2', 'Account not authorized')+ )+ end++ it 'logs even when EasyPost gives no reason for the empty rate list' do+ empty_shipment = double(id: 'shp_empty', rates: [], messages: [])+ allow(shipment_service).to receive(:create).and_return(empty_shipment)+ allow(Rails.logger).to receive(:warn)++ expect(provider.estimates(package)).to eq([])+ expect(Rails.logger).to have_received(:warn).with(a_string_including('no carrier messages given'))+ end+describe 'parcel dimensions' dobefore dostore.update!(