GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat(nuxt): Instrument Nitro v3 cache storage by sentry-junior[bot] · Pull Request #25951 · getsentry/sentry-javascript

feat(nuxt): Instrument Nitro v3 cache storage #25951

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
mydea merged 10 commits into develop from feat/nuxt-nitro-v3-cache-instrumentation
Nov 13, 2026

Uh oh!

There was an error while loading. Please reload this page.

Merged

feat(nuxt): Instrument Nitro v3 cache storage #25951

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
10 commits
Select commit Hold shift + click to select a range
5ec2b5e
ref(server-runtime-injection): Say when hook registration fails becau…
sentry-junior[bot] Nov 13, 2026
98d18f2
feat(nuxt): Instrument Nitro v3 cache storage
sentry-junior[bot] Oct 30, 2026
2e9978a
test(nuxt): Type cache storage mock set options
sentry-junior[bot] Oct 30, 2026
fc16ac1
ref(nuxt): Rely on startSpan to set error status for cache spans
sentry-junior[bot] Nov 3, 2026
cf1e2d3
ref(nuxt): Use handleCallbackErrors for cache span errors
sentry-junior[bot] Nov 3, 2026
72a11ca
ref(nuxt): Wrap cache span in handleCallbackErrors
sentry-junior[bot] Nov 3, 2026
871217e
ref(nuxt): Drop explicit OK status on cache spans
sentry-junior[bot] Nov 4, 2026
9b2efb4
ref(nuxt): Hardcode cache storage mechanism type
sentry-junior[bot] Nov 4, 2026
7e80366
test(nuxt): Add kv cache driver variant to nuxt-5 cache tests
sentry-junior[bot] Nov 4, 2026
9414e89
test(nuxt): Use conventions constants in cache storage tests
sentry-junior[bot] Nov 4, 2026
File filter
Filter by extension


Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view

There are no files selected for viewing

4 changes: 1 addition & 3 deletions 4 dev-packages/e2e-tests/test-applications/nuxt-5/nuxt.config.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,7 @@ export default defineNuxtConfig({
},
},
nitro: {
// Nitro v3 only routes `defineCachedFunction`/`defineCachedHandler` through KV storage (which the SDK
// instruments) with the `kv` cache driver. The default `memory` driver bypasses KV storage entirely.
cache: { driver: 'kv' },
...(process.env.E2E_TEST_CACHE_DRIVER && { cache: { driver: process.env.E2E_TEST_CACHE_DRIVER } }),
experimental: {
database: true,
},
Expand Down
9 changes: 8 additions & 1 deletion 9 dev-packages/e2e-tests/test-applications/nuxt-5/package.json
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@
"test:assert": "pnpm test:prod && pnpm test:dev",
"test:build:tunnel-basepath": "pnpm install && E2E_TEST_TUNNEL=1 E2E_TEST_BASE_PATH=/app pnpm build",
"test:assert:tunnel-basepath": "E2E_TEST_TUNNEL=1 E2E_TEST_BASE_PATH=/app TEST_ENV=production playwright test tunnel",
"test:assert:tunnel-dev": "E2E_TEST_TUNNEL=1 TEST_ENV=development playwright test tunnel"
"test:assert:tunnel-dev": "E2E_TEST_TUNNEL=1 TEST_ENV=development playwright test tunnel",
"test:build:kv-cache": "pnpm install && E2E_TEST_CACHE_DRIVER=kv pnpm build",
"test:assert:kv-cache": "E2E_TEST_CACHE_DRIVER=kv TEST_ENV=production playwright test cache"
},
"//": [
"Currently, we need to install the Nuxt nightlies as those contain Nuxt v5",
Expand Down Expand Up @@ -54,6 +56,11 @@
"build-command": "pnpm install",
"assert-command": "pnpm test:assert:tunnel-dev",
"label": "nuxt-5 (tunnel-dev)"
},
{
"build-command": "pnpm test:build:kv-cache",
"assert-command": "pnpm test:assert:kv-cache",
"label": "nuxt-5 (kv-cache)"
}
]
}
Expand Down
29 changes: 19 additions & 10 deletions 29 dev-packages/e2e-tests/test-applications/nuxt-5/tests/cache.test.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
import { expect, test } from '@playwright/test';
import { collectStreamedSpansUntilSegment } from '@sentry-internal/test-utils';

