feat(admin): add server runtime config settings (#7618)

This commit is contained in:
JimmFly
2024-08-13 14:51:31 +08:00
committed by GitHub
parent 7f7c0519a0
commit bf6e36de37
17 changed files with 762 additions and 223 deletions
@@ -0,0 +1,81 @@
import { Button } from '@affine/admin/components/ui/button';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@affine/admin/components/ui/dialog';
import type { ModifiedValues } from './index';
export const ConfirmChanges = ({
open,
onClose,
onConfirm,
onOpenChange,
modifiedValues,
}: {
open: boolean;
onClose: () => void;
onConfirm: () => void;
onOpenChange: (open: boolean) => void;
modifiedValues: ModifiedValues[];
}) => {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:w-[460px]">
<DialogHeader>
<DialogTitle className="leading-7">
Save Runtime Configurations ?
</DialogTitle>
<DialogDescription className="leading-6">
Are you sure you want to save the following changes?
</DialogDescription>
</DialogHeader>
{modifiedValues.length > 0 ? (
<pre className="flex flex-col text-sm bg-zinc-100 gap-1 min-h-[64px] rounded-md p-[12px_16px_16px_12px] mt-2 overflow-hidden">
<p>{'{'}</p>
{modifiedValues.map(({ id, expiredValue, newValue }) => (
<p key={id}>
{' '} {id}:{' '}
<span
className="mr-2 line-through "
style={{
color: 'rgba(198, 34, 34, 1)',
backgroundColor: 'rgba(254, 213, 213, 1)',
}}
>
{JSON.stringify(expiredValue)}
</span>
<span
style={{
color: 'rgba(20, 147, 67, 1)',
backgroundColor: 'rgba(225, 250, 177, 1)',
}}
>
{JSON.stringify(newValue)}
</span>
,
</p>
))}
<p>{'}'}</p>
</pre>
) : (
'There is no change.'
)}
<DialogFooter>
<div className="flex justify-end items-center w-full space-x-4">
<Button type="button" onClick={onClose} variant="outline">
<span>Cancel</span>
</Button>
<Button type="button" onClick={onConfirm}>
<span>Save</span>
</Button>
</div>
</DialogFooter>
</DialogContent>
</Dialog>
);
};
@@ -0,0 +1,193 @@
import { Button } from '@affine/admin/components/ui/button';
import { ScrollArea } from '@affine/admin/components/ui/scroll-area';
import { Separator } from '@affine/admin/components/ui/separator';
import type { RuntimeConfigType } from '@affine/graphql';
import { CheckIcon } from 'lucide-react';
import type { Dispatch, SetStateAction } from 'react';
import { useCallback, useMemo, useState } from 'react';
import { Layout } from '../layout';
import { useNav } from '../nav/context';
import { ConfirmChanges } from './confirm-changes';
import { RuntimeSettingRow } from './runtime-setting-row';
import { useGetServerRuntimeConfig } from './use-get-server-runtime-config';
import { useUpdateServerRuntimeConfigs } from './use-update-server-runtime-config';
import {
formatValue,
formatValueForInput,
isEqual,
renderInput,
} from './utils';
export type ModifiedValues = {
id: string;
expiredValue: any;
newValue: any;
};
export function Settings() {
return <Layout content={<SettingsPage />} />;
}
export function SettingsPage() {
const { trigger } = useUpdateServerRuntimeConfigs();
const { serverRuntimeConfig } = useGetServerRuntimeConfig();
const [open, setOpen] = useState(false);
const [configValues, setConfigValues] = useState(
serverRuntimeConfig.reduce(
(acc, config) => {
acc[config.id] = config.value;
return acc;
},
{} as Record<string, any>
)
);
const modifiedValues: ModifiedValues[] = useMemo(() => {
return serverRuntimeConfig
.filter(config => !isEqual(config.value, configValues[config.id]))
.map(config => ({
id: config.id,
key: config.key,
expiredValue: config.value,
newValue: configValues[config.id],
}));
}, [configValues, serverRuntimeConfig]);
const handleSave = useCallback(() => {
// post value example: { "key1": "newValue1","key2": "newValue2"}
const updates: Record<string, any> = {};
modifiedValues.forEach(item => {
if (item.id && item.newValue !== undefined) {
updates[item.id] = item.newValue;
}
});
trigger({ updates });
}, [modifiedValues, trigger]);
const disableSave = modifiedValues.length === 0;
const onOpen = useCallback(() => setOpen(true), [setOpen]);
const onClose = useCallback(() => setOpen(false), [setOpen]);
const onConfirm = useCallback(() => {
if (disableSave) {
return;
}
handleSave();
onClose();
}, [disableSave, handleSave, onClose]);
return (
<div className=" h-screen flex-1 flex-col flex">
<div className="flex items-center justify-between px-6 py-3 max-md:ml-9">
<div className="text-base font-medium">Settings</div>
<Button
type="submit"
size="icon"
className="w-7 h-7"
variant="ghost"
onClick={onOpen}
disabled={disableSave}
>
<CheckIcon size={20} />
</Button>
</div>
<Separator />
<AdminPanel
configValues={configValues}
setConfigValues={setConfigValues}
/>
<ConfirmChanges
modifiedValues={modifiedValues}
open={open}
onOpenChange={setOpen}
onClose={onClose}
onConfirm={onConfirm}
/>
</div>
);
}
export const AdminPanel = ({
setConfigValues,
configValues,
}: {
setConfigValues: Dispatch<SetStateAction<Record<string, any>>>;
configValues: Record<string, any>;
}) => {
const { configGroup } = useGetServerRuntimeConfig();
const { currentModule } = useNav();
const handleInputChange = useCallback(
(key: string, value: any, type: RuntimeConfigType) => {
const newValue = formatValueForInput(value, type);
setConfigValues(prevValues => ({
...prevValues,
[key]: newValue,
}));
},
[setConfigValues]
);
return (
<ScrollArea>
<div className="flex flex-col h-full gap-3 py-5 px-6 w-full">
{configGroup
.filter(group => group.moduleName === currentModule)
.map(group => {
const { moduleName, configs } = group;
return (
<div
className="flex flex-col gap-5"
id={moduleName}
key={moduleName}
>
<div className="text-xl font-semibold">{moduleName}</div>
{configs?.map((config, index) => {
const { id, type, description, updatedAt } = config;
const isValueEqual = isEqual(config.value, configValues[id]);
const formatServerValue = formatValue(config.value);
const formatCurrentValue = formatValue(configValues[id]);
return (
<div key={id} className="flex flex-col gap-10">
{index !== 0 && <Separator />}
<RuntimeSettingRow
key={id}
id={id}
description={description}
lastUpdatedTime={updatedAt}
operation={renderInput(type, configValues[id], value =>
handleInputChange(id, value, type)
)}
>
<div style={{ opacity: isValueEqual ? 0 : 1 }}>
<span
className="line-through"
style={{
color: 'rgba(198, 34, 34, 1)',
backgroundColor: 'rgba(254, 213, 213, 1)',
}}
>
{formatServerValue}
</span>{' '}
=&gt;{' '}
<span
style={{
color: 'rgba(20, 147, 67, 1)',
backgroundColor: 'rgba(225, 250, 177, 1)',
}}
>
{formatCurrentValue}
</span>
</div>
</RuntimeSettingRow>
</div>
);
})}
</div>
);
})}
</div>
</ScrollArea>
);
};
export { Settings as Component };
@@ -0,0 +1,39 @@
import { type ReactNode } from 'react';
export const RuntimeSettingRow = ({
id,
description,
lastUpdatedTime,
operation,
children,
}: {
id: string;
description: string;
lastUpdatedTime: string;
operation: ReactNode;
children: ReactNode;
}) => {
const formatTime = new Date(lastUpdatedTime).toLocaleString();
return (
<div
className="flex justify-between flex-grow overflow-y-auto space-y-[10px] gap-5"
id={id}
>
<div className="flex flex-col gap-1">
<div className="text-base font-bold">{description}</div>
<div className="">
<code className="text-xs bg-zinc-100 text-gray-500 px-[4px] py-[2px] rounded">
{id}
</code>
</div>
<div className="text-xs text-gray-500">
last updated at: {formatTime}
</div>
</div>
<div className="flex flex-col items-end gap-2 mr-1">
{operation}
{children}
</div>
</div>
);
};
@@ -0,0 +1,57 @@
import { useQuery } from '@affine/core/hooks/use-query';
import { getServerRuntimeConfigQuery } from '@affine/graphql';
import { useMemo } from 'react';
export const useGetServerRuntimeConfig = () => {
const { data } = useQuery({
query: getServerRuntimeConfigQuery,
});
const serverRuntimeConfig = useMemo(
() =>
data?.serverRuntimeConfig.sort((a, b) => a.id.localeCompare(b.id)) ?? [],
[data]
);
// collect all the modules and config keys in each module
const moduleList = useMemo(() => {
const moduleMap: { [key: string]: string[] } = {};
serverRuntimeConfig.forEach(config => {
if (!moduleMap[config.module]) {
moduleMap[config.module] = [];
}
moduleMap[config.module].push(config.key);
});
return Object.keys(moduleMap)
.sort((a, b) => a.localeCompare(b))
.map(moduleName => ({
moduleName,
keys: moduleMap[moduleName].sort((a, b) => a.localeCompare(b)),
}));
}, [serverRuntimeConfig]);
// group config by module name
const configGroup = useMemo(() => {
const configMap = new Map<string, typeof serverRuntimeConfig>();
serverRuntimeConfig.forEach(config => {
if (!configMap.has(config.module)) {
configMap.set(config.module, []);
}
configMap.get(config.module)?.push(config);
});
return Array.from(configMap.entries()).map(([moduleName, configs]) => ({
moduleName,
configs,
}));
}, [serverRuntimeConfig]);
return {
serverRuntimeConfig,
moduleList,
configGroup,
};
};
@@ -0,0 +1,41 @@
import { notify } from '@affine/component';
import { useAsyncCallback } from '@affine/core/hooks/affine-async-hooks';
import {
useMutateQueryResource,
useMutation,
} from '@affine/core/hooks/use-mutation';
import {
getServerRuntimeConfigQuery,
updateServerRuntimeConfigsMutation,
} from '@affine/graphql';
export const useUpdateServerRuntimeConfigs = () => {
const { trigger, isMutating } = useMutation({
mutation: updateServerRuntimeConfigsMutation,
});
const revalidate = useMutateQueryResource();
return {
trigger: useAsyncCallback(
async (values: any) => {
try {
await trigger(values);
await revalidate(getServerRuntimeConfigQuery);
notify.success({
title: 'Saved successfully',
message: 'Runtime configurations have been saved successfully.',
});
} catch (e) {
notify.error({
title: 'Failed to save',
message:
'Failed to save runtime configurations, please try again later.',
});
console.error(e);
}
},
[revalidate, trigger]
),
isMutating,
};
};
@@ -0,0 +1,73 @@
import { Input } from '@affine/admin/components/ui/input';
import { Switch } from '@affine/admin/components/ui/switch';
import type { RuntimeConfigType } from '@affine/graphql';
export const renderInput = (
type: RuntimeConfigType,
value: any,
onChange: (value?: any) => void
) => {
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
onChange(e.target.value);
};
const handleSwitchChange = (checked: boolean) => {
onChange(checked);
};
switch (type) {
case 'Boolean':
return <Switch checked={value} onCheckedChange={handleSwitchChange} />;
case 'String':
return (
<Input
type="text"
minLength={1}
value={value}
onChange={handleInputChange}
/>
);
case 'Number':
return (
<div style={{ width: '100%' }}>
<Input type="number" value={value} onChange={handleInputChange} />
</div>
);
// TODO(@JimmFly): add more types
default:
return null;
}
};
export const isEqual = (a: any, b: any) => {
if (typeof a !== typeof b) return false;
if (typeof a === 'object') return JSON.stringify(a) === JSON.stringify(b);
return a === b;
};
export const formatValue = (value: any) => {
if (typeof value === 'object') return JSON.stringify(value);
return value.toString();
};
export const formatValueForInput = (value: any, type: RuntimeConfigType) => {
let newValue = null;
switch (type) {
case 'Boolean':
newValue = !!value;
break;
case 'String':
newValue = value;
break;
case 'Number':
newValue = Number(value);
break;
case 'Array':
newValue = value.split(',');
break;
case 'Object':
newValue = JSON.parse(value);
break;
default:
break;
}
return newValue;
};