/** * Site settings for schedules (RFC-0008 §15.1 "Site settings", §11.5–§11.6): the General section's * "Time zone" field (`Site.timeZone`, a `Combobox` over the browser's IANA zones with the browser's * own suggested), and the Schedules section — the scheduler's health, the site's kill switch (with * a reason, confirmed) and the daily automation write cap with today's use. Words come from the * lazy `scheduleSettings` namespace, loaded with the settings route. */ import { formatNumber } from "@cloudhal/messages/format"; import { Badge, Banner, Button, Combobox, Input, InputArea, LayerDialog, Meter, SkeletonLine, Switch, Text, } from "@cloudhal/ui"; import { ArrowClockwise, PauseCircle, WarningCircle } from "@phosphor-icons/react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useEffect, useMemo, useState } from "react"; import { useI18n } from "../i18n/index.tsx"; import { ApiRequestError, api, isNotEnabled, type ScheduleSettings } from "../lib/api.ts"; import { apiErrorText } from "../lib/api-errors.ts"; import { browserZone, formatMoment, knownZones, zoneLabel } from "../lib/schedules.ts"; import { schedulesApi } from "../lib/schedules-api.ts"; import { SettingRow, SettingsSection } from "./Settings.tsx"; import { useToast } from "./Toast.ts"; import { useGate } from "./useMe.ts"; export const SCHEDULE_SETTINGS_SECTION = "schedules"; interface ZoneOption { value: string; label: string; } /** * "Time zone" (`Site.timeZone`): a searchable `Combobox` of the zones this browser knows, written * "Istanbul (UTC+3)", with the browser's own zone offered first. Empty means UTC. */ export function TimeZoneField({ value, onChange, disabled, invalid, }: { value: string; onChange: (zone: string) => void; disabled?: boolean; /** The server refused the zone (`invalid_time_zone`). */ invalid?: boolean; }) { const { t } = useI18n("scheduleSettings"); const z = "scheduleSettings.timeZone" as const; const mine = browserZone(); const options: ZoneOption[] = useMemo(() => { const now = Date.now(); const zones = knownZones(); const ordered = [mine, ...zones.filter((zone) => zone !== mine)]; return ordered.map((zone) => ({ value: zone, label: `${zoneLabel(zone, now)} · ${zone}` })); }, [mine]); const selected = options.find((o) => o.value === (value || "UTC")) ?? null; return (
onChange((v as ZoneOption | null)?.value ?? "")} isItemEqualToValue={(a: ZoneOption, b: ZoneOption) => a.value === b.value} itemToStringLabel={(o: ZoneOption) => o.label} label={t(`${z}.label`)} description={t(`${z}.description`)} error={invalid ? t(`${z}.invalid`) : undefined} disabled={disabled} > {t(`${z}.empty`)} {(o: ZoneOption) => ( {o.label} )} {mine !== (value || "UTC") && (
)}
); } const isConflict = (e: unknown) => e instanceof ApiRequestError && e.status === 409; /** Site › Settings › Schedules: scheduler health, the kill switch and the daily write cap. */ export function ScheduleSettingsSection({ siteId }: { siteId: string }) { const { t, locale } = useI18n("scheduleSettings"); const qc = useQueryClient(); const toast = useToast(); const gate = useGate("schedules.settings"); const s = "scheduleSettings" as const; const key = ["schedules", siteId, "settings"] as const; const settings = useQuery({ queryKey: key, queryFn: () => schedulesApi.settings.get(siteId), retry: (count, error) => !isNotEnabled(error) && count < 1, }); const scheduler = useQuery({ queryKey: ["scheduler"], queryFn: api.scheduler, retry: false, }); const [cap, setCap] = useState(""); const [confirming, setConfirming] = useState<"pause" | "resume" | undefined>(); const [reason, setReason] = useState(""); const savedCap = settings.data?.dailyWriteCap; useEffect(() => { if (savedCap !== undefined) setCap(String(savedCap)); }, [savedCap]); const put = useMutation({ mutationFn: (input: { rev: number; paused?: boolean; reason?: string; dailyWriteCap?: number; }) => schedulesApi.settings.put(siteId, input), onSuccess: async (next: ScheduleSettings, input) => { qc.setQueryData(key, (prev: ScheduleSettings | undefined) => ({ ...prev, ...next })); await qc.invalidateQueries({ queryKey: ["schedules", siteId] }); setConfirming(undefined); toast.success( input.paused === true ? t(`${s}.killSwitch.pausedToast`) : input.paused === false ? t(`${s}.killSwitch.resumedToast`) : t(`${s}.cap.saved`), ); }, }); if (isNotEnabled(settings.error)) return ( } description={t(`${s}.unavailable`)} /> ); const data = settings.data; const capNumber = Number(cap); const capValid = Number.isInteger(capNumber) && capNumber >= 1 && capNumber <= 100_000; const capDirty = data !== undefined && capValid && capNumber !== data.dailyWriteCap; const health = scheduler.data; const tone = health?.state === "running" ? "success" : health?.state === "unknown" ? "neutral" : "error"; return ( }> {t(`${s}.health.state.stopped`)} ) : undefined } footer={ <> {cap !== String(data?.dailyWriteCap ?? "") && ( )} } > {!data ? (
{t("common.loading")}
) : ( <> {put.error && ( } title={t(`${s}.failed`)} description={isConflict(put.error) ? t(`${s}.conflict`) : apiErrorText(t, put.error)} action={ isConflict(put.error) ? ( } onClick={() => { put.reset(); void settings.refetch(); }} > {t(`${s}.reload`)} ) : undefined } /> )}
{health ? ( {t(`${s}.health.state.${health.state}`)} {health.lastTickAt ? t(`${s}.health.lastTick`, { time: formatMoment(health.lastTickAt, locale) }) : t(`${s}.health.never`)} {t(`${s}.health.modes.${health.mode ?? "unknown"}`)} ) : ( )} { setReason(""); setConfirming(on ? "pause" : "resume"); }} />
)} { if (!open) setConfirming(undefined); }} dismissDisabled={put.isPending} > {confirming === "pause" ? t(`${s}.killSwitch.confirmTitle`) : t(`${s}.killSwitch.resumeTitle`)} {confirming === "pause" ? t(`${s}.killSwitch.confirmDescription`) : t(`${s}.killSwitch.resumeDescription`)} {confirming === "pause" ? ( ) : ( )} data && put.mutate({ rev: data.rev, paused: confirming === "pause", ...(confirming === "pause" && reason.trim() ? { reason: reason.trim() } : {}), }) } > {confirming === "pause" ? t(`${s}.killSwitch.pause`) : t(`${s}.killSwitch.resume`)}
); }