// Nitro v3 only routes cached functions and handlers through KV storage with the `kv` cache driver,
// so the default (`memory`) driver is traced through ocache's storage instead.
const isKvCacheDriver = process.env.E2E_TEST_CACHE_DRIVER === 'kv';
const GET_METHOD = isKvCacheDriver ? 'getItem' : 'get';
const SET_METHOD = isKvCacheDriver ? 'setItem' : 'set';
const STORAGE_ATTRIBUTES = isKvCacheDriver
? { 'db.collection.name': { type: 'string', value: expect.stringMatching(/^(cache)?$/) } }
: { 'db.system.name': { type: 'string', value: 'memory' } };

test.describe('Cache Instrumentation', () => {
const SEMANTIC_ATTRIBUTE_CACHE_KEY = 'cache.key';
const SEMANTIC_ATTRIBUTE_CACHE_HIT = 'cache.hit';
Expand Down Expand Up @@ -34,8 +43,8 @@ test.describe('Cache Instrumentation', () => {

const getCacheKey = (span: (typeof allCacheSpans)[number]) => span.attributes[SEMANTIC_ATTRIBUTE_CACHE_KEY]?.value;

// Test getItem spans for cachedFunction - should have both cache miss and cache hit
const getItemSpans = findSpansByMethod('getItem');
// Test read spans for cachedFunction - should have both cache miss and cache hit
const getItemSpans = findSpansByMethod(GET_METHOD);
expect(getItemSpans.length).toBeGreaterThan(0);

// Find cache miss (first call to getCachedUser('123'))
Expand All @@ -51,8 +60,8 @@ test.describe('Cache Instrumentation', () => {
'cache.operation': { type: 'string', value: 'get' },
'sentry.origin': { type: 'string', value: 'auto.cache.nuxt' },
[SEMANTIC_ATTRIBUTE_CACHE_HIT]: { type: 'boolean', value: false },
'db.operation.name': { type: 'string', value: 'getItem' },
'db.collection.name': { type: 'string', value: expect.stringMatching(/^(cache)?$/) },
'db.operation.name': { type: 'string', value: GET_METHOD },
...STORAGE_ATTRIBUTES,
});
}

Expand All @@ -69,13 +78,13 @@ test.describe('Cache Instrumentation', () => {
'cache.operation': { type: 'string', value: 'get' },
'sentry.origin': { type: 'string', value: 'auto.cache.nuxt' },
[SEMANTIC_ATTRIBUTE_CACHE_HIT]: { type: 'boolean', value: true },
'db.operation.name': { type: 'string', value: 'getItem' },
'db.collection.name': { type: 'string', value: expect.stringMatching(/^(cache)?$/) },
'db.operation.name': { type: 'string', value: GET_METHOD },
...STORAGE_ATTRIBUTES,
});
}

// Test setItem spans for cachedFunction - when cache miss occurs, value is set
const setItemSpans = findSpansByMethod('setItem');
// Test write spans for cachedFunction - when cache miss occurs, value is set
const setItemSpans = findSpansByMethod(SET_METHOD);
expect(setItemSpans.length).toBeGreaterThan(0);

const cacheSetSpan = setItemSpans.find(
Expand All @@ -86,8 +95,8 @@ test.describe('Cache Instrumentation', () => {
'sentry.op': { type: 'string', value: 'cache.put' },
'cache.operation': { type: 'string', value: 'put' },
'sentry.origin': { type: 'string', value: 'auto.cache.nuxt' },
'db.operation.name': { type: 'string', value: 'setItem' },
'db.collection.name': { type: 'string', value: expect.stringMatching(/^(cache)?$/) },
'db.operation.name': { type: 'string', value: SET_METHOD },
...STORAGE_ATTRIBUTES,
});
}

Expand Down
152 changes: 119 additions & 33 deletions 152 packages/nuxt/src/runtime/utils/instrumentStorage.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,9 @@ import {
captureException,
debug,
getClient,
handleCallbackErrors,
hasSpanStreamingEnabled,
isObjectLike,
SPAN_STATUS_ERROR,
SPAN_STATUS_OK,
type SpanAttributes,
startSpan,
type StartSpanOptions,
Expand All @@ -32,6 +31,7 @@ import type { Driver, Storage } from 'unstorage';
interface CacheEntry<T = unknown> {
value?: T;
expires?: number;
stale?: boolean;
}

/**
Expand Down Expand Up @@ -180,33 +180,119 @@ function createMethodWrapper(

debug.log(`[storage] Running method: "${methodName}" on driver: "${driver.name ?? 'unknown'}"`);

return startSpan(options, async span => {
try {
const result = await target.apply(thisArg, args);
span.setStatus({ code: SPAN_STATUS_OK });

if (CACHE_HIT_METHODS.has(methodName)) {
span.setAttribute(CACHE_HIT, resolveCacheHit(methodName, args[0], result));
}

return result;
} catch (error) {
span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });
captureException(error, {
mechanism: {
handled: false,
type: options.attributes?.[SENTRY_ORIGIN],
},
});

// Re-throw the error to be handled by the caller
throw error;
} finally {
await flushIfServerless();
return traceCacheOperation(
options,
() => target.apply(thisArg, args),
CACHE_HIT_METHODS.has(methodName) ? result => resolveCacheHit(methodName, args[0], result) : undefined,
);
},
});
}

/**
* Runs a cache operation in a span, optionally recording whether the result was a cache hit.
*/
function traceCacheOperation(
options: StartSpanOptions,
operation: () => unknown,
getCacheHit?: (result: unknown) => boolean,
Comment thread
sentry-junior[bot] marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.

): Promise<unknown> {
return handleCallbackErrors(
() =>
startSpan(options, async span => {
const result = await operation();

if (getCacheHit) {
span.setAttribute(CACHE_HIT, getCacheHit(result));
}

return result;
}),
error => {
captureException(error, {
mechanism: {
handled: false,
type: 'auto.cache.nuxt',
},
Comment thread
sentry-junior[bot] marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.

});
},
});
() => {
void flushIfServerless();
},
);
}

/**
* The storage behind Nitro v3's `defineCachedFunction` and `defineCachedHandler` (an `ocache` storage).
*/
interface NitroCacheStorage {
get(key: string): unknown;
set(key: string, value: unknown, opts?: { ttl?: number }): unknown;
}

/**
* Instruments the storage that Nitro v3 caches functions and handlers in.
*
* Unlike Nitro v2, Nitro v3 only writes its cache to KV storage with the `kv` cache driver, so the KV
* driver instrumentation doesn't see the default `memory` or the `fs` cache driver.
* The storage is patched in place because `ocache` reads other properties, like `binary`, from it.
*/
export function instrumentCacheStorage<T extends NitroCacheStorage>(
storage: MaybeInstrumented<T>,
driverName: string,
): T {
if (storage.__sentry_instrumented__) {
return storage;
}

const originalGet = storage.get.bind(storage);
const originalSet = storage.set.bind(storage);

storage.get = (key: string) =>
traceCacheOperation(
createCacheStorageSpanStartOptions('get', CACHE_GET, key, driverName),
() => originalGet(key),
isCacheEntryHit,
);

storage.set = (key: string, value: unknown, opts?: { ttl?: number }) =>
// `ocache` deletes an entry by setting it to `null`
traceCacheOperation(
createCacheStorageSpanStartOptions('set', value == null ? CACHE_REMOVE : CACHE_PUT, key, driverName),
() => originalSet(key, value, opts),
);

storage.__sentry_instrumented__ = true;

return storage;
}

function createCacheStorageSpanStartOptions(
methodName: keyof NitroCacheStorage,
cacheOperation: typeof CACHE_GET | typeof CACHE_PUT | typeof CACHE_REMOVE,
key: string,
driverName: string,
): StartSpanOptions {
const client = getClient();
return {
// With span streaming, span names have to be low cardinality, so we can't fall back to the cache key.
name: client && hasSpanStreamingEnabled(client) ? cacheOperation : key,
attributes: {
[SENTRY_OP]: cacheOperation,
[CACHE_OPERATION]: CACHE_OPERATION_NAMES[cacheOperation],
[SENTRY_ORIGIN]: 'auto.cache.nuxt',
[CACHE_KEY]: key,
[DB_OPERATION_NAME]: methodName,
[DB_SYSTEM_NAME]: driverName,
},
};
}

/**
* `ocache` storage holds full cache entries, so a stored but expired or stale entry is a miss.
*/
function isCacheEntryHit(entry: unknown): boolean {
return isObjectLike(entry) && !(entry as CacheEntry).stale && isFreshCacheEntry(entry);
}

/**
Expand Down Expand Up @@ -338,13 +424,7 @@ function validateCacheEntry(
key: string,
entry: CacheEntry | CacheEntry<ResponseCacheEntry & { status: number }>,
): boolean {
if (entry.value == null) {
return false;
}

// Date.now is used by Nitro internally, so safe to use here.
// https://github.com/nitrojs/nitro/blob/5508f71b77730e967fb131de817725f5aa7c4862/src/runtime/internal/cache.ts#L78
if (Date.now() > (entry.expires || 0)) {
if (!isFreshCacheEntry(entry)) {
return false;
}

Expand All @@ -369,6 +449,12 @@ function validateCacheEntry(
return true;
}

function isFreshCacheEntry<T>(entry: CacheEntry<T>): entry is CacheEntry<T> & { value: NonNullable<T> } {
// Date.now is used by Nitro internally, so safe to use here.
// https://github.com/nitrojs/nitro/blob/5508f71b77730e967fb131de817725f5aa7c4862/src/runtime/internal/cache.ts#L78
return entry.value != null && Date.now() <= (entry.expires || 0);
}

/**
* Checks if the cache entry is a response cache entry.
*/
Expand Down
6 changes: 5 additions & 1 deletion 6 packages/nuxt/src/vite/nitroServer.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
} from './addServerConfig';
import { addDatabaseInstrumentation } from './databaseConfig';
import { addMiddlewareImports, addMiddlewareInstrumentation } from './middlewareConfig';
import { addStorageInstrumentation } from './storageConfig';
import { addCacheStorageInstrumentation, addStorageInstrumentation } from './storageConfig';
import { addRuntimeInjectionTraceDep, type ServerApi } from './utils';

