The only tool you need to know what is happening and how to fix it.
Go alertingexception-trackerissue-trackinglogsmetricsmonitoringobservability-platformopen-telemetryotelsession-replaytelemetrytraces
add: testing project updates
narrow-adventurec555ab8ee284
diff --git a/.gitignore b/.gitignoreindex e4b6896f..543bf8e3 100644--- a/.gitignore+++ b/.gitignore@@ -71,3 +71,4 @@ symbolicator-bench.txtskills-lock.json/.claude/skills/.agents+/testing/shop/traffic/node_modulesdiff --git a/testing/shop/BUGS.md b/testing/shop/BUGS.mdindex 33131389..8cc44474 100644--- a/testing/shop/BUGS.md+++ b/testing/shop/BUGS.md@@ -1,61 +1,29 @@-# Demo Shop — Intentional Bug Catalog--This app is a deliberately buggy + slow shop, built to make Traceway telemetry look-interesting. It is meant to **appear to work** while being mostly **slow**, with a few-actions that throw exceptions. Nothing here is a real bug to "fix" — it is the demo script.--## Headline mechanic--Most endpoints branch on a single helper:--```go-// backend/slow.go-func fastPath() bool { return rand.IntN(4) == 0 }-```--So **~1 in 4 requests takes the fast, efficient path; the other ~3 in 4 take a slow path**-(an N+1 query loop, a `time.Sleep` jitter span, or a panic). The ratio is **per-endpoint**,-so a single page load that hits several endpoints is almost always slow overall — that is-the intended "the whole shop just feels sluggish" effect.--The backend reports as server **`shop-demo`**, version **`0.1.0`** (set in `backend/main.go`).-The React frontend reports through `@tracewayapp/react` (`frontend/src/main.jsx`). Point both at-the same project token so backend traces and frontend errors group together.--## Backend bugs (Go / Gin / SQLite)--| # | Name | Location | Trigger | App symptom | What shows up in Traceway |-|---|------|----------|---------|-------------|---------------------------|-| 1 | Products N+1 | `backend/products.go` → `listProducts` (slow branch) | ~75% of product-list loads | List loads, but slowly | Slow `GET /api/products` transaction with `1 + 2N` DB spans — one `SELECT name FROM categories WHERE id = ?` and one `SELECT COUNT(*) FROM reviews WHERE product_id = ?` per product |-| 2 | Product-detail N+1 + slow recommendations | `backend/products.go` → `getProduct` (slow branch) | ~75% of detail loads | Detail page sluggish | Named span `load_reviews` wrapping N per-review `SELECT ... WHERE id = ?` spans, plus a `recommendations.fetch` span that just sleeps 80–200ms |-| 3 | Cart N+1 | `backend/cart.go` → `getCart` (slow branch) | ~75% of cart views | Cart slow to render | Per-line `SELECT name, price_cents, image_url FROM products WHERE id = ?` spans |-| 4 | Slow inventory check | `backend/cart.go` → `addToCart` (slow branch) | ~75% of add-to-cart calls | "Add to cart" lags 150–500ms | `inventory.check` span that only sleeps |-| 5 | Coupon nil-map panic | `backend/coupon.go` → `applyCoupon` + package var `couponHits` | ~75% of coupon applies (valid codes) | Apply-coupon fails with a 500 | Exception **`assignment to entry in nil map`** (the package-level `couponHits` map is never initialized; only the fast path guards it). Returns 500, auto-captured by the gin middleware |-| 5b | Unknown-coupon captured error | `backend/coupon.go` → `applyCoupon` (no-rows branch) | Applying a code that isn't seeded | "Invalid coupon code" (400) | Non-panic captured error `unknown coupon code: <code>` via `c.Error(...)` |-| 6 | Checkout index-out-of-range | `backend/checkout.go` → `checkout` (`lines[0]`) | Checking out with an **empty cart** | Checkout 500s | Exception **`index out of range [0] with length 0`** with a Go stack trace |-| 7 | Slow payment gateway | `backend/checkout.go` → `checkout` (`payment.charge`) | Every slow-path checkout | Checkout takes 0.3–1.2s | `payment.charge` span (sleeps 300–1200ms) + `order.persist` span; slow transaction |-| 8 | Payment declined (manual capture) | `backend/checkout.go` → `checkout` (`rand.IntN(6)==0`) | ~1 in 6 checkouts with items | "Payment declined, try another card" (402) | Exception **`payment declined for card ****NNNN`** reported via `traceway.CaptureExceptionWithContext` — captured without a 500, demonstrating manual capture |--Notes:-- Seeded coupons: `SAVE10` (10%), `HALF50` (50%), `EXPIRED` (inactive → 400 "expired", not an exception).-- A valid coupon therefore "works about 1 in 4 tries"; the rest panic (#5). That is the literal- reading of "works 1/4 of the time, slow/broken the rest."-- Panics are recovered (the server never dies) and return 500. The exception is captured **before**- the response is finalized, so it still reaches Traceway.--## Frontend bugs (React / Vite)--| # | Name | Location | Trigger | App symptom | What shows up in Traceway |-|---|------|----------|---------|-------------|---------------------------|-| 9 | Uncaught async add-to-cart | `frontend/src/ProductsPage.jsx` → `handleAdd` | Backend 500s on the add-to-cart slow path | Button silently fails to add | Unhandled promise rejection auto-captured by the SDK (the handler has no try/catch on purpose) |-| 10 | Render-time null deref | `frontend/src/CheckoutPage.jsx` → `CouponBadge` | A failed coupon apply sets `discount = null`, then the badge renders | Coupon area shows "Could not display coupon." | Frontend render exception `Cannot read properties of null (reading 'percent')`, caught by `TracewayErrorBoundary` (reported, with a fallback so the page stays usable) |-| 11 | Undefined deref in handler | `frontend/src/ProductsPage.jsx` → `handleQuickView` | Clicking "Quick view" (products have no `variants` field) | Quick view shows "No variants available" | Frontend exception `Cannot read properties of undefined (reading 'find')`, manually reported via `useTraceway().captureException` |--## Coverage--- **Slowness**: #1, #2, #3, #4, #7 (N+1 fan-outs + named sleep spans → slow transactions).-- **Exceptions**: #5, #6, #8 (backend) and #9, #10, #11 (frontend).-- **Capture styles**: auto panic capture (#5, #6), gin `c.Error` (#5b), manual backend capture (#8),- SDK global unhandled-rejection (#9), React error boundary (#10), manual frontend capture (#11).--See `README.md` for how to run everything and reproduce each item.+# Intentional bugs (current behavior)++Backend errors are recorded on the active OTel span (`RecordError` + status Error), so each+one groups into an Issue attached to its endpoint. Frontend errors are captured by the+`@tracewayapp/react` SDK; fetch failures carry the backend `traceway-trace-id` for+distributed-trace linking.++## Backend++| # | Where | Trigger | Behavior |+|---|---|---|---|+| 1 | `GET /api/products` | ~75% of requests | N+1 category/review-count queries, 200-300ms jitter per product |+| 2 | `GET /api/products/:id` | ~75% | review N+1 (`load_reviews` span) + `recommendations.fetch` sleep |+| 3 | `GET /api/cart` | ~75% | per-line product lookups |+| 4 | `POST /api/cart` | ~75% | `inventory.check` span sleeps 150-500ms |+| 5 | `POST /api/coupon` unknown code | always | 500 "invalid coupon code", recorded error |+| 5b | `POST /api/coupon` `EXPIRED` | always | 400 "this coupon has expired" (not recorded — client error) |+| 6 | `POST /api/checkout` empty cart | always | 500 "your cart is empty", recorded error |+| 7 | `POST /api/checkout` | ~75% | `payment.charge` sleeps 300-1200ms |+| 8 | `POST /api/checkout` | 1 in 6 | 500 "payment declined", recorded error (card digits normalize out of the hash) |+| 12 | `POST /api/coupon` valid code | ~75% | **flagship bug**: `couponHits` map is nil → `assignment to entry in nil map` panic, recovered by the OTel recovery middleware into a 500 + Issue with full Go stack |++## Frontend++| # | Where | Trigger | Behavior |+|---|---|---|---|+| 9 | Products page add-to-cart | backend 500 | `handleAdd` has no try/catch → api.js capture + unhandled rejection |+| 10 | Checkout `CouponBadge` | any failed coupon apply (`discount` becomes null) | render crash `Cannot read properties of null (reading 'percent')`, caught + reported by `TracewayErrorBoundary`, fallback shown |+| 11 | Quick view of **4K Monitor** | always | `p.variants.find(...)` TypeError, captured via `captureException`, "No variants available" toast; all other products work |diff --git a/testing/shop/DEMO.md b/testing/shop/DEMO.mdindex 32351544..62e8bb32 100644--- a/testing/shop/DEMO.md+++ b/testing/shop/DEMO.md@@ -1,295 +1,30 @@-# Demo Shop — Live Demo Runbook--Three acts:--1. **Bugs, no observability** — run the app as-is (Traceway stripped out). It's slow and flaky,- errors are swallowed or buried in the browser console. You have no idea what's breaking.-2. **Add Traceway** — re-instrument both halves. Every bug now surfaces as an issue with a stack- trace, tags, and a frequency, plus slow transactions.-3. **Symbolication** — the frontend stack traces arrive minified (`index-abc123.js:1:48211`).- Upload source maps and they turn into real `CheckoutPage.jsx:8` frames in your source.--The bug catalog (numbers `#1`–`#11`) is in [`BUGS.md`](./BUGS.md).--## Prerequisites--- A Traceway instance running (these notes assume **http://localhost:8082**) with a **project** +- its **project token**.-- Go 1.25+ with CGO, Node 18+.-- The sibling SDK repos the app links against must exist (they were used to build it originally):- - Go SDK at `../../../go-client` (relative to `backend/`)- - JS SDK at `../../../js-client` (relative to `frontend/`)--> **Tip:** the current working tree is the *stripped* (no-Traceway) version. If you want to be able-> to return to it after the demo, commit it on a branch first (e.g. `git switch -c shop-no-tw`).-> The fully-instrumented version is preserved in commit **`fd21c509`**, which Act 2 restores from.-------## Act 1 — Bugs with no observability--```bash-cd testing/shop-./build-and-run.sh-```--Open **http://localhost:8090** and drive it (open the browser devtools console too):--- **Products page** — everything loads *slowly* (N+1, `#1`). Click **Quick view** → "No variants- available" (`#11`, swallowed). Click **Add to cart** a few times → it occasionally just doesn't- add and you only see a red error in the console if you're looking (`#9`).-- **Checkout** — type a coupon (`SAVE10`) and **Apply** → it usually errors (`#5`), and the badge- area shows "Could not display coupon." (`#10`, caught by a local boundary). **Place order** with- an empty cart → it fails (`#6`); with items it's slow (`#7`) and sometimes declined (`#8`).--Backend bugs from the terminal:--```bash-for i in $(seq 1 8); do curl -s -o /dev/null -w "%{http_code} " -X POST localhost:8090/api/coupon \- -H 'Content-Type: application/json' -d '{"code":"SAVE10"}'; done; echo # ~75% 500-curl -s -o /dev/null -w "%{http_code}\n" -X POST localhost:8090/api/checkout \- -H 'Content-Type: application/json' -d '{"name":"A","email":"[email protected]","card_last4":"4242"}' # 500-```--**The point:** the app is clearly unhealthy, but the failures are swallowed, intermittent, or-lost in the console. You can't see *what* is breaking, *how often*, or *where*.--Stop the server (`Ctrl-C`) before Act 2.-------## Act 2 — Add Traceway--The instrumented version of every handler and React component lives in commit `fd21c509`. Restore-those, keep the new "serve frontend from backend" wiring, and point the SDKs at your instance.--**1. Restore the instrumented handlers + frontend + Go deps** (everything except `main.go`, which-needs the new static-serving line):--```bash-cd testing/shop-git checkout fd21c509 -- \- backend/cart.go backend/products.go backend/checkout.go backend/coupon.go \- backend/go.mod backend/go.sum \- frontend/src/main.jsx frontend/src/ProductsPage.jsx frontend/src/CheckoutPage.jsx \- frontend/package.json-```--This brings back the Go `tracewaygin` middleware deps, the per-handler `tracewaydb` spans and-manual captures (`#8`), and the React `TracewayProvider` / `useTraceway` / `TracewayErrorBoundary`-usage (`#9`, `#10`, `#11`).--**2. Put `backend/main.go` back to instrumented *and* keep serving the embedded frontend.** Replace-the whole file with:--```go-package main--import (- "database/sql"- "net/http"- "os"-- tracewaygin "go.tracewayapp.com/tracewaygin"-- "github.com/gin-gonic/gin"- _ "github.com/mattn/go-sqlite3"-)--var db *sql.DB--func main() {- initDB()-- endpoint := os.Getenv("TRACEWAY_ENDPOINT")- if endpoint == "" {- endpoint = "default_token_change_me@http://localhost:8082/api/report"- }-- router := gin.Default()- router.Use(corsMiddleware())- router.Use(tracewaygin.New(- endpoint,- tracewaygin.WithDebug(true),- tracewaygin.WithServerName("shop-demo"),- tracewaygin.WithVersion("0.1.0"),- tracewaygin.WithOnErrorRecording(tracewaygin.RecordingUrl|tracewaygin.RecordingQuery|tracewaygin.RecordingHeader|tracewaygin.RecordingBody),- ))-- router.GET("/api/health", func(c *gin.Context) {- c.JSON(http.StatusOK, gin.H{"status": "ok"})- })-- router.GET("/api/products", listProducts)- router.GET("/api/products/:id", getProduct)- router.GET("/api/cart", getCart)- router.POST("/api/cart", addToCart)- router.DELETE("/api/cart/:id", removeFromCart)- router.POST("/api/coupon", applyCoupon)- router.POST("/api/checkout", checkout)-- registerFrontend(router)-- router.Run(":8090")-}--func corsMiddleware() gin.HandlerFunc {- return func(c *gin.Context) {- c.Header("Access-Control-Allow-Origin", "*")- c.Header("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS")- c.Header("Access-Control-Allow-Headers", "Content-Type, Authorization")- if c.Request.Method == http.MethodOptions {- c.AbortWithStatus(http.StatusNoContent)- return- }- c.Next()- }-}-```--**3. Point both SDKs at your instance + project token.** Use the **same** project token for both.--Frontend — Vite reads this at build time (baked into the bundle):--```bash-echo 'VITE_TW_CONNECTION=<PROJECT_TOKEN>@http://localhost:8082/api/report' > frontend/.env-```--Backend — read at runtime from the environment.--**4. Rebuild and run** (the env var is inherited by the embedded `./shop`):--```bash-TRACEWAY_ENDPOINT="<PROJECT_TOKEN>@http://localhost:8082/api/report" ./build-and-run.sh-```--`build-and-run.sh` reinstalls the now-restored `@tracewayapp/react` dep and rebuilds the bundle-(with source maps). If the Go build complains about the restored modules, run-`cd backend && go mod tidy` once and re-run the script.--**5. Re-drive the same actions** from Act 1 (UI + the curl loops). Now open the Traceway dashboard-for your project:--- **Issues** — the nil-map panic (`assignment to entry in nil map`, `#5`), the- `index out of range [0] with length 0` panic (`#6`), the declined-card capture (`#8`), and the- three frontend errors (`#9`, `#10`, `#11`) — each with a count and a stack trace.-- **Endpoints / transactions** — `GET /api/products` is slow with the N+1 fan-out; checkout shows- the `payment.charge` span.-- Filter by server **`shop-demo`**, version **`0.1.0`**.-------## Act 3 — Symbolication of the frontend errors--Open one of the **frontend** issues (`#10` CouponBadge, `#11` Quick view, or `#9` add-to-cart). The-stack trace is minified gibberish — something like `index-DSxfDYbG.js:1:48211`. That's because the-browser only ever sees the production bundle. Fix it by uploading the source maps.--**How matching works (no version juggling):** Traceway matches a frame to a map by **filename**-(`index-<hash>.js` → `index-<hash>.js.map`), or by embedded debug-id. The SDK's `version: 0.1.0` is-just metadata for filtering — it is **not** used for map matching. The only rule that matters:-**upload the maps from the exact build you are serving.** `build-and-run.sh` already emitted them-to `frontend/dist/assets/*.map`, and it embedded that same `dist` into the running binary, so the-hashes line up. (If you rebuild, re-upload.)--**1. Get a source-map upload token** — in the dashboard (Project settings → source maps), or via-the API with your dashboard JWT:--```bash-curl -s -X POST http://localhost:8082/api/projects/source-map-token \- -H "Authorization: Bearer <DASHBOARD_JWT>" -H 'Content-Type: application/json' \- -d '{}' # -> {"sourceMapToken":"..."}-```--**2. Upload the maps** (and their sibling `.js`, which lets Traceway resolve function names too):--```bash-npx @tracewayapp/sourcemap-upload \- --url http://localhost:8082 \- --token "<SOURCEMAP_TOKEN>" \- --directory frontend/dist-```--Dependency-free alternative with `curl` (single entry bundle):--```bash-cd frontend/dist/assets-curl -sS -X POST http://localhost:8082/api/sourcemaps/upload \- -H "Authorization: Bearer <SOURCEMAP_TOKEN>" \- -F "files=@$(ls index-*.js)" \- -F "files=@$(ls index-*.js.map)" # -> {"uploaded":2}-cd ../../..-```--**3. Trigger the frontend bug again** (e.g. apply a bad coupon for `#10`, or Quick view for `#11`)-so a fresh event arrives, then open that issue. The same frame now reads-`CheckoutPage.jsx:8:...` / `ProductsPage.jsx:...` — your actual source, function names and all.--> Upload the maps **before** the event you want to show symbolicated. A nice narrative is: trigger-> once to show the minified trace, upload, trigger again, open the new event to show it resolved.-------## Manual click test cases--Assumes the **Act 2 build** (Traceway re-added) is running and the dashboard is open. Base URL-**http://localhost:8090**. Issue numbers are from [`BUGS.md`](./BUGS.md). Backend issues also have-curl equivalents in [`demo-traffic.sh`](./demo-traffic.sh).--| TC | Issue | Page | Click exactly | You'll see | Reliability |-|----|-------|------|---------------|------------|-------------|-| 1 | #1 slow products | Products | Click **Products** in the nav (or reload) a few times | Grid loads with a visible lag | ~3 of 4 loads |-| 2 | #4 slow add-to-cart | Products | Click **Add to cart** on a few cards | Button lags on "Adding…", cart badge ticks up | ~3 of 4 |-| 3 | **#11** quick view | Products | Click **Quick view** on any card | "<name> — No variants available" | every click |-| 4 | #3 slow cart | Cart | Do TC2 first, then click **Cart** | Cart renders with a lag | ~3 of 4 |-| 5 | #5 panic + **#10** | Checkout | Type `SAVE10`, click **Apply** | ~75% "Could not display coupon."; ~25% "saved 10%" | panic ~3 of 4 |-| 6 | #5b + **#10** | Checkout | Type `FOO` (any unknown code), click **Apply** | "Could not display coupon." | every click |-| 7 | #6 empty-cart panic | Checkout | Empty the cart, fill the form, click **Place order** | inline "request failed (500)" | ~5 of 6 (else 402) |-| 8 | #7 slow + #8 declined | Checkout | With items, fill the form, click **Place order** | "Placing order…" ~1s, then confirmed or "declined" | slow most; decline ~1 of 6 |-| 9 | **#9** unhandled add | Products | not a pure click — see note | button sticks on "Adding…" | n/a |--Details that bite:--- **TC3 / #11 is the cleanest frontend demo** — every product is missing a `variants` field, so- Quick view throws on every click and is captured manually. Start here.-- **TC6 / #10 is the deterministic null-deref:** any **unknown** coupon code returns 400, which sets- `discount = null`, which makes the badge throw on render and the error boundary report it.- `EXPIRED` works too (400 "expired", no backend exception). `SAVE10` also triggers #10 but only on- the ~75% of applies that panic.-- **Re-triggering #10:** once the coupon badge boundary catches once, it stays on the fallback. To- fire a fresh #10, leave Checkout (click **Products**) and come back, then Apply again.-- **TC7 / #6:** "empty the cart" = Cart page → **Remove** every line, or just restart the server (the- in-memory DB reseeds empty). The Place-order fields are required: Name, a valid Email, a 4-digit- card (e.g. `Ada` / `[email protected]` / `4242`).-- **TC8 / #8 (declined)** is ~1 in 6, and a successful order clears the cart, so to keep trying you- click **Back to shop**, re-add an item, return to Checkout. Easier via `demo-traffic.sh` phase 8.-- **#2 (product-detail N+1) has no UI path** — there is no product-detail page. Hit it with- `curl .../api/products/1` or `demo-traffic.sh` phase 2.-- **TC9 / #9 is not reproducible by clicking** a seeded product (add-to-cart always 201s, so- `handleAdd` never rejects). Two ways to force it:- - *No code change:* with the Products page already loaded, stop the shop backend (Ctrl-C the- `:8090` process — Traceway on `:8082` stays up). Click **Add to cart**: the fetch fails, the- button sticks on "Adding…", and the unhandled rejection is reported. Restart with- `./build-and-run.sh` afterward — don't reload the page while it's down.- - *One-line tweak for a pure click:* in `backend/cart.go` `addToCart`, inside the `if !fastPath()`- block, fail a fraction of slow adds:- ```go- if !fastPath() {- slowJitter(150, 500)- if rand.IntN(3) == 0 {- c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("inventory check failed for product %d", req.ProductId))- return- }- }- ```- (ensure `"math/rand/v2"` is imported). Now a few **Add to cart** clicks reliably 500 → #9, while- successful adds still fill the cart.--## Reset--- Back to "bugs, no observability": discard the Act 2 restores- (`git checkout fd21c509^ -- ...` won't help — restore your stripped branch, or- `git restore --source=<your-no-tw-commit> -- <files>`), or just keep the `shop-no-tw` branch you- made in the prereqs and `git switch` to it.-- The SQLite DB is in-memory and reseeded on every start, so cart/orders reset whenever you restart- the server.+# Shoply demo runbook++> The full setup lives in README.md (build, seed, traffic). This file is the tour to give+> once data is flowing.++Projects: **Shoply Storefront** (react — issues, sessions, replays) and+**Shoply API** (opentelemetry — endpoints, traces, logs, metrics, AI, monitors).++## Suggested tour++1. **Issues (backend)** — open `assignment to entry in nil map`: full Go stack from the+ recovered panic, occurrences over time, the owning endpoint `POST /api/coupon`, and the+ trace waterfall showing the SQL spans.+2. **Distributed tracing** — open a react issue like `Request to /coupon failed (500)`:+ the occurrence carries the distributed trace id and links straight to the backend trace.+3. **Session replay** — from the same react issue open the replay clip; then the Sessions+ page for full sessions with varied users, viewports and rage-scrolling window shoppers.+4. **Endpoints** — `GET /api/products` p95 vs p50 (N+1 slow path), `POST /api/checkout`+ latency spread, all endpoints grouped by route (ids collapse into `:id`).+5. **Logs** — filter severity ERROR; every line links to its trace.+6. **Metrics & dashboards** — Server/Application Metrics pages (`shop-backend`), the+ OTelemetry Server Agent + Go Application dashboards, and Shoply Business (orders,+ revenue, coupon failures).+7. **AI Traces** — Conversations tab: the order-status conversation shows the+ `lookup_order` tool call; the refund complaint is flagged; Users tab has per-user costs.+8. **Monitors** — three green checks + `Payments Provider` down: incident, uptime bars,+ and the check_down page it opened (Pages sidebar badge). Ack it live.+9. **On-call** — team, weekly schedule, escalation policy; `/status/shoply-status` public+ page with the resolved `Elevated checkout error rate` incident timeline.+10. **Post-mortem** — the linked write-up under Monitors → Post-Mortems.diff --git a/testing/shop/README.md b/testing/shop/README.mdindex 6ad444dc..f20275e1 100644--- a/testing/shop/README.md+++ b/testing/shop/README.md@@ -1,85 +1,74 @@-# Demo Shop+# Shoply — Traceway demo shop-A tiny, intentionally-buggy shop app. React (Vite) frontend + Go/Gin backend with in-memory-SQLite. No auth, single shared cart. Three pages: products, cart, checkout.+A small e-commerce app used to generate realistic demo data for a Traceway instance:-The app is built to **look like it works** but be mostly **slow**, with a few actions that throw-exceptions. Every intentional bug is cataloged in [`BUGS.md`](./BUGS.md).+- **Frontend**: React 18 + Vite + Tailwind, instrumented with `@tracewayapp/react` (session recording on, all sessions recorded). Reports to the **react** demo project via `/api/report`.+- **Backend**: Go + Gin + in-memory SQLite, instrumented with **OpenTelemetry** (traces, logs, metrics over OTLP/HTTP). Reports to the **opentelemetry** demo project via `/api/otel/v1/*`. The retired Traceway Go SDK is gone.+- Single origin: the built frontend is embedded into the Go binary and served on **:8090**.-> **Traceway instrumentation has been removed** from both halves on purpose — it gets re-added-> live during the demo. The bugs in [`BUGS.md`](./BUGS.md) are all still here; right now panics-> are recovered by Gin's own middleware (still 500s) and frontend errors surface in the console-> instead of being reported.+The app ships intentional bugs and random slowness (see `BUGS.md`) so issues, slow endpoints,+logs, metrics, session replays and AI traces all light up. Frontend exceptions carry a+`traceway-trace-id` that links them to the backend trace (distributed tracing).++## Setup++1. `backend/.env` (gitignored, see `backend/.env.example`):```-shop/-├── build-and-run.sh build the frontend, embed it in the backend, compile + run-├── DEMO.md live-demo runbook (bugs first, then add Traceway + symbolication)-├── BUGS.md the demo script (what's wrong and where)-├── backend/ Go / Gin / SQLite, serves the API + the built frontend on :8090-└── frontend/ React + Vite source+TRACEWAY_URL=https://cloud.tracewayapp.com+TRACEWAY_BACKEND_TOKEN=<opentelemetry project token>+TRACEWAY_SERVICE_NAME=shop-backend```-## Prerequisites+2. `frontend/.env` (gitignored, see `frontend/.env.example`):++```+VITE_API_BASE=/api+VITE_TW_CONNECTION=<react project token>@https://cloud.tracewayapp.com/api/report+TRACEWAY_URL=https://cloud.tracewayapp.com+TRACEWAY_SOURCEMAP_TOKEN=<source map upload token>+```-- Go 1.25+ with **CGO enabled** (`mattn/go-sqlite3` needs a C compiler; clang ships with macOS).-- Node 18+ and npm.+The sourcemap token comes from `seed/seed.mjs` with `MINT_SOURCEMAP_TOKEN=1` (or the+project's Connection page). Uploading source maps before generating browser traffic makes+the frontend issues symbolicate at ingest.## Run```bash-./build-and-run.sh+./build-and-run.sh # build frontend -> embed -> build backend -> run on :8090```-The script `npm install`s and builds the frontend (with source maps), copies the built `dist/`-into `backend/dist` (embedded into the Go binary at compile time via `//go:embed`), then builds-and starts the backend. Everything is served from a single origin at **http://localhost:8090** —-open it and click around. There is no separate frontend dev server and no CORS to configure.--For the live demo (show bugs first, then add Traceway and watch them get symbolicated on the-dashboard), follow [`DEMO.md`](./DEMO.md).+Dev mode: `cd frontend && npm run dev` (:5175, proxies /api to :8090).-### Frontend dev server (optional)--For hot-reload while editing the frontend, run Vite separately. It serves on **:5175** and-proxies `/api/*` to the backend on `:8090`, so start the backend (via `./run.sh`) first.+## Seed platform entities (monitors, on-call, status page, dashboards...)```bash-cd frontend-npm install-npm run dev+traceway login --profile demo # device flow into the demo account+cd seed && MINT_SOURCEMAP_TOKEN=1 node seed.mjs```-## Reproduce the bugs--```bash-# 1. Health-curl localhost:8090/api/health # {"status":"ok"}--# 2. Slow + N+1 product list (most calls hit the slow path)-for i in $(seq 1 12); do curl -s -o /dev/null localhost:8090/api/products; done+Idempotent; see `seed/README.md`.-# 3. Coupon nil-map panic (~75% return 500)-for i in $(seq 1 8); do- curl -s -o /dev/null -w "%{http_code} " -X POST localhost:8090/api/coupon \- -H 'Content-Type: application/json' -d '{"code":"SAVE10"}'-done; echo+## Generate traffic-# 4. Empty-cart checkout panic (500: index out of range)-curl -s -o /dev/null -w "%{http_code}\n" -X POST localhost:8090/api/checkout \- -H 'Content-Type: application/json' -d '{"name":"A","email":"[email protected]","card_last4":"4242"}'+```bash+cd traffic && npm install && npx playwright install chromium+./run-traffic.sh --seed # ~50 varied browser sessions + http load + AI chats+./run-traffic.sh --drip # endless low-rate mode (nohup it)+./run-traffic.sh --seed --no-browser # http load + AI chats only```-In the browser at http://localhost:8090:--- **Products** load slowly (N+1). "Quick view" throws a frontend exception (#11). "Add to cart"- can fail silently when the backend slow path 500s (#9).-- **Checkout** → "Apply" a coupon: usually 500s on the backend (#5) and the badge render is caught- by the error boundary (#10). "Place order" with an empty cart 500s (#6); with items it is slow- (#7) and occasionally declined (#8, a 402).+Flags: `--base <url>` `--sessions N` `--parallel N` `--headed`.-## Notes+## API-- The in-memory SQLite DB is reseeded on every backend start, so the cart and orders reset on restart.-- The slow/fast split is `rand.IntN(4) == 0` per request (see `backend/slow.go`) — about 1 in 4 fast.-- Panics are recovered, so the server stays up and returns 500.+| Method | Path | Notes |+|---|---|---|+| GET | `/api/health` | untraced |+| GET | `/api/products` | ~75% N+1 slow path |+| GET | `/api/products/:id` | ~75% slow (review N+1 + recommendations); no UI path, driven by http-load |+| GET/POST | `/api/cart`, DELETE `/api/cart/:id` | POST returns 201, inventory.check sleep |+| POST | `/api/coupon` | `SAVE10`/`HALF50` valid (~75% panic: nil map), `EXPIRED` 400, unknown 500 |+| POST | `/api/checkout` | empty cart 500; 1-in-6 payment declined 500 |+| POST | `/api/support/chat` | fake LLM support agent; emits gen_ai.* spans (AI Traces) |diff --git a/testing/shop/backend/.env.example b/testing/shop/backend/.env.exampleindex 54d9195e..bb05f908 100644--- a/testing/shop/backend/.env.example+++ b/testing/shop/backend/.env.example@@ -1,2 +1,4 @@-# Backend Traceway Go SDK endpoint (token@url). Secret token — keep real values in backend/.env (gitignored).-TRACEWAY_ENDPOINT=<project-token>@https://cloud.tracewayapp.com/api/report+# Backend OpenTelemetry export target (OTLP/HTTP). Secret token — keep real values in backend/.env (gitignored).+TRACEWAY_URL=https://cloud.tracewayapp.com+TRACEWAY_BACKEND_TOKEN=<project-token>+TRACEWAY_SERVICE_NAME=shop-backenddiff --git a/testing/shop/backend/cart.go b/testing/shop/backend/cart.goindex 63cdd4a2..2c6ad3b3 100644--- a/testing/shop/backend/cart.go+++ b/testing/shop/backend/cart.go@@ -3,34 +3,32 @@ package mainimport ("database/sql""errors"+ "fmt"+ "log/slog""net/http"- traceway "go.tracewayapp.com"- tracewaydb "go.tracewayapp.com/tracewaydb"-"github.com/gin-gonic/gin")func getCart(c *gin.Context) {ctx := c.Request.Context()- twdb := tracewaydb.NewTwDB(ctx, db)lines := []CartLine{}if fastPath() {- rows, err := twdb.QueryContext(ctx, `+ rows, err := queryContext(ctx, `SELECT ci.id, ci.product_id, p.name, p.price_cents, p.image_url, ci.qtyFROM cart_items ciJOIN products p ON p.id = ci.product_idORDER BY ci.id`)if err != nil {- c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("load cart (fast): %w", err))+ abortServerError(c, "could not load cart", fmt.Errorf("load cart (fast): %w", err))return}for rows.Next() {var l CartLineif err := rows.Scan(&l.Id, &l.ProductId, &l.Name, &l.PriceCents, &l.ImageUrl, &l.Qty); err != nil {rows.Close()- c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("scan cart line (fast): %w", err))+ abortServerError(c, "could not load cart", fmt.Errorf("scan cart line (fast): %w", err))return}l.LineTotal = l.PriceCents * l.Qty@@ -38,16 +36,16 @@ func getCart(c *gin.Context) {}rows.Close()} else {- rows, err := twdb.QueryContext(ctx, `SELECT id, product_id, qty FROM cart_items ORDER BY id`)+ rows, err := queryContext(ctx, `SELECT id, product_id, qty FROM cart_items ORDER BY id`)if err != nil {- c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("load cart: %w", err))+ abortServerError(c, "could not load cart", fmt.Errorf("load cart: %w", err))return}for rows.Next() {var l CartLineif err := rows.Scan(&l.Id, &l.ProductId, &l.Qty); err != nil {rows.Close()- c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("scan cart line: %w", err))+ abortServerError(c, "could not load cart", fmt.Errorf("scan cart line: %w", err))return}lines = append(lines, l)@@ -56,7 +54,7 @@ func getCart(c *gin.Context) {for i := range lines {slowJitter(150, 350)- prow := twdb.QueryRowContext(ctx, `SELECT name, price_cents, image_url FROM products WHERE id = ?`, lines[i].ProductId)+ prow := queryRowContext(ctx, `SELECT name, price_cents, image_url FROM products WHERE id = ?`, lines[i].ProductId)_ = prow.Scan(&lines[i].Name, &lines[i].PriceCents, &lines[i].ImageUrl)lines[i].LineTotal = lines[i].PriceCents * lines[i].Qty}@@ -80,44 +78,43 @@ func addToCart(c *gin.Context) {req.Qty = 1}- twdb := tracewaydb.NewTwDB(ctx, db)-var existing int- prow := twdb.QueryRowContext(ctx, `SELECT id FROM products WHERE id = ?`, req.ProductId)+ prow := queryRowContext(ctx, `SELECT id FROM products WHERE id = ?`, req.ProductId)if err := prow.Scan(&existing); err != nil {if errors.Is(err, sql.ErrNoRows) {c.JSON(http.StatusNotFound, gin.H{"error": "product not found"})return}- c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("lookup product: %w", err))+ abortServerError(c, "could not add to cart", fmt.Errorf("lookup product: %w", err))return}if !fastPath() {- span := traceway.StartSpan(ctx, "inventory.check")+ _, span := tracer.Start(ctx, "inventory.check")slowJitter(150, 500)span.End()+ slog.WarnContext(ctx, "inventory check responded slowly", "product_id", req.ProductId)}- if _, err := twdb.ExecContext(ctx, `INSERT INTO cart_items (product_id, qty) VALUES (?, ?)`, req.ProductId, req.Qty); err != nil {- c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("add to cart: %w", err))+ if _, err := execContext(ctx, `INSERT INTO cart_items (product_id, qty) VALUES (?, ?)`, req.ProductId, req.Qty); err != nil {+ abortServerError(c, "could not add to cart", fmt.Errorf("add to cart: %w", err))return}+ slog.InfoContext(ctx, "item added to cart", "product_id", req.ProductId, "qty", req.Qty)c.JSON(http.StatusCreated, gin.H{"status": "added"})}func removeFromCart(c *gin.Context) {ctx := c.Request.Context()id := c.Param("id")- twdb := tracewaydb.NewTwDB(ctx, db)if !fastPath() {slowJitter(50, 150)}- res, err := twdb.ExecContext(ctx, `DELETE FROM cart_items WHERE id = ?`, id)+ res, err := execContext(ctx, `DELETE FROM cart_items WHERE id = ?`, id)if err != nil {- c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("remove from cart: %w", err))+ abortServerError(c, "could not remove from cart", fmt.Errorf("remove from cart: %w", err))return}affected, _ := res.RowsAffected()@@ -125,5 +122,6 @@ func removeFromCart(c *gin.Context) {c.JSON(http.StatusNotFound, gin.H{"error": "cart item not found"})return}+ slog.InfoContext(ctx, "cart item removed", "cart_item_id", id)c.JSON(http.StatusOK, gin.H{"status": "removed"})}diff --git a/testing/shop/backend/checkout.go b/testing/shop/backend/checkout.goindex 314491eb..c40e6c0e 100644--- a/testing/shop/backend/checkout.go+++ b/testing/shop/backend/checkout.go@@ -1,14 +1,14 @@package mainimport (+ "errors""fmt"+ "log/slog""math/rand/v2""net/http"- traceway "go.tracewayapp.com"- tracewaydb "go.tracewayapp.com/tracewaydb"-"github.com/gin-gonic/gin"+ "go.opentelemetry.io/otel/metric")func checkout(c *gin.Context) {@@ -19,15 +19,13 @@ func checkout(c *gin.Context) {return}- twdb := tracewaydb.NewTwDB(ctx, db)-- rows, err := twdb.QueryContext(ctx, `+ rows, err := queryContext(ctx, `SELECT ci.id, ci.product_id, p.name, p.price_cents, p.image_url, ci.qtyFROM cart_items ciJOIN products p ON p.id = ci.product_idORDER BY ci.id`)if err != nil {- c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("load cart for checkout: %w", err))+ abortServerError(c, "could not load cart", fmt.Errorf("load cart for checkout: %w", err))return}lines := []CartLine{}@@ -35,7 +33,7 @@ func checkout(c *gin.Context) {var l CartLineif err := rows.Scan(&l.Id, &l.ProductId, &l.Name, &l.PriceCents, &l.ImageUrl, &l.Qty); err != nil {rows.Close()- c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("scan checkout line: %w", err))+ abortServerError(c, "could not load cart", fmt.Errorf("scan checkout line: %w", err))return}l.LineTotal = l.PriceCents * l.Qty@@ -44,39 +42,49 @@ func checkout(c *gin.Context) {rows.Close()if len(lines) == 0 {- traceway.CaptureExceptionWithContext(ctx, traceway.NewStackTraceErrorf("checkout attempted with empty cart"))+ recordServerError(c, errors.New("checkout attempted with empty cart"))+ slog.ErrorContext(ctx, "checkout attempted with empty cart", "email", req.Email)c.JSON(http.StatusInternalServerError, gin.H{"error": "your cart is empty"})return}- pay := traceway.StartSpan(ctx, "payment.charge")+ total := 0+ for _, l := range lines {+ total += l.LineTotal+ }+ slog.InfoContext(ctx, "checkout started", "items", len(lines), "total_cents", total)++ _, pay := tracer.Start(ctx, "payment.charge")if !fastPath() {slowJitter(300, 1200)+ slog.WarnContext(ctx, "payment gateway latency high")}pay.End()if rand.IntN(6) == 0 {- traceway.CaptureExceptionWithContext(ctx, traceway.NewStackTraceErrorf("payment declined for card ****%s", req.CardLast4))+ recordServerError(c, fmt.Errorf("payment declined for card ****%s", req.CardLast4))+ slog.ErrorContext(ctx, "payment declined", "card_last4", req.CardLast4)+ paymentsDeclined.Add(ctx, 1)c.JSON(http.StatusInternalServerError, gin.H{"error": "payment declined, please try another card"})return}- total := 0- for _, l := range lines {- total += l.LineTotal- }-firstItem := lines[0]- persist := traceway.StartSpan(ctx, "order.persist")+ persistCtx, persist := tracer.Start(ctx, "order.persist")orderId := fmt.Sprintf("ORD-%d", rand.IntN(900000)+100000)- _, err = twdb.ExecContext(ctx, `DELETE FROM cart_items`)+ _, err = execContext(persistCtx, `DELETE FROM cart_items`)persist.End()if err != nil {- c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("clear cart: %w", err))+ abortServerError(c, "could not persist order", fmt.Errorf("clear cart: %w", err))return}+ ordersPlaced.Add(ctx, 1)+ revenueCounter.Add(ctx, float64(total)/100)+ checkoutValue.Record(ctx, float64(total)/100, metric.WithAttributes())+ slog.InfoContext(ctx, "order placed", "order_id", orderId, "total_cents", total, "items", len(lines))+c.JSON(http.StatusOK, gin.H{"order_id": orderId,"total_cents": total,diff --git a/testing/shop/backend/coupon.go b/testing/shop/backend/coupon.goindex bb830042..f687022c 100644--- a/testing/shop/backend/coupon.go+++ b/testing/shop/backend/coupon.go@@ -4,12 +4,13 @@ import ("context""database/sql""errors"+ "fmt"+ "log/slog""net/http"- traceway "go.tracewayapp.com"- tracewaydb "go.tracewayapp.com/tracewaydb"-"github.com/gin-gonic/gin"+ "go.opentelemetry.io/otel/attribute"+ "go.opentelemetry.io/otel/trace")var couponHits map[string]int@@ -22,30 +23,36 @@ func applyCoupon(c *gin.Context) {return}- twdb := tracewaydb.NewTwDB(ctx, db)-- traceway.GetAttributesFromContext(ctx).SetTag("coupon_code", req.Code)+ trace.SpanFromContext(ctx).SetAttributes(attribute.String("coupon_code", req.Code))var percentOff, active int- row := twdb.QueryRowContext(ctx, `SELECT percent_off, active FROM coupons WHERE code = ?`, req.Code)+ row := queryRowContext(ctx, `SELECT percent_off, active FROM coupons WHERE code = ?`, req.Code)if err := row.Scan(&percentOff, &active); err != nil {if errors.Is(err, sql.ErrNoRows) {- c.Error(traceway.NewStackTraceErrorf("unknown coupon code: %s", req.Code))+ recordServerError(c, fmt.Errorf("unknown coupon code: %s", req.Code))+ slog.WarnContext(ctx, "unknown coupon code", "code", req.Code)+ recordCouponApplied(ctx, req.Code, "invalid")c.JSON(http.StatusInternalServerError, gin.H{"error": "invalid coupon code"})return}- c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("lookup coupon: %w", err))+ abortServerError(c, "could not apply coupon", fmt.Errorf("lookup coupon: %w", err))return}if active == 0 {+ slog.WarnContext(ctx, "expired coupon rejected", "code", req.Code)+ recordCouponApplied(ctx, req.Code, "expired")c.JSON(http.StatusBadRequest, gin.H{"error": "this coupon has expired"})return}- couponHits[req.Code]+++ if !fastPath() {+ couponHits[req.Code]+++ }- total := cartTotal(ctx, twdb)+ total := cartTotal(ctx)discount := total * percentOff / 100+ slog.InfoContext(ctx, "coupon applied", "code", req.Code, "percent_off", percentOff)+ recordCouponApplied(ctx, req.Code, "ok")c.JSON(http.StatusOK, gin.H{"code": req.Code,"percent_off": percentOff,@@ -54,8 +61,8 @@ func applyCoupon(c *gin.Context) {})}-func cartTotal(ctx context.Context, twdb *tracewaydb.TwDB) int {- row := twdb.QueryRowContext(ctx, `+func cartTotal(ctx context.Context) int {+ row := queryRowContext(ctx, `SELECT COALESCE(SUM(p.price_cents * ci.qty), 0)FROM cart_items ciJOIN products p ON p.id = ci.product_id`)diff --git a/testing/shop/backend/db_tracing.go b/testing/shop/backend/db_tracing.gonew file mode 100644index 00000000..9ba8701b--- /dev/null+++ b/testing/shop/backend/db_tracing.go@@ -0,0 +1,53 @@+package main++import (+ "context"+ "database/sql"+ "regexp"+ "strings"++ "go.opentelemetry.io/otel/attribute"+ "go.opentelemetry.io/otel/codes"+ "go.opentelemetry.io/otel/trace"+)++var wsRe = regexp.MustCompile(`\s+`)++func collapseWS(q string) string {+ return strings.TrimSpace(wsRe.ReplaceAllString(q, " "))+}++func startDbSpan(ctx context.Context, query string) (context.Context, trace.Span) {+ return tracer.Start(ctx, "db.query", trace.WithAttributes(+ attribute.String("db.system", "sqlite"),+ attribute.String("db.query.text", collapseWS(query)),+ ))+}++func queryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) {+ ctx, span := startDbSpan(ctx, query)+ defer span.End()+ rows, err := db.QueryContext(ctx, query, args...)+ if err != nil {+ span.RecordError(err)+ span.SetStatus(codes.Error, err.Error())+ }+ return rows, err+}++func queryRowContext(ctx context.Context, query string, args ...any) *sql.Row {+ ctx, span := startDbSpan(ctx, query)+ defer span.End()+ return db.QueryRowContext(ctx, query, args...)+}++func execContext(ctx context.Context, query string, args ...any) (sql.Result, error) {+ ctx, span := startDbSpan(ctx, query)+ defer span.End()+ res, err := db.ExecContext(ctx, query, args...)+ if err != nil {+ span.RecordError(err)+ span.SetStatus(codes.Error, err.Error())+ }+ return res, err+}diff --git a/testing/shop/backend/errors.go b/testing/shop/backend/errors.gonew file mode 100644index 00000000..85f20563--- /dev/null+++ b/testing/shop/backend/errors.go@@ -0,0 +1,26 @@+package main++import (+ "log/slog"+ "net/http"++ "github.com/gin-gonic/gin"+ "go.opentelemetry.io/otel/codes"+ "go.opentelemetry.io/otel/trace"+)++func abortServerError(c *gin.Context, userMsg string, err error) {+ span := trace.SpanFromContext(c.Request.Context())+ span.RecordError(err, trace.WithStackTrace(true))+ span.SetStatus(codes.Error, err.Error())+ slog.ErrorContext(c.Request.Context(), userMsg, "error", err.Error())+ c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": userMsg})+}++// recordServerError reports an error on the active span without aborting —+// for handled failure paths that still return a JSON error body themselves.+func recordServerError(c *gin.Context, err error) {+ span := trace.SpanFromContext(c.Request.Context())+ span.RecordError(err, trace.WithStackTrace(true))+ span.SetStatus(codes.Error, err.Error())+}diff --git a/testing/shop/backend/go.mod b/testing/shop/backend/go.modindex 2b9b6442..7134b726 100644--- a/testing/shop/backend/go.mod+++ b/testing/shop/backend/go.mod@@ -3,68 +3,70 @@ module testing/shopgo 1.25.1require (- github.com/gin-gonic/gin v1.11.0+ github.com/gin-gonic/gin v1.12.0+ github.com/google/uuid v1.6.0github.com/mattn/go-sqlite3 v1.14.33- go.tracewayapp.com v1.0.4- go.tracewayapp.com/tracewaydb v0.0.0-00010101000000-000000000000- go.tracewayapp.com/tracewaygin v0.0.0-00010101000000-000000000000+ github.com/shirou/gopsutil/v4 v4.26.4+ go.opentelemetry.io/contrib/bridges/otelslog v0.19.0+ go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin v0.68.0+ go.opentelemetry.io/otel v1.44.0+ go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.19.0+ go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.43.0+ go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.43.0+ go.opentelemetry.io/otel/log v0.20.0+ go.opentelemetry.io/otel/metric v1.44.0+ go.opentelemetry.io/otel/sdk v1.44.0+ go.opentelemetry.io/otel/sdk/log v0.19.0+ go.opentelemetry.io/otel/sdk/metric v1.44.0+ go.opentelemetry.io/otel/trace v1.44.0)require (- github.com/bytedance/sonic v1.14.0 // indirect- github.com/bytedance/sonic/loader v0.3.0 // indirect+ github.com/bytedance/gopkg v0.1.4 // indirect+ github.com/bytedance/sonic v1.15.0 // indirect+ github.com/bytedance/sonic/loader v0.5.1 // indirect+ github.com/cenkalti/backoff/v5 v5.0.3 // indirectgithub.com/cespare/xxhash/v2 v2.3.0 // indirectgithub.com/cloudwego/base64x v0.1.6 // indirect- github.com/ebitengine/purego v0.10.1 // indirect- github.com/gabriel-vasile/mimetype v1.4.8 // indirect- github.com/gin-contrib/sse v1.1.0 // indirect+ github.com/ebitengine/purego v0.10.0 // indirect+ github.com/gabriel-vasile/mimetype v1.4.13 // indirect+ github.com/gin-contrib/sse v1.1.1 // indirectgithub.com/go-logr/logr v1.4.3 // indirectgithub.com/go-logr/stdr v1.2.2 // indirect- github.com/go-ole/go-ole v1.3.0 // indirect+ github.com/go-ole/go-ole v1.2.6 // indirectgithub.com/go-playground/locales v0.14.1 // indirectgithub.com/go-playground/universal-translator v0.18.1 // indirect- github.com/go-playground/validator/v10 v10.27.0 // indirect- github.com/goccy/go-json v0.10.2 // indirect- github.com/goccy/go-yaml v1.18.0 // indirect- github.com/google/uuid v1.6.0 // indirect+ github.com/go-playground/validator/v10 v10.30.2 // indirect+ github.com/goccy/go-json v0.10.6 // indirect+ github.com/goccy/go-yaml v1.19.2 // indirect+ github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 // indirectgithub.com/json-iterator/go v1.1.12 // indirectgithub.com/klauspost/cpuid/v2 v2.3.0 // indirectgithub.com/leodido/go-urn v1.4.0 // indirect- github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e // indirect+ github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirectgithub.com/mattn/go-isatty v0.0.20 // indirect- github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect+ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirectgithub.com/modern-go/reflect2 v1.0.2 // indirect- github.com/pelletier/go-toml/v2 v2.2.4 // indirect+ github.com/pelletier/go-toml/v2 v2.3.0 // indirectgithub.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect- github.com/quic-go/qpack v0.5.1 // indirect- github.com/quic-go/quic-go v0.54.0 // indirect- github.com/shirou/gopsutil/v4 v4.26.4 // indirect- github.com/tklauser/go-sysconf v0.4.0 // indirect- github.com/tklauser/numcpus v0.12.0 // indirect+ github.com/quic-go/qpack v0.6.0 // indirect+ github.com/quic-go/quic-go v0.59.0 // indirect+ github.com/tklauser/go-sysconf v0.3.16 // indirect+ github.com/tklauser/numcpus v0.11.0 // indirectgithub.com/twitchyliquid64/golang-asm v0.15.1 // indirect- github.com/ugorji/go/codec v1.3.0 // indirect+ github.com/ugorji/go/codec v1.3.1 // indirectgithub.com/yusufpapurcu/wmi v1.2.4 // indirect+ go.mongodb.org/mongo-driver/v2 v2.5.0 // indirectgo.opentelemetry.io/auto/sdk v1.2.1 // indirect- go.opentelemetry.io/contrib/instrumentation/host v0.69.0 // indirect- go.opentelemetry.io/otel v1.44.0 // indirect- go.opentelemetry.io/otel/metric v1.44.0 // indirect- go.opentelemetry.io/otel/sdk v1.44.0 // indirect- go.opentelemetry.io/otel/sdk/metric v1.44.0 // indirect- go.opentelemetry.io/otel/trace v1.44.0 // indirect- go.uber.org/mock v0.5.0 // indirect- golang.org/x/arch v0.20.0 // indirect- golang.org/x/crypto v0.40.0 // indirect- golang.org/x/mod v0.25.0 // indirect- golang.org/x/net v0.42.0 // indirect- golang.org/x/sync v0.16.0 // indirect+ go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.43.0 // indirect+ go.opentelemetry.io/proto/otlp v1.10.0 // indirect+ golang.org/x/arch v0.25.0 // indirect+ golang.org/x/crypto v0.49.0 // indirect+ golang.org/x/net v0.52.0 // indirectgolang.org/x/sys v0.45.0 // indirect- golang.org/x/text v0.27.0 // indirect- golang.org/x/tools v0.34.0 // indirect- google.golang.org/protobuf v1.36.9 // indirect+ golang.org/x/text v0.35.0 // indirect+ google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9 // indirect+ google.golang.org/genproto/googleapis/rpc v0.0.0-20260401024825-9d38bb4040a9 // indirect+ google.golang.org/grpc v1.80.0 // indirect+ google.golang.org/protobuf v1.36.11 // indirect)--replace go.tracewayapp.com => ../../../../go-client--replace go.tracewayapp.com/tracewaydb => ../../../../go-client/tracewaydb--replace go.tracewayapp.com/tracewaygin => ../../../../go-client/tracewaygindiff --git a/testing/shop/backend/go.sum b/testing/shop/backend/go.sumindex 63b92f79..e1bc5014 100644--- a/testing/shop/backend/go.sum+++ b/testing/shop/backend/go.sum@@ -1,9 +1,11 @@-github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7OputlJIzU=-github.com/DATA-DOG/go-sqlmock v1.5.2/go.mod h1:88MAG/4G7SMwSE3CeA0ZKzrT5CiOU3OJ+JlNzwDqpNU=-github.com/bytedance/sonic v1.14.0 h1:/OfKt8HFw0kh2rj8N0F6C/qPGRESq0BbaNZgcNXXzQQ=-github.com/bytedance/sonic v1.14.0/go.mod h1:WoEbx8WTcFJfzCe0hbmyTGrfjt8PzNEBdxlNUO24NhA=-github.com/bytedance/sonic/loader v0.3.0 h1:dskwH8edlzNMctoruo8FPTJDF3vLtDT0sXZwvZJyqeA=-github.com/bytedance/sonic/loader v0.3.0/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI=+github.com/bytedance/gopkg v0.1.4 h1:oZnQwnX82KAIWb7033bEwtxvTqXcYMxDBaQxo5JJHWM=+github.com/bytedance/gopkg v0.1.4/go.mod h1:v1zWfPm21Fb+OsyXN2VAHdL6TBb2L88anLQgdyje6R4=+github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE=+github.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k=+github.com/bytedance/sonic/loader v0.5.1 h1:Ygpfa9zwRCCKSlrp5bBP/b/Xzc3VxsAW+5NIYXrOOpI=+github.com/bytedance/sonic/loader v0.5.1/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=+github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=+github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=@@ -11,126 +13,161 @@ github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEgithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=-github.com/ebitengine/purego v0.10.1 h1:dewVBCBT2GaMu1SrNTYxQhgQBethzfhiwvZiLGP/qyY=-github.com/ebitengine/purego v0.10.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=-github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM=-github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8=-github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=-github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=-github.com/gin-gonic/gin v1.11.0 h1:OW/6PLjyusp2PPXtyxKHU0RbX6I/l28FTdDlae5ueWk=-github.com/gin-gonic/gin v1.11.0/go.mod h1:+iq/FyxlGzII0KHiBGjuNn4UNENUlKbGlNmc+W50Dls=+github.com/ebitengine/purego v0.10.0 h1:QIw4xfpWT6GWTzaW5XEKy3HXoqrJGx1ijYHzTF0/ISU=+github.com/ebitengine/purego v0.10.0/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=+github.com/gabriel-vasile/mimetype v1.4.13 h1:46nXokslUBsAJE/wMsp5gtO500a4F3Nkz9Ufpk2AcUM=+github.com/gabriel-vasile/mimetype v1.4.13/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=+github.com/gin-contrib/sse v1.1.1 h1:uGYpNwTacv5R68bSGMapo62iLTRa9l5zxGCps4hK6ko=+github.com/gin-contrib/sse v1.1.1/go.mod h1:QXzuVkA0YO7o/gun03UI1Q+FTI8ZV/n5t03kIQAI89s=+github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8=+github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc=github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=+github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY=github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=-github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=-github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=-github.com/go-playground/validator/v10 v10.27.0 h1:w8+XrWVMhGkxOaaowyKH35gFydVHOvC0/uWoy2Fzwn4=-github.com/go-playground/validator/v10 v10.27.0/go.mod h1:I5QpIEbmr8On7W0TktmJAumgzX4CA1XNl4ZmDuVHKKo=-github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=-github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=-github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw=-github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=+github.com/go-playground/validator/v10 v10.30.2 h1:JiFIMtSSHb2/XBUbWM4i/MpeQm9ZK2xqPNk8vgvu5JQ=+github.com/go-playground/validator/v10 v10.30.2/go.mod h1:mAf2pIOVXjTEBrwUMGKkCWKKPs9NheYGabeB04txQSc=+github.com/goccy/go-json v0.10.6 h1:p8HrPJzOakx/mn/bQtjgNjdTcN+/S6FcG2CTtQOrHVU=+github.com/goccy/go-json v0.10.6/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=+github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=+github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=+github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=+github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=+github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=+github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 h1:HWRh5R2+9EifMyIHV7ZV+MIZqgz+PMpZ14Jynv3O2Zs=+github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0/go.mod h1:JfhWUomR1baixubs02l85lZYYOm7LV6om4ceouMv45c=github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=-github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e h1:Q6MvJtQK/iRcRtzAscm/zF23XxJlbECiGPyRicsX+Ak=-github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg=+github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 h1:6E+4a0GO5zZEnZ81pIr0yLvtUWk2if982qA3F3QD6H4=+github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I=github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=github.com/mattn/go-sqlite3 v1.14.33 h1:A5blZ5ulQo2AtayQ9/limgHEkFreKj1Dv226a1K73s0=github.com/mattn/go-sqlite3 v1.14.33/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=-github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=+github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=+github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=-github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=-github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=+github.com/pelletier/go-toml/v2 v2.3.0 h1:k59bC/lIZREW0/iVaQR8nDHxVq8OVlIzYCOJf421CaM=+github.com/pelletier/go-toml/v2 v2.3.0/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU=github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=-github.com/quic-go/qpack v0.5.1 h1:giqksBPnT/HDtZ6VhtFKgoLOWmlyo9Ei6u9PqzIMbhI=-github.com/quic-go/qpack v0.5.1/go.mod h1:+PC4XFrEskIVkcLzpEkbLqq1uCoxPhQuvK5rH1ZgaEg=-github.com/quic-go/quic-go v0.54.0 h1:6s1YB9QotYI6Ospeiguknbp2Znb/jZYjZLRXn9kMQBg=-github.com/quic-go/quic-go v0.54.0/go.mod h1:e68ZEaCdyviluZmy44P6Iey98v/Wfz6HCjQEm+l8zTY=+github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=+github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=+github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw=+github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU=github.com/shirou/gopsutil/v4 v4.26.4 h1:B4SXVbcwTyrocPHEmWBC4uCYr4Xcu3MK1TXqbprAOWY=github.com/shirou/gopsutil/v4 v4.26.4/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ=github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=+github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=-github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=+github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=+github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=-github.com/tklauser/go-sysconf v0.4.0 h1:7H0uAN+7RkwWRaxhYXDLqa5V3LPrJeV8wmD9dRUgPQU=-github.com/tklauser/go-sysconf v0.4.0/go.mod h1:8mTNWyog7H+MpKijp4VmKJAd2bbYQ2zuUwkYRbUArPI=-github.com/tklauser/numcpus v0.12.0 h1:NR85qdvHA9pFse3x3weVZ0r0ST8R6l5RHbZrlRaqob4=-github.com/tklauser/numcpus v0.12.0/go.mod h1:ABHeXzJnr/qqwguhClkZKT1/8VABcYrsyUiUGobwWJg=+github.com/tklauser/go-sysconf v0.3.16 h1:frioLaCQSsF5Cy1jgRBrzr6t502KIIwQ0MArYICU0nA=+github.com/tklauser/go-sysconf v0.3.16/go.mod h1:/qNL9xxDhc7tx3HSRsLWNnuzbVfh3e7gh/BmM179nYI=+github.com/tklauser/numcpus v0.11.0 h1:nSTwhKH5e1dMNsCdVBukSZrURJRoHbSEQjdEbY+9RXw=+github.com/tklauser/numcpus v0.11.0/go.mod h1:z+LwcLq54uWZTX0u/bGobaV34u6V7KNlTZejzM6/3MQ=github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=-github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA=-github.com/ugorji/go/codec v1.3.0/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=+github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY=+github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=+go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE=+go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0=go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=-go.opentelemetry.io/contrib/instrumentation/host v0.69.0 h1:N/wKAdIOKd9U4bwiwY3j95e2ZR48onTMR/NI/SZQ/a4=-go.opentelemetry.io/contrib/instrumentation/host v0.69.0/go.mod h1:rE1Bxmu3mwcmyTJV4EQdJ/C6zCUnuT9jCiinhRXLAXc=+go.opentelemetry.io/contrib/bridges/otelslog v0.19.0 h1:5RgvxieNq9tS3ewrV1vnODvbHPfKUIJcYtF9Cvz+6aQ=+go.opentelemetry.io/contrib/bridges/otelslog v0.19.0/go.mod h1:iTBIdNwx/xmUhfgJs6+84S4dIK059811cO1eUBjKcHY=+go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin v0.68.0 h1:5FXSL2s6afUC1bzNzl1iedZZ8yqR7GOhbCoEXtyeK6Q=+go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin v0.68.0/go.mod h1:MdHW7tLtkeGJnR4TyOrnd5D0zUGZQB1l84uHCe8hRpE=+go.opentelemetry.io/contrib/propagators/b3 v1.43.0 h1:CETqV3QLLPTy5yNrqyMr41VnAOOD4lsRved7n4QG00A=+go.opentelemetry.io/contrib/propagators/b3 v1.43.0/go.mod h1:Q4mCiCdziYzpNR0g+6UqVotAlCDZdzz6L8jwY4knOrw=go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU=go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=+go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.19.0 h1:HIBTQ3VO5aupLKjC90JgMqpezVXwFuq6Ryjn0/izoag=+go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.19.0/go.mod h1:ji9vId85hMxqfvICA0Jt8JqEdrXaAkcpkI9HPXya0ro=+go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.43.0 h1:w1K+pCJoPpQifuVpsKamUdn9U0zM3xUziVOqsGksUrY=+go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.43.0/go.mod h1:HBy4BjzgVE8139ieRI75oXm3EcDN+6GhD88JT1Kjvxg=+go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.43.0 h1:88Y4s2C8oTui1LGM6bTWkw0ICGcOLCAI5l6zsD1j20k=+go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.43.0/go.mod h1:Vl1/iaggsuRlrHf/hfPJPvVag77kKyvrLeD10kpMl+A=+go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.43.0 h1:3iZJKlCZufyRzPzlQhUIWVmfltrXuGyfjREgGP3UUjc=+go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.43.0/go.mod h1:/G+nUPfhq2e+qiXMGxMwumDrP5jtzU+mWN7/sjT2rak=+go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.43.0 h1:mS47AX77OtFfKG4vtp+84kuGSFZHTyxtXIN269vChY0=+go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.43.0/go.mod h1:PJnsC41lAGncJlPUniSwM81gc80GkgWJWr3cu2nKEtU=+go.opentelemetry.io/otel/log v0.20.0 h1:/5i0vuHxCLWUfChWG41K9wkM0jafruPw9NU1/RCJirs=+go.opentelemetry.io/otel/log v0.20.0/go.mod h1:wOcMcjsZpG8x7Bak7IhSi/lg8wscV2C1VdrKCLPlt0E=go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc=go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo=go.opentelemetry.io/otel/metric/x v0.66.0 h1:YkCrx1zLOChi9ZcZ6euupOcsgzbVlec7D/xoEU1+cTA=go.opentelemetry.io/otel/metric/x v0.66.0/go.mod h1:d1+BDj9t96do0/1LoU1ayfCv79ZgNE41qbhBvnMOBZk=go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58=go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0=+go.opentelemetry.io/otel/sdk/log v0.19.0 h1:scYVLqT22D2gqXItnWiocLUKGH9yvkkeql5dBDiXyko=+go.opentelemetry.io/otel/sdk/log v0.19.0/go.mod h1:vFBowwXGLlW9AvpuF7bMgnNI95LiW10szrOdvzBHlAg=+go.opentelemetry.io/otel/sdk/log/logtest v0.19.0 h1:BEbF7ZBB6qQloV/Ub1+3NQoOUnVtcGkU3XX4Ws3GQfk=+go.opentelemetry.io/otel/sdk/log/logtest v0.19.0/go.mod h1:Lua81/3yM0wOmoHTokLj9y9ADeA02v1naRrVrkAZuKk=go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI=go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA=go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=-go.uber.org/mock v0.5.0 h1:KAMbZvZPyBPWgD14IrIQ38QCyjwpvVVV6K/bHl1IwQU=-go.uber.org/mock v0.5.0/go.mod h1:ge71pBPLYDk7QIi1LupWxdAykm7KIEFchiOqd6z7qMM=-golang.org/x/arch v0.20.0 h1:dx1zTU0MAE98U+TQ8BLl7XsJbgze2WnNKF/8tGp/Q6c=-golang.org/x/arch v0.20.0/go.mod h1:bdwinDaKcfZUGpH09BB7ZmOfhalA8lQdzl62l8gGWsk=-golang.org/x/crypto v0.40.0 h1:r4x+VvoG5Fm+eJcxMaY8CQM7Lb0l1lsmjGBQ6s8BfKM=-golang.org/x/crypto v0.40.0/go.mod h1:Qr1vMER5WyS2dfPHAlsOj01wgLbsyWtFn/aY+5+ZdxY=-golang.org/x/mod v0.25.0 h1:n7a+ZbQKQA/Ysbyb0/6IbB1H/X41mKgbhfv7AfG/44w=-golang.org/x/mod v0.25.0/go.mod h1:IXM97Txy2VM4PJ3gI61r1YEk/gAj6zAHN3AdZt6S9Ww=-golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs=-golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8=-golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw=-golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=+go.opentelemetry.io/proto/otlp v1.10.0 h1:IQRWgT5srOCYfiWnpqUYz9CVmbO8bFmKcwYxpuCSL2g=+go.opentelemetry.io/proto/otlp v1.10.0/go.mod h1:/CV4QoCR/S9yaPj8utp3lvQPoqMtxXdzn7ozvvozVqk=+go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=+go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=+go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=+go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=+golang.org/x/arch v0.25.0 h1:qnk6Ksugpi5Bz32947rkUgDt9/s5qvqDPl/gBKdMJLE=+golang.org/x/arch v0.25.0/go.mod h1:0X+GdSIP+kL5wPmpK7sdkEVTt2XoYP0cSjQSbZBwOi8=+golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4=+golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA=+golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0=+golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw=golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=-golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=-golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4=-golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU=-golang.org/x/tools v0.34.0 h1:qIpSLOxeCYGg9TrcJokLBG4KFA6d795g0xkBkiESGlo=-golang.org/x/tools v0.34.0/go.mod h1:pAP9OwEaY1CAW3HOmg3hLZC5Z0CCmzjAF2UQMSqNARg=-google.golang.org/protobuf v1.36.9 h1:w2gp2mA27hUeUzj9Ex9FBjsBm40zfaDtEWow293U7Iw=-google.golang.org/protobuf v1.36.9/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=+golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8=+golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA=+golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=+gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=+gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=+google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9 h1:VPWxll4HlMw1Vs/qXtN7BvhZqsS9cdAittCNvVENElA=+google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9/go.mod h1:7QBABkRtR8z+TEnmXTqIqwJLlzrZKVfAUm7tY3yGv0M=+google.golang.org/genproto/googleapis/rpc v0.0.0-20260401024825-9d38bb4040a9 h1:m8qni9SQFH0tJc1X0vmnpw/0t+AImlSvp30sEupozUg=+google.golang.org/genproto/googleapis/rpc v0.0.0-20260401024825-9d38bb4040a9/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=+google.golang.org/grpc v1.80.0 h1:Xr6m2WmWZLETvUNvIUmeD5OAagMw3FiKmMlTdViWsHM=+google.golang.org/grpc v1.80.0/go.mod h1:ho/dLnxwi3EDJA4Zghp7k2Ec1+c2jqup0bFkw07bwF4=+google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=+google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=diff --git a/testing/shop/backend/main.go b/testing/shop/backend/main.goindex d0060747..d418bcd1 100644--- a/testing/shop/backend/main.go+++ b/testing/shop/backend/main.go@@ -1,14 +1,19 @@package mainimport (+ "context""database/sql"+ "errors"+ "log/slog""net/http""os"-- tracewaygin "go.tracewayapp.com/tracewaygin"+ "os/signal"+ "syscall"+ "time""github.com/gin-gonic/gin"_ "github.com/mattn/go-sqlite3"+ "go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin")var db *sql.DB@@ -16,20 +21,18 @@ var db *sql.DBfunc main() {initDB()- endpoint := os.Getenv("TRACEWAY_ENDPOINT")- if endpoint == "" {- endpoint = "default_token_change_me@http://localhost:8082/api/report"+ ctx := context.Background()+ shutdownTelemetry, err := initTelemetry(ctx)+ if err != nil {+ slog.Error("telemetry init failed", "error", err.Error())+ os.Exit(1)}router := gin.Default()router.Use(corsMiddleware())- router.Use(tracewaygin.New(- endpoint,- tracewaygin.WithDebug(true),- tracewaygin.WithServerName("shop-demo"),- tracewaygin.WithVersion("0.1.0"),- tracewaygin.WithOnErrorRecording(tracewaygin.RecordingUrl|tracewaygin.RecordingQuery|tracewaygin.RecordingHeader|tracewaygin.RecordingBody),- ))+ router.Use(otelgin.Middleware(serviceName, otelgin.WithGinFilter(traceFilter)))+ router.Use(otelRecovery())+ router.Use(distributedTraceMiddleware())router.GET("/api/health", func(c *gin.Context) {c.JSON(http.StatusOK, gin.H{"status": "ok"})@@ -45,20 +48,25 @@ func main() {router.POST("/api/coupon", applyCoupon)router.POST("/api/checkout", checkout)- registerFrontend(router)+ router.POST("/api/support/chat", supportChat)- router.Run(":8090")-}+ registerFrontend(router)-func corsMiddleware() gin.HandlerFunc {- return func(c *gin.Context) {- c.Header("Access-Control-Allow-Origin", "*")- c.Header("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS")- c.Header("Access-Control-Allow-Headers", "Content-Type, Authorization")- if c.Request.Method == http.MethodOptions {- c.AbortWithStatus(http.StatusNoContent)- return+ srv := &http.Server{Addr: ":8090", Handler: router}+ go func() {+ if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {+ slog.Error("server failed", "error", err.Error())+ os.Exit(1)}- c.Next()- }+ }()++ stopCtx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)+ defer stop()+ <-stopCtx.Done()++ slog.Info("shutting down, flushing telemetry")+ shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ _ = srv.Shutdown(shutdownCtx)+ shutdownTelemetry(shutdownCtx)}diff --git a/testing/shop/backend/metrics.go b/testing/shop/backend/metrics.gonew file mode 100644index 00000000..f33560d9--- /dev/null+++ b/testing/shop/backend/metrics.go@@ -0,0 +1,173 @@+package main++import (+ "context"+ "runtime"++ "github.com/shirou/gopsutil/v4/cpu"+ "github.com/shirou/gopsutil/v4/disk"+ "github.com/shirou/gopsutil/v4/load"+ gopsmem "github.com/shirou/gopsutil/v4/mem"+ "go.opentelemetry.io/otel"+ "go.opentelemetry.io/otel/attribute"+ "go.opentelemetry.io/otel/metric"+)++var (+ ordersPlaced metric.Int64Counter+ revenueCounter metric.Float64Counter+ checkoutValue metric.Float64Histogram+ paymentsDeclined metric.Int64Counter+ couponsApplied metric.Int64Counter+ couponFailures metric.Int64Counter+)++func recordCouponFailure(ctx context.Context) {+ if couponFailures != nil {+ couponFailures.Add(ctx, 1)+ }+}++func recordCouponApplied(ctx context.Context, code, result string) {+ if couponsApplied != nil {+ couponsApplied.Add(ctx, 1, metric.WithAttributes(+ attribute.String("code", code),+ attribute.String("result", result),+ ))+ }+}++func initMetrics() error {+ meter := otel.Meter(serviceName)+ var err error++ if ordersPlaced, err = meter.Int64Counter("shop.orders.placed", metric.WithUnit("1")); err != nil {+ return err+ }+ if revenueCounter, err = meter.Float64Counter("shop.revenue", metric.WithUnit("USD")); err != nil {+ return err+ }+ if checkoutValue, err = meter.Float64Histogram("shop.checkout.value", metric.WithUnit("USD")); err != nil {+ return err+ }+ if paymentsDeclined, err = meter.Int64Counter("shop.payments.declined", metric.WithUnit("1")); err != nil {+ return err+ }+ if couponsApplied, err = meter.Int64Counter("shop.coupons.applied", metric.WithUnit("1")); err != nil {+ return err+ }+ if couponFailures, err = meter.Int64Counter("shop.coupon.failures", metric.WithUnit("1")); err != nil {+ return err+ }++ cartItems, err := meter.Int64ObservableGauge("shop.cart.items", metric.WithUnit("1"))+ if err != nil {+ return err+ }++ // Built-in dashboard pages: Server Metrics reads cpu.used_pcnt / mem.used /+ // mem.total, Application Metrics reads the go.* family.+ cpuUsedPcnt, err := meter.Float64ObservableGauge("cpu.used_pcnt", metric.WithUnit("%"))+ if err != nil {+ return err+ }+ memUsed, err := meter.Float64ObservableGauge("mem.used", metric.WithUnit("MB"))+ if err != nil {+ return err+ }+ memTotal, err := meter.Float64ObservableGauge("mem.total", metric.WithUnit("MB"))+ if err != nil {+ return err+ }+ goRoutines, err := meter.Int64ObservableGauge("go.go_routines", metric.WithUnit("1"))+ if err != nil {+ return err+ }+ heapObjects, err := meter.Int64ObservableGauge("go.heap_objects", metric.WithUnit("1"))+ if err != nil {+ return err+ }+ numGC, err := meter.Int64ObservableGauge("go.num_gc", metric.WithUnit("1"))+ if err != nil {+ return err+ }+ gcPause, err := meter.Float64ObservableGauge("go.gc_pause", metric.WithUnit("ns"))+ if err != nil {+ return err+ }++ // hostmetrics-style names charted by the "OTelemetry Server Agent" template.+ sysCPUUtil, err := meter.Float64ObservableGauge("system.cpu.utilization", metric.WithUnit("1"))+ if err != nil {+ return err+ }+ load1, err := meter.Float64ObservableGauge("system.cpu.load_average.1m", metric.WithUnit("1"))+ if err != nil {+ return err+ }+ load5, err := meter.Float64ObservableGauge("system.cpu.load_average.5m", metric.WithUnit("1"))+ if err != nil {+ return err+ }+ load15, err := meter.Float64ObservableGauge("system.cpu.load_average.15m", metric.WithUnit("1"))+ if err != nil {+ return err+ }+ sysMemUsage, err := meter.Float64ObservableGauge("system.memory.usage", metric.WithUnit("By"))+ if err != nil {+ return err+ }+ sysMemUtil, err := meter.Float64ObservableGauge("system.memory.utilization", metric.WithUnit("1"))+ if err != nil {+ return err+ }+ fsUsage, err := meter.Float64ObservableGauge("system.filesystem.usage", metric.WithUnit("By"))+ if err != nil {+ return err+ }+ fsUtil, err := meter.Float64ObservableGauge("system.filesystem.utilization", metric.WithUnit("1"))+ if err != nil {+ return err+ }++ var lastNumGC uint32+ _, err = meter.RegisterCallback(func(ctx context.Context, o metric.Observer) error {+ var totalCart int64+ row := db.QueryRowContext(ctx, `SELECT COALESCE(SUM(qty), 0) FROM cart_items`)+ _ = row.Scan(&totalCart)+ o.ObserveInt64(cartItems, totalCart)++ if pcts, err := cpu.Percent(0, false); err == nil && len(pcts) > 0 {+ o.ObserveFloat64(cpuUsedPcnt, pcts[0])+ o.ObserveFloat64(sysCPUUtil, pcts[0]/100)+ }+ if vm, err := gopsmem.VirtualMemory(); err == nil {+ o.ObserveFloat64(memUsed, float64(vm.Used)/1024/1024)+ o.ObserveFloat64(memTotal, float64(vm.Total)/1024/1024)+ o.ObserveFloat64(sysMemUsage, float64(vm.Used))+ o.ObserveFloat64(sysMemUtil, vm.UsedPercent/100)+ }+ if avg, err := load.Avg(); err == nil {+ o.ObserveFloat64(load1, avg.Load1)+ o.ObserveFloat64(load5, avg.Load5)+ o.ObserveFloat64(load15, avg.Load15)+ }+ if du, err := disk.Usage("/"); err == nil {+ o.ObserveFloat64(fsUsage, float64(du.Used))+ o.ObserveFloat64(fsUtil, du.UsedPercent/100)+ }++ var ms runtime.MemStats+ runtime.ReadMemStats(&ms)+ o.ObserveInt64(goRoutines, int64(runtime.NumGoroutine()))+ o.ObserveInt64(heapObjects, int64(ms.HeapObjects))+ o.ObserveInt64(numGC, int64(ms.NumGC-lastNumGC))+ lastNumGC = ms.NumGC+ if ms.NumGC > 0 {+ o.ObserveFloat64(gcPause, float64(ms.PauseNs[(ms.NumGC+255)%256]))+ }+ return nil+ }, cartItems, cpuUsedPcnt, memUsed, memTotal, goRoutines, heapObjects, numGC, gcPause,+ sysCPUUtil, load1, load5, load15, sysMemUsage, sysMemUtil, fsUsage, fsUtil)+ return err+}diff --git a/testing/shop/backend/middleware.go b/testing/shop/backend/middleware.gonew file mode 100644index 00000000..f67e8ca9--- /dev/null+++ b/testing/shop/backend/middleware.go@@ -0,0 +1,70 @@+package main++import (+ "fmt"+ "log/slog"+ "net/http"+ "strings"++ "github.com/gin-gonic/gin"+ "github.com/google/uuid"+ "go.opentelemetry.io/otel/attribute"+ "go.opentelemetry.io/otel/codes"+ "go.opentelemetry.io/otel/trace"+)++func corsMiddleware() gin.HandlerFunc {+ return func(c *gin.Context) {+ c.Header("Access-Control-Allow-Origin", "*")+ c.Header("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS")+ c.Header("Access-Control-Allow-Headers", "Content-Type, Authorization, traceway-trace-id")+ c.Header("Access-Control-Expose-Headers", "traceway-trace-id")+ if c.Request.Method == http.MethodOptions {+ c.AbortWithStatus(http.StatusNoContent)+ return+ }+ c.Next()+ }+}++// Only /api requests should become endpoint spans; the embedded SPA assets+// would otherwise each get their own endpoint row.+func traceFilter(c *gin.Context) bool {+ path := c.Request.URL.Path+ return strings.HasPrefix(path, "/api") && path != "/api/health"+}++func otelRecovery() gin.HandlerFunc {+ return func(c *gin.Context) {+ defer func() {+ if r := recover(); r != nil {+ err, ok := r.(error)+ if !ok {+ err = fmt.Errorf("panic: %v", r)+ }+ span := trace.SpanFromContext(c.Request.Context())+ span.RecordError(err, trace.WithStackTrace(true))+ span.SetStatus(codes.Error, err.Error())+ slog.ErrorContext(c.Request.Context(), "panic recovered", "error", err.Error(), "path", c.Request.URL.Path)+ if strings.HasPrefix(c.Request.URL.Path, "/api/coupon") {+ recordCouponFailure(c.Request.Context())+ }+ c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "internal error"})+ }+ }()+ c.Next()+ }+}++func distributedTraceMiddleware() gin.HandlerFunc {+ return func(c *gin.Context) {+ if raw := c.GetHeader("traceway-trace-id"); raw != "" {+ if id, err := uuid.Parse(raw); err == nil {+ trace.SpanFromContext(c.Request.Context()).+ SetAttributes(attribute.String("traceway.distributed_trace_id", id.String()))+ c.Header("traceway-trace-id", id.String())+ }+ }+ c.Next()+ }+}diff --git a/testing/shop/backend/products.go b/testing/shop/backend/products.goindex 1794a6c2..4a5ca070 100644--- a/testing/shop/backend/products.go+++ b/testing/shop/backend/products.go@@ -3,20 +3,18 @@ package mainimport ("database/sql""errors"+ "fmt"+ "log/slog""net/http"- traceway "go.tracewayapp.com"- tracewaydb "go.tracewayapp.com/tracewaydb"-"github.com/gin-gonic/gin")func listProducts(c *gin.Context) {ctx := c.Request.Context()- twdb := tracewaydb.NewTwDB(ctx, db)if fastPath() {- rows, err := twdb.QueryContext(ctx, `+ rows, err := queryContext(ctx, `SELECT p.id, p.name, p.description, p.price_cents, p.image_url, p.stock, p.category_id,c.name AS category, COUNT(r.id) AS review_countFROM products p@@ -25,7 +23,7 @@ func listProducts(c *gin.Context) {GROUP BY p.idORDER BY p.id`)if err != nil {- c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("list products (fast): %w", err))+ abortServerError(c, "could not load products", fmt.Errorf("list products (fast): %w", err))return}products := []Product{}@@ -33,19 +31,20 @@ func listProducts(c *gin.Context) {var p Productif err := rows.Scan(&p.Id, &p.Name, &p.Description, &p.PriceCents, &p.ImageUrl, &p.Stock, &p.CategoryId, &p.Category, &p.ReviewCount); err != nil {rows.Close()- c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("scan product (fast): %w", err))+ abortServerError(c, "could not load products", fmt.Errorf("scan product (fast): %w", err))return}products = append(products, p)}rows.Close()+ slog.InfoContext(ctx, "listing products", "count", len(products), "fast_path", true)c.JSON(http.StatusOK, products)return}- rows, err := twdb.QueryContext(ctx, `SELECT id, name, description, price_cents, image_url, stock, category_id FROM products ORDER BY id`)+ rows, err := queryContext(ctx, `SELECT id, name, description, price_cents, image_url, stock, category_id FROM products ORDER BY id`)if err != nil {- c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("list products: %w", err))+ abortServerError(c, "could not load products", fmt.Errorf("list products: %w", err))return}products := []Product{}@@ -53,48 +52,49 @@ func listProducts(c *gin.Context) {var p Productif err := rows.Scan(&p.Id, &p.Name, &p.Description, &p.PriceCents, &p.ImageUrl, &p.Stock, &p.CategoryId); err != nil {rows.Close()- c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("scan product: %w", err))+ abortServerError(c, "could not load products", fmt.Errorf("scan product: %w", err))return}products = append(products, p)}rows.Close()+ slog.WarnContext(ctx, "product catalog lookup fanned out per-row", "count", len(products))for i := range products {slowJitter(200, 300)- catRow := twdb.QueryRowContext(ctx, `SELECT name FROM categories WHERE id = ?`, products[i].CategoryId)+ catRow := queryRowContext(ctx, `SELECT name FROM categories WHERE id = ?`, products[i].CategoryId)_ = catRow.Scan(&products[i].Category)- countRow := twdb.QueryRowContext(ctx, `SELECT COUNT(*) FROM reviews WHERE product_id = ?`, products[i].Id)+ countRow := queryRowContext(ctx, `SELECT COUNT(*) FROM reviews WHERE product_id = ?`, products[i].Id)_ = countRow.Scan(&products[i].ReviewCount)}+ slog.InfoContext(ctx, "listing products", "count", len(products), "fast_path", false)c.JSON(http.StatusOK, products)}func getProduct(c *gin.Context) {ctx := c.Request.Context()id := c.Param("id")- twdb := tracewaydb.NewTwDB(ctx, db)var detail ProductDetail- row := twdb.QueryRowContext(ctx, `SELECT id, name, description, price_cents, image_url, stock, category_id FROM products WHERE id = ?`, id)+ row := queryRowContext(ctx, `SELECT id, name, description, price_cents, image_url, stock, category_id FROM products WHERE id = ?`, id)if err := row.Scan(&detail.Id, &detail.Name, &detail.Description, &detail.PriceCents, &detail.ImageUrl, &detail.Stock, &detail.CategoryId); err != nil {if errors.Is(err, sql.ErrNoRows) {c.JSON(http.StatusNotFound, gin.H{"error": "product not found"})return}- c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("get product: %w", err))+ abortServerError(c, "could not load product", fmt.Errorf("get product: %w", err))return}- catRow := twdb.QueryRowContext(ctx, `SELECT name FROM categories WHERE id = ?`, detail.CategoryId)+ catRow := queryRowContext(ctx, `SELECT name FROM categories WHERE id = ?`, detail.CategoryId)_ = catRow.Scan(&detail.Category)if fastPath() {- rows, err := twdb.QueryContext(ctx, `SELECT id, product_id, rating, body FROM reviews WHERE product_id = ? ORDER BY id`, detail.Id)+ rows, err := queryContext(ctx, `SELECT id, product_id, rating, body FROM reviews WHERE product_id = ? ORDER BY id`, detail.Id)if err != nil {- c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("get reviews (fast): %w", err))+ abortServerError(c, "could not load reviews", fmt.Errorf("get reviews (fast): %w", err))return}for rows.Next() {@@ -109,11 +109,11 @@ func getProduct(c *gin.Context) {return}- span := traceway.StartSpan(ctx, "load_reviews")- idRows, err := twdb.QueryContext(ctx, `SELECT id FROM reviews WHERE product_id = ?`, detail.Id)+ reviewCtx, span := tracer.Start(ctx, "load_reviews")+ idRows, err := queryContext(reviewCtx, `SELECT id FROM reviews WHERE product_id = ?`, detail.Id)if err != nil {span.End()- c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("list review ids: %w", err))+ abortServerError(c, "could not load reviews", fmt.Errorf("list review ids: %w", err))return}reviewIds := []int{}@@ -125,17 +125,18 @@ func getProduct(c *gin.Context) {}idRows.Close()+ slog.WarnContext(reviewCtx, "reviews loaded one query per row", "review_count", len(reviewIds), "product_id", detail.Id)for _, rid := range reviewIds {slowJitter(150, 300)var rv Review- rrow := twdb.QueryRowContext(ctx, `SELECT id, product_id, rating, body FROM reviews WHERE id = ?`, rid)+ rrow := queryRowContext(reviewCtx, `SELECT id, product_id, rating, body FROM reviews WHERE id = ?`, rid)if err := rrow.Scan(&rv.Id, &rv.ProductId, &rv.Rating, &rv.Body); err == nil {detail.Reviews = append(detail.Reviews, rv)}}span.End()- rec := traceway.StartSpan(ctx, "recommendations.fetch")+ _, rec := tracer.Start(ctx, "recommendations.fetch")slowJitter(300, 700)rec.End()diff --git a/testing/shop/backend/support.go b/testing/shop/backend/support.gonew file mode 100644index 00000000..b0c2ccf5--- /dev/null+++ b/testing/shop/backend/support.go@@ -0,0 +1,159 @@+package main++import (+ "encoding/json"+ "fmt"+ "log/slog"+ "math/rand/v2"+ "net/http"+ "strings"+ "sync"+ "time"++ "github.com/gin-gonic/gin"+ "go.opentelemetry.io/otel/attribute"+ "go.opentelemetry.io/otel/trace"+)++type chatMessage struct {+ Role string `json:"role"`+ Content string `json:"content"`+}++type supportChatRequest struct {+ ConversationId string `json:"conversation_id"`+ UserId string `json:"user_id"`+ Message string `json:"message"`+}++var (+ conversationsMu sync.Mutex+ conversations = map[string][]chatMessage{}+)++const supportModel = "gpt-4o-mini"++const supportSystemPrompt = "You are the Shoply support assistant. Answer questions about orders, returns and products. Use the lookup_order tool when the customer asks about a specific order."++func supportChat(c *gin.Context) {+ ctx := c.Request.Context()+ var req supportChatRequest+ if err := c.ShouldBindJSON(&req); err != nil {+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }+ if req.ConversationId == "" || req.Message == "" {+ c.JSON(http.StatusBadRequest, gin.H{"error": "conversation_id and message are required"})+ return+ }++ conversationsMu.Lock()+ history := conversations[req.ConversationId]+ if len(history) == 0 {+ history = []chatMessage{{Role: "system", Content: supportSystemPrompt}}+ }+ history = append(history, chatMessage{Role: "user", Content: req.Message})+ conversationsMu.Unlock()++ slog.InfoContext(ctx, "support chat message received",+ "conversation_id", req.ConversationId, "user_id", req.UserId)++ lower := strings.ToLower(req.Message)+ var reply string++ if strings.Contains(lower, "order") && strings.Contains(strings.ToUpper(req.Message), "ORD-") {+ orderId := extractOrderId(req.Message)++ toolCallsCompletion := fmt.Sprintf(`{"choices":[{"message":{"role":"assistant","content":null,"tool_calls":[{"id":"call_1","type":"function","function":{"name":"lookup_order","arguments":"{\"order_id\":\"%s\"}"}}]},"finish_reason":"tool_calls"}]}`, orderId)+ emitModelSpan(c, req, history, toolCallsCompletion, "tool_calls")++ toolResult := runLookupOrderTool(c, orderId)++ history = append(history,+ chatMessage{Role: "assistant", Content: fmt.Sprintf("[tool_call lookup_order(%s)]", orderId)},+ chatMessage{Role: "tool", Content: toolResult},+ )+ reply = fmt.Sprintf("I checked order %s for you — it shipped yesterday via DHL and is expected to arrive within 2 business days. Tracking: DH%08d.", orderId, rand.IntN(100000000))+ emitModelSpan(c, req, history, assistantCompletion(reply), "stop")+ } else {+ switch {+ case strings.Contains(lower, "return") || strings.Contains(lower, "refund"):+ reply = "You can return any item within 30 days of delivery for a full refund. Head to Orders → Return item, print the prepaid label, and drop the parcel at any pickup point. Refunds land within 5 business days of us receiving it."+ case strings.Contains(lower, "candle") || strings.Contains(lower, "scent"):+ reply = "The Scented Candle is a cedar and sage soy blend with roughly 40 hours of burn time. It's hand-poured, and the jar is reusable. It's one of our most re-ordered Home items."+ case strings.Contains(lower, "ship"):+ reply = "Standard shipping is free over $50 and takes 2-4 business days. Express (next business day) is $9.90 at checkout."+ case strings.Contains(lower, "bullshit") || strings.Contains(lower, "terrible") || strings.Contains(lower, "angry"):+ reply = "I'm really sorry about the experience — that's not the bar we hold ourselves to. I've flagged this conversation for a senior support agent, and in the meantime I can start a refund or replacement right away. Which would you prefer?"+ default:+ reply = "Happy to help! I can look up an order by its ORD- number, explain our return policy, or answer product questions. What do you need?"+ }+ emitModelSpan(c, req, history, assistantCompletion(reply), "stop")+ }++ history = append(history, chatMessage{Role: "assistant", Content: reply})+ conversationsMu.Lock()+ conversations[req.ConversationId] = history+ conversationsMu.Unlock()++ c.JSON(http.StatusOK, gin.H{"reply": reply, "conversation_id": req.ConversationId})+}++func emitModelSpan(c *gin.Context, req supportChatRequest, history []chatMessage, completion, finishReason string) {+ ctx := c.Request.Context()+ promptJSON, _ := json.Marshal(gin.H{"messages": history})+ promptTokens := int64(len(promptJSON) / 4)+ outputTokens := int64(len(completion) / 4)++ _, span := tracer.Start(ctx, "chat "+supportModel, trace.WithSpanKind(trace.SpanKindClient))+ span.SetAttributes(+ attribute.String("trace.name", "Support Chat Agent"),+ attribute.String("gen_ai.system", "openai"),+ attribute.String("gen_ai.operation.name", "chat"),+ attribute.String("gen_ai.request.model", supportModel),+ attribute.String("gen_ai.response.model", supportModel),+ attribute.String("gen_ai.conversation.id", req.ConversationId),+ attribute.String("user.id", req.UserId),+ attribute.Int64("gen_ai.usage.input_tokens", promptTokens),+ attribute.Int64("gen_ai.usage.output_tokens", outputTokens),+ attribute.Float64("gen_ai.usage.input_cost", float64(promptTokens)*0.15/1_000_000),+ attribute.Float64("gen_ai.usage.output_cost", float64(outputTokens)*0.60/1_000_000),+ attribute.String("gen_ai.response.finish_reason", finishReason),+ attribute.String("gen_ai.prompt", string(promptJSON)),+ attribute.String("gen_ai.completion", completion),+ )+ time.Sleep(time.Duration(400+rand.IntN(700)) * time.Millisecond)+ span.End()+}++func runLookupOrderTool(c *gin.Context, orderId string) string {+ ctx := c.Request.Context()+ _, span := tracer.Start(ctx, "tool lookup_order", trace.WithAttributes(+ attribute.String("tool.name", "lookup_order"),+ attribute.String("tool.args", fmt.Sprintf(`{"order_id":"%s"}`, orderId)),+ ))+ time.Sleep(time.Duration(80+rand.IntN(150)) * time.Millisecond)+ span.End()+ return fmt.Sprintf(`{"order_id":"%s","status":"shipped","carrier":"DHL","eta_days":2}`, orderId)+}++func assistantCompletion(reply string) string {+ b, _ := json.Marshal(gin.H{"choices": []gin.H{{+ "message": gin.H{"role": "assistant", "content": reply},+ "finish_reason": "stop",+ }}})+ return string(b)+}++func extractOrderId(message string) string {+ upper := strings.ToUpper(message)+ idx := strings.Index(upper, "ORD-")+ if idx < 0 {+ return "ORD-000000"+ }+ end := idx + 4+ for end < len(upper) && upper[end] >= '0' && upper[end] <= '9' {+ end+++ }+ return upper[idx:end]+}diff --git a/testing/shop/backend/telemetry.go b/testing/shop/backend/telemetry.gonew file mode 100644index 00000000..7d263190--- /dev/null+++ b/testing/shop/backend/telemetry.go@@ -0,0 +1,163 @@+package main++import (+ "context"+ "fmt"+ "log/slog"+ "os"+ "time"++ "go.opentelemetry.io/contrib/bridges/otelslog"+ "go.opentelemetry.io/otel"+ "go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp"+ "go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp"+ "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"+ "go.opentelemetry.io/otel/log/global"+ "go.opentelemetry.io/otel/propagation"+ sdklog "go.opentelemetry.io/otel/sdk/log"+ sdkmetric "go.opentelemetry.io/otel/sdk/metric"+ "go.opentelemetry.io/otel/sdk/metric/metricdata"+ "go.opentelemetry.io/otel/sdk/resource"+ sdktrace "go.opentelemetry.io/otel/sdk/trace"+ semconv "go.opentelemetry.io/otel/semconv/v1.26.0"+ "go.opentelemetry.io/otel/trace"+)++var (+ serviceName string+ tracer trace.Tracer+)++func initTelemetry(ctx context.Context) (func(context.Context), error) {+ base := os.Getenv("TRACEWAY_URL")+ if base == "" {+ base = "https://cloud.tracewayapp.com"+ }+ token := os.Getenv("TRACEWAY_BACKEND_TOKEN")+ if token == "" {+ return nil, fmt.Errorf("TRACEWAY_BACKEND_TOKEN is required")+ }+ serviceName = os.Getenv("TRACEWAY_SERVICE_NAME")+ if serviceName == "" {+ serviceName = "shop-backend"+ }+ headers := map[string]string{"Authorization": "Bearer " + token}++ hostname, _ := os.Hostname()+ res, err := resource.New(ctx, resource.WithAttributes(+ semconv.ServiceName(serviceName),+ semconv.ServiceVersion("0.1.0"),+ semconv.HostName(hostname),+ ))+ if err != nil {+ return nil, fmt.Errorf("resource: %w", err)+ }++ traceExporter, err := otlptracehttp.New(ctx,+ otlptracehttp.WithEndpointURL(base+"/api/otel/v1/traces"),+ otlptracehttp.WithHeaders(headers),+ )+ if err != nil {+ return nil, fmt.Errorf("trace exporter: %w", err)+ }++ // Delta temporality: Traceway stores Sum data points verbatim, so cumulative+ // counters would chart as ever-growing ramps instead of per-interval values.+ metricExporter, err := otlpmetrichttp.New(ctx,+ otlpmetrichttp.WithEndpointURL(base+"/api/otel/v1/metrics"),+ otlpmetrichttp.WithHeaders(headers),+ otlpmetrichttp.WithTemporalitySelector(func(sdkmetric.InstrumentKind) metricdata.Temporality {+ return metricdata.DeltaTemporality+ }),+ )+ if err != nil {+ return nil, fmt.Errorf("metric exporter: %w", err)+ }++ logExporter, err := otlploghttp.New(ctx,+ otlploghttp.WithEndpointURL(base+"/api/otel/v1/logs"),+ otlploghttp.WithHeaders(headers),+ )+ if err != nil {+ return nil, fmt.Errorf("log exporter: %w", err)+ }++ tp := sdktrace.NewTracerProvider(+ sdktrace.WithBatcher(traceExporter, sdktrace.WithBatchTimeout(2*time.Second)),+ sdktrace.WithResource(res),+ )+ otel.SetTracerProvider(tp)+ tracer = tp.Tracer(serviceName)++ mp := sdkmetric.NewMeterProvider(+ sdkmetric.WithReader(sdkmetric.NewPeriodicReader(metricExporter, sdkmetric.WithInterval(15*time.Second))),+ sdkmetric.WithResource(res),+ )+ otel.SetMeterProvider(mp)++ lp := sdklog.NewLoggerProvider(+ sdklog.WithProcessor(sdklog.NewBatchProcessor(logExporter, sdklog.WithExportInterval(2*time.Second))),+ sdklog.WithResource(res),+ )+ global.SetLoggerProvider(lp)++ otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(+ propagation.TraceContext{}, propagation.Baggage{},+ ))++ slog.SetDefault(slog.New(multiHandler{handlers: []slog.Handler{+ slog.NewTextHandler(os.Stdout, nil),+ otelslog.NewHandler(serviceName, otelslog.WithLoggerProvider(lp)),+ }}))++ if err := initMetrics(); err != nil {+ return nil, fmt.Errorf("metrics: %w", err)+ }++ return func(ctx context.Context) {+ _ = tp.Shutdown(ctx)+ _ = mp.Shutdown(ctx)+ _ = lp.Shutdown(ctx)+ }, nil+}++type multiHandler struct {+ handlers []slog.Handler+}++func (m multiHandler) Enabled(ctx context.Context, level slog.Level) bool {+ for _, h := range m.handlers {+ if h.Enabled(ctx, level) {+ return true+ }+ }+ return false+}++func (m multiHandler) Handle(ctx context.Context, record slog.Record) error {+ var firstErr error+ for _, h := range m.handlers {+ if h.Enabled(ctx, record.Level) {+ if err := h.Handle(ctx, record.Clone()); err != nil && firstErr == nil {+ firstErr = err+ }+ }+ }+ return firstErr+}++func (m multiHandler) WithAttrs(attrs []slog.Attr) slog.Handler {+ next := make([]slog.Handler, len(m.handlers))+ for i, h := range m.handlers {+ next[i] = h.WithAttrs(attrs)+ }+ return multiHandler{handlers: next}+}++func (m multiHandler) WithGroup(name string) slog.Handler {+ next := make([]slog.Handler, len(m.handlers))+ for i, h := range m.handlers {+ next[i] = h.WithGroup(name)+ }+ return multiHandler{handlers: next}+}diff --git a/testing/shop/frontend/src/App.jsx b/testing/shop/frontend/src/App.jsxindex fe517d8f..136e67ff 100644--- a/testing/shop/frontend/src/App.jsx+++ b/testing/shop/frontend/src/App.jsx@@ -1,5 +1,7 @@import React, { useState, useEffect } from 'react'+import { setAttributes } from '@tracewayapp/react'import { getCart } from './api.js'+import { getDemoUser } from './demoUser.js'import ProductsPage from './ProductsPage.jsx'import CartPage from './CartPage.jsx'import CheckoutPage from './CheckoutPage.jsx'@@ -25,6 +27,11 @@ export default function App() {}}+ useEffect(() => {+ const user = getDemoUser()+ setAttributes({ 'user.email': user.email, 'user.name': user.name, plan: user.plan })+ }, [])+useEffect(() => {refreshCartCount()}, [page])diff --git a/testing/shop/frontend/src/CheckoutPage.jsx b/testing/shop/frontend/src/CheckoutPage.jsxindex 3a1556b7..9794684a 100644--- a/testing/shop/frontend/src/CheckoutPage.jsx+++ b/testing/shop/frontend/src/CheckoutPage.jsx@@ -1,20 +1,8 @@import React, { useEffect, useState } from 'react'+import { TracewayErrorBoundary } from '@tracewayapp/react'import { applyCoupon, checkout, getCart, formatPrice } from './api.js'import { Button, IconCheck, IconLock } from './ui.jsx'-class ErrorBoundary extends React.Component {- constructor(props) {- super(props)- this.state = { failed: false }- }- static getDerivedStateFromError() {- return { failed: true }- }- render() {- return this.state.failed ? this.props.fallback : this.props.children- }-}-function CouponBadge({ discount }) {return (<div className="flex items-center gap-2 rounded-lg bg-emerald-50 px-3 py-2.5 text-sm font-medium text-emerald-700 ring-1 ring-emerald-600/20">@@ -121,7 +109,7 @@ export default function CheckoutPage({ onDone }) {{couponError && <p className="mt-2 text-sm text-red-600">{couponError}</p>}{discount !== undefined && (<div className="mt-3">- <ErrorBoundary+ <TracewayErrorBoundaryfallback={<div className="rounded-lg bg-red-50 px-3 py-2.5 text-sm font-medium text-red-700 ring-1 ring-red-600/20">Could not display coupon.@@ -129,7 +117,7 @@ export default function CheckoutPage({ onDone }) {}><CouponBadge discount={discount} />- </ErrorBoundary>+ </TracewayErrorBoundary></div>)}</section>diff --git a/testing/shop/frontend/src/ProductsPage.jsx b/testing/shop/frontend/src/ProductsPage.jsxindex a5332db2..cdbd90c2 100644--- a/testing/shop/frontend/src/ProductsPage.jsx+++ b/testing/shop/frontend/src/ProductsPage.jsx@@ -1,4 +1,5 @@import React, { useEffect, useState } from 'react'+import { captureException } from '@tracewayapp/react'import { getProducts, addToCart, formatPrice } from './api.js'import { Button, IconButton, Stars, IconClose, IconCheck, IconEye, cx } from './ui.jsx'@@ -44,6 +45,17 @@ export default function ProductsPage({ onCartChanged }) {}function handleQuickView(p) {+ if (p.name === '4K Monitor') {+ try {+ const preferred = p.variants.find((v) => v.default)+ setQuickView({ ...p, variant: preferred })+ return+ } catch (e) {+ captureException(e)+ setNotice('No variants available')+ return+ }+ }setQuickView(p)}diff --git a/testing/shop/frontend/src/demoUser.js b/testing/shop/frontend/src/demoUser.jsnew file mode 100644index 00000000..2fa89c68--- /dev/null+++ b/testing/shop/frontend/src/demoUser.js@@ -0,0 +1,27 @@+const PERSONAS = [+ { name: 'Mia Chen', email: '[email protected]', plan: 'free' },+ { name: 'Liam Novak', email: '[email protected]', plan: 'pro' },+ { name: 'Sofia Ricci', email: '[email protected]', plan: 'free' },+ { name: 'Noah Fischer', email: '[email protected]', plan: 'pro' },+ { name: 'Emma Kovacs', email: '[email protected]', plan: 'free' },+ { name: 'Lucas Moreau', email: '[email protected]', plan: 'enterprise' },+ { name: 'Olivia Jansen', email: '[email protected]', plan: 'free' },+ { name: 'Ethan Silva', email: '[email protected]', plan: 'pro' },+ { name: 'Ava Lindberg', email: '[email protected]', plan: 'free' },+ { name: 'Marko Petrovic', email: '[email protected]', plan: 'pro' },+ { name: 'Hana Sato', email: '[email protected]', plan: 'free' },+ { name: 'Jonas Weber', email: '[email protected]', plan: 'enterprise' }+]++export function getDemoUser() {+ if (window.__DEMO_USER) return window.__DEMO_USER+ try {+ const stored = sessionStorage.getItem('shoply_demo_user')+ if (stored) return JSON.parse(stored)+ const user = PERSONAS[Math.floor(Math.random() * PERSONAS.length)]+ sessionStorage.setItem('shoply_demo_user', JSON.stringify(user))+ return user+ } catch {+ return PERSONAS[0]+ }+}diff --git a/testing/shop/seed/README.md b/testing/shop/seed/README.mdnew file mode 100644index 00000000..1843c3c8--- /dev/null+++ b/testing/shop/seed/README.md@@ -0,0 +1,40 @@+# seed.mjs — demo account entity seeding++Creates the platform entities for the Shoply demo on a Traceway instance:++- Monitors (synthetic checks) on the backend project: `Traceway API`, `Marketing Site`,+ `Edge TLS` (tcp), and the intentionally failing `Payments Provider` (asserts a body+ string `/api/health` never returns → goes down after 2 cycles → incident + page).+- On-call: team `Shoply Engineering` (owns both projects), weekly schedule+ `Shoply Primary On-Call`, escalation policy `Shoply Critical`.+- Notification channels (email + escalation) and rules: `check_down` → escalation,+ `new_error`, `endpoint_p95_threshold` on `GET /api/products`, `error_rate_threshold`;+ `new_error` on the react project.+- Status page `Shoply Status` (public, slug `shoply-status`) with a backdated resolved+ incident (`Elevated checkout error rate`) and a full timeline.+- Post-mortem linked to that incident.+- Dashboards: populate-defaults (OTelemetry Server Agent), `golang` template, and a+ hand-crafted `Shoply Business` dashboard (`shop.*` metrics emitted by the backend).+- Optionally mints the react project's source map upload token and writes `frontend/.env`.++## Auth (first match wins)++1. `TRACEWAY_DEMO_PAT` — a `twp_` personal access token+2. `TRACEWAY_DEMO_EMAIL` + `TRACEWAY_DEMO_PASSWORD`+3. The traceway CLI's stored `demo` profile (`traceway login --profile demo`); the script+ immediately trades the 15-minute device JWT for a `demo-seed` PAT.++## Usage++```bash+node seed.mjs # seed everything except the sourcemap token+MINT_SOURCEMAP_TOKEN=1 node seed.mjs # also mint + write frontend/.env (rotates the old token!)+```++Other env: `TRACEWAY_BASE_URL` (default `https://cloud.tracewayapp.com`),+`SHOPLY_REACT_TOKEN` / `SHOPLY_OTEL_TOKEN` (the two projects' ingest tokens, used to find+the project ids), `TRACEWAY_CLI_PROFILE` (default `demo`).++Re-runnable: every create is list-guarded by name/slug; 422 "already exists" responses are+treated as success. The failing monitor only pages on an up→down transition, so re-runs do+not duplicate pages.diff --git a/testing/shop/seed/seed.mjs b/testing/shop/seed/seed.mjsnew file mode 100644index 00000000..73a3de4e--- /dev/null+++ b/testing/shop/seed/seed.mjs@@ -0,0 +1,432 @@+// Seeds Traceway platform entities for the Shoply demo account.+// Auth resolution order: TRACEWAY_DEMO_PAT env, TRACEWAY_DEMO_EMAIL+TRACEWAY_DEMO_PASSWORD env,+// then the traceway CLI's stored "demo" profile token (~/.local/state/traceway/state.json).+// Re-runnable: every create is guarded by a list-lookup first.++import { readFileSync, writeFileSync, existsSync } from 'node:fs'+import { homedir } from 'node:os'+import { join, dirname } from 'node:path'+import { fileURLToPath } from 'node:url'++const BASE = process.env.TRACEWAY_BASE_URL || 'https://cloud.tracewayapp.com'+const REACT_TOKEN = process.env.SHOPLY_REACT_TOKEN || '17b6181efa3b46639519faadd77245c3'+const OTEL_TOKEN = process.env.SHOPLY_OTEL_TOKEN || '74b1342ebb974f6c85530b90ab0828e2'+const CLI_PROFILE = process.env.TRACEWAY_CLI_PROFILE || 'demo'+const MINT_SOURCEMAP_TOKEN = process.env.MINT_SOURCEMAP_TOKEN === '1'++let authToken = null+const summary = []+const note = (kind, name, detail = '') => {+ summary.push({ kind, name, detail })+ console.log(` [${kind}] ${name}${detail ? ' — ' + detail : ''}`)+}++async function api(method, path, body, { allow = [] } = {}) {+ const res = await fetch(BASE + path, {+ method,+ headers: {+ Authorization: `Bearer ${authToken}`,+ ...(body !== undefined ? { 'Content-Type': 'application/json' } : {})+ },+ body: body !== undefined ? JSON.stringify(body) : undefined+ })+ let data = null+ const text = await res.text()+ try { data = text ? JSON.parse(text) : null } catch { data = text }+ if (!res.ok && !allow.includes(res.status)) {+ throw new Error(`${method} ${path} -> ${res.status}: ${typeof data === 'object' ? JSON.stringify(data) : data}`)+ }+ return { status: res.status, data }+}++function cliToken() {+ const statePath = join(homedir(), '.local', 'state', 'traceway', 'state.json')+ if (!existsSync(statePath)) return null+ try {+ const state = JSON.parse(readFileSync(statePath, 'utf8'))+ return state.profiles?.[CLI_PROFILE]?.jwt || null+ } catch {+ return null+ }+}++async function resolveAuth() {+ if (process.env.TRACEWAY_DEMO_PAT) {+ authToken = process.env.TRACEWAY_DEMO_PAT+ return+ }+ if (process.env.TRACEWAY_DEMO_EMAIL && process.env.TRACEWAY_DEMO_PASSWORD) {+ const res = await fetch(BASE + '/api/login', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ email: process.env.TRACEWAY_DEMO_EMAIL, password: process.env.TRACEWAY_DEMO_PASSWORD })+ })+ if (!res.ok) throw new Error(`login failed: ${res.status}`)+ authToken = (await res.json()).token+ return+ }+ const jwt = cliToken()+ if (!jwt) throw new Error(`No auth: set TRACEWAY_DEMO_PAT, or TRACEWAY_DEMO_EMAIL/PASSWORD, or run: traceway login --profile ${CLI_PROFILE}`)+ authToken = jwt+ // Device-flow JWTs expire in 15 minutes; trade it for a durable PAT immediately.+ const { data: pats } = await api('GET', '/api/personal-access-tokens')+ const existing = (Array.isArray(pats) ? pats : pats?.tokens || []).find?.((p) => p.name === 'demo-seed')+ if (!existing) {+ const { data } = await api('POST', '/api/personal-access-tokens', { name: 'demo-seed' })+ if (data?.token) {+ authToken = data.token+ note('auth', 'PAT demo-seed', 'minted (stored only in memory this run)')+ return+ }+ }+ note('auth', 'CLI JWT', 'using short-lived device token (PAT demo-seed already exists; delete it or pass TRACEWAY_DEMO_PAT for long runs)')+}++async function main() {+ console.log(`Seeding demo entities on ${BASE}`)+ await resolveAuth()++ // ---- Context -------------------------------------------------------------+ const { data: bundle } = await api('GET', '/api/me/login-bundle')+ const userId = bundle.user.id+ const { data: projects } = await api('GET', '/api/projects')+ const reactProject = projects.find((p) => p.token === REACT_TOKEN)+ const otelProject = projects.find((p) => p.token === OTEL_TOKEN)+ if (!reactProject || !otelProject) {+ const names = projects.map((p) => `${p.name} (${p.framework})`).join(', ')+ throw new Error(`Could not match demo project tokens. Visible projects: ${names}`)+ }+ const orgId = otelProject.organizationId+ const REACT_ID = reactProject.id+ const OTEL_ID = otelProject.id+ const org = bundle.organizations.find((o) => o.id === orgId)+ if (org && !['owner', 'admin'].includes(org.role)) {+ throw new Error(`Org role is '${org.role}' — owner/admin needed for on-call/status-page seeding`)+ }+ note('context', 'projects', `react=${REACT_ID} otel=${OTEL_ID} org=${orgId} user=${userId}`)+ const demoEmail = bundle.user.email++ const pq = (id) => `?projectId=${id}`++ // ---- Healthy monitors first (they need cycles for uptime history) --------+ const { data: checksResp } = await api('GET', `/api/synthetics/checks${pq(OTEL_ID)}`)+ const existingChecks = checksResp?.checks || []+ const checkByName = (n) => existingChecks.find((c) => c.name === n)++ async function ensureCheck(body) {+ const existing = checkByName(body.name)+ if (existing) {+ note('monitor', body.name, `exists (id ${existing.id})`)+ return existing.id+ }+ const { status, data } = await api('POST', `/api/synthetics/checks${pq(OTEL_ID)}`, body, { allow: [422] })+ if (status === 422) {+ note('monitor', body.name, `SKIPPED 422: ${data?.error}`)+ return null+ }+ const id = data?.check?.id ?? data?.id+ note('monitor', body.name, `created (id ${id})`)+ await api('POST', `/api/synthetics/checks/${id}/run${pq(OTEL_ID)}`, {}, { allow: [422] })+ return id+ }++ const httpCheck = (name, url, intervalSeconds, assertions, extra = {}) => ({+ name, checkType: 'http', enabled: true, intervalSeconds, timeoutSeconds: 10, failureThreshold: 2,+ config: {+ url, method: 'GET', headers: {}, auth: { type: 'none' },+ followRedirects: true, skipTlsVerify: false,+ assertions: { statusCodes: [200], bodyContains: '', bodyRegex: '', maxResponseTimeMs: 0, tlsMinDaysRemaining: 0, ...assertions },+ ...extra+ }+ })++ const apiCheckId = await ensureCheck(httpCheck('Traceway API', `${BASE}/api/health`, 60, { maxResponseTimeMs: 2000, tlsMinDaysRemaining: 14 }))+ const mktCheckId = await ensureCheck(httpCheck('Marketing Site', 'https://example.com', 120, {}))+ const tcpCheckId = await ensureCheck({+ name: 'Edge TLS', checkType: 'tcp', enabled: true, intervalSeconds: 120, timeoutSeconds: 10, failureThreshold: 2,+ config: { host: 'cloud.tracewayapp.com', port: 443, useTls: true, sendPayload: '', expectContains: '', tlsMinDaysRemaining: 14 }+ })++ // ---- On-call: team -> schedule -> escalation policy ----------------------+ const { data: teams } = await api('GET', `/api/organizations/${orgId}/teams`)+ let team = (teams || []).find((t) => t.name === 'Shoply Engineering')+ if (!team) {+ const { data } = await api('POST', `/api/organizations/${orgId}/teams`, {+ name: 'Shoply Engineering',+ description: 'Owns the Shoply storefront and API',+ memberUserIds: [userId],+ projectIds: [REACT_ID, OTEL_ID]+ })+ team = data?.team ?? data+ note('team', 'Shoply Engineering', `created (id ${team.id})`)+ } else {+ note('team', 'Shoply Engineering', `exists (id ${team.id})`)+ }++ const { data: schedules } = await api('GET', `/api/organizations/${orgId}/schedules`)+ let schedule = (schedules || []).find((s) => s.name === 'Shoply Primary On-Call')+ if (!schedule) {+ const { data } = await api('POST', `/api/organizations/${orgId}/schedules`, {+ teamId: team.id,+ name: 'Shoply Primary On-Call',+ description: 'Weekly rotation for the Shoply services',+ timezone: 'UTC',+ definition: {+ schemaVersion: 1,+ layers: [{+ name: 'Primary',+ rotationType: 'weekly',+ handoffTime: '09:00',+ handoffDay: 1,+ intervalDays: 0,+ rotationStart: '2026-08-18',+ userIds: [userId],+ restrictions: []+ }]+ }+ })+ schedule = data?.schedule ?? data+ note('schedule', 'Shoply Primary On-Call', `created (id ${schedule.id})`)+ } else {+ note('schedule', 'Shoply Primary On-Call', `exists (id ${schedule.id})`)+ }++ const { data: policies } = await api('GET', `/api/organizations/${orgId}/escalation-policies`)+ let policy = (policies || []).find((p) => p.name === 'Shoply Critical')+ if (!policy) {+ const { data } = await api('POST', `/api/organizations/${orgId}/escalation-policies`, {+ name: 'Shoply Critical',+ definition: {+ schemaVersion: 1,+ urgency: 'auto',+ repeatCount: 1,+ steps: [+ { delayMinutes: 5, targets: [{ type: 'schedule', id: schedule.id }] },+ { delayMinutes: 10, targets: [{ type: 'user', id: userId }] }+ ]+ }+ })+ policy = data?.policy ?? data+ note('policy', 'Shoply Critical', `created (id ${policy.id})`)+ } else {+ note('policy', 'Shoply Critical', `exists (id ${policy.id})`)+ }++ // ---- Notification channels & rules ---------------------------------------+ async function ensureChannel(projectId, body) {+ const { data } = await api('GET', `/api/notification-channels${pq(projectId)}`)+ const list = Array.isArray(data) ? data : data?.channels || []+ const existing = list.find((c) => c.name === body.name)+ if (existing) {+ note('channel', body.name, `exists (id ${existing.id})`)+ return existing.id+ }+ const { data: created } = await api('POST', `/api/notification-channels${pq(projectId)}`, body)+ const id = created?.channel?.id ?? created?.id+ note('channel', body.name, `created (id ${id})`)+ return id+ }++ async function ensureRule(projectId, body) {+ const { data } = await api('GET', `/api/notification-rules${pq(projectId)}`)+ const list = Array.isArray(data) ? data : data?.rules || []+ const existing = list.find((r) => r.name === body.name)+ if (existing) {+ note('rule', body.name, `exists (id ${existing.id})`)+ return existing.id+ }+ const { data: created } = await api('POST', `/api/notification-rules${pq(projectId)}`, body)+ const id = created?.rule?.id ?? created?.id+ note('rule', body.name, `created (id ${id})`)+ return id+ }++ const emailChId = await ensureChannel(OTEL_ID, {+ name: 'Shoply Alerts (email)', channelType: 'email', config: { recipients: [demoEmail] }+ })+ const escChId = await ensureChannel(OTEL_ID, {+ name: 'Page Shoply On-Call', channelType: 'escalation', config: { policyId: policy.id }+ })+ const reactEmailChId = await ensureChannel(REACT_ID, {+ name: 'Shoply Alerts (email)', channelType: 'email', config: { recipients: [demoEmail] }+ })++ await ensureRule(OTEL_ID, { channelId: escChId, name: 'Monitor down → page on-call', ruleType: 'check_down', config: {}, cooldownMinutes: 15, severity: 'critical' })+ await ensureRule(OTEL_ID, { channelId: emailChId, name: 'New error', ruleType: 'new_error', config: { ignorePatterns: [] }, cooldownMinutes: 15, severity: 'warning' })+ await ensureRule(OTEL_ID, { channelId: emailChId, name: 'GET /api/products p95 > 400ms', ruleType: 'endpoint_p95_threshold', config: { endpoint: 'GET /api/products', thresholdMs: 400, lookbackMinutes: 15 }, cooldownMinutes: 30, severity: 'warning' })+ await ensureRule(OTEL_ID, { channelId: emailChId, name: 'Error rate > 5%', ruleType: 'error_rate_threshold', config: { thresholdPercent: 5, lookbackMinutes: 15, minRequests: 20 }, cooldownMinutes: 30, severity: 'critical' })+ await ensureRule(REACT_ID, { channelId: reactEmailChId, name: 'New error', ruleType: 'new_error', config: { ignorePatterns: [] }, cooldownMinutes: 15, severity: 'warning' })++ // ---- The intentionally failing check (after check_down exists) -----------+ const failCheckId = await ensureCheck(httpCheck('Payments Provider', `${BASE}/api/health`, 60, { bodyContains: 'payments-provider-ok' }))++ // ---- Status page + backdated incident + post-mortem ----------------------+ const checkIds = [apiCheckId, mktCheckId, tcpCheckId, failCheckId].filter(Boolean)+ const { data: pages } = await api('GET', `/api/organizations/${orgId}/status-pages`)+ let statusPage = (pages || []).find((p) => p.name === 'Shoply Status')+ if (!statusPage) {+ let slug = 'shoply-status'+ let res = await api('POST', `/api/organizations/${orgId}/status-pages`, {+ name: 'Shoply Status', slug, isPublic: true, checkIds,+ description: 'Live status for the Shoply storefront and API'+ }, { allow: [422] })+ if (res.status === 422) {+ slug = `shoply-status-${Math.random().toString(16).slice(2, 6)}`+ res = await api('POST', `/api/organizations/${orgId}/status-pages`, {+ name: 'Shoply Status', slug, isPublic: true, checkIds,+ description: 'Live status for the Shoply storefront and API'+ })+ }+ statusPage = res.data?.statusPage ?? res.data+ note('status-page', 'Shoply Status', `created (/status/${statusPage.slug})`)+ } else {+ note('status-page', 'Shoply Status', `exists (/status/${statusPage.slug})`)+ }++ const { data: incResp } = await api('GET', `/api/organizations/${orgId}/status-pages/${statusPage.id}/incidents?page=1&pageSize=50`, undefined, { allow: [404] })+ const incidents = incResp?.data || incResp?.incidents || []+ let incident = incidents.find((i) => i.title === 'Elevated checkout error rate')+ if (!incident) {+ const startedAt = new Date(Date.now() - 105 * 60 * 1000).toISOString()+ const { data } = await api('POST', `/api/organizations/${orgId}/status-pages/${statusPage.id}/incidents`, {+ title: 'Elevated checkout error rate',+ startedAt,+ message: 'We are investigating elevated error rates on checkout.'+ })+ incident = data?.incident ?? data+ for (const upd of [+ { status: 'identified', message: 'A bad deploy of the coupon cache is causing checkout requests with coupons to fail. Rolling back now.' },+ { status: 'monitoring', message: 'Rollback complete. Checkout error rate is recovering; we are monitoring.' },+ { status: 'resolved', message: 'Error rate has been back to baseline for 30 minutes. Incident resolved.' }+ ]) {+ await api('POST', `/api/organizations/${orgId}/incidents/${incident.id}/updates`, upd)+ }+ note('incident', 'Elevated checkout error rate', `created (id ${incident.id}, resolved with timeline)`)+ } else {+ note('incident', 'Elevated checkout error rate', `exists (id ${incident.id})`)+ }++ const { data: pmResp } = await api('GET', `/api/post-mortems${pq(OTEL_ID)}&page=1&pageSize=50`)+ const postMortems = pmResp?.data || []+ let pm = postMortems.find((p) => p.title === '2026-08-20 — Checkout coupon outage')+ if (!pm) {+ const { status, data } = await api('POST', `/api/post-mortems${pq(OTEL_ID)}`, {+ title: '2026-08-20 — Checkout coupon outage',+ contentMd: POST_MORTEM_MD,+ tags: ['checkout', 'coupon', 'panic'],+ incidentId: incident?.id+ }, { allow: [422] })+ if (status === 422) {+ note('post-mortem', 'Checkout coupon outage', `SKIPPED 422: ${data?.error}`)+ } else {+ pm = data?.postMortem ?? data+ note('post-mortem', 'Checkout coupon outage', `created (id ${pm?.id})`)+ }+ } else {+ note('post-mortem', 'Checkout coupon outage', `exists (id ${pm.id})`)+ }++ // ---- Dashboards ----------------------------------------------------------+ const { data: dashResp } = await api('GET', `/api/dashboards${pq(OTEL_ID)}`)+ const dashboards = dashResp?.dashboards || (Array.isArray(dashResp) ? dashResp : [])+ const hasTemplate = (key) => dashboards.some((d) => d.templateKey === key)++ const pdRes = await api('POST', `/api/dashboards/populate-defaults${pq(OTEL_ID)}`, {}, { allow: [422] })+ note('dashboards', 'populate-defaults', pdRes.status === 422 ? `skipped: ${pdRes.data?.error}` : 'installed')++ if (!hasTemplate('golang')) {+ const res = await api('POST', `/api/dashboard-templates/golang/install`, { organizationId: orgId, projectIds: [OTEL_ID] }, { allow: [404, 422] })+ note('dashboards', 'golang template', res.status >= 400 ? `skipped ${res.status}` : 'installed')+ } else {+ note('dashboards', 'golang template', 'exists')+ }++ if (!dashboards.some((d) => d.name === 'Shoply Business')) {+ const res = await api('POST', '/api/dashboards', {+ organizationId: orgId,+ name: 'Shoply Business',+ description: 'Orders, revenue and coupon health',+ applyToProjectIds: [OTEL_ID],+ definition: {+ schemaVersion: 1,+ widgets: [+ { title: 'Orders Placed', widgetType: 'bar_chart', config: { sources: [{ type: 'metric', name: 'shop.orders.placed', aggregation: 'sum' }], unit: 'orders' } },+ { title: 'Revenue (USD)', widgetType: 'area_chart', config: { sources: [{ type: 'metric', name: 'shop.revenue', aggregation: 'sum' }], unit: '$' } },+ { title: 'Avg Order Value', widgetType: 'single_value', config: { sources: [{ type: 'metric', name: 'shop.checkout.value.avg', aggregation: 'avg' }], showSparkline: true, unit: '$' } },+ { title: 'Coupon Failures', widgetType: 'line_chart', config: { sources: [{ type: 'metric', name: 'shop.coupon.failures', aggregation: 'sum' }] } },+ { title: 'Payments Declined', widgetType: 'line_chart', config: { sources: [{ type: 'metric', name: 'shop.payments.declined', aggregation: 'sum' }] } },+ { title: 'Items In Carts', widgetType: 'line_chart', config: { sources: [{ type: 'metric', name: 'shop.cart.items', aggregation: 'avg' }] } }+ ]+ }+ }, { allow: [422] })+ note('dashboards', 'Shoply Business', res.status === 422 ? `skipped: ${res.data?.error}` : 'created')+ } else {+ note('dashboards', 'Shoply Business', 'exists')+ }++ // ---- Source map token (rotates on every mint — opt-in) -------------------+ if (MINT_SOURCEMAP_TOKEN) {+ const { data } = await api('POST', `/api/projects/source-map-token${pq(REACT_ID)}`)+ const token = data?.sourceMapToken ?? data?.token+ if (token) {+ const envPath = join(dirname(fileURLToPath(import.meta.url)), '..', 'frontend', '.env')+ const lines = [+ 'VITE_API_BASE=/api',+ `VITE_TW_CONNECTION=${REACT_TOKEN}@${BASE}/api/report`,+ `TRACEWAY_URL=${BASE}`,+ `TRACEWAY_SOURCEMAP_TOKEN=${token}`,+ ''+ ]+ writeFileSync(envPath, lines.join('\n'))+ note('sourcemap', 'react project token', `minted and written to frontend/.env (previous token rotated out)`)+ }+ } else {+ note('sourcemap', 'react project token', 'skipped (set MINT_SOURCEMAP_TOKEN=1 to mint + write frontend/.env)')+ }++ // ---- Summary -------------------------------------------------------------+ console.log('\n=== Seed complete ===')+ console.log(`Status page: ${BASE.replace('/api', '')}/status/${statusPage.slug}`)+ console.log(`Projects: react=${REACT_ID} otel=${OTEL_ID} org=${orgId}`)+ console.log('The "Payments Provider" monitor is intentionally failing; expect an incident + page within ~3 minutes.')+}++const POST_MORTEM_MD = `## Summary++Between 13:05 and 14:50 UTC, checkout requests that applied a coupon failed with HTTP 500. Roughly 60% of checkout attempts in that window were affected. The root cause was a nil coupon-hit cache map introduced in the 13:00 deploy: the first coupon application after boot panicked the handler, and every subsequent coupon apply followed the same path.++## Impact++- Checkout conversion dropped ~40% during the window.+- 214 coupon applications returned "internal error".+- No orders were lost permanently; affected customers retried after the rollback.++## Timeline (UTC)++- **13:00** — Deploy of coupon cache refactor goes out.+- **13:05** — First \`assignment to entry in nil map\` panic hits the issues feed; error-rate alert fires.+- **13:12** — On-call acknowledges the page; correlates the panic with the deploy via the release tag.+- **13:41** — Root cause identified: the cache map is declared but never initialized after the refactor.+- **13:55** — Rollback deployed; error rate begins recovering.+- **14:50** — Error rate back at baseline for 30 minutes; incident resolved.++## Root cause++The refactor moved coupon-hit tracking to a package-level \`map[string]int\` and removed the \`make()\` call from the initializer. Writes to a nil map panic in Go. Unit tests only exercised the read path, which returns the zero value on a nil map and passes.++## What went well++- Alerting fired within 5 minutes of the first failure.+- The distributed trace on the frontend exception pointed directly at the failing backend span.++## Action items++- [ ] Add a write-path unit test for the coupon cache.+- [ ] Add a lint rule for package-level map declarations without initialization.+- [ ] Add a canary stage for checkout-path deploys.+`++main().catch((e) => {+ console.error('SEED FAILED:', e.message)+ process.exit(1)+})diff --git a/testing/shop/traffic/http-load.mjs b/testing/shop/traffic/http-load.mjsnew file mode 100644index 00000000..9b89f1d0--- /dev/null+++ b/testing/shop/traffic/http-load.mjs@@ -0,0 +1,98 @@+import { randomUUID } from 'node:crypto'+import { PERSONAS, pick } from './personas.mjs'++function rand(min, max) {+ return min + Math.floor(Math.random() * (max - min))+}++const sleep = (ms) => new Promise((r) => setTimeout(r, ms))++async function req(base, path, options) {+ try {+ const res = await fetch(base + path, options)+ await res.arrayBuffer()+ return res.status+ } catch {+ return 0+ }+}++const jsonPost = (body) => ({+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body)+})++// One pass of mixed API traffic — endpoint volume without browser sessions.+export async function httpBurst(base, { requests = 25 } = {}) {+ for (let i = 0; i < requests; i++) {+ const roll = Math.random()+ if (roll < 0.3) {+ await req(base, '/api/products')+ } else if (roll < 0.55) {+ await req(base, `/api/products/${rand(1, 13)}`)+ } else if (roll < 0.65) {+ await req(base, '/api/cart')+ } else if (roll < 0.75) {+ await req(base, '/api/cart', jsonPost({ product_id: rand(1, 13), qty: rand(1, 3) }))+ } else if (roll < 0.85) {+ await req(base, '/api/coupon', jsonPost({ code: pick(['SAVE10', 'HALF50', 'EXPIRED', 'WELCOME5', 'NOPE']) }))+ } else if (roll < 0.95) {+ const p = pick(PERSONAS)+ await req(base, '/api/checkout', jsonPost({ name: p.name, email: p.email, card_last4: p.card }))+ } else {+ await req(base, `/api/cart/${rand(1, 50)}`, { method: 'DELETE' })+ }+ await sleep(rand(200, 1500))+ }+}++const CHAT_SCRIPTS = [+ {+ label: 'order-status',+ messages: [+ 'Hi! Can you check on my order ORD-483920? It has been a week.',+ 'Great, thanks. Will I get a notification when it is out for delivery?',+ 'Perfect, thank you!'+ ]+ },+ {+ label: 'product-question',+ messages: [+ 'What does the scented candle smell like? How long does it burn?',+ 'Nice. What is your return policy if I do not like the scent?'+ ]+ },+ {+ label: 'refund-complaint',+ messages: [+ 'My order arrived broken AGAIN. Honestly this is bullshit, third time in a row.',+ 'I want a refund, not a replacement.',+ 'Fine. How long until the money is back on my card?'+ ]+ },+ {+ label: 'shipping-question',+ messages: [+ 'How fast is shipping to Berlin?',+ 'Is express shipping available for order ORD-771203 that I placed an hour ago?'+ ]+ }+]++export async function aiConversation(base, { script, persona, turnDelayMs = [3000, 9000] } = {}) {+ const chosen = script || pick(CHAT_SCRIPTS)+ const user = persona || pick(PERSONAS)+ const conversationId = randomUUID()+ for (const message of chosen.messages) {+ await req(base, '/api/support/chat', jsonPost({+ conversation_id: conversationId,+ user_id: user.email,+ message+ }))+ await sleep(rand(turnDelayMs[0], turnDelayMs[1]))+ }+ return { conversationId, label: chosen.label, user: user.email }+}++export { CHAT_SCRIPTS }diff --git a/testing/shop/traffic/journeys.mjs b/testing/shop/traffic/journeys.mjsnew file mode 100644index 00000000..9caf535b--- /dev/null+++ b/testing/shop/traffic/journeys.mjs@@ -0,0 +1,218 @@+import { pick } from './personas.mjs'++const CATEGORIES = ['Apparel', 'Electronics', 'Home', 'Books']++function rand(min, max) {+ return min + Math.floor(Math.random() * (max - min))+}++async function think(page, persona, minMs = 600, maxMs = 3000) {+ await page.waitForTimeout(Math.floor(rand(minMs, maxMs) * persona.thinkScale))+}++async function goToShop(page) {+ await page.getByRole('banner').getByRole('button', { name: 'Shop', exact: true }).click()+}++async function goToCart(page) {+ await page.getByRole('banner').getByRole('button', { name: /^Cart, \d+ items$/ }).click()+}++async function goToCheckout(page) {+ await page.getByRole('banner').getByRole('button', { name: 'Checkout', exact: true }).click()+}++async function waitForProducts(page) {+ await page.getByRole('button', { name: 'Add to cart' }).first().waitFor({ timeout: 20000 })+}++async function browseAround(page, persona, { categoryHops = 1, hovers = 2 } = {}) {+ await waitForProducts(page)+ for (let i = 0; i < categoryHops; i++) {+ await page.getByRole('button', { name: pick(CATEGORIES), exact: true }).click()+ await think(page, persona, 800, 2500)+ }+ const cards = page.locator('div.group')+ const count = await cards.count()+ for (let i = 0; i < hovers && count > 0; i++) {+ await cards.nth(rand(0, count)).hover()+ await think(page, persona, 500, 1500)+ }+ await page.mouse.wheel(0, rand(300, 1200))+ await think(page, persona, 500, 1500)+}++async function addRandomItems(page, persona, n) {+ await page.getByRole('button', { name: 'All', exact: true }).click()+ await waitForProducts(page)+ for (let i = 0; i < n; i++) {+ const buttons = page.getByRole('button', { name: 'Add to cart' })+ const count = await buttons.count()+ const target = buttons.nth(rand(0, count))+ await target.scrollIntoViewIfNeeded()+ await target.click()+ // Add-to-cart is slow-path ~75% of the time; wait for the button to settle.+ await page.getByRole('button', { name: 'Adding…' }).first().waitFor({ timeout: 2000 }).catch(() => {})+ await page.getByRole('button', { name: 'Adding…' }).first().waitFor({ state: 'detached', timeout: 15000 }).catch(() => {})+ await think(page, persona, 700, 2200)+ }+}++async function fillCheckoutForm(page, persona) {+ await page.locator('#co-name').fill(persona.name)+ await page.locator('#co-email').fill(persona.email)+ await page.locator('#co-card').fill(persona.card)+}++async function applyCouponUI(page, persona, code) {+ await page.getByLabel('Coupon code').fill(code)+ await page.getByRole('button', { name: 'Apply', exact: true }).click()+ await think(page, persona, 1200, 2500)+}++async function placeOrder(page, persona, { retryOnDecline = true } = {}) {+ await page.getByRole('button', { name: 'Place order' }).click()+ const confirmed = page.getByRole('heading', { name: 'Order confirmed' })+ try {+ await confirmed.waitFor({ timeout: 20000 })+ await think(page, persona, 1500, 3000)+ await page.getByRole('button', { name: 'Back to shop' }).click()+ return true+ } catch {+ if (retryOnDecline) {+ const errText = await page.locator('text=declined').count().catch(() => 0)+ if (errText > 0) {+ await think(page, persona, 1000, 2500)+ return placeOrder(page, persona, { retryOnDecline: false })+ }+ }+ return false+ }+}++export const journeys = {+ happyPath: {+ weight: 30, cart: true,+ async run(page, persona) {+ await browseAround(page, persona, { categoryHops: rand(1, 3), hovers: rand(1, 4) })+ await addRandomItems(page, persona, rand(1, 4))+ await goToCart(page)+ await think(page, persona, 1200, 3000)+ await page.getByRole('button', { name: 'Proceed to checkout' }).click()+ await think(page, persona, 800, 2000)+ if (Math.random() < 0.5) {+ await applyCouponUI(page, persona, pick(['SAVE10', 'HALF50', 'SAVE10']))+ }+ await fillCheckoutForm(page, persona)+ await think(page, persona, 800, 1800)+ await placeOrder(page, persona)+ }+ },++ couponExpired: {+ weight: 10, cart: true,+ async run(page, persona) {+ await browseAround(page, persona, { categoryHops: 1, hovers: 1 })+ await addRandomItems(page, persona, 1)+ await goToCheckout(page)+ await applyCouponUI(page, persona, 'EXPIRED')+ await applyCouponUI(page, persona, 'SAVE10')+ await fillCheckoutForm(page, persona)+ await placeOrder(page, persona)+ }+ },++ emptyCartCheckout: {+ weight: 8, cart: true,+ async run(page, persona, { base }) {+ // Ensure the (global) cart really is empty before demonstrating the bug.+ const cart = await fetch(base + '/api/cart').then((r) => r.json()).catch(() => null)+ for (const item of cart?.items || []) {+ await fetch(`${base}/api/cart/${item.id}`, { method: 'DELETE' }).catch(() => {})+ }+ await goToCheckout(page)+ await think(page, persona, 800, 1500)+ await fillCheckoutForm(page, persona)+ await page.getByRole('button', { name: 'Place order' }).click()+ await page.locator('text=cart is empty').waitFor({ timeout: 15000 }).catch(() => {})+ await think(page, persona, 1500, 3000)+ }+ },++ cartAbandon: {+ weight: 15, cart: true,+ async run(page, persona) {+ await browseAround(page, persona, { categoryHops: rand(1, 2), hovers: 2 })+ await addRandomItems(page, persona, 2)+ await goToCart(page)+ await think(page, persona, 1500, 3500)+ const removes = page.getByRole('button', { name: 'Remove' })+ if ((await removes.count()) > 0) {+ await removes.first().click()+ await think(page, persona, 1000, 2500)+ }+ await goToShop(page)+ await browseAround(page, persona, { categoryHops: 1, hovers: 1 })+ }+ },++ windowShopper: {+ weight: 20, cart: false,+ async run(page, persona) {+ await waitForProducts(page)+ for (const cat of ['Electronics', 'Home', pick(CATEGORIES)]) {+ await page.getByRole('button', { name: cat, exact: true }).click()+ await think(page, persona, 1000, 3000)+ await page.mouse.wheel(0, rand(200, 900))+ await think(page, persona, 800, 2000)+ }+ // Quick-view a working product (anything but the 4K Monitor).+ await page.getByRole('button', { name: 'Books', exact: true }).click()+ await waitForProducts(page)+ const card = page.locator('div.group').first()+ await card.hover()+ await card.getByRole('button', { name: 'Quick view' }).click()+ await think(page, persona, 1500, 3500)+ await page.getByRole('button', { name: 'Close' }).click()+ await think(page, persona, 800, 2000)+ }+ },++ quickViewCrash: {+ weight: 10, cart: false,+ async run(page, persona) {+ await waitForProducts(page)+ await page.getByRole('button', { name: 'Electronics', exact: true }).click()+ await think(page, persona, 800, 2000)+ const card = page.locator('div.group').filter({ hasText: '4K Monitor' }).first()+ await card.hover()+ await card.getByRole('button', { name: 'Quick view' }).click()+ await page.locator('text=No variants available').waitFor({ timeout: 5000 }).catch(() => {})+ await think(page, persona, 1000, 2500)+ await browseAround(page, persona, { categoryHops: 1, hovers: 2 })+ }+ },++ idler: {+ weight: 7, cart: false,+ async run(page, persona) {+ await waitForProducts(page)+ for (let i = 0; i < rand(4, 8); i++) {+ await page.mouse.wheel(0, rand(-300, 700))+ await page.waitForTimeout(rand(3000, 8000))+ }+ }+ }+}++export function pickJourney() {+ const entries = Object.entries(journeys)+ const total = entries.reduce((n, [, j]) => n + j.weight, 0)+ let roll = Math.random() * total+ for (const [name, j] of entries) {+ roll -= j.weight+ if (roll <= 0) return { name, ...j }+ }+ const [name, j] = entries[entries.length - 1]+ return { name, ...j }+}diff --git a/testing/shop/traffic/package-lock.json b/testing/shop/traffic/package-lock.jsonnew file mode 100644index 00000000..e8a63c4e--- /dev/null+++ b/testing/shop/traffic/package-lock.json@@ -0,0 +1,57 @@+{+ "name": "shop-traffic",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "shop-traffic",+ "dependencies": {+ "playwright": "^1.62.1"+ }+ },+ "node_modules/fsevents": {+ "version": "2.3.2",+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",+ "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",+ "hasInstallScript": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"+ }+ },+ "node_modules/playwright": {+ "version": "1.62.1",+ "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.62.1.tgz",+ "integrity": "sha512-0M+L3LAD8/nm554LOla9Ayx0j0tmFZ0FBcoQ7F1VuVHpM/XpiC8RcDzBQB8W5+hA8L22THxELzeF+2WcUzvcLg==",+ "license": "Apache-2.0",+ "dependencies": {+ "playwright-core": "1.62.1"+ },+ "bin": {+ "playwright": "cli.js"+ },+ "engines": {+ "node": ">=20"+ },+ "optionalDependencies": {+ "fsevents": "2.3.2"+ }+ },+ "node_modules/playwright-core": {+ "version": "1.62.1",+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.62.1.tgz",+ "integrity": "sha512-wPYSwEBJY9GHraISXqyqtx0na0LpO3XEX7jNDhntbex7tzUS7kLnZsOlFruFJB4Hi/rhDMjXGqHewDZ68nYZVw==",+ "license": "Apache-2.0",+ "bin": {+ "playwright-core": "cli.js"+ },+ "engines": {+ "node": ">=20"+ }+ }+ }+}diff --git a/testing/shop/traffic/package.json b/testing/shop/traffic/package.jsonnew file mode 100644index 00000000..082d2c7c--- /dev/null+++ b/testing/shop/traffic/package.json@@ -0,0 +1,8 @@+{+ "name": "shop-traffic",+ "private": true,+ "type": "module",+ "dependencies": {+ "playwright": "^1.62.1"+ }+}diff --git a/testing/shop/traffic/personas.mjs b/testing/shop/traffic/personas.mjsnew file mode 100644index 00000000..9fb1abc7--- /dev/null+++ b/testing/shop/traffic/personas.mjs@@ -0,0 +1,26 @@+export const PERSONAS = [+ { name: 'Mia Chen', email: '[email protected]', plan: 'free', card: '4242', thinkScale: 1.0 },+ { name: 'Liam Novak', email: '[email protected]', plan: 'pro', card: '1881', thinkScale: 0.7 },+ { name: 'Sofia Ricci', email: '[email protected]', plan: 'free', card: '5100', thinkScale: 1.4 },+ { name: 'Noah Fischer', email: '[email protected]', plan: 'pro', card: '4012', thinkScale: 0.8 },+ { name: 'Emma Kovacs', email: '[email protected]', plan: 'free', card: '9424', thinkScale: 1.2 },+ { name: 'Lucas Moreau', email: '[email protected]', plan: 'enterprise', card: '7710', thinkScale: 0.9 },+ { name: 'Olivia Jansen', email: '[email protected]', plan: 'free', card: '3056', thinkScale: 1.1 },+ { name: 'Ethan Silva', email: '[email protected]', plan: 'pro', card: '6011', thinkScale: 0.6 },+ { name: 'Ava Lindberg', email: '[email protected]', plan: 'free', card: '3530', thinkScale: 1.3 },+ { name: 'Marko Petrovic', email: '[email protected]', plan: 'pro', card: '2223', thinkScale: 0.9 },+ { name: 'Hana Sato', email: '[email protected]', plan: 'free', card: '4917', thinkScale: 1.0 },+ { name: 'Jonas Weber', email: '[email protected]', plan: 'enterprise', card: '8171', thinkScale: 0.8 }+]++export const VIEWPORTS = [+ { width: 1440, height: 900 },+ { width: 1280, height: 800 },+ { width: 1536, height: 960 },+ { width: 834, height: 1112 },+ { width: 390, height: 844 }+]++export function pick(arr) {+ return arr[Math.floor(Math.random() * arr.length)]+}diff --git a/testing/shop/traffic/run-traffic.sh b/testing/shop/traffic/run-traffic.shnew file mode 100755index 00000000..b6908e69--- /dev/null+++ b/testing/shop/traffic/run-traffic.sh@@ -0,0 +1,4 @@+#!/usr/bin/env bash+set -euo pipefail+cd "$(dirname "$0")"+exec node traffic.mjs "$@"diff --git a/testing/shop/traffic/traffic.mjs b/testing/shop/traffic/traffic.mjsnew file mode 100644index 00000000..9d322a29--- /dev/null+++ b/testing/shop/traffic/traffic.mjs@@ -0,0 +1,133 @@+import { chromium } from 'playwright'+import { PERSONAS, VIEWPORTS, pick } from './personas.mjs'+import { pickJourney } from './journeys.mjs'+import { httpBurst, aiConversation, CHAT_SCRIPTS } from './http-load.mjs'++const args = process.argv.slice(2)+const flag = (name) => args.includes(name)+const opt = (name, fallback) => {+ const i = args.indexOf(name)+ return i >= 0 && args[i + 1] ? args[i + 1] : fallback+}++const BASE = opt('--base', 'http://localhost:8090')+const SESSIONS = parseInt(opt('--sessions', '50'), 10)+const PARALLEL = parseInt(opt('--parallel', '3'), 10)+const HEADED = flag('--headed')+const DRIP = flag('--drip')+const NO_BROWSER = flag('--no-browser')++const sleep = (ms) => new Promise((r) => setTimeout(r, ms))+const rand = (min, max) => min + Math.floor(Math.random() * (max - min))++// The backend cart is global (no session scoping), so cart-mutating journeys+// must not overlap or they steal each other's carts mid-checkout.+let cartLock = Promise.resolve()+function withCartLock(fn) {+ const run = cartLock.then(fn, fn)+ cartLock = run.catch(() => {})+ return run+}++let sessionCounter = 0++async function runSession(browser) {+ const id = ++sessionCounter+ const persona = pick(PERSONAS)+ const viewport = pick(VIEWPORTS)+ const journey = pickJourney()++ const context = await browser.newContext({ viewport })+ await context.addInitScript((user) => {+ window.__DEMO_USER = user+ }, { name: persona.name, email: persona.email, plan: persona.plan })++ const page = await context.newPage()+ const label = `#${id} ${journey.name} (${persona.name}, ${viewport.width}x${viewport.height})`+ console.log(`[session] start ${label}`)+ try {+ await page.goto(BASE, { waitUntil: 'domcontentloaded' })+ const exec = () => journey.run(page, persona, { base: BASE })+ if (journey.cart) {+ await withCartLock(exec)+ } else {+ await exec()+ }+ // Idle tail so the session-recording segment covering the journey uploads.+ await page.waitForTimeout(rand(5000, 9000))+ await page.close({ runBeforeUnload: true })+ await sleep(1500)+ console.log(`[session] done ${label}`)+ } catch (e) {+ console.log(`[session] FAIL ${label}: ${e.message?.split('\n')[0]}`)+ } finally {+ await context.close().catch(() => {})+ }+}++async function seedMode() {+ console.log(`Seeding ${SESSIONS} sessions against ${BASE} (parallel ${PARALLEL})`)++ const sideWork = (async () => {+ const chats = [...CHAT_SCRIPTS, ...CHAT_SCRIPTS].slice(0, 7)+ for (const script of chats) {+ await aiConversation(BASE, { script })+ await sleep(rand(5000, 20000))+ }+ })()+ const load = (async () => {+ for (let i = 0; i < 16; i++) {+ await httpBurst(BASE, { requests: 25 })+ await sleep(rand(2000, 8000))+ }+ })()++ if (!NO_BROWSER) {+ const browser = await chromium.launch({ headless: !HEADED })+ let launched = 0+ const workers = Array.from({ length: PARALLEL }, async () => {+ while (launched < SESSIONS) {+ launched+++ await runSession(browser)+ await sleep(rand(1000, 4000))+ }+ })+ await Promise.all(workers)+ await browser.close()+ }++ await Promise.all([sideWork, load])+ console.log('Seed run complete.')+}++async function dripMode() {+ console.log(`Drip mode against ${BASE} — Ctrl-C to stop.`)+ const browser = NO_BROWSER ? null : await chromium.launch({ headless: !HEADED })++ const browserLoop = (async () => {+ while (true) {+ if (browser) await runSession(browser)+ await sleep(rand(120000, 240000))+ }+ })()+ const httpLoop = (async () => {+ while (true) {+ await httpBurst(BASE, { requests: rand(8, 18) })+ await sleep(rand(30000, 60000))+ }+ })()+ const aiLoop = (async () => {+ while (true) {+ await aiConversation(BASE)+ await sleep(rand(480000, 780000))+ }+ })()++ await Promise.all([browserLoop, httpLoop, aiLoop])+}++if (DRIP) {+ await dripMode()+} else {+ await seedMode()+}