mirror of
https://github.com/webstudio-is/webstudio.git
synced 2026-12-01 21:05:42 +09:00
fix: capture fast form redirects and profile E2E resources
This commit is contained in:
1 parent
fb3588b2e6
commit
33769adf4d
6 files changed
+231
-15
No files matched your search
@@ -68,7 +68,8 @@ runs:
|
||||
if [ -n "$E2E_TEST_PARTITION" ]; then
|
||||
args+=(--shard="$E2E_TEST_PARTITION")
|
||||
fi
|
||||
pnpm --filter @webstudio-is/builder e2e:ci:shard -- "${args[@]}"
|
||||
bash apps/builder/e2e/measure-resources.sh \
|
||||
pnpm --filter @webstudio-is/builder e2e:ci:shard -- "${args[@]}"
|
||||
|
||||
- name: Upload report
|
||||
if: failure()
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { SerializedPages } from "@webstudio-is/project-migrations/pages";
|
||||
import type { Instance, Prop } from "@webstudio-is/sdk";
|
||||
import { loadDevBuild } from "../db";
|
||||
@@ -116,7 +117,7 @@ export const createDragProject = async (
|
||||
context,
|
||||
email: `drag-${name}@webstudio.test`,
|
||||
title: `Drag ${name}`,
|
||||
builderToken: `drag-${name}-builder-token`,
|
||||
builderToken: `drag-${name}-${randomUUID()}-builder-token`,
|
||||
createBuildUpdate: (build) => seedBuild(build.pages),
|
||||
});
|
||||
};
|
||||
|
||||
@@ -18,7 +18,9 @@ export const dragPointer = async ({
|
||||
page: Page;
|
||||
source: Locator;
|
||||
target: Locator;
|
||||
targetPoint?: (bounds: Bounds) => { x: number; y: number };
|
||||
targetPoint?: (
|
||||
bounds: Bounds
|
||||
) => Promise<{ x: number; y: number }> | { x: number; y: number };
|
||||
ready: () => Promise<boolean>;
|
||||
attempts?: number;
|
||||
beforeAttempt?: () => Promise<void>;
|
||||
@@ -45,7 +47,7 @@ export const dragPointer = async ({
|
||||
if (before === null) {
|
||||
throw new Error("Expected visible drag target");
|
||||
}
|
||||
const to = targetPoint(before);
|
||||
const to = await targetPoint(before);
|
||||
jiggle = jiggle === 0 ? 1 : 0;
|
||||
await page.mouse.move(to.x + jiggle, to.y, { steps: 3 });
|
||||
await page.waitForTimeout(120);
|
||||
@@ -90,10 +92,17 @@ export const dragTreeRow = async (
|
||||
page,
|
||||
source,
|
||||
target,
|
||||
targetPoint: ({ x, y, width, height }) => ({
|
||||
x: x + width / 2,
|
||||
y: y + height * (position === "above" ? 0.1 : 0.5),
|
||||
}),
|
||||
targetPoint: async (bounds) => {
|
||||
const button = await target
|
||||
.locator("[data-tree-button]")
|
||||
.first()
|
||||
.boundingBox();
|
||||
const { x, y, width, height } = button ?? bounds;
|
||||
return {
|
||||
x: x + width / 2,
|
||||
y: y + height * (position === "above" ? 0.1 : 0.5),
|
||||
};
|
||||
},
|
||||
ready: async () =>
|
||||
(await target.getAttribute("data-is-drop-over")) === "true" &&
|
||||
(position === "inside" ||
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
samples="$(mktemp)"
|
||||
trap 'rm -f "$samples"' EXIT
|
||||
|
||||
read_metric() {
|
||||
local file="$1"
|
||||
local key="$2"
|
||||
if [ -r "$file" ]; then
|
||||
awk -v key="$key" '$1 == key { print $2; exit }' "$file"
|
||||
fi
|
||||
}
|
||||
|
||||
read_pressure() {
|
||||
local file="$1"
|
||||
if [ -r "$file" ]; then
|
||||
awk '$1 == "some" { for (i = 2; i <= NF; i++) if ($i ~ /^total=/) { sub(/^total=/, "", $i); print $i; exit } }' "$file"
|
||||
fi
|
||||
}
|
||||
|
||||
sample() {
|
||||
local cpu_usage cpu_pressure memory_usage memory_pressure oom
|
||||
cpu_usage="$(read_metric /sys/fs/cgroup/cpu.stat usage_usec)"
|
||||
cpu_pressure="$(read_pressure /sys/fs/cgroup/cpu.pressure)"
|
||||
memory_usage="$(cat /sys/fs/cgroup/memory.current 2>/dev/null || true)"
|
||||
memory_pressure="$(read_pressure /sys/fs/cgroup/memory.pressure)"
|
||||
oom="$(read_metric /sys/fs/cgroup/memory.events oom)"
|
||||
printf '%s\t%s\t%s\t%s\t%s\t%s\n' \
|
||||
"$(date +%s%N)" "$cpu_usage" "$cpu_pressure" \
|
||||
"$memory_usage" "$memory_pressure" "$oom" >> "$samples"
|
||||
}
|
||||
|
||||
printf '[e2e:resources] logical_cpus=%s cpu_quota=%s memory_limit=%s\n' \
|
||||
"$(nproc 2>/dev/null || true)" \
|
||||
"$(cat /sys/fs/cgroup/cpu.max 2>/dev/null || true)" \
|
||||
"$(cat /sys/fs/cgroup/memory.max 2>/dev/null || true)"
|
||||
|
||||
sample
|
||||
(
|
||||
while true; do
|
||||
sleep 2
|
||||
sample
|
||||
done
|
||||
) &
|
||||
sampler_pid=$!
|
||||
|
||||
if "$@"; then
|
||||
result=0
|
||||
else
|
||||
result=$?
|
||||
fi
|
||||
|
||||
kill "$sampler_pid" 2>/dev/null || true
|
||||
wait "$sampler_pid" 2>/dev/null || true
|
||||
sample
|
||||
|
||||
python3 - "$samples" <<'PY'
|
||||
import sys
|
||||
|
||||
rows = []
|
||||
for line in open(sys.argv[1]):
|
||||
values = line.rstrip("\n").split("\t")
|
||||
if len(values) != 6:
|
||||
continue
|
||||
rows.append([int(value) if value.isdigit() else None for value in values])
|
||||
|
||||
if len(rows) >= 2:
|
||||
elapsed = (rows[-1][0] - rows[0][0]) / 1_000_000_000
|
||||
def delta(index):
|
||||
first, last = rows[0][index], rows[-1][index]
|
||||
return None if first is None or last is None else last - first
|
||||
def pressure(index):
|
||||
change = delta(index)
|
||||
return "unavailable" if change is None else f"{change / 10_000 / elapsed:.1f}%"
|
||||
cpu = delta(1)
|
||||
memory = [row[3] for row in rows if row[3] is not None]
|
||||
print(
|
||||
"[e2e:resources] "
|
||||
f"elapsed={elapsed:.1f}s "
|
||||
f"cpu_cores_avg={'unavailable' if cpu is None else f'{cpu / 1_000_000 / elapsed:.2f}'} "
|
||||
f"cpu_pressure={pressure(2)} "
|
||||
f"memory_peak_gib={'unavailable' if not memory else f'{max(memory) / 2**30:.2f}'} "
|
||||
f"memory_pressure={pressure(4)} "
|
||||
f"oom_events={delta(5)}"
|
||||
)
|
||||
PY
|
||||
|
||||
exit "$result"
|
||||
@@ -954,6 +954,7 @@ const createManagedFormSocket = ({
|
||||
bodyDelay = 0,
|
||||
unreadable = false,
|
||||
navigationGap = false,
|
||||
fastRedirect = false,
|
||||
unrelated,
|
||||
}: {
|
||||
body?: string;
|
||||
@@ -961,6 +962,7 @@ const createManagedFormSocket = ({
|
||||
bodyDelay?: number;
|
||||
unreadable?: boolean;
|
||||
navigationGap?: boolean | "stalled";
|
||||
fastRedirect?: boolean;
|
||||
unrelated?: { method: string; url: string; frameId: string };
|
||||
} = {}) => {
|
||||
const url = "http://127.0.0.1:5173/contact";
|
||||
@@ -974,6 +976,8 @@ const createManagedFormSocket = ({
|
||||
reads: [] as string[],
|
||||
lateReads: 0,
|
||||
gaps: 0,
|
||||
interceptedReads: 0,
|
||||
continuedResponses: 0,
|
||||
};
|
||||
const emit = (method: string, params: unknown) =>
|
||||
socket.emit("message", { data: JSON.stringify({ method, params }) });
|
||||
@@ -1003,6 +1007,31 @@ const createManagedFormSocket = ({
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (message.method === "Fetch.getResponseBody") {
|
||||
counters.interceptedReads += 1;
|
||||
setTimeout(
|
||||
() =>
|
||||
socket.emit("message", {
|
||||
data: JSON.stringify({
|
||||
id: message.id,
|
||||
result: { body, base64Encoded },
|
||||
}),
|
||||
}),
|
||||
0
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (message.method === "Fetch.continueResponse") {
|
||||
counters.continuedResponses += 1;
|
||||
send(data);
|
||||
setTimeout(() => {
|
||||
navigated = true;
|
||||
emit("Page.frameNavigated", {
|
||||
frame: { id: "main", url: "http://127.0.0.1:5173/thanks" },
|
||||
});
|
||||
}, 0);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
navigationGap &&
|
||||
message.method === "Runtime.evaluate" &&
|
||||
@@ -1076,11 +1105,22 @@ const createManagedFormSocket = ({
|
||||
});
|
||||
emit("Network.loadingFinished", { requestId: "unrelated" });
|
||||
}
|
||||
emit("Network.loadingFinished", { requestId: "managed" });
|
||||
navigated = true;
|
||||
emit("Page.frameNavigated", {
|
||||
frame: { id: "main", url: "http://127.0.0.1:5173/thanks" },
|
||||
});
|
||||
if (fastRedirect) {
|
||||
emit("Fetch.requestPaused", {
|
||||
requestId: "intercepted-managed",
|
||||
responseStatusCode: 200,
|
||||
request: {
|
||||
method: "POST",
|
||||
url: "http://127.0.0.1:5173/__ws-form/contact",
|
||||
},
|
||||
});
|
||||
} else {
|
||||
emit("Network.loadingFinished", { requestId: "managed" });
|
||||
navigated = true;
|
||||
emit("Page.frameNavigated", {
|
||||
frame: { id: "main", url: "http://127.0.0.1:5173/thanks" },
|
||||
});
|
||||
}
|
||||
}, 5);
|
||||
}
|
||||
};
|
||||
@@ -1142,6 +1182,31 @@ test.each([false, true])(
|
||||
}
|
||||
);
|
||||
|
||||
test("captures managed Form results before a fast redirect discards the network body", async () => {
|
||||
const { socket, counters } = createManagedFormSocket({ fastRedirect: true });
|
||||
const session = await createFormBrowserSession(socket);
|
||||
try {
|
||||
const result = await session.submitForm!({
|
||||
url: "http://127.0.0.1:5173/contact",
|
||||
selector: "form",
|
||||
values: [],
|
||||
timeout: 1000,
|
||||
});
|
||||
expect(result).toMatchObject({
|
||||
status: "submitted",
|
||||
results: [{ status: 201, resourceId: "action" }],
|
||||
});
|
||||
expect(counters).toMatchObject({
|
||||
submissions: 1,
|
||||
interceptedReads: 1,
|
||||
continuedResponses: 1,
|
||||
reads: [],
|
||||
});
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("continues observing across a navigation execution-context gap without replaying the Form", async () => {
|
||||
const { socket, counters } = createManagedFormSocket({ navigationGap: true });
|
||||
const session = await createFormBrowserSession(socket);
|
||||
|
||||
@@ -2400,6 +2400,9 @@ const submitFormWithBrowserRuntime = async (
|
||||
let managedResponseBody:
|
||||
| Promise<{ body?: string; base64Encoded?: boolean } | undefined>
|
||||
| undefined;
|
||||
let interceptedManagedResponseBody:
|
||||
| Promise<{ body?: string; base64Encoded?: boolean } | undefined>
|
||||
| undefined;
|
||||
const submissionRequestIds = new Set<string>();
|
||||
const completedRequestIds = new Set<string>();
|
||||
let navigationObserved = false;
|
||||
@@ -2547,6 +2550,46 @@ const submitFormWithBrowserRuntime = async (
|
||||
}
|
||||
}
|
||||
});
|
||||
cdp.on("Fetch.requestPaused", (params) => {
|
||||
if (
|
||||
typeof params !== "object" ||
|
||||
params === null ||
|
||||
!("requestId" in params) ||
|
||||
typeof params.requestId !== "string"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const requestId = params.requestId;
|
||||
if (
|
||||
"responseStatusCode" in params &&
|
||||
typeof params.responseStatusCode === "number" &&
|
||||
"request" in params &&
|
||||
typeof params.request === "object" &&
|
||||
params.request !== null &&
|
||||
"url" in params.request &&
|
||||
typeof params.request.url === "string" &&
|
||||
"method" in params.request &&
|
||||
params.request.method === "POST"
|
||||
) {
|
||||
const responseUrl = new URL(params.request.url);
|
||||
const initialUrl = new URL(initialPageUrl);
|
||||
if (
|
||||
responseUrl.origin === initialUrl.origin &&
|
||||
responseUrl.pathname ===
|
||||
`/__ws-form${initialUrl.pathname === "/" ? "" : initialUrl.pathname}`
|
||||
) {
|
||||
// Read before releasing the response so a fast redirect cannot discard it.
|
||||
interceptedManagedResponseBody = send<{
|
||||
body?: string;
|
||||
base64Encoded?: boolean;
|
||||
}>("Fetch.getResponseBody", { requestId }).finally(() =>
|
||||
send("Fetch.continueResponse", { requestId })
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
void send("Fetch.continueResponse", { requestId }).catch(() => undefined);
|
||||
});
|
||||
await Promise.all([
|
||||
send("Page.enable"),
|
||||
send("Runtime.enable"),
|
||||
@@ -2555,6 +2598,9 @@ const submitFormWithBrowserRuntime = async (
|
||||
maxTotalBufferSize: 4_000_000,
|
||||
maxResourceBufferSize: 1_000_000,
|
||||
}),
|
||||
send("Fetch.enable", {
|
||||
patterns: [{ urlPattern: "*__ws-form*", requestStage: "Response" }],
|
||||
}),
|
||||
send("Page.setLifecycleEventsEnabled", { enabled: true }),
|
||||
]);
|
||||
const navigation = await navigateAndWaitForLifecycle(
|
||||
@@ -2680,8 +2726,13 @@ const submitFormWithBrowserRuntime = async (
|
||||
resourceName?: string;
|
||||
}[] = [];
|
||||
const errors: { status?: number; name?: string; message: string }[] = [];
|
||||
if (managedResponseBody !== undefined) {
|
||||
const body = await managedResponseBody;
|
||||
if (
|
||||
interceptedManagedResponseBody !== undefined ||
|
||||
managedResponseBody !== undefined
|
||||
) {
|
||||
const body =
|
||||
(await interceptedManagedResponseBody?.catch(() => undefined)) ??
|
||||
(await managedResponseBody);
|
||||
if (body?.body !== undefined && body.body.length < 1_000_000) {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(
|
||||
|
||||
Reference in new issue
Block a user