Skip to content
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

Update server network debug tool #1511

Merged
merged 59 commits into from
Jan 11, 2024
Merged
Show file tree
Hide file tree
Changes from 58 commits
Commits
Show all changes
59 commits
Select commit Hold shift + click to select a range
3551ee8
header styles
wizardlyhel Nov 8, 2023
9ccad38
style flamechart
wizardlyhel Nov 8, 2023
11e235d
start building table
wizardlyhel Nov 9, 2023
18b9ebf
request table styling
wizardlyhel Nov 9, 2023
581d092
onclick handler
wizardlyhel Nov 10, 2023
d3df6f1
request details styling
wizardlyhel Nov 10, 2023
30f5870
Fix rendering issues
frandiox Nov 14, 2023
92e17a2
Implement preserve log
frandiox Nov 14, 2023
d76dab5
Save settings in local storage
frandiox Nov 14, 2023
be2b3f8
Rebuild CLI when changing CSS
frandiox Nov 14, 2023
ddcfb6b
Fix RequestTable height
frandiox Nov 14, 2023
754a7dd
Fix RequestWaterfall resizing
frandiox Nov 14, 2023
3068ec7
fix styling and add close button
wizardlyhel Nov 14, 2023
2c69835
Use callsites to find the location where subrequests originated
frandiox Nov 15, 2023
176feac
fix waterfall chart height
wizardlyhel Nov 15, 2023
6ba2b8d
add scroll in view
wizardlyhel Nov 15, 2023
cdc4f4b
style empty state
wizardlyhel Nov 15, 2023
e7572e2
Fix preserve log timeline
wizardlyhel Nov 15, 2023
a77ba82
remove uneeded asset
wizardlyhel Nov 15, 2023
f2e2df2
work around for a flame-chart-js bug
wizardlyhel Nov 16, 2023
99678aa
pull in more data for debug
wizardlyhel Nov 16, 2023
2c945ad
remove console log
wizardlyhel Nov 16, 2023
73810f3
add display name option
wizardlyhel Nov 17, 2023
864b57f
IDE doc
wizardlyhel Nov 17, 2023
8e63970
lighter timeframe chart
wizardlyhel Nov 17, 2023
018b818
Fix error when clicking outside of the bars
frandiox Nov 20, 2023
a745900
Fix active selection
wizardlyhel Nov 20, 2023
a392140
clean up
wizardlyhel Nov 20, 2023
d7e48aa
Merge remote-tracking branch 'origin/main' into hl-network-debug
wizardlyhel Nov 21, 2023
26e5a51
fix resizing on flamechart
wizardlyhel Nov 23, 2023
a894a0a
Fix tab styling
wizardlyhel Nov 23, 2023
71851e3
table row hover state
wizardlyhel Nov 23, 2023
9fc3596
prettier
wizardlyhel Nov 23, 2023
19f40ce
Fix non-absolute file path in workerd
frandiox Nov 24, 2023
35dfb1a
Fix stackOffset for cart queries
frandiox Nov 24, 2023
d637c4d
Merge remote-tracking branch 'origin/main' into hl-network-debug
wizardlyhel Dec 8, 2023
159d29c
adjust to new mock styles
wizardlyhel Dec 11, 2023
0f1cc92
clean up
wizardlyhel Dec 11, 2023
eb1ae80
notification banner styling
wizardlyhel Dec 12, 2023
fa819ee
header styling tweak
wizardlyhel Dec 12, 2023
56ff3cf
mobile styling
wizardlyhel Dec 12, 2023
a1e549b
fade scroll tabs
wizardlyhel Dec 13, 2023
c27c5ed
styling tweaks
wizardlyhel Dec 13, 2023
c81f490
style tweaks
wizardlyhel Dec 13, 2023
4ff53de
prettier
wizardlyhel Dec 13, 2023
d3f568f
add changeset
wizardlyhel Dec 13, 2023
8463770
remove empty file
wizardlyhel Dec 13, 2023
4169eb0
make createWithCache usage better
wizardlyhel Dec 14, 2023
303de1e
feedbacks
wizardlyhel Dec 14, 2023
66c50e8
update changeset
wizardlyhel Dec 14, 2023
876b965
prettier
wizardlyhel Dec 14, 2023
b9e9f1f
fix error
wizardlyhel Dec 14, 2023
0d41172
Clean up
wizardlyhel Jan 10, 2024
e6cc20e
Merge remote-tracking branch 'origin/main' into hl-network-debug
wizardlyhel Jan 10, 2024
4d077e3
Update name to subrequest profiler
wizardlyhel Jan 10, 2024
b4a8b6b
request error color
wizardlyhel Jan 10, 2024
f0e9547
simplify withCache debug param
wizardlyhel Jan 10, 2024
e8e7da3
prettier
wizardlyhel Jan 10, 2024
938f854
Merge remote-tracking branch 'origin/main' into hl-network-debug
wizardlyhel Jan 11, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions .changeset/neat-falcons-add.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
---
'@shopify/remix-oxygen': patch
'@shopify/hydrogen': patch
'@shopify/cli-hydrogen': patch
'@shopify/create-hydrogen': patch
---

