Skip to content

Modern Docker Management, Designed for Everyone

27.2 KB
Raw Blame
<script lang="ts">
	import { onMount, onDestroy } from 'svelte';
	import { toast } from 'svelte-sonner';

	import { ArcaneButton } from '#lib/components/arcane-button/index.js';
	import ArcaneTable from '#lib/components/arcane-table/arcane-table.svelte';
	import { backupRunColumns, backupRunMobileFields, backupManagementBadge } from '#lib/components/arcane-table/backup-columns.js';
	import BackupDestinationCell from '#lib/components/arcane-table/cells/backup-destination-cell.svelte';
	import BackupManagementCell from '#lib/components/arcane-table/cells/backup-management-cell.svelte';
	import BackupSizeCell from '#lib/components/arcane-table/cells/backup-size-cell.svelte';
	import BackupStatusCell from '#lib/components/arcane-table/cells/backup-status-cell.svelte';
	import BackupTriggerCell from '#lib/components/arcane-table/cells/backup-trigger-cell.svelte';
	import CreatedAtCell from '#lib/components/arcane-table/cells/created-at-cell.svelte';
	import {
		UniversalMobileCard,
		type BulkAction,
		type ColumnSpec,
		type MobileFieldVisibility
	} from '#lib/components/arcane-table/index.js';
	import BackupFilePicker from '#lib/components/backup-file-picker.svelte';
	import BackupPolicyCard from '#lib/components/backup-policy-card.svelte';
	import BackupPolicyDialog from '#lib/components/backup-policy-dialog.svelte';
	import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';
	import RowActionsMenu from '#lib/components/file-browser/row-actions-menu.svelte';
	import SelectWithLabel from '#lib/components/form/select-with-label.svelte';
	import IfPermitted from '#lib/components/if-permitted.svelte';
	import * as Alert from '#lib/components/ui/alert/index.js';
	import * as ButtonGroup from '#lib/components/ui/button-group/index.js';
	import * as DropdownMenu from '#lib/components/ui/dropdown-menu/index.js';
	import { ResponsiveDialog } from '#lib/components/ui/responsive-dialog/index.js';
	import { useBackupActivity } from '#lib/hooks/use-backup-activity.svelte.js';
	import {
		TrashIcon,
		AddIcon,
		ClockIcon,
		VolumesIcon,
		InfoIcon,
		DownloadIcon,
		RestartIcon,
		FileTextIcon,
		AlertIcon,
		UploadIcon,
		ArrowDownIcon
	} from '#lib/icons/index.js';
	import { m } from '#lib/paraglide/messages.js';
	import { s3DestinationService } from '#lib/services/s3-destination-service.js';
	import { volumeBackupService, type VolumeBackupListResponse } from '#lib/services/volume-backup-service.js';
	import { volumeService } from '#lib/services/volume-service.js';
	import { activityStore } from '#lib/stores/activity.store.svelte.js';
	import { environmentStore } from '#lib/stores/environment.store.svelte.js';
	import { GLOBAL_SCOPE } from '#lib/types/auth.js';
	import type { BackupFileProvider } from '#lib/types/backup.js';
	import type { S3Destination } from '#lib/types/s3-destination.js';
	import type { BackupEntry, CreateVolumeBackupRequest, VolumeBackupPolicy } from '#lib/types/shared.js';
	import type { SearchPaginationSortRequest } from '#lib/types/shared.js';
	import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast.js';
	import { extractApiErrorMessage } from '#lib/utils/api.js';
	import { hasPermission } from '#lib/utils/auth.js';
	import {
		backupDestinationDisplay,
		backupManagementFilterOptions,
		backupTriggerLabel,
		s3DestinationOptions as buildS3DestinationOptions
	} from '#lib/utils/backups.js';
	import { bulkConfirmAndRun } from '#lib/utils/bulk-actions.js';
	import { bytes, formatDateTimeShort } from '#lib/utils/formatting.js';
	import { tryCatch } from '#lib/utils/try-catch.js';

	let {
		volumeName,
		environmentId,
		hasWorkspaceChanges = false,
		onWorkspaceRestored
	}: {
		volumeName: string;
		environmentId: string;
		hasWorkspaceChanges?: boolean;
		onWorkspaceRestored?: () => void | Promise<void>;
	} = $props();

	const currentEnvId = $derived(environmentId);
	const canReadActivities = $derived(hasPermission('activities:read', currentEnvId));
	const canBackupVolume = $derived(hasPermission('volumes:backup', currentEnvId));
	const canDeleteBackup = $derived(hasPermission('volumes:backup', currentEnvId));
	// Destinations are a global resource; an environment-scoped backup grant does not cover them.
	const canListS3Destinations = $derived(hasPermission('s3-destinations:list', GLOBAL_SCOPE));

	let backupsPaginated = $state<VolumeBackupListResponse>({
		data: [],
		pagination: {
			currentPage: 1,
			totalPages: 1,
			totalItems: 0,
			itemsPerPage: 10
		}
	});
	let backupWarnings = $state<string[]>([]);
	let backupPolicies = $state<VolumeBackupPolicy[]>([]);
	let s3Destinations = $state<S3Destination[]>([]);
	let s3DestinationsError = $state<string | null>(null);
	let showBackupPolicy = $state(false);
	let policySession = $state(0);
	let editingBackupPolicyId = $state<string | undefined>();
	let showS3DestinationDialog = $state(false);
	let onDemandDestination = $state<'s3' | 'local_s3'>('s3');
	let onDemandS3DestinationId = $state('');
	const s3DestinationOptions = $derived(buildS3DestinationOptions(s3Destinations));

	let requestOptions = $state<SearchPaginationSortRequest>({
		pagination: { page: 1, limit: 10 },
		sort: { column: 'createdAt', direction: 'desc' }
	});

	let creating = $state(false);
	let deletingSelected = $state(false);
	let selectedIds = $state<string[]>([]);
	let uploadingBackupId = $state<string | null>(null);
	let restoringFiles = $state(false);
	let showRestoreFiles = $state(false);
	let restoreTarget = $state<BackupEntry | null>(null);
	let backupFileProvider = $state<BackupFileProvider | null>(null);
	let backupFilesSearch = $state('');
	let selectedPaths = $state<string[]>([]);
	let selectAllBackupFiles = $state(false);
	let backupLoadVersion = 0;
	let active = true;
	onDestroy(() => {
		active = false;
		backupLoadVersion += 1;
	});

	async function loadData(options: SearchPaginationSortRequest): Promise<VolumeBackupListResponse> {
		await environmentStore.ready;
		if (!active) return backupsPaginated;
		const environmentId = currentEnvId;
		const name = volumeName;
		const version = ++backupLoadVersion;
		const result = await tryCatch(volumeBackupService.listBackups(name, options, environmentId));
		if (version !== backupLoadVersion || environmentId !== currentEnvId || name !== volumeName) return backupsPaginated;
		if (result.error !== null) {
			let message: string = m.volumes_backup_load_failed();
			if (result.error instanceof Error) message = result.error.message;
			toast.error(message);
			return backupsPaginated;
		}
		backupsPaginated = result.data;
		backupWarnings = result.data.warnings ?? [];
		return result.data;
	}

	const backupActivity = useBackupActivity(
		() => currentEnvId,
		(activity) => {
			const action = activity.metadata?.['action'];
			return (
				((action === 'create_volume_backup' || action === 'scheduled_volume_backup') && activity.resourceName === volumeName) ||
				(action === 'run_system_volume_backups' &&
					Array.isArray(activity.metadata?.['volumeNames']) &&
					activity.metadata['volumeNames'].includes(volumeName))
			);
		},
		() => loadData(requestOptions),
		() => volumeName,
		() => {
			const name = volumeName;
			if (canReadActivities) return undefined;
			return async (environmentId) => {
				const ids: string[] = [];
				let page = 1;
				let totalPages = 1;
				do {
					const result = await volumeBackupService.listBackups(
						name,
						{
							search: 'running',
							pagination: { page, limit: 100 }
						},
						environmentId
					);
					ids.push(...result.data.filter((backup) => backup.status === 'running').map((backup) => backup.id));
					totalPages = result.pagination.totalPages;
					page++;
				} while (page <= totalPages);
				return ids;
			};
		}
	);

	async function handleCreate(request?: CreateVolumeBackupRequest) {
		if (creating || backupActivity.activeIds.length) return false;
		creating = true;
		const environmentId = currentEnvId;
		const name = volumeName;
		const tracksActivities = canReadActivities;
		try {
			const operationResult = await tryCatch(
				(async () => {
					const result = await volumeBackupService.createBackup(name, request, environmentId);
					if (!active || environmentId !== currentEnvId || name !== volumeName) return false;
					showS3DestinationDialog = false;
					onDemandS3DestinationId = '';
					creating = false;
					let activityId: string | undefined = result.id;
					if (tracksActivities) activityId = extractActivityId(result);
					backupActivity.accepted(activityId);
					toast.success(
						m.backups_started(),
						canReadActivities ? activityToastOptions(extractActivityId(result), false) : undefined
					);
					void loadData(requestOptions);
					return true;
				})()
			);
			if (operationResult.error !== null) {
				const error = operationResult.error;

				toast.error(error instanceof Error ? error.message : m.common_failed());
				return false;
			} else {
				return operationResult.data;
			}
		} finally {
			creating = false;
		}
	}

	function openS3DestinationDialog(destination: 's3' | 'local_s3') {
		onDemandDestination = destination;
		onDemandS3DestinationId = s3Destinations.length === 1 ? (s3Destinations[0]?.id ?? '') : '';
		showS3DestinationDialog = true;
	}

	async function createS3Backup() {
		if (!onDemandS3DestinationId) return;
		const created = await handleCreate({
			destination: onDemandDestination,
			s3DestinationId: onDemandS3DestinationId
		});
		if (created) {
			showS3DestinationDialog = false;
			onDemandS3DestinationId = '';
		}
	}

	async function handleDelete(backup: BackupEntry) {
		openConfirmDialog({
			title: m.common_remove_title({ resource: m.volumes_workspace_backup() }),
			message: m.volumes_backup_delete_confirm(),
			confirm: {
				label: m.common_remove(),
				destructive: true,
				action: async () => {
					const operationResult = await tryCatch(
						(async () => {
							const result = await volumeBackupService.deleteBackup(backup.id, currentEnvId);
							toast.success(
								m.common_delete_success({ resource: m.volumes_workspace_backup() }),
								activityToastOptions(extractActivityId(result))
							);
							await loadData(requestOptions);
						})()
					);
					if (operationResult.error !== null) {
						const error = operationResult.error;

						toast.error(extractApiErrorMessage(error));
						await loadData(requestOptions);
					}
				}
			}
		});
	}

	function handleDeleteSelected(ids: string[]) {
		bulkConfirmAndRun({
			ids,
			title: m.volume_backups_remove_selected_title({ count: ids.length }),
			message: m.volume_backups_remove_selected_message({ count: ids.length }),
			confirmLabel: m.common_remove(),
			destructive: true,
			run: (id) => volumeBackupService.deleteBackup(id, currentEnvId),
			messages: {
				success: (count) => m.common_bulk_remove_success({ count, resource: m.volumes_backups_title() }),
				partial: (success, total, failed) =>
					m.common_bulk_remove_partial({ success, total, failed, resource: m.volumes_backups_title() }),
				failure: () => m.common_bulk_remove_failed({ count: ids.length, resource: m.volumes_backups_title() })
			},
			setLoading: (loading) => (deletingSelected = loading),
			onItemFailure: (_id, error) => toast.error(extractApiErrorMessage(error)),
			onComplete: () => loadData(requestOptions),
			clearSelection: () => (selectedIds = [])
		});
	}

	async function runBackupAction(
		run: () => Promise<unknown>,
		successMessage: () => string,
		failureMessage: () => string,
		afterRun?: () => void | Promise<void>
	) {
		const result = await tryCatch(
			(async () => {
				const response = await run();
				await afterRun?.();
				toast.success(successMessage(), activityToastOptions(extractActivityId(response)));
				await loadData(requestOptions);
			})()
		);
		if (result.error !== null) {
			toast.error(result.error instanceof Error ? result.error.message : failureMessage());
		}
	}

	async function handleUpload(backup: BackupEntry, s3DestinationId: string) {
		uploadingBackupId = backup.id;
		try {
			await runBackupAction(
				() => volumeBackupService.uploadBackup(backup.id, s3DestinationId, currentEnvId),
				m.backups_upload_s3_success,
				m.backups_upload_s3_failed
			);
		} finally {
			uploadingBackupId = null;
		}
	}

	function openRestoreFilesDialog(backup: BackupEntry) {
		restoreTarget = backup;
		selectedPaths = [];
		selectAllBackupFiles = false;
		backupFilesSearch = '';
		backupFileProvider = {
			browse: (request) => volumeBackupService.browseBackupFiles(backup.id, request, environmentId)
		};
		showRestoreFiles = true;
	}

	async function handleRestore(backup: BackupEntry) {
		const name = volumeName;
		const environmentId = currentEnvId;
		// Check if volume is in use
		let usageWarning = '';
		const operationResult = await tryCatch(
			(async () => {
				const usage = await volumeService.getVolumeUsage(volumeName, environmentId);
				if (usage.inUse && usage.containers?.length > 0) {
					usageWarning = m.volumes_backup_restore_in_use_warning({ count: usage.containers.length });
				}
			})()
		);
		if (operationResult.error !== null) {
			// Ignore errors checking usage
		}

		openConfirmDialog({
			title: m.volumes_backup_restore_title(),
			message:
				m.volumes_backup_restore_message({ volumeName }) +
				usageWarning +
				(hasWorkspaceChanges ? `\n\n${m.volumes_backup_restore_discard_changes()}` : ''),
			confirm: {
				label: m.volumes_backups_restore(),
				destructive: !!usageWarning || hasWorkspaceChanges,
				action: () =>
					runBackupAction(
						() => volumeBackupService.restoreBackup(name, backup.id, environmentId),
						m.volumes_backup_restore_success,
						m.common_failed,
						() => onWorkspaceRestored?.()
					)
			}
		});
	}

	async function handleRestoreFiles() {
		if (!restoreTarget) return;
		if (!selectAllBackupFiles && !selectedPaths.length) return;

		const name = volumeName;
		const backupId = restoreTarget.id;
		const environmentId = currentEnvId;
		const selection = { paths: [...selectedPaths], selectAll: selectAllBackupFiles };
		restoringFiles = true;
		try {
			const operationResult = await tryCatch(
				(async () => {
					const result = await volumeBackupService.restoreBackupFiles(
						name,
						backupId,
						{ ...selection, search: selection.selectAll ? backupFilesSearch.trim() : undefined },
						environmentId
					);
					await onWorkspaceRestored?.();
					toast.success(m.volumes_backup_restore_selection_success(), activityToastOptions(extractActivityId(result)));
					showRestoreFiles = false;
				})()
			);
			if (operationResult.error !== null) {
				const error = operationResult.error;

				toast.error(error instanceof Error ? error.message : m.common_failed());
			}
		} finally {
			restoringFiles = false;
		}
	}

	function formatBytes(value: number): string {
		return bytes.format(value, { unitSeparator: ' ' }) ?? '-';
	}

	onMount(async () => {
		await environmentStore.ready;
		const environmentId = currentEnvId;
		const name = volumeName;
		const [collection, destinations] = await Promise.all([
			volumeBackupService.getPolicies(name, environmentId),
			canBackupVolume && canListS3Destinations ? tryCatch(s3DestinationService.listAll()) : Promise.resolve(null),
			loadData(requestOptions)
		]);
		if (!active || environmentId !== currentEnvId || name !== volumeName) return;
		backupPolicies = collection.policies;
		if (destinations === null) return;
		if (destinations.error !== null) {
			s3DestinationsError = extractApiErrorMessage(destinations.error);
		} else {
			s3Destinations = destinations.data;
		}
	});

	const columns = [
		{ accessorKey: 'id', title: m.common_id(), sortable: true, cell: IdCell },
		{
			accessorKey: 'type',
			title: m.common_type(),
			sortable: false,
			cell: TypeCell,
			filterOptions: backupManagementFilterOptions()
		},
		...backupRunColumns({ status: StatusCell, trigger: TriggerCell, destination: DestinationCell, size: SizeCell }),
		{ accessorKey: 'createdAt', title: m.common_created(), sortable: true, cell: CreatedCell },
		{
			accessorKey: 'remoteSnapshotId',
			title: m.volume_backup_remote_snapshot(),
			sortable: true,
			cell: RemoteSnapshotCell,
			hidden: true
		},
		{ accessorKey: 'error', title: m.common_error(), sortable: false, cell: ErrorCell, hidden: true }
	] satisfies ColumnSpec<BackupEntry>[];

	const mobileFields = [
		...backupRunMobileFields(),
		{ id: 'remoteSnapshotId', label: m.volume_backup_remote_snapshot(), defaultVisible: false }
	];

	const bulkActions = $derived.by<BulkAction[]>(() => [
		{
			id: 'remove',
			label: m.common_remove_selected_count({ count: selectedIds.length }),
			action: 'remove',
			onClick: handleDeleteSelected,
			loading: deletingSelected,
			disabled: !canDeleteBackup || deletingSelected || selectedIds.length === 0,
			icon: TrashIcon
		}
	]);

	let mobileFieldVisibility = $state<Record<string, boolean>>({});