type NitroModuleOptions = Omit<SentryNuxtModuleOptions, 'experimental_entrypointWrappedFunctions'> &
Expand Down Expand Up @@ -65,6 +65,10 @@ export function setupNitroServer(

addMiddlewareInstrumentation(nitro, isNitroV3);

if (isNitroV3) {
addCacheStorageInstrumentation(nitro);
}

if (deprecatedInjectMode) {
setupDeprecatedInjectMode(nitro, deprecatedInjectMode, isNitroV3, serverConfigFile, moduleOptions);
return;
Expand Down
49 changes: 49 additions & 0 deletions 49 packages/nuxt/src/vite/storageConfig.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import { addNitroPlugin, createResolver } from '@nuxt/kit';
import type { Nuxt } from '@nuxt/schema';
import type { Nitro } from 'nitropack/types';
import type { InputPluginOption } from 'rollup';
import { addServerTemplate } from '../vendor/server-template';

const NITRO_CACHE_VIRTUAL_MODULE_ID = '#nitro/virtual/cache';
const CREATE_CACHE_STORAGE_EXPORT = 'export const createCacheStorage =';

/**
* Prepares the storage config export to be used in the runtime storage instrumentation.
*/
Expand All @@ -23,3 +28,47 @@ export function addStorageInstrumentation(nuxt: Nuxt, isLegacyNitro: boolean): v
addNitroPlugin(moduleDirResolver.resolve('./runtime/plugins/storage.server'));
}
}

