forked from QuantumNous/new-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlog-settings-section.tsx
More file actions
616 lines (570 loc) 路 20.3 KB
/
Copy pathlog-settings-section.tsx
File metadata and controls
616 lines (570 loc) 路 20.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { zodResolver } from '@hookform/resolvers/zod'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { useForm } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import * as z from 'zod'
import { DateTimePicker } from '@/components/datetime-picker'
import { Alert, AlertDescription } from '@/components/ui/alert'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from '@/components/ui/alert-dialog'
import { Button } from '@/components/ui/button'
import {
Form,
FormControl,
FormDescription,
FormField,
FormLabel,
FormMessage,
} from '@/components/ui/form'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Progress } from '@/components/ui/progress'
import {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { Separator } from '@/components/ui/separator'
import { Switch } from '@/components/ui/switch'
import { api } from '@/lib/api'
import dayjs from '@/lib/dayjs'
import { formatTimestampToDate } from '@/lib/format'
import {
getCurrentLogCleanupTask,
getSystemTask,
startLogCleanupTask,
} from '../api'
import {
SettingsControlGroup,
SettingsForm,
SettingsSwitchContent,
SettingsSwitchItem,
} from '../components/settings-form-layout'
import { SettingsPageFormActions } from '../components/settings-page-context'
import { SettingsSection } from '../components/settings-section'
import { useUpdateOption } from '../hooks/use-update-option'
import type { LogCleanupTask } from '../types'
const logSettingsSchema = z.object({
LogConsumeEnabled: z.boolean(),
})
type LogSettingsFormValues = z.infer<typeof logSettingsSchema>
type LogSettingsSectionProps = {
defaultEnabled: boolean
}
type ServerLogInfo = {
enabled: boolean
log_dir: string
file_count: number
total_size: number
oldest_time?: string
newest_time?: string
}
const HOURS_IN_DAY = 24
function formatBytes(bytes: number, decimals = 2): string {
if (!bytes || Number.isNaN(bytes)) return '0 Bytes'
if (bytes === 0) return '0 Bytes'
if (bytes < 0) return `-${formatBytes(-bytes, decimals)}`
const k = 1024
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']
const i = Math.floor(Math.log(Math.abs(bytes)) / Math.log(k))
if (i < 0 || i >= sizes.length) return `${bytes} Bytes`
return `${Number.parseFloat((bytes / Math.pow(k, i)).toFixed(decimals))} ${
sizes[i]
}`
}
const getDateHoursAgo = (hours: number) => {
const date = new Date()
date.setHours(date.getHours() - hours)
return date
}
const getDateDaysAgo = (days: number) => getDateHoursAgo(days * HOURS_IN_DAY)
const quickSelectOptions = [
{
label: '24 hours ago',
getValue: () => getDateHoursAgo(24),
},
{
label: '7 days ago',
getValue: () => getDateDaysAgo(7),
},
{
label: '30 days ago',
getValue: () => getDateDaysAgo(30),
},
]
function isActiveLogCleanupTask(task: LogCleanupTask | null) {
return task?.status === 'pending' || task?.status === 'running'
}
export function LogSettingsSection({
defaultEnabled,
}: LogSettingsSectionProps) {
const { t } = useTranslation()
const updateOption = useUpdateOption()
const form = useForm<LogSettingsFormValues>({
resolver: zodResolver(logSettingsSchema),
defaultValues: {
LogConsumeEnabled: defaultEnabled,
},
})
const [purgeDate, setPurgeDate] = useState<Date | undefined>(() =>
getDateDaysAgo(30)
)
const [isStartingLogCleanup, setIsStartingLogCleanup] = useState(false)
const [logCleanupTask, setLogCleanupTask] = useState<LogCleanupTask | null>(
null
)
const [showConfirmDialog, setShowConfirmDialog] = useState(false)
const [serverLogInfo, setServerLogInfo] = useState<ServerLogInfo | null>(null)
const [serverLogCleanupMode, setServerLogCleanupMode] = useState('by_count')
const [serverLogCleanupValue, setServerLogCleanupValue] = useState(10)
const [serverLogCleanupLoading, setServerLogCleanupLoading] = useState(false)
const fetchServerLogInfo = useCallback(async () => {
try {
const res = await api.get('/api/performance/logs')
if (res.data.success) setServerLogInfo(res.data.data)
} catch {
/* ignore */
}
}, [])
useEffect(() => {
form.reset({ LogConsumeEnabled: defaultEnabled })
}, [defaultEnabled, form])
useEffect(() => {
fetchServerLogInfo()
}, [fetchServerLogInfo])
useEffect(() => {
let cancelled = false
async function fetchCurrentLogCleanupTask() {
try {
const res = await getCurrentLogCleanupTask()
if (!cancelled && res.success && res.data) {
setLogCleanupTask(res.data)
}
} catch {
/* ignore */
}
}
fetchCurrentLogCleanupTask()
return () => {
cancelled = true
}
}, [])
const purgeTimestamp = useMemo(() => {
if (!purgeDate) return null
return Math.floor(purgeDate.getTime() / 1000)
}, [purgeDate])
const formattedPurgeDate = useMemo(() => {
if (!purgeDate) return ''
return formatTimestampToDate(purgeDate.getTime(), 'milliseconds')
}, [purgeDate])
const logCleanupActive = isActiveLogCleanupTask(logCleanupTask)
const logCleanupState = logCleanupTask?.state
const logCleanupProgress = Math.min(
100,
Math.max(0, logCleanupState?.progress ?? 0)
)
const logCleanupProcessed = logCleanupState?.processed ?? 0
const logCleanupTotal = logCleanupState?.total ?? 0
const logCleanupTaskId = logCleanupTask?.task_id
useEffect(() => {
if (!logCleanupTaskId || !logCleanupActive) return
let cancelled = false
const interval = window.setInterval(async () => {
try {
const res = await getSystemTask(logCleanupTaskId)
if (cancelled || !res.success || !res.data) return
setLogCleanupTask(res.data)
if (!isActiveLogCleanupTask(res.data)) {
if (res.data.status === 'succeeded') {
const count =
res.data.result?.deleted_count ?? res.data.state?.processed ?? 0
toast.success(
count > 0
? t('{{count}} log entries removed.', { count })
: t('No log entries matched the selected time.')
)
} else if (res.data.status === 'failed') {
toast.error(res.data.error || t('Failed to clean logs'))
}
}
} catch {
/* keep polling */
}
}, 1000)
return () => {
cancelled = true
window.clearInterval(interval)
}
}, [logCleanupActive, logCleanupTaskId, t])
const onSubmit = async (values: LogSettingsFormValues) => {
if (values.LogConsumeEnabled === defaultEnabled) return
await updateOption.mutateAsync({
key: 'LogConsumeEnabled',
value: values.LogConsumeEnabled,
})
}
const handleRequestCleanLogs = () => {
if (!purgeTimestamp) {
toast.error(t('Select a timestamp before clearing logs.'))
return
}
setShowConfirmDialog(true)
}
const handleCleanLogs = async () => {
if (!purgeTimestamp) {
toast.error(t('Select a timestamp before clearing logs.'))
return
}
setIsStartingLogCleanup(true)
try {
const res = await startLogCleanupTask(purgeTimestamp)
if (!res.success) {
throw new Error(res.message || t('Failed to clean logs'))
}
if (!res.data) {
throw new Error(t('Failed to clean logs'))
}
setLogCleanupTask(res.data)
setShowConfirmDialog(false)
toast.success(t('Log cleanup task started.'))
} catch (error) {
const message =
error instanceof Error ? error.message : t('Failed to clean logs')
toast.error(message)
} finally {
setIsStartingLogCleanup(false)
}
}
const cleanupServerLogFiles = async () => {
if (
!serverLogCleanupValue ||
Number.isNaN(serverLogCleanupValue) ||
serverLogCleanupValue < 1
) {
toast.error(t('Please enter a valid number'))
return
}
setServerLogCleanupLoading(true)
try {
const res = await api.delete(
`/api/performance/logs?mode=${serverLogCleanupMode}&value=${serverLogCleanupValue}`
)
if (res.data.success) {
const { deleted_count, freed_bytes } = res.data.data
toast.success(
t('Cleaned up {{count}} log files, freed {{size}}', {
count: deleted_count,
size: formatBytes(freed_bytes),
})
)
} else {
toast.error(res.data.message || t('Cleanup failed'))
}
fetchServerLogInfo()
} catch {
toast.error(t('Cleanup failed'))
} finally {
setServerLogCleanupLoading(false)
}
}
return (
<SettingsSection title={t('Log Maintenance')}>
<Form {...form}>
<SettingsForm onSubmit={form.handleSubmit(onSubmit)}>
<SettingsPageFormActions
onSave={form.handleSubmit(onSubmit)}
isSaving={updateOption.isPending}
saveLabel='Save log settings'
/>
<FormField
control={form.control}
name='LogConsumeEnabled'
render={({ field }) => (
<SettingsSwitchItem>
<SettingsSwitchContent>
<FormLabel>{t('Record quota usage')}</FormLabel>
<FormDescription>
{t(
'Track per-request consumption to power usage analytics. Keeping this on increases database writes.'
)}
</FormDescription>
</SettingsSwitchContent>
<FormControl>
<Switch
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
<FormMessage />
</SettingsSwitchItem>
)}
/>
<SettingsControlGroup className='space-y-3'>
<div>
<h4 className='text-sm font-medium'>{t('Clean history logs')}</h4>
<p className='text-muted-foreground text-sm'>
{t(
'Remove all log entries created before the selected timestamp.'
)}
</p>
</div>
<DateTimePicker value={purgeDate} onChange={setPurgeDate} />
<div className='flex flex-wrap gap-3'>
{quickSelectOptions.map((option) => (
<Button
key={option.label}
type='button'
variant='outline'
onClick={() => setPurgeDate(option.getValue())}
>
{t(option.label)}
</Button>
))}
<Button
type='button'
variant='destructive'
onClick={handleRequestCleanLogs}
disabled={isStartingLogCleanup || logCleanupActive}
>
{isStartingLogCleanup || logCleanupActive
? t('Cleaning...')
: t('Clean logs')}
</Button>
</div>
{logCleanupTask && (
<div className='rounded-md border p-3'>
<div className='mb-2 flex items-center justify-between gap-3 text-sm'>
<span className='font-medium'>
{t('Log cleanup progress')}
</span>
<span className='text-muted-foreground tabular-nums'>
{logCleanupProgress}%
</span>
</div>
<Progress value={logCleanupProgress} />
<div className='text-muted-foreground mt-2 text-xs'>
{t('{{processed}} of {{total}} log entries processed.', {
processed: logCleanupProcessed,
total: logCleanupTotal,
})}
</div>
{logCleanupTask.status === 'failed' && logCleanupTask.error && (
<div className='text-destructive mt-2 text-xs'>
{logCleanupTask.error}
</div>
)}
</div>
)}
</SettingsControlGroup>
</SettingsForm>
</Form>
<Separator />
<div className='space-y-4'>
<div>
<h4 className='font-medium'>{t('Server Log Management')}</h4>
<p className='text-muted-foreground mt-1 text-xs'>
{t(
'Manage server log files. Log files accumulate over time; regular cleanup is recommended to free disk space.'
)}
</p>
</div>
{serverLogInfo !== null &&
(serverLogInfo.enabled ? (
<div className='space-y-4'>
<div className='rounded-lg border p-4'>
<div className='grid grid-cols-2 gap-2 text-sm md:grid-cols-4'>
<div>
<span className='text-muted-foreground'>
{t('Log Directory')}:
</span>{' '}
<span className='font-mono text-xs'>
{serverLogInfo.log_dir}
</span>
</div>
<div>
<span className='text-muted-foreground'>
{t('Log File Count')}:
</span>{' '}
{serverLogInfo.file_count}
</div>
<div>
<span className='text-muted-foreground'>
{t('Total Log Size')}:
</span>{' '}
{formatBytes(serverLogInfo.total_size)}
</div>
{serverLogInfo.oldest_time && serverLogInfo.newest_time && (
<div>
<span className='text-muted-foreground'>
{t('Date Range')}:
</span>{' '}
{dayjs(serverLogInfo.oldest_time).format('YYYY-MM-DD')} ~{' '}
{dayjs(serverLogInfo.newest_time).format('YYYY-MM-DD')}
</div>
)}
</div>
</div>
<div className='flex flex-wrap items-end gap-3'>
<div className='grid gap-1.5'>
<Label className='text-xs'>{t('Cleanup Mode')}</Label>
<Select
items={[
{ value: 'by_count', label: t('Retain last N files') },
{ value: 'by_days', label: t('Retain last N days') },
]}
value={serverLogCleanupMode}
onValueChange={(value) =>
value !== null && setServerLogCleanupMode(value)
}
>
<SelectTrigger className='w-[160px]'>
<SelectValue />
</SelectTrigger>
<SelectContent alignItemWithTrigger={false}>
<SelectGroup>
<SelectItem value='by_count'>
{t('Retain last N files')}
</SelectItem>
<SelectItem value='by_days'>
{t('Retain last N days')}
</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
</div>
<div className='grid gap-1.5'>
<Label className='text-xs'>
{serverLogCleanupMode === 'by_count'
? t('Files to Retain')
: t('Days to Retain')}
</Label>
<Input
type='number'
min={1}
max={serverLogCleanupMode === 'by_count' ? 1000 : 3650}
value={serverLogCleanupValue}
onChange={(event) =>
setServerLogCleanupValue(Number(event.target.value))
}
className='w-[120px]'
/>
</div>
<AlertDialog>
<AlertDialogTrigger
render={
<Button
type='button'
variant='destructive'
size='sm'
disabled={serverLogCleanupLoading}
/>
}
>
{serverLogCleanupLoading
? t('Cleaning...')
: t('Clean Up Log Files')}
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{t('Confirm log file cleanup?')}
</AlertDialogTitle>
<AlertDialogDescription>
{serverLogCleanupMode === 'by_count'
? t(
'Only the last {{value}} log files will be retained; the rest will be deleted.',
{
value: serverLogCleanupValue,
}
)
: t(
'Log files older than {{value}} days will be deleted.',
{
value: serverLogCleanupValue,
}
)}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{t('Cancel')}</AlertDialogCancel>
<AlertDialogAction
variant='destructive'
onClick={cleanupServerLogFiles}
>
{t('Confirm Cleanup')}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</div>
) : (
<Alert>
<AlertDescription>
{t(
'Server logging is not enabled (log directory not configured)'
)}
</AlertDescription>
</Alert>
))}
</div>
<AlertDialog open={showConfirmDialog} onOpenChange={setShowConfirmDialog}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t('Confirm log cleanup')}</AlertDialogTitle>
<AlertDialogDescription>
{formattedPurgeDate
? t(
'This will permanently remove all log entries created before {{date}}.',
{ date: formattedPurgeDate }
)
: t(
'This will permanently remove log entries before the selected timestamp.'
)}{' '}
{t('This action cannot be undone.')}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={isStartingLogCleanup}>
{t('Cancel')}
</AlertDialogCancel>
<AlertDialogAction
variant='destructive'
onClick={handleCleanLogs}
disabled={isStartingLogCleanup}
>
{isStartingLogCleanup ? t('Cleaning...') : t('Delete logs')}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</SettingsSection>
)
}