chore: import upstream snapshot with attribution

This commit is contained in:
wehub-resource-sync
2026-07-13 13:32:57 +08:00
commit cd420f9332
4811 changed files with 884702 additions and 0 deletions
@@ -0,0 +1,305 @@
import { useFetcher } from "@remix-run/react";
import { useEffect, useState } from "react";
import stableStringify from "json-stable-stringify";
import {
Dialog,
DialogContent,
DialogHeader,
DialogDescription,
DialogFooter,
} from "~/components/primitives/Dialog";
import { Button } from "~/components/primitives/Buttons";
import { Callout } from "~/components/primitives/Callout";
import { LockClosedIcon } from "@heroicons/react/20/solid";
import { CheckboxWithLabel } from "~/components/primitives/Checkbox";
import { cn } from "~/utils/cn";
import { FEATURE_FLAG, ORG_LOCKED_FLAGS, type FlagControlType } from "~/v3/featureFlags";
import {
UNSET_VALUE,
BooleanControl,
EnumControl,
NumberControl,
StringControl,
WorkerGroupControl,
type WorkerGroup,
} from "./FlagControls";
type LoaderData = {
org: { id: string; title: string; slug: string };
orgFlags: Record<string, unknown>;
globalFlags: Record<string, unknown>;
controlTypes: Record<string, FlagControlType>;
workerGroupName?: string;
workerGroups?: WorkerGroup[];
isManagedCloud?: boolean;
};
type ActionData = {
success?: boolean;
error?: string;
};
type FeatureFlagsDialogProps = {
orgId: string | null;
orgTitle: string;
open: boolean;
onOpenChange: (open: boolean) => void;
};
export function FeatureFlagsDialog({
orgId,
orgTitle,
open,
onOpenChange,
}: FeatureFlagsDialogProps) {
const loadFetcher = useFetcher<LoaderData>();
const saveFetcher = useFetcher<ActionData>();
const [overrides, setOverrides] = useState<Record<string, unknown>>({});
const [initialOverrides, setInitialOverrides] = useState<Record<string, unknown>>({});
const [saveError, setSaveError] = useState<string | null>(null);
const [unlocked, setUnlocked] = useState(false);
const isLocked = (key: string) => !unlocked && ORG_LOCKED_FLAGS.includes(key);
useEffect(() => {
if (open && orgId) {
setSaveError(null);
setOverrides({});
setInitialOverrides({});
loadFetcher.load(`/admin/api/v2/orgs/${orgId}/feature-flags`);
}
}, [open, orgId]);
useEffect(() => {
if (loadFetcher.data) {
const loaded = loadFetcher.data.orgFlags ?? {};
setOverrides({ ...loaded });
setInitialOverrides({ ...loaded });
}
}, [loadFetcher.data]);
useEffect(() => {
if (saveFetcher.data?.success) {
onOpenChange(false);
} else if (saveFetcher.data?.error) {
setSaveError(saveFetcher.data.error);
}
}, [saveFetcher.data]);
const isDirty = stableStringify(overrides) !== stableStringify(initialOverrides);
const setFlagValue = (key: string, value: unknown) => {
setOverrides((prev) => ({ ...prev, [key]: value }));
};
const unsetFlag = (key: string) => {
setOverrides((prev) => {
const next = { ...prev };
delete next[key];
return next;
});
};
const handleSave = () => {
if (!orgId) return;
const body = Object.keys(overrides).length === 0 ? null : overrides;
saveFetcher.submit(JSON.stringify(body), {
method: "POST",
action: `/admin/api/v2/orgs/${orgId}/feature-flags`,
encType: "application/json",
});
};
const data = loadFetcher.data;
const isLoading = loadFetcher.state === "loading";
const isSaving = saveFetcher.state === "submitting";
const jsonPreview =
Object.keys(overrides).length === 0 ? "null" : JSON.stringify(overrides, null, 2);
const sortedFlagKeys = data ? Object.keys(data.controlTypes).sort() : [];
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-lg">
<DialogHeader>Feature flags - {orgTitle}</DialogHeader>
<DialogDescription>
Org-level overrides. Unset flags inherit from global defaults.
</DialogDescription>
{data && (
<div className={data.isManagedCloud ? "cursor-not-allowed" : undefined}>
<CheckboxWithLabel
variant="simple/small"
label={
data.isManagedCloud
? "Unlock read-only flags (only in unmanaged cloud)"
: "Unlock read-only flags"
}
defaultChecked={unlocked}
onChange={setUnlocked}
disabled={data.isManagedCloud}
className={data.isManagedCloud ? "pointer-events-none" : undefined}
/>
</div>
)}
<div className="max-h-[60vh] overflow-y-auto">
{isLoading ? (
<div className="py-8 text-center text-sm text-text-dimmed">Loading flags...</div>
) : data ? (
<div className="flex flex-col gap-1.5">
{sortedFlagKeys.map((key) => {
const control = data.controlTypes[key];
const locked = isLocked(key);
const globalValue = data.globalFlags[key as keyof typeof data.globalFlags];
const isWorkerGroup = key === FEATURE_FLAG.defaultWorkerInstanceGroupId;
const globalDisplay =
isWorkerGroup && data.workerGroupName && globalValue !== undefined
? `${data.workerGroupName} (${String(globalValue).slice(0, 8)}...)`
: globalValue !== undefined
? String(globalValue)
: "unset";
if (locked) {
return (
<div
key={key}
className="flex items-center justify-between rounded-md border border-transparent bg-background-hover px-3 py-2.5"
title="Global-level setting - not editable per org"
>
<div className="min-w-0 flex-1">
<div className="truncate text-sm text-text-dimmed">{key}</div>
<div className="text-xs text-text-dimmed">global: {globalDisplay}</div>
</div>
<LockClosedIcon className="size-4 text-text-faint" />
</div>
);
}
const isOverridden = key in overrides;
return (
<div
key={key}
className={cn(
"flex items-center justify-between rounded-md border px-3 py-2.5",
isOverridden
? "border-indigo-500/20 bg-indigo-500/5"
: "border-transparent bg-background-hover"
)}
>
<div className="min-w-0 flex-1">
<div
className={cn(
"truncate text-sm",
isOverridden ? "text-text-bright" : "text-text-dimmed"
)}
>
{key}
</div>
<div className="text-xs text-text-dimmed">global: {globalDisplay}</div>
</div>
<div className="flex items-center gap-2">
<Button
variant="minimal/small"
onClick={() => unsetFlag(key)}
className={cn(!isOverridden && "invisible")}
>
unset
</Button>
{isWorkerGroup && data.workerGroups ? (
<WorkerGroupControl
value={isOverridden ? (overrides[key] as string) : undefined}
workerGroups={data.workerGroups as WorkerGroup[]}
onChange={(val) => {
if (val === UNSET_VALUE) {
unsetFlag(key);
} else {
setFlagValue(key, val);
}
}}
dimmed={!isOverridden}
/>
) : control.type === "boolean" ? (
<BooleanControl
value={isOverridden ? (overrides[key] as boolean) : undefined}
onChange={(val) => setFlagValue(key, val)}
dimmed={!isOverridden}
/>
) : control.type === "enum" ? (
<EnumControl
value={isOverridden ? (overrides[key] as string) : undefined}
options={control.options}
onChange={(val) => {
if (val === UNSET_VALUE) {
unsetFlag(key);
} else {
setFlagValue(key, val);
}
}}
dimmed={!isOverridden}
/>
) : control.type === "number" ? (
<NumberControl
value={isOverridden ? (overrides[key] as number) : undefined}
min={control.min}
max={control.max}
onChange={(val) => {
if (val === undefined) {
unsetFlag(key);
} else {
setFlagValue(key, val);
}
}}
dimmed={!isOverridden}
/>
) : control.type === "string" ? (
<StringControl
value={isOverridden ? (overrides[key] as string) : ""}
onChange={(val) => {
if (val === "") {
unsetFlag(key);
} else {
setFlagValue(key, val);
}
}}
dimmed={!isOverridden}
/>
) : null}
</div>
</div>
);
})}
</div>
) : null}
</div>
{data && (
<details className="mt-2">
<summary className="cursor-pointer text-xs text-text-dimmed hover:text-text-bright">
Preview JSON
</summary>
<pre className="mt-1 max-h-40 overflow-auto rounded bg-background-bright p-2 text-xs text-text-dimmed">
{jsonPreview}
</pre>
</details>
)}
{saveError && <Callout variant="error">{saveError}</Callout>}
<DialogFooter>
<Button variant="tertiary/small" onClick={() => onOpenChange(false)}>
Cancel
</Button>
<Button variant="primary/small" onClick={handleSave} disabled={!isDirty || isSaving}>
{isSaving ? "Saving..." : "Save changes"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,155 @@
import { Switch } from "~/components/primitives/Switch";
import { Select, SelectItem } from "~/components/primitives/Select";
import { Input } from "~/components/primitives/Input";
import { cn } from "~/utils/cn";
export const UNSET_VALUE = "__unset__";
export function BooleanControl({
value,
onChange,
dimmed,
}: {
value: boolean | undefined;
onChange: (val: boolean) => void;
dimmed: boolean;
}) {
return (
<Switch
variant="small"
checked={value ?? false}
onCheckedChange={onChange}
className={cn(dimmed && "opacity-50")}
/>
);
}
export function EnumControl({
value,
options,
onChange,
dimmed,
}: {
value: string | undefined;
options: string[];
onChange: (val: string) => void;
dimmed: boolean;
}) {
const items = [UNSET_VALUE, ...options];
return (
<Select
variant="tertiary/small"
value={value ?? UNSET_VALUE}
setValue={onChange}
items={items}
text={(val) => (val === UNSET_VALUE ? "unset" : val)}
className={cn(dimmed && "opacity-50")}
>
{(items) =>
items.map((item) => (
<SelectItem key={item} value={item}>
{item === UNSET_VALUE ? "unset" : item}
</SelectItem>
))
}
</Select>
);
}
export type WorkerGroup = { id: string; name: string };
export function WorkerGroupControl({
value,
workerGroups,
onChange,
dimmed,
}: {
value: string | undefined;
workerGroups: WorkerGroup[];
onChange: (val: string) => void;
dimmed: boolean;
}) {
const items = [UNSET_VALUE, ...workerGroups.map((wg) => wg.id)];
return (
<Select
variant="tertiary/small"
value={value ?? UNSET_VALUE}
setValue={onChange}
items={items}
text={(val) => {
if (val === UNSET_VALUE) return "unset";
const wg = workerGroups.find((w) => w.id === val);
return wg ? wg.name : val;
}}
className={cn(dimmed && "opacity-50")}
>
{(items) =>
items.map((item) => {
const wg = workerGroups.find((w) => w.id === item);
return (
<SelectItem key={item} value={item}>
{item === UNSET_VALUE ? "unset" : wg ? wg.name : item}
</SelectItem>
);
})
}
</Select>
);
}
export function NumberControl({
value,
onChange,
min,
max,
dimmed,
}: {
value: number | undefined;
onChange: (val: number | undefined) => void;
min?: number;
max?: number;
dimmed: boolean;
}) {
// Number and string fields share the same input shape; surface the range
// (or "number") as the placeholder so an unset field still signals its type.
const placeholder = min !== undefined && max !== undefined ? `${min}-${max}` : "number";
return (
<Input
type="number"
variant="small"
// Empty string when unset so the placeholder shows instead of "0".
value={value ?? ""}
min={min}
max={max}
step={1}
onChange={(e) => {
const next = e.target.valueAsNumber;
onChange(Number.isNaN(next) ? undefined : next);
}}
placeholder={placeholder}
className={cn("w-40", dimmed && "opacity-50")}
/>
);
}
export function StringControl({
value,
onChange,
dimmed,
}: {
value: string;
onChange: (val: string) => void;
dimmed: boolean;
}) {
return (
<Input
variant="small"
value={value}
onChange={(e) => onChange(e.target.value)}
placeholder="unset"
className={cn("w-40", dimmed && "opacity-50")}
/>
);
}
@@ -0,0 +1,56 @@
import { prisma } from "~/db.server";
import { env } from "~/env.server";
import { logger } from "~/services/logger.server";
import { type Duration } from "~/services/rateLimiter.server";
import { controlPlaneResolver } from "~/v3/runOpsMigration/controlPlaneResolver.server";
import { API_RATE_LIMIT_INTENT } from "./ApiRateLimitSection";
import {
handleRateLimitAction,
resolveEffectiveRateLimit,
type RateLimitActionResult,
type RateLimitDomain,
} from "./RateLimitSection.server";
import type { EffectiveRateLimit } from "./RateLimitSection";
export const apiRateLimitDomain: RateLimitDomain = {
intent: API_RATE_LIMIT_INTENT,
systemDefault: () => ({
type: "tokenBucket",
refillRate: env.API_RATE_LIMIT_REFILL_RATE,
interval: env.API_RATE_LIMIT_REFILL_INTERVAL as Duration,
maxTokens: env.API_RATE_LIMIT_MAX,
}),
apply: async (orgId, next, adminUserId) => {
const existing = await prisma.organization.findFirst({
where: { id: orgId },
select: { apiRateLimiterConfig: true },
});
if (!existing) {
throw new Response(null, { status: 404 });
}
await prisma.organization.update({
where: { id: orgId },
data: { apiRateLimiterConfig: next as any },
});
// apiRateLimiterConfig is embedded in every env of the org; drop all its cached env rows.
controlPlaneResolver.invalidateOrganization(orgId);
logger.info("admin.backOffice.apiRateLimit", {
adminUserId,
orgId,
previous: existing.apiRateLimiterConfig,
next,
});
},
};
export function resolveEffectiveApiRateLimit(override: unknown): EffectiveRateLimit {
return resolveEffectiveRateLimit(override, apiRateLimitDomain);
}
export function handleApiRateLimitAction(
formData: FormData,
orgId: string,
adminUserId: string
): Promise<RateLimitActionResult> {
return handleRateLimitAction(formData, orgId, adminUserId, apiRateLimitDomain);
}
@@ -0,0 +1,8 @@
import { RateLimitSection, type RateLimitWrapperProps } from "./RateLimitSection";
export const API_RATE_LIMIT_INTENT = "set-rate-limit";
export const API_RATE_LIMIT_SAVED_VALUE = "rate-limit";
export function ApiRateLimitSection(props: RateLimitWrapperProps) {
return <RateLimitSection title="API rate limit" intent={API_RATE_LIMIT_INTENT} {...props} />;
}
@@ -0,0 +1,56 @@
import { prisma } from "~/db.server";
import { env } from "~/env.server";
import { logger } from "~/services/logger.server";
import { type Duration } from "~/services/rateLimiter.server";
import { controlPlaneResolver } from "~/v3/runOpsMigration/controlPlaneResolver.server";
import { BATCH_RATE_LIMIT_INTENT } from "./BatchRateLimitSection";
import {
handleRateLimitAction,
resolveEffectiveRateLimit,
type RateLimitActionResult,
type RateLimitDomain,
} from "./RateLimitSection.server";
import type { EffectiveRateLimit } from "./RateLimitSection";
export const batchRateLimitDomain: RateLimitDomain = {
intent: BATCH_RATE_LIMIT_INTENT,
systemDefault: () => ({
type: "tokenBucket",
refillRate: env.BATCH_RATE_LIMIT_REFILL_RATE,
interval: env.BATCH_RATE_LIMIT_REFILL_INTERVAL as Duration,
maxTokens: env.BATCH_RATE_LIMIT_MAX,
}),
apply: async (orgId, next, adminUserId) => {
const existing = await prisma.organization.findFirst({
where: { id: orgId },
select: { batchRateLimitConfig: true },
});
if (!existing) {
throw new Response(null, { status: 404 });
}
await prisma.organization.update({
where: { id: orgId },
data: { batchRateLimitConfig: next as any },
});
// batchRateLimitConfig is embedded in every env of the org; drop all its cached env rows.
controlPlaneResolver.invalidateOrganization(orgId);
logger.info("admin.backOffice.batchRateLimit", {
adminUserId,
orgId,
previous: existing.batchRateLimitConfig,
next,
});
},
};
export function resolveEffectiveBatchRateLimit(override: unknown): EffectiveRateLimit {
return resolveEffectiveRateLimit(override, batchRateLimitDomain);
}
export function handleBatchRateLimitAction(
formData: FormData,
orgId: string,
adminUserId: string
): Promise<RateLimitActionResult> {
return handleRateLimitAction(formData, orgId, adminUserId, batchRateLimitDomain);
}
@@ -0,0 +1,8 @@
import { RateLimitSection, type RateLimitWrapperProps } from "./RateLimitSection";
export const BATCH_RATE_LIMIT_INTENT = "set-batch-rate-limit";
export const BATCH_RATE_LIMIT_SAVED_VALUE = "batch-rate-limit";
export function BatchRateLimitSection(props: RateLimitWrapperProps) {
return <RateLimitSection title="Batch rate limit" intent={BATCH_RATE_LIMIT_INTENT} {...props} />;
}
@@ -0,0 +1,48 @@
import { z } from "zod";
import { prisma } from "~/db.server";
import { logger } from "~/services/logger.server";
import { MAX_PROJECTS_INTENT } from "./MaxProjectsSection";
const SetMaxProjectsSchema = z.object({
intent: z.literal(MAX_PROJECTS_INTENT),
// Capped at PostgreSQL INTEGER max (Prisma Int) so oversized input fails
// validation cleanly instead of crashing the update.
maximumProjectCount: z.coerce.number().int().min(1).max(2_147_483_647),
});
export type MaxProjectsActionResult =
| { ok: true }
| { ok: false; errors: Record<string, string[] | undefined> };
export async function handleMaxProjectsAction(
formData: FormData,
orgId: string,
adminUserId: string
): Promise<MaxProjectsActionResult> {
const submission = SetMaxProjectsSchema.safeParse(Object.fromEntries(formData));
if (!submission.success) {
return { ok: false, errors: submission.error.flatten().fieldErrors };
}
const existing = await prisma.organization.findFirst({
where: { id: orgId },
select: { maximumProjectCount: true },
});
if (!existing) {
throw new Response(null, { status: 404 });
}
await prisma.organization.update({
where: { id: orgId },
data: { maximumProjectCount: submission.data.maximumProjectCount },
});
logger.info("admin.backOffice.maxProjects", {
adminUserId,
orgId,
previous: existing.maximumProjectCount,
next: submission.data.maximumProjectCount,
});
return { ok: true };
}
@@ -0,0 +1,109 @@
import { Form } from "@remix-run/react";
import { useEffect, useState } from "react";
import { Button } from "~/components/primitives/Buttons";
import { FormError } from "~/components/primitives/FormError";
import { Header2 } from "~/components/primitives/Headers";
import { Input } from "~/components/primitives/Input";
import { Label } from "~/components/primitives/Label";
import { Paragraph } from "~/components/primitives/Paragraph";
import * as Property from "~/components/primitives/PropertyTable";
export const MAX_PROJECTS_INTENT = "set-max-projects";
export const MAX_PROJECTS_SAVED_VALUE = "max-projects";
type FieldErrors = Record<string, string[] | undefined> | null;
type Props = {
maximumProjectCount: number;
errors: FieldErrors;
savedJustNow: boolean;
isSubmitting: boolean;
};
export function MaxProjectsSection({
maximumProjectCount,
errors,
savedJustNow,
isSubmitting,
}: Props) {
const hasFieldErrors = !!errors && Object.keys(errors).length > 0;
const fieldError = (field: string) =>
errors && field in errors ? errors[field]?.[0] : undefined;
const [isEditing, setIsEditing] = useState(hasFieldErrors);
const [value, setValue] = useState(String(maximumProjectCount));
useEffect(() => {
if (hasFieldErrors) setIsEditing(true);
}, [hasFieldErrors]);
useEffect(() => {
if (savedJustNow && !hasFieldErrors) setIsEditing(false);
}, [savedJustNow, hasFieldErrors]);
return (
<section className="flex flex-col gap-3 rounded-md border border-grid-bright bg-background-bright p-4">
<div className="flex items-center justify-between">
<Header2>Maximum projects</Header2>
{!isEditing && (
<Button
variant="tertiary/small"
onClick={() => setIsEditing(true)}
disabled={isSubmitting}
>
Edit
</Button>
)}
</div>
{savedJustNow && (
<div className="rounded-md border border-green-600/40 bg-green-600/10 px-3 py-2">
<Paragraph variant="small" className="text-green-500">
Saved.
</Paragraph>
</div>
)}
{!isEditing ? (
<Property.Table>
<Property.Item>
<Property.Label>Limit</Property.Label>
<Property.Value>{maximumProjectCount.toLocaleString()}</Property.Value>
</Property.Item>
</Property.Table>
) : (
<Form method="post" className="flex flex-col gap-3 pt-2">
<input type="hidden" name="intent" value={MAX_PROJECTS_INTENT} />
<div className="flex flex-col gap-1">
<Label>Maximum projects</Label>
<Input
name="maximumProjectCount"
type="number"
min={1}
value={value}
onChange={(e) => setValue(e.target.value)}
required
/>
<FormError>{fieldError("maximumProjectCount")}</FormError>
</div>
<div className="flex items-center gap-2">
<Button type="submit" variant="primary/medium" disabled={isSubmitting || !value.trim()}>
Save
</Button>
<Button
type="button"
variant="tertiary/medium"
onClick={() => {
setValue(String(maximumProjectCount));
setIsEditing(false);
}}
disabled={isSubmitting}
>
Cancel
</Button>
</div>
</Form>
)}
</section>
);
}
@@ -0,0 +1,69 @@
import { z } from "zod";
import {
RateLimitTokenBucketConfig,
RateLimiterConfig,
} from "~/services/authorizationRateLimitMiddleware.server";
import { parseDurationToMs, type EffectiveRateLimit } from "./RateLimitSection";
export type RateLimitDomain = {
intent: string;
systemDefault: () => RateLimiterConfig;
apply: (orgId: string, next: RateLimitTokenBucketConfig, adminUserId: string) => Promise<void>;
};
export function resolveEffectiveRateLimit(
override: unknown,
domain: RateLimitDomain
): EffectiveRateLimit {
if (override == null) {
return { source: "default", config: domain.systemDefault() };
}
const parsed = RateLimiterConfig.safeParse(override);
if (parsed.success) {
return { source: "override", config: parsed.data };
}
// Column holds malformed JSON — fall back silently. Admin must investigate
// at the DB level; this UI can't recover it.
return { source: "default", config: domain.systemDefault() };
}
export type RateLimitActionResult =
| { ok: true }
| { ok: false; errors: Record<string, string[] | undefined> };
export async function handleRateLimitAction(
formData: FormData,
orgId: string,
adminUserId: string,
domain: RateLimitDomain
): Promise<RateLimitActionResult> {
const schema = z.object({
intent: z.literal(domain.intent),
refillRate: z.coerce.number().int().min(1),
interval: z
.string()
.trim()
.refine((v) => parseDurationToMs(v) > 0, {
message: "Must be a duration like 10s, 1m, 500ms.",
}),
maxTokens: z.coerce.number().int().min(1),
});
const submission = schema.safeParse(Object.fromEntries(formData));
if (!submission.success) {
return { ok: false, errors: submission.error.flatten().fieldErrors };
}
const built = RateLimitTokenBucketConfig.safeParse({
type: "tokenBucket",
refillRate: submission.data.refillRate,
interval: submission.data.interval,
maxTokens: submission.data.maxTokens,
});
if (!built.success) {
return { ok: false, errors: built.error.flatten().fieldErrors };
}
await domain.apply(orgId, built.data, adminUserId);
return { ok: true };
}
@@ -0,0 +1,288 @@
import { Form } from "@remix-run/react";
import { useEffect, useState } from "react";
import { Button } from "~/components/primitives/Buttons";
import { FormError } from "~/components/primitives/FormError";
import { Header2 } from "~/components/primitives/Headers";
import { Input } from "~/components/primitives/Input";
import { Label } from "~/components/primitives/Label";
import { Paragraph } from "~/components/primitives/Paragraph";
import * as Property from "~/components/primitives/PropertyTable";
// Local shape mirrors the server-side discriminated union just enough for this
// view. Decoupled from the .server module so the component stays client-safe.
// Duration fields are always suffixed strings — the server's DurationSchema
// rejects anything else, so non-string overrides fall back to the default.
export type RateLimitConfig =
| {
type: "tokenBucket";
refillRate: number;
interval: string;
maxTokens: number;
}
| {
type: "fixedWindow" | "slidingWindow";
window: string;
tokens: number;
};
export type EffectiveRateLimit = {
source: "override" | "default";
config: RateLimitConfig;
};
export type FieldErrors = Record<string, string[] | undefined> | null;
// Props shared by every per-domain wrapper (Api / Batch / future ones).
export type RateLimitWrapperProps = {
effective: EffectiveRateLimit;
errors: FieldErrors;
savedJustNow: boolean;
isSubmitting: boolean;
};
type Props = RateLimitWrapperProps & {
title: string;
intent: string;
};
export function RateLimitSection({
title,
intent,
effective,
errors,
savedJustNow,
isSubmitting,
}: Props) {
const hasFieldErrors = !!errors && Object.keys(errors).length > 0;
const fieldError = (field: string) =>
errors && field in errors ? errors[field]?.[0] : undefined;
const current = effective.config.type === "tokenBucket" ? effective.config : null;
const [isEditing, setIsEditing] = useState(hasFieldErrors);
const [refillRate, setRefillRate] = useState(current ? String(current.refillRate) : "");
const [intervalStr, setIntervalStr] = useState(current ? String(current.interval) : "");
const [maxTokens, setMaxTokens] = useState(current ? String(current.maxTokens) : "");
useEffect(() => {
if (hasFieldErrors) setIsEditing(true);
}, [hasFieldErrors]);
useEffect(() => {
if (savedJustNow && !hasFieldErrors) setIsEditing(false);
}, [savedJustNow, hasFieldErrors]);
const currentDescription = current
? describeRateLimit(
current.refillRate,
parseDurationToMs(String(current.interval)),
current.maxTokens
)
: null;
const previewDescription = describeRateLimit(
Number(refillRate) || 0,
parseDurationToMs(intervalStr),
Number(maxTokens) || 0
);
const cancelEdit = () => {
setRefillRate(current ? String(current.refillRate) : "");
setIntervalStr(current ? String(current.interval) : "");
setMaxTokens(current ? String(current.maxTokens) : "");
setIsEditing(false);
};
return (
<section className="flex flex-col gap-3 rounded-md border border-grid-bright bg-background-bright p-4">
<div className="flex items-center justify-between">
<Header2>{title}</Header2>
{!isEditing && (
<Button
variant="tertiary/small"
onClick={() => setIsEditing(true)}
disabled={isSubmitting || effective.config.type !== "tokenBucket"}
>
Edit
</Button>
)}
</div>
{savedJustNow && (
<div className="rounded-md border border-green-600/40 bg-green-600/10 px-3 py-2">
<Paragraph variant="small" className="text-green-500">
Saved.
</Paragraph>
</div>
)}
<Paragraph variant="small">
Status:{" "}
{effective.source === "override" ? "Custom override active." : "Using system default."}
</Paragraph>
{!isEditing ? (
<>
<Property.Table>
{effective.config.type === "tokenBucket" ? (
currentDescription ? (
<>
<Property.Item>
<Property.Label>Sustained rate</Property.Label>
<Property.Value>{currentDescription.sustained}</Property.Value>
</Property.Item>
<Property.Item>
<Property.Label>Burst allowance</Property.Label>
<Property.Value>{currentDescription.burst}</Property.Value>
</Property.Item>
</>
) : (
<Property.Item>
<Property.Value>Invalid interval on the stored config.</Property.Value>
</Property.Item>
)
) : (
<>
<Property.Item>
<Property.Label>Type</Property.Label>
<Property.Value>{effective.config.type}</Property.Value>
</Property.Item>
<Property.Item>
<Property.Label>Window</Property.Label>
<Property.Value>{String(effective.config.window)}</Property.Value>
</Property.Item>
<Property.Item>
<Property.Label>Tokens</Property.Label>
<Property.Value>{effective.config.tokens.toLocaleString()}</Property.Value>
</Property.Item>
</>
)}
</Property.Table>
{effective.config.type !== "tokenBucket" && (
<Paragraph variant="small" className="text-amber-500">
This override is a {effective.config.type} limit and can't be edited from this form.
Change it in the database directly.
</Paragraph>
)}
</>
) : (
<Form method="post" className="flex flex-col gap-3 pt-2">
<input type="hidden" name="intent" value={intent} />
<div className="flex flex-col gap-1">
<Label>Refill rate (tokens per interval)</Label>
<Input
name="refillRate"
type="number"
min={1}
value={refillRate}
onChange={(e) => setRefillRate(e.target.value)}
required
/>
<FormError>{fieldError("refillRate")}</FormError>
</div>
<div className="flex flex-col gap-1">
<Label>Interval (e.g. 10s, 1m)</Label>
<Input
name="interval"
type="text"
value={intervalStr}
onChange={(e) => setIntervalStr(e.target.value)}
required
/>
<FormError>{fieldError("interval")}</FormError>
</div>
<div className="flex flex-col gap-1">
<Label>Max tokens (burst allowance)</Label>
<Input
name="maxTokens"
type="number"
min={1}
value={maxTokens}
onChange={(e) => setMaxTokens(e.target.value)}
required
/>
<FormError>{fieldError("maxTokens")}</FormError>
</div>
<Paragraph variant="small" className="text-text-dimmed">
{previewDescription
? `Preview: ${previewDescription.sustained} · ${previewDescription.burst}.`
: "Preview: enter valid values to see the effective limit."}
</Paragraph>
<div className="flex items-center gap-2">
<Button
type="submit"
variant="primary/medium"
disabled={
isSubmitting || !refillRate.trim() || !intervalStr.trim() || !maxTokens.trim()
}
>
Save
</Button>
<Button
type="button"
variant="tertiary/medium"
onClick={cancelEdit}
disabled={isSubmitting}
>
Cancel
</Button>
</div>
</Form>
)}
</section>
);
}
export function parseDurationToMs(duration: string): number {
const match = duration.trim().match(/^(\d+)\s*(ms|s|m|h|d)$/);
if (!match) return 0;
const value = parseInt(match[1], 10);
switch (match[2]) {
case "ms":
return value;
case "s":
return value * 1_000;
case "m":
return value * 60_000;
case "h":
return value * 3_600_000;
case "d":
return value * 86_400_000;
default:
return 0;
}
}
function describeRateLimit(
refillRate: number,
intervalMs: number,
maxTokens: number
): { sustained: string; burst: string } | null {
if (refillRate <= 0 || intervalMs <= 0 || maxTokens <= 0) return null;
const perMin = (refillRate * 60_000) / intervalMs;
let sustained: string;
if (perMin >= 1) {
sustained = `${formatRateValue(perMin)} requests per minute`;
} else {
const perHour = perMin * 60;
if (perHour >= 1) {
sustained = `${formatRateValue(perHour)} requests per hour`;
} else {
const perDay = perHour * 24;
sustained = `${formatRateValue(perDay)} requests per day`;
}
}
return {
sustained,
burst: `${maxTokens.toLocaleString()} request burst allowance`,
};
}
function formatRateValue(value: number): string {
return value >= 10 ? Math.round(value).toLocaleString() : value.toFixed(1);
}
@@ -0,0 +1,398 @@
import { useIsImpersonating } from "~/hooks/useOrganizations";
import { useHasAdminAccess } from "~/hooks/useUser";
import { Button } from "../primitives/Buttons";
import { Dialog, DialogContent, DialogHeader, DialogTrigger } from "../primitives/Dialog";
import { Cog6ToothIcon } from "@heroicons/react/20/solid";
import { type loader } from "~/routes/resources.taskruns.$runParam.debug";
import type { UseDataFunctionReturn } from "remix-typedjson";
import { useTypedFetcher } from "remix-typedjson";
import { useEffect } from "react";
import { Spinner } from "../primitives/Spinner";
import * as Property from "~/components/primitives/PropertyTable";
import { ClipboardField } from "../primitives/ClipboardField";
import { MarQSShortKeyProducer } from "~/v3/marqs/marqsKeyProducer";
export function AdminDebugRun({ friendlyId }: { friendlyId: string }) {
const hasAdminAccess = useHasAdminAccess();
const isImpersonating = useIsImpersonating();
if (!hasAdminAccess && !isImpersonating) {
return null;
}
return (
<Dialog key={`debug-${friendlyId}`}>
<DialogTrigger asChild>
<Button variant="tertiary/small" LeadingIcon={Cog6ToothIcon}>
Debug run
</Button>
</DialogTrigger>
<DebugRunDialog friendlyId={friendlyId} />
</Dialog>
);
}
export function DebugRunDialog({ friendlyId }: { friendlyId: string }) {
return (
<DialogContent
key={`debug`}
className="overflow-y-auto sm:h-[80vh] sm:max-h-[80vh] sm:max-w-[50vw]"
>
<DebugRunContent friendlyId={friendlyId} />
</DialogContent>
);
}
function DebugRunContent({ friendlyId }: { friendlyId: string }) {
const fetcher = useTypedFetcher<typeof loader>();
const isLoading = fetcher.state === "loading";
useEffect(() => {
fetcher.load(`/resources/taskruns/${friendlyId}/debug`);
}, [friendlyId]);
return (
<>
<DialogHeader>Debugging run</DialogHeader>
{isLoading ? (
<div className="grid place-items-center p-6">
<Spinner />
</div>
) : fetcher.data ? (
<DebugRunData {...fetcher.data} />
) : (
<>Failed to get run debug data</>
)}
</>
);
}
function DebugRunData(props: UseDataFunctionReturn<typeof loader>) {
if (props.engine === "V1") {
return <DebugRunDataEngineV1 {...props} />;
}
return <DebugRunDataEngineV2 {...props} />;
}
function DebugRunDataEngineV1({
run,
environment,
queueConcurrencyLimit,
queueCurrentConcurrency,
envConcurrencyLimit,
envCurrentConcurrency,
queueReserveConcurrency,
envReserveConcurrency,
}: UseDataFunctionReturn<typeof loader>) {
const keys = new MarQSShortKeyProducer("marqs:");
const withPrefix = (key: string) => `marqs:${key}`;
return (
<Property.Table>
<Property.Item>
<Property.Label>ID</Property.Label>
<Property.Value className="flex items-center gap-2">
<ClipboardField value={run.id} variant="tertiary/small" iconButton />
</Property.Value>
</Property.Item>
<Property.Item>
<Property.Label>Message key</Property.Label>
<Property.Value className="flex items-center gap-2">
<ClipboardField
value={withPrefix(keys.messageKey(run.id))}
variant="tertiary/small"
iconButton
/>
</Property.Value>
</Property.Item>
<Property.Item>
<Property.Label>GET message</Property.Label>
<Property.Value className="flex items-center gap-2">
<ClipboardField
value={`GET ${withPrefix(keys.messageKey(run.id))}`}
variant="tertiary/small"
iconButton
/>
</Property.Value>
</Property.Item>
<Property.Item>
<Property.Label>Queue key</Property.Label>
<Property.Value className="flex items-center gap-2">
<ClipboardField
value={withPrefix(
keys.queueKey(environment, run.queue, run.concurrencyKey ?? undefined)
)}
variant="tertiary/small"
iconButton
/>
</Property.Value>
</Property.Item>
<Property.Item>
<Property.Label>Get queue set</Property.Label>
<Property.Value className="flex items-center gap-2">
<ClipboardField
value={`ZRANGE ${withPrefix(
keys.queueKey(environment, run.queue, run.concurrencyKey ?? undefined)
)} 0 -1`}
variant="tertiary/small"
iconButton
/>
</Property.Value>
</Property.Item>
<Property.Item>
<Property.Label>Queue current concurrency key</Property.Label>
<Property.Value className="flex items-center gap-2">
<ClipboardField
value={withPrefix(
keys.queueCurrentConcurrencyKey(
environment,
run.queue,
run.concurrencyKey ?? undefined
)
)}
variant="tertiary/small"
iconButton
/>
</Property.Value>
</Property.Item>
<Property.Item>
<Property.Label>Get queue current concurrency</Property.Label>
<Property.Value className="flex items-center gap-2">
<ClipboardField
value={`SMEMBERS ${withPrefix(
keys.queueCurrentConcurrencyKey(
environment,
run.queue,
run.concurrencyKey ?? undefined
)
)}`}
variant="tertiary/small"
iconButton
/>
</Property.Value>
</Property.Item>
<Property.Item>
<Property.Label>Queue current concurrency</Property.Label>
<Property.Value className="flex items-center gap-2">
<span>{queueCurrentConcurrency ?? "0"}</span>
</Property.Value>
</Property.Item>
<Property.Item>
<Property.Label>Queue reserve concurrency key</Property.Label>
<Property.Value className="flex items-center gap-2">
<ClipboardField
value={withPrefix(
keys.queueReserveConcurrencyKeyFromQueue(
keys.queueKey(environment, run.queue, run.concurrencyKey ?? undefined)
)
)}
variant="tertiary/small"
iconButton
/>
</Property.Value>
</Property.Item>
<Property.Item>
<Property.Label>Get queue reserve concurrency</Property.Label>
<Property.Value className="flex items-center gap-2">
<ClipboardField
value={`SMEMBERS ${withPrefix(
keys.queueReserveConcurrencyKeyFromQueue(
keys.queueKey(environment, run.queue, run.concurrencyKey ?? undefined)
)
)}`}
variant="tertiary/small"
iconButton
/>
</Property.Value>
</Property.Item>
<Property.Item>
<Property.Label>Queue reserve concurrency</Property.Label>
<Property.Value className="flex items-center gap-2">
<span>{queueReserveConcurrency ?? "0"}</span>
</Property.Value>
</Property.Item>
<Property.Item>
<Property.Label>Queue concurrency limit key</Property.Label>
<Property.Value className="flex items-center gap-2">
<ClipboardField
value={withPrefix(keys.queueConcurrencyLimitKey(environment, run.queue))}
variant="tertiary/small"
iconButton
/>
</Property.Value>
</Property.Item>
<Property.Item>
<Property.Label>GET queue concurrency limit</Property.Label>
<Property.Value className="flex items-center gap-2">
<ClipboardField
value={`GET ${withPrefix(keys.queueConcurrencyLimitKey(environment, run.queue))}`}
variant="tertiary/small"
iconButton
/>
</Property.Value>
</Property.Item>
<Property.Item>
<Property.Label>Queue concurrency limit</Property.Label>
<Property.Value className="flex items-center gap-2">
<span>{queueConcurrencyLimit ?? "Not set"}</span>
</Property.Value>
</Property.Item>
<Property.Item>
<Property.Label>Env current concurrency key</Property.Label>
<Property.Value className="flex items-center gap-2">
<ClipboardField
value={withPrefix(keys.envCurrentConcurrencyKey(environment))}
variant="tertiary/small"
iconButton
/>
</Property.Value>
</Property.Item>
<Property.Item>
<Property.Label>Get env current concurrency</Property.Label>
<Property.Value className="flex items-center gap-2">
<ClipboardField
value={`SMEMBERS ${withPrefix(keys.envCurrentConcurrencyKey(environment))}`}
variant="tertiary/small"
iconButton
/>
</Property.Value>
</Property.Item>
<Property.Item>
<Property.Label>Env current concurrency</Property.Label>
<Property.Value className="flex items-center gap-2">
<span>{envCurrentConcurrency ?? "0"}</span>
</Property.Value>
</Property.Item>
<Property.Item>
<Property.Label>Env reserve concurrency key</Property.Label>
<Property.Value className="flex items-center gap-2">
<ClipboardField
value={withPrefix(keys.envReserveConcurrencyKey(environment.id))}
variant="tertiary/small"
iconButton
/>
</Property.Value>
</Property.Item>
<Property.Item>
<Property.Label>Get env reserve concurrency</Property.Label>
<Property.Value className="flex items-center gap-2">
<ClipboardField
value={`SMEMBERS ${withPrefix(keys.envReserveConcurrencyKey(environment.id))}`}
variant="tertiary/small"
iconButton
/>
</Property.Value>
</Property.Item>
<Property.Item>
<Property.Label>Env reserve concurrency</Property.Label>
<Property.Value className="flex items-center gap-2">
<span>{envReserveConcurrency ?? "0"}</span>
</Property.Value>
</Property.Item>
<Property.Item>
<Property.Label>Env concurrency limit key</Property.Label>
<Property.Value className="flex items-center gap-2">
<ClipboardField
value={withPrefix(keys.envConcurrencyLimitKey(environment))}
variant="tertiary/small"
iconButton
/>
</Property.Value>
</Property.Item>
<Property.Item>
<Property.Label>GET env concurrency limit</Property.Label>
<Property.Value className="flex items-center gap-2">
<ClipboardField
value={`GET ${withPrefix(keys.envConcurrencyLimitKey(environment))}`}
variant="tertiary/small"
iconButton
/>
</Property.Value>
</Property.Item>
<Property.Item>
<Property.Label>Env concurrency limit</Property.Label>
<Property.Value className="flex items-center gap-2">
<span>{envConcurrencyLimit ?? "Not set"}</span>
</Property.Value>
</Property.Item>
<Property.Item>
<Property.Label>Shared queue key</Property.Label>
<Property.Value className="flex items-center gap-2">
<ClipboardField
value={`GET ${withPrefix(keys.envSharedQueueKey(environment))}`}
variant="tertiary/small"
iconButton
/>
</Property.Value>
</Property.Item>
<Property.Item>
<Property.Label>Get shared queue set</Property.Label>
<Property.Value className="flex items-center gap-2">
<ClipboardField
value={`ZRANGEBYSCORE ${withPrefix(
keys.envSharedQueueKey(environment)
)} -inf ${Date.now()} WITHSCORES`}
variant="tertiary/small"
iconButton
/>
</Property.Value>
</Property.Item>
</Property.Table>
);
}
function DebugRunDataEngineV2({
run,
queueConcurrencyLimit,
queueCurrentConcurrency,
envConcurrencyLimit,
envCurrentConcurrency,
keys,
}: UseDataFunctionReturn<typeof loader>) {
return (
<Property.Table>
<Property.Item>
<Property.Label>ID</Property.Label>
<Property.Value className="flex items-center gap-2">
<ClipboardField value={run.id} variant="tertiary/small" iconButton />
</Property.Value>
</Property.Item>
<Property.Item>
<Property.Label>Queue current concurrency</Property.Label>
<Property.Value className="flex items-center gap-2">
<span>{queueCurrentConcurrency ?? "0"}</span>
</Property.Value>
</Property.Item>
<Property.Item>
<Property.Label>Queue concurrency limit</Property.Label>
<Property.Value className="flex items-center gap-2">
<span>{queueConcurrencyLimit ?? "Not set"}</span>
</Property.Value>
</Property.Item>
<Property.Item>
<Property.Label>Env current concurrency</Property.Label>
<Property.Value className="flex items-center gap-2">
<span>{envCurrentConcurrency ?? "0"}</span>
</Property.Value>
</Property.Item>
<Property.Item>
<Property.Label>Env concurrency limit</Property.Label>
<Property.Value className="flex items-center gap-2">
<span>{envConcurrencyLimit ?? "Not set"}</span>
</Property.Value>
</Property.Item>
{keys.map((key) => (
<Property.Item key={key.key}>
<Property.Label>{key.label}</Property.Label>
<Property.Value className="flex items-center gap-2">
<ClipboardField value={key.key} variant="tertiary/small" iconButton />
</Property.Value>
</Property.Item>
))}
</Property.Table>
);
}
@@ -0,0 +1,87 @@
import { ShieldCheckIcon } from "@heroicons/react/20/solid";
import * as Property from "~/components/primitives/PropertyTable";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "~/components/primitives/Tooltip";
import { useOptionalEnvironment } from "~/hooks/useEnvironment";
import { useIsImpersonating, useOptionalOrganization } from "~/hooks/useOrganizations";
import { useOptionalProject } from "~/hooks/useProject";
import { useHasAdminAccess, useUser } from "~/hooks/useUser";
export function AdminDebugTooltip({ children }: { children?: React.ReactNode }) {
const hasAdminAccess = useHasAdminAccess();
const isImpersonating = useIsImpersonating();
if (!hasAdminAccess && !isImpersonating) {
return null;
}
return (
<TooltipProvider>
<Tooltip>
<TooltipTrigger>
<ShieldCheckIcon className="size-5" />
</TooltipTrigger>
<TooltipContent className="max-h-[90vh] overflow-y-auto">
<Content>{children}</Content>
</TooltipContent>
</Tooltip>
</TooltipProvider>
);
}
function Content({ children }: { children: React.ReactNode }) {
const organization = useOptionalOrganization();
const project = useOptionalProject();
const environment = useOptionalEnvironment();
const user = useUser();
return (
<div className="flex flex-col gap-2 divide-y divide-slate-700">
<Property.Table>
<Property.Item>
<Property.Label>User ID</Property.Label>
<Property.Value>{user.id}</Property.Value>
</Property.Item>
{organization && (
<Property.Item>
<Property.Label>Org ID</Property.Label>
<Property.Value>{organization.id}</Property.Value>
</Property.Item>
)}
{project && (
<>
<Property.Item>
<Property.Label>Project ID</Property.Label>
<Property.Value>{project.id}</Property.Value>
</Property.Item>
<Property.Item>
<Property.Label>Project ref</Property.Label>
<Property.Value>{project.externalRef}</Property.Value>
</Property.Item>
</>
)}
{environment && (
<>
<Property.Item>
<Property.Label>Environment ID</Property.Label>
<Property.Value>{environment.id}</Property.Value>
</Property.Item>
<Property.Item>
<Property.Label>Environment type</Property.Label>
<Property.Value>{environment.type}</Property.Value>
</Property.Item>
<Property.Item>
<Property.Label>Environment paused</Property.Label>
<Property.Value>{environment.paused ? "Yes" : "No"}</Property.Value>
</Property.Item>
</>
)}
</Property.Table>
<div className="pt-2">{children}</div>
</div>
);
}