/**
* Instruments the storage behind Nitro v3's cached functions and handlers.
*
* Nitro v3 creates that storage in the `#nitro/virtual/cache` module, which is generated at build time and
* can't be reached at runtime, so the module's `createCacheStorage` export is wrapped while bundling.
*/
export function addCacheStorageInstrumentation(nitro: Nitro): void {
nitro.hooks.hook('rollup:before', (nitro, rollupConfig) => {
if (!rollupConfig.plugins) {
rollupConfig.plugins = [];
}

if (!Array.isArray(rollupConfig.plugins)) {
rollupConfig.plugins = [rollupConfig.plugins];
}

rollupConfig.plugins.push(cacheStorageInstrumentationPlugin(nitro));
});
}

function cacheStorageInstrumentationPlugin(nitro: Nitro): InputPluginOption {
const instrumentStoragePath = createResolver(import.meta.url).resolve('./runtime/utils/instrumentStorage');

return {
name: 'sentry-nuxt-cache-storage-instrumentation',
transform(code: string, id: string) {
// The `kv` driver re-exports a KV-backed storage, which the storage plugin already instruments
if (id !== NITRO_CACHE_VIRTUAL_MODULE_ID || !code.includes(CREATE_CACHE_STORAGE_EXPORT)) {
return null;
}

const driverName = (nitro.options as { cache?: { driver?: string } }).cache?.driver ?? 'memory';

return {
code: `import { instrumentCacheStorage } from ${JSON.stringify(instrumentStoragePath)};
${code.replace(CREATE_CACHE_STORAGE_EXPORT, 'const createUninstrumentedCacheStorage =')}
export const createCacheStorage = () => instrumentCacheStorage(createUninstrumentedCacheStorage(), ${JSON.stringify(driverName)});
`,
map: null,
};
},
};
}
Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.