Subrequest Profiler (stable) - Provides an overview of network requests happening on the server side

#### How to use:

1. Run `h2 dev`
2. Visit http://localhost:3000/subrequest-profiler

#### Set request display name with `storefront.query`:

```tsx
context.storefront.query(
HOMEPAGE_FEATURED_PRODUCTS_QUERY,
{
displayName: 'Feature products',
variables: {
country,
language,
},
},
)
```

#### Set request debug information with `createWithCache`:

```tsx
const withCache = createWithCache({
cache,
waitUntil,
request,
});

const data3p = async () => {
return await withCache(
['Some unique cache keys'],
CacheLong(),
({addDebugData}) => {
return fetch('https://some-3p-endpoint.com').then(async (response) => {
if (process.env.NODE_ENV === 'development') {
addDebugData({
displayName: '3p endpoint display name',
response,
});
}

return await response.json();
});
},
);
};
```

21 changes: 8 additions & 13 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"type": "module",
"scripts": {
"build": "tsup && node scripts/build-check.mjs",
"dev": "tsup --watch",
"dev": "tsup --watch ./src",
"typecheck": "tsc --noEmit",
"generate:manifest": "node scripts/generate-manifest.mjs",
"test": "cross-env SHOPIFY_UNIT_TEST=1 vitest run --test-timeout=20000",
Expand All @@ -26,7 +26,7 @@
"@vitest/coverage-v8": "^1.0.4",
"devtools-protocol": "^0.0.1177611",
"fast-glob": "^3.2.12",
"flame-chart-js": "2.3.1",
"flame-chart-js": "2.3.2",
"get-port": "^7.0.0",
"type-fest": "^4.5.0",
"vitest": "^1.0.4"
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/commands/hydrogen/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ async function runDev({
})}`,
),
colors.dim(
`\nView server-side network requests: ${miniOxygen.listeningAt}/debug-network`,
`\nView server network requests: ${miniOxygen.listeningAt}/subrequest-profiler`,
),
],
});
Expand Down
3 changes: 2 additions & 1 deletion packages/cli/src/lib/mini-oxygen/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import type {MiniOxygenInstance, MiniOxygenOptions} from './types.js';
import {OXYGEN_HEADERS_MAP, logRequestLine} from './common.js';
import {
H2O_BINDING_NAME,
logRequestEvent,
createLogRequestEvent,
handleDebugNetworkRequest,
} from '../request-events.js';

Expand All @@ -31,6 +31,7 @@ export async function startNodeServer({
}),
);

const logRequestEvent = createLogRequestEvent();
const asyncLocalStorage = new AsyncLocalStorage();
const serviceBindings = {
[H2O_BINDING_NAME]: {
Expand Down
4 changes: 2 additions & 2 deletions packages/cli/src/lib/mini-oxygen/workerd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import {OXYGEN_HEADERS_MAP, logRequestLine} from './common.js';
import {
H2O_BINDING_NAME,
handleDebugNetworkRequest,
logRequestEvent,
createLogRequestEvent,
setConstructors,
} from '../request-events.js';
import {
Expand Down Expand Up @@ -97,7 +97,7 @@ export async function startWorkerdServer({
compatibilityDate: '2022-10-31',
bindings: {...env},
serviceBindings: {
[H2O_BINDING_NAME]: logRequestEvent,
[H2O_BINDING_NAME]: createLogRequestEvent({absoluteBundlePath}),
},
},
],
Expand Down
114 changes: 80 additions & 34 deletions packages/cli/src/lib/request-events.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import path from 'node:path';
import {EventEmitter} from 'node:events';
import {ReadableStream} from 'node:stream/web';
import {getGraphiQLUrl} from './graphiql-url.js';
Expand All @@ -7,6 +8,7 @@ import type {
Response as WorkerdResponse,
ResponseInit,
} from 'miniflare';
import {mapSourcePosition} from 'source-map-support';

export const H2O_BINDING_NAME = 'H2O_LOG_EVENT';

Expand All @@ -23,7 +25,7 @@ export function setConstructors(constructors: {
ResponseConstructor = constructors.Response;
}

export const DEV_ROUTES = new Set(['/graphiql', '/debug-network']);
export const DEV_ROUTES = new Set(['/graphiql', '/subrequest-profiler']);

type RequestEvent = {
event: string;
Expand All @@ -44,15 +46,29 @@ export type H2OEvent = {
cacheStatus?: 'MISS' | 'HIT' | 'STALE' | 'PUT';
waitUntil?: ExecutionContext['waitUntil'];
graphql?: string;
stackInfo?: {
file?: string;
func?: string;
line?: number;
column?: number;
};
responsePayload?: any;
responseInit?: ResponseInit;
cache?: {
status?: string;
strategy?: string;
key?: string | readonly unknown[];
};
displayName?: string;
};

async function getRequestInfo(request: RequestKind) {
const data = (await request.json()) as H2OEvent;

return {
id: data.requestId ?? '',
...data,
requestId: data.requestId ?? '',
eventType: data.eventType || 'unknown',
startTime: data.startTime,
endTime: data.endTime || Date.now(),
purpose: data.purpose === 'prefetch' ? '(prefetch)' : '',
cacheStatus: data.cacheStatus ?? '',
Expand All @@ -79,45 +95,75 @@ async function clearHistory<R extends RequestKind>(
return createResponse<R>();
}

export async function logRequestEvent<R extends RequestKind>(
request: R,
): Promise<InferredResponse<R>> {
const url = new URL(request.url);
if (DEV_ROUTES.has(url.pathname)) {
return createResponse<R>();
}
export function createLogRequestEvent(options?: {absoluteBundlePath?: string}) {
return async function logRequestEvent<R extends RequestKind>(
request: R,
): Promise<InferredResponse<R>> {
const url = new URL(request.url);
if (DEV_ROUTES.has(url.pathname)) {
return createResponse<R>();
}

const {eventType, purpose, graphql, ...data} = await getRequestInfo(request);
const {eventType, purpose, graphql, stackInfo, ...data} =
await getRequestInfo(request);

let graphiqlLink = '';
let description = request.url;
let graphiqlLink = '';
let description = request.url;

if (eventType === 'subrequest') {
description =
graphql?.query
.match(/(query|mutation)\s+(\w+)/)?.[0]
?.replace(/\s+/, ' ') || decodeURIComponent(url.search.slice(1));
if (eventType === 'subrequest') {
description =
graphql?.query
.match(/(query|mutation)\s+(\w+)/)?.[0]
?.replace(/\s+/, ' ') ||
decodeURIComponent(url.search.slice(1)) ||
request.url;

if (graphql) {
graphiqlLink = getGraphiQLUrl({graphql});
if (graphql) {
graphiqlLink = getGraphiQLUrl({graphql});
}
}
}

const event = {
event: EVENT_MAP[eventType] || eventType,
data: JSON.stringify({
...data,
url: `${purpose} ${description}`.trim(),
graphiqlLink,
}),
};

eventHistory.push(event);
if (eventHistory.length > 100) eventHistory.shift();
let stackLine: string | null = null;
let stackLink: string | null = null;

eventEmitter.emit('request', event);
if (stackInfo?.file) {
if (!path.isAbsolute(stackInfo.file) && options?.absoluteBundlePath) {
stackInfo.file = options.absoluteBundlePath;
}

return createResponse<R>();
const {source, line, column} = mapSourcePosition({
source: stackInfo.file,
line: stackInfo.line ?? 0,
column: stackInfo.column ?? 0,
});

stackLine = `${source}:${line}:${column + 1}`;
stackLink = `vscode://${path.join('file', stackLine)}`;

stackLine = stackLine.split(path.sep + 'app' + path.sep)[1] ?? stackLine;
if (stackInfo.func) {
stackLine = `${stackInfo.func.replace(/\d+$/, '')} (${stackLine})`;
}
}

const event = {
event: EVENT_MAP[eventType] || eventType,
data: JSON.stringify({
...data,
url: `${purpose} ${description}`.trim(),
graphiqlLink,
stackLine,
stackLink,
}),
};

eventHistory.push(event);
if (eventHistory.length > 100) eventHistory.shift();

eventEmitter.emit('request', event);

return createResponse<R>();
};
}

function streamRequestEvents<R extends RequestKind>(
Expand Down
Loading
Loading