Skip to content

A modern and easy to use dashboard. 80+ integrations. 20K+ icons built in. Authentication out of the box. No YAML, drag and drop configuration.

fix(custom-widgets): exclude cache hits from query budgets (#7305)

Thomas3279486ea6b8
diff --git a/packages/api/src/router/widgets/custom-api.ts b/packages/api/src/router/widgets/custom-api.ts
index a1cf6c884..d21a431ec 100644
--- a/packages/api/src/router/widgets/custom-api.ts
+++ b/packages/api/src/router/widgets/custom-api.ts
@@ -131,6 +131,7 @@ const withRequestLimit = async <T>(
category: RequestLimitInput["category"],
callback: () => Promise<T>,
load?: RequestLimitInput["load"],
+ phase?: RequestLimitInput["phase"],
) => {
const release = await acquireCustomWidgetRequestLimit({
category,
@@ -139,6 +140,7 @@ const withRequestLimit = async <T>(
itemId: resolved.item.id,
definitionId: resolved.stored.id,
load,
+ phase,
});
try {
return await callback();
@@ -162,6 +164,12 @@ const executeRequest = async (
const values = resolveCustomWidgetRequestValues(request, resolved.configuration, params);
let category: RequestLimitInput["category"] = "query";
if (request.kind === "action") category = request.method === "DELETE" ? "delete" : "action";
+ let phase: RequestLimitInput["phase"];
+ let beforeRequest: (() => Promise<void>) | undefined;
+ if (request.kind === "query") {
+ phase = "concurrency";
+ beforeRequest = () => withRequestLimit(ctx, resolved, "query", async () => undefined, load, "rate");
+ }
return withRequestLimit(
ctx,
resolved,
@@ -185,10 +193,12 @@ const executeRequest = async (
cacheKey:
request.kind === "query" ? `${getCacheKey(resolved, request, values)}:${connection.cacheVersion}` : undefined,
cacheTtlSeconds: request.cacheSeconds,
+ beforeRequest,
});
return { ...response, sourceCacheVersion: connection.cacheVersion };
},
load,
+ phase,
);
};
diff --git a/packages/custom-widgets/src/core/request-schema.ts b/packages/custom-widgets/src/core/request-schema.ts
index 5dd57c61e..cfdb48423 100644
--- a/packages/custom-widgets/src/core/request-schema.ts
+++ b/packages/custom-widgets/src/core/request-schema.ts
@@ -174,7 +174,13 @@ export const customJsxRequestSchema = z
headers: headersSchema.optional(),
auth: z.enum(["inherit", "none"]).default("inherit"),
permission: z.enum(["view", "modify", "full"]).optional(),
- cacheSeconds: z.number().int().min(0).max(3600).optional(),
+ cacheSeconds: z
+ .number()
+ .int()
+ .min(0)
+ .max(3600)
+ .optional()
+ .describe("Query response cache lifetime in seconds. Defaults to 30; set 0 to disable caching."),
confirmation: confirmationSchema.optional(),
invalidates: z.array(customWidgetIdentifierSchema).max(32).optional(),
})
diff --git a/packages/custom-widgets/src/server/request-dispatcher-lifecycle.ts b/packages/custom-widgets/src/server/request-dispatcher-lifecycle.ts
index 213ebe104..b902099d1 100644
--- a/packages/custom-widgets/src/server/request-dispatcher-lifecycle.ts
+++ b/packages/custom-widgets/src/server/request-dispatcher-lifecycle.ts
@@ -30,7 +30,7 @@ function detachDispatcherDestroy(dispatcher: CustomWidgetDispatcher): void {
}
}
-function abortable<T>(operation: Promise<T>, signal: AbortSignal): Promise<T> {
+export function abortable<T>(operation: Promise<T>, signal: AbortSignal): Promise<T> {
if (signal.aborted) {
void operation.catch(() => undefined);
return Promise.reject(signal.reason ?? createAbortError());
diff --git a/packages/custom-widgets/src/server/request-executor.ts b/packages/custom-widgets/src/server/request-executor.ts
index 649c5b45e..dfd6bb463 100644
--- a/packages/custom-widgets/src/server/request-executor.ts
+++ b/packages/custom-widgets/src/server/request-executor.ts
@@ -13,7 +13,7 @@ import {
resolveSameOriginTarget,
validateCustomWidgetUrl,
} from "./network-policy";
-import { closeDispatcher } from "./request-dispatcher-lifecycle";
+import { abortable, closeDispatcher } from "./request-dispatcher-lifecycle";
import { decodeResponseBody, parseResponseBody, redactResponseSecrets } from "./response";
export { assertSafeStaticHeaders, resolveSameOriginTarget, validateCustomWidgetUrl } from "./network-policy";
@@ -34,7 +34,6 @@ const RESPONSE_TOO_LARGE_ERROR_CODE = "UND_ERR_RES_EXCEEDED_MAX_SIZE";
const cache = new Map<string, { expiresAt: number; response: CustomWidgetHttpResponse }>();
const inFlight = new Map<string, Promise<CustomWidgetHttpResponse>>();
-let cacheEpoch = 0;
type RequestHopResult =
| { kind: "response"; response: CustomWidgetHttpResponse }
@@ -46,7 +45,10 @@ async function performRequest(input: CustomWidgetHttpRequest): Promise<CustomWid
() => controller.abort(),
Math.min(input.timeoutMs ?? MAX_REQUEST_DURATION_MS, MAX_REQUEST_DURATION_MS),
);
+ let preparingRequest = true;
try {
+ if (input.beforeRequest) await abortable(input.beforeRequest(), controller.signal);
+ preparingRequest = false;
assertRequest(input);
return await performAuthenticatedRequest(input, controller.signal, performRequestWithinDeadline);
} catch (error) {
@@ -57,7 +59,7 @@ async function performRequest(input: CustomWidgetHttpRequest): Promise<CustomWid
reason: "timeout",
});
}
- if (error instanceof CustomWidgetDomainError) throw error;
+ if (preparingRequest || error instanceof CustomWidgetDomainError) throw error;
input.logError?.({
origin: URL.canParse(input.baseUrl) ? new URL(input.baseUrl).origin : "invalid",
method: input.method,
@@ -253,13 +255,13 @@ export async function executeCustomWidgetRequest(input: CustomWidgetHttpRequest)
if (cached) cache.delete(key);
const pending = inFlight.get(key);
if (pending) return pending;
- const requestEpoch = cacheEpoch;
+ const cacheTtlSeconds = input.cacheTtlSeconds ?? 30;
let request: Promise<CustomWidgetHttpResponse>;
request = performRequest(input)
.then((response) => {
- if (response.ok && (input.cacheTtlSeconds ?? 0) > 0 && requestEpoch === cacheEpoch) {
+ if (response.ok && cacheTtlSeconds > 0 && inFlight.get(key) === request) {
pruneCache();
- cache.set(key, { expiresAt: Date.now() + (input.cacheTtlSeconds ?? 0) * 1000, response });
+ cache.set(key, { expiresAt: Date.now() + cacheTtlSeconds * 1000, response });
}
return response;
})
@@ -272,7 +274,6 @@ 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 inFlight.keys()) if (prefixes.some((prefix) => key.startsWith(prefix))) inFlight.delete(key);
}
diff --git a/packages/custom-widgets/src/server/request-limits.ts b/packages/custom-widgets/src/server/request-limits.ts
index 0dbd841f7..6b99b25ef 100644
--- a/packages/custom-widgets/src/server/request-limits.ts
+++ b/packages/custom-widgets/src/server/request-limits.ts
@@ -21,6 +21,7 @@ export interface RequestLimitInput {
itemId: string;
definitionId: string;
load?: { signal?: AbortSignal };
+ phase?: "rate" | "concurrency";
}
export interface RequestLimitStore {
@@ -65,6 +66,7 @@ export class CustomWidgetRequestLimiter {
input.category,
input.load,
unattributedRateKey,
+ input.phase,
);
try {
return await this.acquireStored(
@@ -76,6 +78,7 @@ export class CustomWidgetRequestLimiter {
this.options.store,
input.load,
unattributedRateKey,
+ input.phase,
);
} catch (error) {
if (error instanceof CustomWidgetDomainError) throw error;
@@ -95,12 +98,22 @@ export class CustomWidgetRequestLimiter {
category: RequestCategory,
load: RequestLimitInput["load"],
unattributedRateKey: string | undefined,
+ phase: RequestLimitInput["phase"],
) {
- const now = Date.now();
- if (unattributedRateKey)
- this.acquireLocalRate(unattributedRateKey, CATEGORY_LIMITS[category], now, load, UNATTRIBUTED_LOAD_RATE_MESSAGE);
- this.acquireLocalRate(rateKey, CATEGORY_LIMITS[category], now, load);
- this.acquireLocalRate(definitionRateKey, DEFINITION_CATEGORY_LIMITS[category], now, load);
+ if (phase !== "concurrency") {
+ const now = Date.now();
+ if (unattributedRateKey)
+ this.acquireLocalRate(
+ unattributedRateKey,
+ CATEGORY_LIMITS[category],
+ now,
+ load,
+ UNATTRIBUTED_LOAD_RATE_MESSAGE,
+ );
+ this.acquireLocalRate(rateKey, CATEGORY_LIMITS[category], now, load);
+ this.acquireLocalRate(definitionRateKey, DEFINITION_CATEGORY_LIMITS[category], now, load);
+ }
+ if (phase === "rate") return async () => undefined;
return this.waitForCapacity(() => {
if (!this.acquireLocalConcurrency(userKey, CUSTOM_WIDGET_USER_ITEM_CONCURRENCY_LIMIT)) return undefined;
if (!this.acquireLocalConcurrency(definitionKey, CUSTOM_WIDGET_DEFINITION_CONCURRENCY_LIMIT)) {
@@ -126,17 +139,24 @@ export class CustomWidgetRequestLimiter {
store: RequestLimitStore,
load: RequestLimitInput["load"],
unattributedRateKey: string | undefined,
+ phase: RequestLimitInput["phase"],
) {
- if (unattributedRateKey) {
- const rate = await store.incrementRate(unattributedRateKey, WINDOW_MS);
- if (rate.count > CATEGORY_LIMITS[category])
- throwLimit(rate.retryAfterMs, load ? UNATTRIBUTED_LOAD_RATE_MESSAGE : undefined);
+ if (phase !== "concurrency") {
+ if (unattributedRateKey) {
+ const rate = await store.incrementRate(unattributedRateKey, WINDOW_MS);
+ if (rate.count > CATEGORY_LIMITS[category])
+ throwLimit(rate.retryAfterMs, load ? UNATTRIBUTED_LOAD_RATE_MESSAGE : undefined);
+ }
+ const rate = await store.incrementRate(rateKey, WINDOW_MS);
+ if (rate.count > CATEGORY_LIMITS[category]) throwLimit(rate.retryAfterMs, load ? LOAD_RATE_MESSAGE : undefined);
+ const definitionRate = await store.incrementRate(definitionRateKey, WINDOW_MS);
+ if (definitionRate.count > DEFINITION_CATEGORY_LIMITS[category])
+ throwLimit(definitionRate.retryAfterMs, load ? LOAD_RATE_MESSAGE : undefined);
+ }
+ if (phase === "rate") {
+ assertLoadActive(load);
+ return async () => undefined;
}
- const rate = await store.incrementRate(rateKey, WINDOW_MS);
- if (rate.count > CATEGORY_LIMITS[category]) throwLimit(rate.retryAfterMs, load ? LOAD_RATE_MESSAGE : undefined);
- const definitionRate = await store.incrementRate(definitionRateKey, WINDOW_MS);
- if (definitionRate.count > DEFINITION_CATEGORY_LIMITS[category])
- throwLimit(definitionRate.retryAfterMs, load ? LOAD_RATE_MESSAGE : undefined);
return this.waitForCapacity(() => this.acquireStoredConcurrency(userKey, definitionKey, store), load);
}
diff --git a/packages/custom-widgets/src/server/request-types.ts b/packages/custom-widgets/src/server/request-types.ts
index 2a6b019b7..b62f66cee 100644
--- a/packages/custom-widgets/src/server/request-types.ts
+++ b/packages/custom-widgets/src/server/request-types.ts
@@ -30,6 +30,7 @@ export interface CustomWidgetHttpRequest {
textFallback?: boolean;
cacheKey?: string;
cacheTtlSeconds?: number;
+ beforeRequest?: () => Promise<void>;
logError?: (event: {
origin: string;
method: CustomWidgetMethod | "HEAD" | "OPTIONS";