fix: address v2 stack review findings
This commit is contained in:
1 parent
53b518960c
commit
263702210a
48 files changed
+1235
-530
No files matched your search
@@ -24,6 +24,10 @@ export interface RenderSafeJsxOptions {
|
||||
budgets?: SafeJsxBudgets;
|
||||
}
|
||||
|
||||
export interface RenderCompiledSafeJsxOptions extends Omit<RenderSafeJsxOptions, "template"> {
|
||||
root: AstNode;
|
||||
}
|
||||
|
||||
export interface SafeJsxRenderResult {
|
||||
node: ReactNode;
|
||||
warnings: string[];
|
||||
@@ -351,11 +355,23 @@ class Interpreter {
|
||||
}
|
||||
}
|
||||
|
||||
export function renderSafeJsx({ template, components, bindings, budgets }: RenderSafeJsxOptions): SafeJsxRenderResult {
|
||||
export function compileSafeJsx(template: string): AstNode {
|
||||
return parseCustomJsxTemplate(template);
|
||||
}
|
||||
|
||||
export function renderCompiledSafeJsx({
|
||||
root,
|
||||
components,
|
||||
bindings,
|
||||
budgets,
|
||||
}: RenderCompiledSafeJsxOptions): SafeJsxRenderResult {
|
||||
const limits: EvaluationBudgets = { ...DEFAULT_BUDGETS, ...budgets };
|
||||
for (const [name, value] of Object.entries(limits)) {
|
||||
if (!Number.isSafeInteger(value) || value <= 0) throw new SafeJsxError(`Invalid interpreter budget: ${name}`);
|
||||
}
|
||||
const root = parseCustomJsxTemplate(template);
|
||||
return new Interpreter(components, new Environment(bindings), limits).render(root);
|
||||
}
|
||||
|
||||
export function renderSafeJsx({ template, ...options }: RenderSafeJsxOptions): SafeJsxRenderResult {
|
||||
return renderCompiledSafeJsx({ ...options, root: compileSafeJsx(template) });
|
||||
}
|
||||
@@ -68,7 +68,7 @@ export function emitJsxElement(
|
||||
child.type === "JSXExpressionContainer" ? asNode(child.expression, "JSX child expression") : null;
|
||||
if (resolvedTag === "SubFetch" && expression?.type === "ArrowFunctionExpression") {
|
||||
const callback = context.createCallback(expression, environment);
|
||||
return (value: unknown) => context.renderCallback(callback, [value], depth + 1);
|
||||
return (value: unknown, metadata: unknown) => context.renderCallback(callback, [value, metadata], depth + 1);
|
||||
}
|
||||
return context.evaluate(child, environment, depth + 1);
|
||||
});
|
||||
|
||||
@@ -3,12 +3,14 @@ import { Component, useCallback, useEffect, useId, useMemo, useState } from "rea
|
||||
import { Alert, Box, Stack, Text } from "@mantine/core";
|
||||
import { IconAlertTriangle } from "@tabler/icons-react";
|
||||
|
||||
import { renderSafeJsx } from "../jsx/interpreter";
|
||||
import { compileSafeJsx, renderCompiledSafeJsx } from "../jsx/interpreter";
|
||||
import { CustomJsxInputsProvider } from "../jsx/runtime-components";
|
||||
import type { WidgetInputType, WidgetInputValue } from "../jsx/runtime-components";
|
||||
import type { CustomJsxRequestCapability } from "./types";
|
||||
|
||||
const EMPTY_RECORD: Record<string, never> = {};
|
||||
const referenceIds = new WeakMap<object, number>();
|
||||
let nextReferenceId = 1;
|
||||
|
||||
const methodColors: Readonly<Record<string, string>> = {
|
||||
GET: "blue",
|
||||
@@ -162,12 +164,27 @@ function CustomJsxRendererSession({
|
||||
},
|
||||
[inputTypes],
|
||||
);
|
||||
const compiled = useMemo(() => {
|
||||
try {
|
||||
return { root: compileSafeJsx(template), error: null };
|
||||
} catch (error) {
|
||||
return { root: null, error: error instanceof Error ? error : new Error(String(error)) };
|
||||
}
|
||||
}, [template]);
|
||||
const rendered = useMemo(() => {
|
||||
if (compiled.error || !compiled.root) {
|
||||
return {
|
||||
node: null,
|
||||
warnings: [],
|
||||
boundaryKey: `${template.length}:compile-error`,
|
||||
error: compiled.error ?? new Error("Template compilation failed"),
|
||||
};
|
||||
}
|
||||
try {
|
||||
const bindings = { ...createBindings(data), status, options, inputs };
|
||||
return {
|
||||
...renderSafeJsx({ template, components, bindings }),
|
||||
boundaryKey: createBoundaryKey(template, bindings),
|
||||
...renderCompiledSafeJsx({ root: compiled.root, components, bindings }),
|
||||
boundaryKey: createBoundaryKey(template, [data, status, options, inputs]),
|
||||
error: null,
|
||||
};
|
||||
} catch (error) {
|
||||
@@ -178,7 +195,7 @@ function CustomJsxRendererSession({
|
||||
error: error instanceof Error ? error : new Error(String(error)),
|
||||
};
|
||||
}
|
||||
}, [components, createBindings, data, inputs, options, status, template]);
|
||||
}, [compiled, components, createBindings, data, inputs, options, status, template]);
|
||||
useEffect(() => setParseErrors([]), [rendered.boundaryKey, template]);
|
||||
const handleError = useCallback(
|
||||
(error: Error) =>
|
||||
@@ -228,9 +245,20 @@ function CustomJsxRendererSession({
|
||||
);
|
||||
}
|
||||
|
||||
function createBoundaryKey(template: string, bindings: Readonly<Record<string, unknown>>) {
|
||||
let hash = 0;
|
||||
const value = `${template}\0${JSON.stringify(bindings)}`;
|
||||
for (let index = 0; index < value.length; index += 1) hash = (hash * 31 + value.charCodeAt(index)) | 0;
|
||||
return `${template.length}:${hash}`;
|
||||
function createBoundaryKey(template: string, values: readonly unknown[]) {
|
||||
return `${template.length}:${values.map(referenceKey).join(":")}`;
|
||||
}
|
||||
|
||||
function referenceKey(value: unknown): string {
|
||||
if ((typeof value === "object" && value !== null) || typeof value === "function") {
|
||||
const reference = value as object;
|
||||
let id = referenceIds.get(reference);
|
||||
if (!id) {
|
||||
id = nextReferenceId;
|
||||
nextReferenceId += 1;
|
||||
referenceIds.set(reference, id);
|
||||
}
|
||||
return `r${id}`;
|
||||
}
|
||||
return `${typeof value}:${String(value)}`;
|
||||
}
|
||||
@@ -37,7 +37,7 @@ export function RefreshButton({ label, color = "gray", variant = "subtle", size
|
||||
size={size as never}
|
||||
onClick={() => void refresh()}
|
||||
loading={loading}
|
||||
disabled={(!runtime.itemId && !runtime.previewSessionId) || runtime.isEditMode}
|
||||
disabled={!runtime.canRefresh || (!runtime.itemId && !runtime.previewSessionId) || runtime.isEditMode}
|
||||
>
|
||||
<IconRefresh size={16} />
|
||||
</ActionIcon>
|
||||
|
||||
@@ -82,6 +82,7 @@ export interface CustomWidgetRuntimeValue {
|
||||
previewSessionId?: string;
|
||||
previewLiveActions?: boolean;
|
||||
queriesDisabled?: boolean;
|
||||
canRefresh?: boolean;
|
||||
isEditMode: boolean;
|
||||
requestCapabilities: readonly CustomJsxRequestCapability[];
|
||||
port: CustomWidgetRuntimePort;
|
||||
|
||||
@@ -33,6 +33,7 @@ export const MAX_REQUEST_BODY_BYTES = 10 * 1024;
|
||||
const REQUEST_TIMEOUT_MS = 10_000;
|
||||
const MAX_QUERY_REDIRECTS = 3;
|
||||
const MAX_RESPONSE_CACHE_ENTRIES = 1_000;
|
||||
const MAX_RESPONSE_CACHE_BYTES = 64 * 1024 * 1024;
|
||||
export const MAX_REQUEST_DURATION_MS = 45_000;
|
||||
const TIMEOUT_ERROR_CODES = new Set(["UND_ERR_CONNECT_TIMEOUT", "UND_ERR_HEADERS_TIMEOUT", "UND_ERR_BODY_TIMEOUT"]);
|
||||
const RESPONSE_TOO_LARGE_ERROR_CODE = "UND_ERR_RES_EXCEEDED_MAX_SIZE";
|
||||
@@ -63,9 +64,10 @@ export interface CustomWidgetHttpResponse {
|
||||
statusText: string;
|
||||
data: unknown;
|
||||
}
|
||||
const cache = new Map<string, { expiresAt: number; response: CustomWidgetHttpResponse }>();
|
||||
const cache = new Map<string, { expiresAt: number; response: CustomWidgetHttpResponse; size: number }>();
|
||||
const inFlight = new Map<string, Promise<CustomWidgetHttpResponse>>();
|
||||
let cacheEpoch = 0;
|
||||
let cacheBytes = 0;
|
||||
|
||||
type RequestHopResult =
|
||||
| { kind: "response"; response: CustomWidgetHttpResponse }
|
||||
@@ -256,8 +258,12 @@ export async function executeCustomWidgetRequest(input: CustomWidgetHttpRequest)
|
||||
const key = input.kind === "query" ? input.cacheKey : undefined;
|
||||
if (!key) return performRequest(input);
|
||||
const cached = cache.get(key);
|
||||
if (cached && cached.expiresAt > Date.now()) return cached.response;
|
||||
if (cached) cache.delete(key);
|
||||
if (cached && cached.expiresAt > Date.now()) {
|
||||
cache.delete(key);
|
||||
cache.set(key, cached);
|
||||
return cached.response;
|
||||
}
|
||||
if (cached) deleteCachedResponse(key);
|
||||
const pending = inFlight.get(key);
|
||||
if (pending) return pending;
|
||||
const requestEpoch = cacheEpoch;
|
||||
@@ -265,8 +271,12 @@ export async function executeCustomWidgetRequest(input: CustomWidgetHttpRequest)
|
||||
request = performRequest(input)
|
||||
.then((response) => {
|
||||
if (response.ok && (input.cacheTtlSeconds ?? 0) > 0 && requestEpoch === cacheEpoch) {
|
||||
pruneCache();
|
||||
cache.set(key, { expiresAt: Date.now() + (input.cacheTtlSeconds ?? 0) * 1000, response });
|
||||
const size = Buffer.byteLength(JSON.stringify(response), "utf8");
|
||||
if (size <= MAX_RESPONSE_CACHE_BYTES) {
|
||||
pruneCache(size);
|
||||
cache.set(key, { expiresAt: Date.now() + (input.cacheTtlSeconds ?? 0) * 1000, response, size });
|
||||
cacheBytes += size;
|
||||
}
|
||||
}
|
||||
return response;
|
||||
})
|
||||
@@ -280,15 +290,22 @@ export async function executeCustomWidgetRequest(input: CustomWidgetHttpRequest)
|
||||
export function invalidateCustomWidgetResponseCache(prefixes: readonly string[]): void {
|
||||
if (prefixes.length === 0) return;
|
||||
cacheEpoch += 1;
|
||||
for (const key of cache.keys()) if (prefixes.some((prefix) => key.startsWith(prefix))) cache.delete(key);
|
||||
for (const key of cache.keys()) if (prefixes.some((prefix) => key.startsWith(prefix))) deleteCachedResponse(key);
|
||||
for (const key of inFlight.keys()) if (prefixes.some((prefix) => key.startsWith(prefix))) inFlight.delete(key);
|
||||
}
|
||||
|
||||
function pruneCache(): void {
|
||||
for (const [key, entry] of cache) if (entry.expiresAt <= Date.now()) cache.delete(key);
|
||||
while (cache.size >= MAX_RESPONSE_CACHE_ENTRIES) {
|
||||
function pruneCache(incomingSize: number): void {
|
||||
for (const [key, entry] of cache) if (entry.expiresAt <= Date.now()) deleteCachedResponse(key);
|
||||
while (cache.size >= MAX_RESPONSE_CACHE_ENTRIES || cacheBytes + incomingSize > MAX_RESPONSE_CACHE_BYTES) {
|
||||
const key = cache.keys().next().value as string | undefined;
|
||||
if (!key) return;
|
||||
cache.delete(key);
|
||||
deleteCachedResponse(key);
|
||||
}
|
||||
}
|
||||
|
||||
function deleteCachedResponse(key: string): void {
|
||||
const cached = cache.get(key);
|
||||
if (!cached) return;
|
||||
cache.delete(key);
|
||||
cacheBytes = Math.max(0, cacheBytes - cached.size);
|
||||
}
|
||||
Reference in new issue
Block a user