Repository navigation
feat(devtools): proxy storage rpc to actual nitro storage runtime #1063
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.
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
Changes from all commits
7bb65a8
673942a
0d7955c
5994256
db1ded6
bce04b7
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,167 @@ | ||
| export const DEVTOOLS_STORAGE_ROUTE = '/__nuxt_devtools__/storage' | ||
|
|
||
| /** | ||
| * Env var carrying the per-process secret shared between the DevTools server | ||
| * and the bridge handler inside the Nitro dev worker. | ||
| */ | ||
| export const DEVTOOLS_STORAGE_BRIDGE_TOKEN_ENV = '__NUXT_DEVTOOLS_STORAGE_BRIDGE_TOKEN__' | ||
|
|
||
| /** | ||
| * Mounts Nitro adds for its own bookkeeping. | ||
| */ | ||
| export const IGNORE_STORAGE_MOUNTS = [ | ||
| 'root', | ||
| 'build', | ||
| 'src', | ||
| 'cache', | ||
| 'assets', | ||
| ] | ||
|
|
||
| /** | ||
| * Same normalisation unstorage applies before routing a key to a mount, so | ||
| * `/root:x`, `:root:x`, `root/x` and `\\root\\x` all resolve to `root`. | ||
| * Inlined to avoid importing either unstorage major. | ||
| */ | ||
| export function normalizeStorageKey(key: string) { | ||
| return key.split('?')[0]?.replace(/[/\\]/g, ':').replace(/:+/g, ':').replace(/^:|:$/g, '') || '' | ||
| } | ||
|
|
||
| // Mounts backed by the project itself (`root`/`src` are the filesystem) stay | ||
| // off limits for listing and for every item operation alike. | ||
| export function shouldIgnoreStorageKey(key: string) { | ||
| return IGNORE_STORAGE_MOUNTS.includes(normalizeStorageKey(key).split(':')[0]!) | ||
| } | ||
|
|
||
| function assertAllowedKey(key: unknown): string { | ||
| if (typeof key !== 'string' || shouldIgnoreStorageKey(key)) | ||
| throw new Error('[nuxt-devtools] Storage key is not allowed') | ||
| return key | ||
| } | ||
|
|
||
| export type StorageBridgeMethod = 'getKeys' | 'getItem' | 'setItem' | 'removeItem' | 'pullWatchEvents' | ||
|
|
||
| export interface StorageBridgeRequest { | ||
| token: string | ||
| method: StorageBridgeMethod | ||
| args?: unknown[] | ||
| } | ||
|
|
||
| export interface StorageBridgeWatchEvent { | ||
| event: 'update' | 'remove' | ||
| key: string | ||
| } | ||
|
|
||
| export interface StorageBridgeWatchBatch { | ||
| instance: string | ||
| cursor: number | ||
| events: StorageBridgeWatchEvent[] | ||
| } | ||
|
|
||
| /** | ||
| * Structural subset of unstorage's `Storage` shared by the v1 instance Nitro v2 | ||
| * bundles and the v2 instance Nitro v3 bundles, so the bridge works against | ||
| * whichever `useStorage()` returns without importing either version. | ||
| */ | ||
| export interface StorageBridgeStorage { | ||
| getKeys: (base?: string) => Promise<string[]> | ||
| getItem: (key: string) => Promise<unknown> | ||
| setItem: (key: string, value: any) => Promise<void> | ||
| removeItem: (key: string) => Promise<void> | ||
| getMounts?: () => Array<{ | ||
| base: string | ||
| driver: { | ||
| watch?: (callback: (event: 'update' | 'remove', key: string) => void) => Promise<unknown> | unknown | ||
| } | ||
| }> | ||
| } | ||
|
|
||
| const MAX_BUFFERED_EVENTS = 500 | ||
|
|
||
| interface WatchState { | ||
| instance: string | ||
| events: Array<StorageBridgeWatchEvent & { id: number }> | ||
| nextId: number | ||
| } | ||
|
|
||
| let watchState: WatchState | undefined | ||
|
|
||
| async function ensureWatcher(storage: StorageBridgeStorage): Promise<WatchState> { | ||
| if (watchState) | ||
| return watchState | ||
| const state: WatchState = { | ||
| instance: Math.random().toString(36).slice(2), | ||
| events: [], | ||
| nextId: 1, | ||
| } | ||
| watchState = state | ||
|
|
||
| const mounts = storage.getMounts?.() ?? [] | ||
| await Promise.all(mounts.map(async ({ base, driver }) => { | ||
| if (!driver?.watch || shouldIgnoreStorageKey(base)) | ||
| return | ||
| try { | ||
| await driver.watch((event, key) => { | ||
| state.events.push({ id: state.nextId++, event, key: base + key }) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Normalise the event key before buffering it. For an fs mount, a nested file emits Apply
|
||
| if (state.events.length > MAX_BUFFERED_EVENTS) | ||
| state.events.splice(0, state.events.length - MAX_BUFFERED_EVENTS) | ||
|
Comment on lines
+105
to
+106
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Signal buffer overflow so the client can refresh lost updates. If the selected item changes and 500 other events arrive before the next poll, this removes its update. The response then advances the client cursor beyond the removed event. Other events refresh the key list, but the editor reloads the selected value only for its matching event. That value therefore remains stale. (raw.githubusercontent.com) Keep the bounded buffer, but report a cursor gap and make the client refresh its keys and selected value when a gap occurs.
|
||
| }) | ||
| } | ||
| catch { | ||
| // Some drivers don't support watching; polling clients see no events for them. | ||
| } | ||
| })) | ||
|
|
||
| return state | ||
| } | ||
|
|
||
| function isValidToken(expected: string | undefined, actual: unknown): boolean { | ||
| if (!expected || typeof actual !== 'string' || actual.length !== expected.length) | ||
| return false | ||
| let diff = 0 | ||
| for (let i = 0; i < expected.length; i++) | ||
| diff |= expected.charCodeAt(i) ^ actual.charCodeAt(i) | ||
| return diff === 0 | ||
| } | ||
|
|
||
| export async function handleStorageBridgeRequest( | ||
| storage: StorageBridgeStorage, | ||
| body: StorageBridgeRequest | undefined, | ||
| token = process.env[DEVTOOLS_STORAGE_BRIDGE_TOKEN_ENV], | ||
| ) { | ||
| if (!body || !isValidToken(token, body.token)) | ||
| throw new Error('[nuxt-devtools] Invalid storage bridge token') | ||
|
|
||
| const args = body.args ?? [] | ||
| switch (body.method) { | ||
| case 'getKeys': { | ||
| const base = args[0] | ||
| if (base != null && typeof base !== 'string') | ||
| throw new Error('[nuxt-devtools] Storage base must be a string') | ||
| const keys = await storage.getKeys(base ?? undefined) | ||
| return { | ||
| result: keys.filter(key => !shouldIgnoreStorageKey(key)), | ||
| } | ||
| } | ||
| case 'getItem': | ||
| return { result: await storage.getItem(assertAllowedKey(args[0])) } | ||
| case 'setItem': | ||
| return { result: await storage.setItem(assertAllowedKey(args[0]), args[1]) } | ||
| case 'removeItem': | ||
| return { result: await storage.removeItem(assertAllowedKey(args[0])) } | ||
| case 'pullWatchEvents': { | ||
| const state = await ensureWatcher(storage) | ||
| const [instance, cursor] = args as [string | undefined, number | undefined] | ||
| const events = instance === state.instance | ||
| ? state.events.filter(e => e.id > (cursor ?? 0)) | ||
| : [] | ||
| const batch: StorageBridgeWatchBatch = { | ||
| instance: state.instance, | ||
| cursor: state.events.at(-1)?.id ?? 0, | ||
| events: events.map(({ event, key }) => ({ event, key })), | ||
| } | ||
| return { result: batch } | ||
| } | ||
| default: | ||
| throw new Error(`[nuxt-devtools] Unknown storage bridge method "${(body as StorageBridgeRequest).method}"`) | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| import { defineEventHandler, readBody } from 'h3' | ||
| import { useStorage } from 'nitropack/runtime' | ||
| import { handleStorageBridgeRequest } from './storage-bridge' | ||
|
|
||
| export default defineEventHandler(async (event) => { | ||
| return handleStorageBridgeRequest(useStorage(), await readBody(event)) | ||
| }) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| import { defineEventHandler, readBody } from 'nitro/h3' | ||
| import { useStorage } from 'nitro/storage' | ||
| import { handleStorageBridgeRequest } from './storage-bridge' | ||
|
|
||
| export default defineEventHandler(async (event) => { | ||
| return handleStorageBridgeRequest(useStorage(), await readBody(event)) | ||
| }) |
This file was deleted.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Use a storage-level subscription instead of watching the live driver directly.
In both resolved unstorage versions, the fs driver accepts only its first watch callback. A later
watch()call returns the existing cleanup function without registering another callback. If DevTools subscribes first, the application's lateruseStorage().watch()subscription receives no fs events. If the application subscribes first, DevTools receives no events. The previous implementation used separate driver instances. (raw.githubusercontent.com)Use the storage-level subscription API to share the driver watcher. Filter ignored keys and release the subscription with the runtime lifecycle. (raw.githubusercontent.com)