Adds logs to identify apps behavior#1043
Conversation
Tagging OptionsShould a new tag be published when this PR is merged?
|
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (4)
✅ Files skipped from review due to trivial changes (1)
🚧 Files skipped from review as they are similar to previous changes (3)
📝 WalkthroughWalkthroughAdds block-level request context propagation (a Changes
Sequence DiagramsequenceDiagram
participant Component as "Component\n(rgba(70,130,180,0.5))"
participant BlockUtils as "Block Utils\n(rgba(100,149,237,0.5))"
participant PatchedFetch as "Patched Fetch\n(rgba(60,179,113,0.5))"
participant Listeners as "Listeners\n(rgba(238,130,238,0.5))"
participant OTEL as "OTEL Logger\n(rgba(255,165,0,0.5))"
Component->>BlockUtils: execute component(fn, ctx)
BlockUtils->>BlockUtils: fnCtx = fnContextFromHttpContext(ctx)\nbound = RequestContext.bind(fnCtx, { blockId: ctx.resolverId })
BlockUtils->>PatchedFetch: call bound function (may trigger fetch)
PatchedFetch->>PatchedFetch: derive app, blockId, url, method\nrecord startedAt
PatchedFetch->>PatchedFetch: perform actual fetch (await)
PatchedFetch->>Listeners: emit FetchCompleteEvent(url,status,ok,duration,error,blockId)
Listeners->>OTEL: default listener logs structured fields
PatchedFetch-->>Component: return result / rethrow error
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 inconclusive)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Fix all issues with AI agents
In `@utils/patched_fetch.ts`:
- Around line 108-109: The computed abort signal is being overwritten when init
contains an explicit signal: undefined because the code uses { signal, ...init }
in the fetch call; change the call in patched_fetch (where fetcher is invoked)
to spread init first and then include the computed signal (e.g., { ...init,
signal }) so the computed signal wins and is preserved even if init.signal is
undefined.
- Around line 83-93: The current default log in the onFetch listener logs
event.url which can contain sensitive query strings; update the onFetch handler
to avoid logging full URLs by parsing event.url (use URL or equivalent) and log
only host and pathname (e.g., "fetch.host" and "fetch.path") or a redacted
version of the URL with query and hash removed, and include a clearly named
field like "fetch.redacted_url" instead of event.url; keep the other fields
(fetch.method, fetch.status, etc.) unchanged and ensure logger.info is updated
to use the redacted fields.
- Around line 96-122: The current globalThis.fetch override only calls
notifyListeners when fetcher resolves, so network errors/aborts are not emitted;
wrap the call to fetcher inside try/catch/finally in globalThis.fetch
(referencing globalThis.fetch, fetcher, RequestContext, listeners,
notifyListeners, Request) so that notifyListeners is always invoked: in the try
block capture the response; in catch record that there is no response and store
a sentinel status (e.g., 0) and ok=false and capture the error; in finally
compute duration and call notifyListeners with app, blockId, url, method,
startedAt, status (real or 0), ok, durationMs and optionally error details, then
rethrow the caught error so behavior is unchanged.
There was a problem hiding this comment.
2 issues found across 4 files
Prompt for AI agents (all issues)
Check if these issues are valid — if so, understand the root cause of each and fix them.
<file name="utils/patched_fetch.ts">
<violation number="1" location="utils/patched_fetch.ts:74">
P2: Iterating directly over the mutable `listeners` array is unsafe. If a listener unsubscribes synchronously during execution, the array is modified (spliced), which can cause subsequent listeners to be skipped. Iterate over a copy instead.</violation>
<violation number="2" location="utils/patched_fetch.ts:105">
P0: Constructing a `new Request(input, init)` consumes the body of `input` if it is a `Request` object. This causes the subsequent `fetcher(input)` call to fail or send an empty body for POST/PUT requests, as the body stream can only be read once. Additionally, `new Request()` throws errors on relative URLs, which are often valid in `fetch`.</violation>
</file>
Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.
There was a problem hiding this comment.
1 issue found across 1 file (changes from recent commits).
Prompt for AI agents (all issues)
Check if these issues are valid — if so, understand the root cause of each and fix them.
<file name="utils/patched_fetch.ts">
<violation number="1" location="utils/patched_fetch.ts:113">
P2: The computed `signal` will be overwritten if `init` contains an explicit `signal: undefined` property. When spreading `{ signal, ...init }`, properties from `init` override earlier properties. Reverse the spread order to ensure the computed signal takes precedence.</violation>
</file>
Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.
1f39cc0 to
7db4ca5
Compare
Add App/Block Identification to Fetch Monitoring
Summary
This PR enhances the fetch monitoring capabilities by tracking which app and block (loader/action) initiated each outgoing HTTP request. This enables better observability and debugging of external API calls across the deco runtime.
Changes
1. Extended
RequestContextwith block identification (deco.ts)blockId?: stringto theRequestContexttypeblockIdgetter toRequestContextBinderinterfaceRequestContext.blockId2. Block context binding in loader/action execution (
blocks/utils.tsx)applyProps()to bind theresolverIdasblockIdtoRequestContextRequestContext.bind()to ensure the context is available during the entire execution of the loader/action, including any fetch calls3. Enhanced fetch monitoring (
utils/patched_fetch.ts)onFetch()subscriber API for custom monitoringvtex/loaders/product/list.ts→vtex)fetch.app- The app that made the call (e.g., "vtex", "shopify")fetch.block_id- Full block identifier (e.g., "vtex/loaders/product/list.ts")fetch.url- The URL being fetchedfetch.method- HTTP method (GET, POST, etc.)fetch.status- Response status code (0 if request failed before response)fetch.ok- Whether response was successful (2xx)fetch.duration_ms- Request duration in millisecondsfetch.error- Error message (only present on failed requests)logger.errorand include the error message4. Exported new APIs (
mod.ts)onFetchfunction for custom monitoringFetchEventandFetchCompleteEventtypesHow It Works
Example Log Output
Successful request
{ "level": "INFO", "message": "outgoing fetch", "fetch.app": "vtex", "fetch.block_id": "vtex/loaders/product/productList.ts", "fetch.url": "https://api.vtex.com/products", "fetch.method": "GET", "fetch.status": 200, "fetch.ok": true, "fetch.duration_ms": 145 }Failed request
{ "level": "ERROR", "message": "outgoing fetch", "fetch.app": "vtex", "fetch.block_id": "vtex/loaders/product/productList.ts", "fetch.url": "https://api.vtex.com/products", "fetch.method": "GET", "fetch.status": 0, "fetch.ok": false, "fetch.duration_ms": 5023, "fetch.error": "connection timed out" }Custom Monitoring API
Users can subscribe to fetch events for custom monitoring:
Files Changed
deco.ts- Extended RequestContext type and interfaceblocks/utils.tsx- Bind blockId in applyProps()utils/patched_fetch.ts- Event system and OTEL loggingmod.ts- Export new APIsTesting
ctx.invoke) maintain correct blockIdonFetchsubscribers receive events correctlySummary by CodeRabbit