</script>

{#snippet IdCell({ item }: { item: BackupEntry })}
	<code class="font-mono text-xs font-medium">{item.id}</code>
{/snippet}

{#snippet StatusCell({ item }: { item: BackupEntry })}
	<BackupStatusCell status={item.status} />
{/snippet}

{#snippet TypeCell({ item }: { item: BackupEntry })}
	<BackupManagementCell type={item.type} />
{/snippet}

{#snippet TriggerCell({ item }: { item: BackupEntry })}
	<BackupTriggerCell trigger={item.trigger} />
{/snippet}

{#snippet DestinationCell({ item }: { item: BackupEntry })}
	<BackupDestinationCell {item} />
{/snippet}

{#snippet SizeCell({ item }: { item: BackupEntry })}
	<BackupSizeCell size={item.size} />
{/snippet}

{#snippet CreatedCell({ item }: { item: BackupEntry })}
	<CreatedAtCell value={item.createdAt} />
{/snippet}

{#snippet RemoteSnapshotCell({ item }: { item: BackupEntry })}
	<code class="text-xs">{item.remoteSnapshotId || m.volume_backup_not_uploaded()}</code>
{/snippet}

{#snippet ErrorCell({ item }: { item: BackupEntry })}
	<span class="line-clamp-2 max-w-80 text-xs text-destructive">{item.error || '-'}</span>
{/snippet}

{#snippet RowActions({ item }: { item: BackupEntry })}
	<RowActionsMenu openMenuLabel={m.common_open_menu()}>
		{#if canBackupVolume}
			<DropdownMenu.Item onclick={() => handleRestore(item)}>
				<RestartIcon class="size-4" />
				{m.volumes_backups_restore()}
			</DropdownMenu.Item>
			<DropdownMenu.Item onclick={() => openRestoreFilesDialog(item)}>
				<FileTextIcon class="size-4" />
				{m.volume_restore_files()}
			</DropdownMenu.Item>
		{/if}
		{#if item.format === 'archive' || item.localSnapshotId}
			<DropdownMenu.Item onclick={() => volumeBackupService.downloadBackup(item.id, currentEnvId)}>
				<DownloadIcon class="size-4" />
				{m.templates_download()}
			</DropdownMenu.Item>
		{/if}
		{#if canBackupVolume && s3Destinations.length}
			{#each s3Destinations as destination (destination.id)}
				<DropdownMenu.Item
					disabled={item.status !== 'succeeded' || Boolean(item.remoteSnapshotId) || uploadingBackupId === item.id}
					onclick={() => handleUpload(item, destination.id)}
				>
					<UploadIcon class="size-4" />
					{m.backups_upload_s3()} · {destination.name}
				</DropdownMenu.Item>
			{/each}
		{/if}
		<IfPermitted perm="volumes:backup" envId={currentEnvId}>
			<DropdownMenu.Separator />
			<DropdownMenu.Item variant="destructive" onclick={() => handleDelete(item)}>
				<TrashIcon class="size-4" />
				{m.common_remove()}
			</DropdownMenu.Item>
		</IfPermitted>
	</RowActionsMenu>
{/snippet}

{#snippet ToolbarActions()}
	{#if canBackupVolume}
		<div class="flex items-center gap-2">
			<ArcaneButton
				action="create"
				customLabel={m.volume_backup_add_schedule()}
				onclick={() => {
					editingBackupPolicyId = undefined;
					policySession += 1;
					showBackupPolicy = true;
				}}
				size="sm"
				icon={AddIcon}
			/>
			<ButtonGroup.Root>
				<ArcaneButton
					action="create"
					customLabel={m.volumes_backup_create()}
					loading={creating}
					disabled={creating || backupActivity.activeIds.length > 0}
					onclick={() => handleCreate()}
					size="sm"
					icon={AddIcon}
				/>
				{#if canListS3Destinations}
					<DropdownMenu.Root>
						<DropdownMenu.Trigger disabled={creating || backupActivity.activeIds.length > 0}>
							{#snippet child({ props })}
								<ArcaneButton
									{...props}
									action="base"
									tone="outline-primary"
									size="icon"
									icon={ArrowDownIcon}
									class="size-8 rounded-md"
									aria-label={m.common_open_menu()}
								/>
							{/snippet}
						</DropdownMenu.Trigger>
						<DropdownMenu.Content align="end" class="w-64">
							<DropdownMenu.Label>{m.backups_destination_label()}</DropdownMenu.Label>
							<DropdownMenu.Item onclick={() => handleCreate({ destination: 'local' })}>
								{m.local()}
							</DropdownMenu.Item>
							<DropdownMenu.Item onclick={() => openS3DestinationDialog('s3')}>
								{m.backups_destination_s3()}
							</DropdownMenu.Item>
							<DropdownMenu.Item onclick={() => openS3DestinationDialog('local_s3')}>
								{m.backups_destination_local_s3()}
							</DropdownMenu.Item>
						</DropdownMenu.Content>
					</DropdownMenu.Root>
				{/if}
			</ButtonGroup.Root>
		</div>
	{/if}
{/snippet}

{#snippet BackupMobileCardSnippet({
	item,
	mobileFieldVisibility
}: {
	item: BackupEntry;
	mobileFieldVisibility: MobileFieldVisibility;
})}
	<UniversalMobileCard
		{item}
		icon={{ component: VolumesIcon, variant: 'blue' }}
		title={(item) => item.id}
		badges={[backupManagementBadge]}
		fields={[
			{
				label: m.volume_backup_trigger(),
				getValue: (item) => backupTriggerLabel(item.trigger),
				icon: ClockIcon,
				iconVariant: 'gray',
				show: mobileFieldVisibility['trigger'] ?? true
			},
			{
				label: m.common_size(),
				getValue: (item) => formatBytes(item.size),
				icon: InfoIcon,
				iconVariant: 'gray',
				show: mobileFieldVisibility['size'] ?? true
			},
			{
				label: m.backups_destination_label(),
				getValue: (item) => backupDestinationDisplay(item),
				icon: DownloadIcon,
				iconVariant: 'gray',
				show: mobileFieldVisibility['destination'] ?? true
			},
			{
				label: m.volume_backup_remote_snapshot(),
				getValue: (item) => item.remoteSnapshotId || m.volume_backup_not_uploaded(),
				icon: DownloadIcon,
				iconVariant: 'gray',
				show: mobileFieldVisibility['remoteSnapshotId'] ?? false
			}
		]}
		footer={{
			label: m.common_created(),
			getValue: (item) => formatDateTimeShort(item.createdAt),
			icon: ClockIcon
		}}
		rowActions={RowActions}
	/>
{/snippet}

<div class="space-y-4">
	{#each backupActivity.activeIds as activityId (activityId)}
		<Alert.Root
			><Alert.Description>
				{m.backups_running()}
				{#if canReadActivities}
					<ArcaneButton
						action="inspect"
						size="sm"
						customLabel={m.activity_view_activity()}
						onclick={() => activityStore.openCenter(activityId)}
					/>
				{/if}
			</Alert.Description></Alert.Root
		>
	{/each}
	<div class="flex items-center justify-between">
		<h2 class="text-lg font-semibold">{m.volumes_backups_title()}</h2>
	</div>
	<div class="grid grid-cols-1 gap-1.5 text-xs text-muted-foreground sm:grid-cols-2 xl:grid-cols-3">
		{#each backupPolicies as policy (policy.id)}
			<BackupPolicyCard
				{policy}
				showStopContainers
				onEdit={canBackupVolume
					? () => {
							editingBackupPolicyId = policy.id;
							policySession += 1;
							showBackupPolicy = true;
						}
					: undefined}
			/>
		{/each}
	</div>

	<Alert.Root size="sm">
		<InfoIcon class="size-4" />
		<Alert.Description>
			{m.volume_backup_encryption_note()}
		</Alert.Description>
	</Alert.Root>

	{#if backupWarnings.length > 0}
		<Alert.Root variant="warning" size="sm">
			<AlertIcon class="size-4" />
			<Alert.Description>
				{backupWarnings[0]}
			</Alert.Description>
		</Alert.Root>
	{/if}

	{#if s3DestinationsError}
		<Alert.Root variant="destructive" size="sm">
			<AlertIcon class="size-4" />
			<Alert.Description>
				{m.s3_destinations_load_failed()}: {s3DestinationsError}
			</Alert.Description>
		</Alert.Root>
	{/if}

	<ArcaneTable
		persistKey="arcane-volume-backup-table"
		items={backupsPaginated}
		bind:selectedIds
		bind:requestOptions
		bind:mobileFieldVisibility
		onRefresh={loadData}
		{columns}
		{mobileFields}
		{bulkActions}
		rowActions={RowActions}
		mobileCard={BackupMobileCardSnippet}
		customToolbarActions={ToolbarActions}
	/>
</div>

<ResponsiveDialog
	bind:open={showRestoreFiles}
	title={m.volume_restore_files()}
	description={m.volumes_backup_restore_desc()}
	contentClass="sm:max-w-160"
>
	{#snippet children()}
		<div class="space-y-3 py-2">
			<Alert.Root size="sm">
				<InfoIcon class="size-4" />
				<Alert.Description>
					{m.volume_backup_restore_files_lifecycle_info()}
				</Alert.Description>
			</Alert.Root>

			{#if backupFileProvider}
				{#key backupFileProvider}
					<BackupFilePicker
						provider={backupFileProvider}
						bind:selectedPaths
						bind:selectAll={selectAllBackupFiles}
						bind:search={backupFilesSearch}
					/>
				{/key}
			{/if}

			<Alert.Root variant="warning" size="sm">
				<AlertIcon class="size-4" />
				<Alert.Description>
					{m.volumes_backup_overwrite_warning()}
				</Alert.Description>
			</Alert.Root>

			{#if hasWorkspaceChanges}
				<Alert.Root variant="warning" size="sm">
					<AlertIcon class="size-4" />
					<Alert.Description>
						{m.volumes_backup_restore_discard_changes()}
					</Alert.Description>
				</Alert.Root>
			{/if}
		</div>
	{/snippet}

	{#snippet footer()}
		<ArcaneButton
			action="cancel"
			onclick={() => {
				showRestoreFiles = false;
			}}
		/>
		{#if canBackupVolume}
			<ArcaneButton
				action="create"
				customLabel={m.volume_restore_files()}
				onclick={handleRestoreFiles}
				loading={restoringFiles}
				disabled={restoringFiles || (!selectAllBackupFiles && selectedPaths.length === 0)}
			/>
		{/if}
	{/snippet}
</ResponsiveDialog>

<ResponsiveDialog
	bind:open={showS3DestinationDialog}
	title={m.volume_backup_choose_s3_destination()}
	description={m.volume_backup_choose_s3_destination_description()}
	contentClass="sm:max-w-130"
>
	{#snippet children()}
		<div class="py-2">
			<SelectWithLabel
				id="on-demand-volume-backup-s3-destination"
				value={onDemandS3DestinationId}
				onValueChange={(value) => (onDemandS3DestinationId = value)}
				label={m.volume_backup_s3_destination_label()}
				description={m.volume_backup_s3_destination_description()}
				options={s3DestinationOptions}
			/>
			{#if s3Destinations.length === 0}
				<p class="mt-2 text-xs text-muted-foreground">{m.volume_backup_no_s3_destinations()}</p>
			{/if}
		</div>
	{/snippet}
	{#snippet footer()}
		<ArcaneButton action="cancel" onclick={() => (showS3DestinationDialog = false)} disabled={creating} />
		<ArcaneButton
			action="create"
			customLabel={m.volumes_backup_create()}
			onclick={createS3Backup}
			loading={creating}
			disabled={creating || backupActivity.activeIds.length > 0 || !onDemandS3DestinationId}
		/>
	{/snippet}
</ResponsiveDialog>

{#if policySession > 0}
	{#key policySession}
		<BackupPolicyDialog
			bind:open={showBackupPolicy}
			idPrefix="volume-backup-policy"
			policies={backupPolicies}
			policyId={editingBackupPolicyId}
			addTitle={m.volume_backup_add_schedule()}
			description={m.volume_backup_policy_description()}
			enabledDescription={m.volume_backup_policy_enabled_description()}
			defaultSchedule="0 0 2 * * *"
			showStopContainers
			destinations={canListS3Destinations && !s3DestinationsError ? s3Destinations : undefined}
			updatePolicies={async (policies) => (await volumeBackupService.updatePolicies(volumeName, policies, currentEnvId)).policies}
			messages={{
				saved: m.volume_backup_policy_saved(),
				saveFailed: m.volume_backup_policy_save_failed(),
				removed: m.volume_backup_schedule_removed()
			}}
			onSaved={(policies) => (backupPolicies = policies)}
		/>
	{/key}
{/if}