building out frontend and docker

This commit is contained in:
C-West8
2026-10-23 06:52:20 -05:00
parent 42a1ce7d30
commit c9ce46d7bc
58 changed files with 2665 additions and 50 deletions

View File

@@ -0,0 +1,13 @@
<script lang="ts">
import { invalidateAll } from '$app/navigation';
/** Reloads the page's data on an interval while the tab is visible. */
let { intervalMs }: { intervalMs: number } = $props();
$effect(() => {
const timer = setInterval(() => {
if (document.visibilityState === 'visible') void invalidateAll();
}, intervalMs);
return () => clearInterval(timer);
});
</script>

View File

@@ -0,0 +1,7 @@
<script lang="ts">
import type { Tone } from '#lib/format.ts';
let { tone, label }: { tone: Tone; label: string } = $props();
</script>
<span class="badge tone-{tone}">{label}</span>

View File

@@ -0,0 +1,179 @@
<script lang="ts">
import { SvelteSet } from 'svelte/reactivity';
import Badge from '#lib/components/Badge.svelte';
import TimeAgo from '#lib/components/TimeAgo.svelte';
import { ITEM_STATUS } from '#lib/format.ts';
import type { TreeNode } from '#lib/server/status/tree-view.ts';
let { nodes }: { nodes: TreeNode[] } = $props();
const collapsed = new SvelteSet<string>();
let attentionOnly = $state(false);
interface Row {
node: TreeNode;
depth: number;
}
const needsAttention = (node: TreeNode): boolean =>
node.status !== 'synced' || node.children.some(needsAttention);
const rows = $derived.by(() => {
const result: Row[] = [];
const walk = (list: TreeNode[], depth: number) => {
for (const node of list) {
if (attentionOnly && !needsAttention(node)) continue;
result.push({ node, depth });
if (node.isFolder && !collapsed.has(node.sourceId)) walk(node.children, depth + 1);
}
};
walk(nodes, 0);
return result;
});
function toggle(id: string) {
if (collapsed.has(id)) collapsed.delete(id);
else collapsed.add(id);
}
function statusOf(node: TreeNode) {
if (node.waiting) return { label: 'Waiting on folder', tone: 'info' as const };
return ITEM_STATUS[node.status];
}
</script>
<div class="toolbar">
<label class="check small">
<input type="checkbox" bind:checked={attentionOnly} />
Only show files that need attention
</label>
</div>
{#if rows.length === 0}
<p class="empty muted">
{attentionOnly
? 'Everything is synced.'
: 'No files yet. They appear here after the first sync.'}
</p>
{:else}
<div class="table-wrap">
<table class="register">
<thead>
<tr>
<th>Name</th>
<th>Status</th>
<th>Changed in SharePoint</th>
<th>Last synced</th>
</tr>
</thead>
<tbody>
{#each rows as { node, depth } (node.sourceId)}
{@const status = statusOf(node)}
<tr class:folder={node.isFolder}>
<td class="name" style:--depth={depth}>
{#if node.isFolder}
<button
type="button"
class="twisty"
aria-expanded={!collapsed.has(node.sourceId)}
aria-label="{collapsed.has(node.sourceId) ? 'Expand' : 'Collapse'} {node.name}"
onclick={() => toggle(node.sourceId)}
>
<svg viewBox="0 0 16 16" aria-hidden="true"><path d="M6 4l4 4-4 4" /></svg>
</button>
<svg class="icon" viewBox="0 0 16 16" aria-hidden="true">
<path d="M1.5 3.5h5l1.5 1.5h6.5v8h-13z" />
</svg>
{:else}
<span class="twisty-spacer"></span>
<svg class="icon" viewBox="0 0 16 16" aria-hidden="true">
<path d="M3.5 1.5h6l3 3v10h-9z M9.5 1.5v3h3" />
</svg>
{/if}
<span title={node.error ?? undefined}>{node.name}</span>
{#if node.problems > 0}
<span class="problems">{node.problems} failed inside</span>
{/if}
</td>
<td><Badge {...status} /></td>
<td class="small"><TimeAgo date={node.isFolder ? null : node.modifiedAt} empty="" /></td
>
<td class="small"><TimeAgo date={node.syncedAt} empty="Not yet" /></td>
</tr>
{/each}
</tbody>
</table>
</div>
{/if}
<style>
.toolbar {
display: flex;
justify-content: flex-end;
}
.empty {
padding: 1.5rem;
border: 1px dashed var(--rule);
text-align: center;
}
.name {
display: flex;
align-items: center;
gap: 0.35rem;
padding-left: calc(0.5rem + var(--depth) * 1.25rem);
min-width: 18rem;
}
.folder .name {
font-weight: 600;
}
.twisty,
.twisty-spacer {
flex: none;
width: 1.25rem;
height: 1.25rem;
}
.twisty {
display: grid;
place-items: center;
padding: 0;
border: 0;
border-radius: var(--radius);
background: none;
color: var(--pencil);
cursor: pointer;
}
.twisty svg {
width: 0.85rem;
height: 0.85rem;
fill: none;
stroke: currentColor;
stroke-width: 1.75;
transition: transform 120ms ease;
}
.twisty[aria-expanded='true'] svg {
transform: rotate(90deg);
}
.icon {
flex: none;
width: 1rem;
height: 1rem;
fill: none;
stroke: var(--pencil);
stroke-width: 1.1;
}
.problems {
margin-left: 0.25rem;
font-size: var(--step--1);
font-weight: 500;
color: var(--danger);
}
</style>

View File

@@ -0,0 +1,62 @@
<script lang="ts">
/** The shared add/edit project form fields. */
let {
values,
rootsLocked = false,
current
}: {
values: { name?: string; sourceInput?: string; targetInput?: string };
/** After the first sync the roots can't change until the project is reset. */
rootsLocked?: boolean;
/** Current root paths, shown when editing. */
current?: { source: string; target: string };
} = $props();
</script>
<div class="field">
<label for="name">Project name</label>
<input id="name" name="name" type="text" required maxlength="100" value={values.name ?? ''} />
</div>
{#if rootsLocked && current}
<div class="notice">
<p><strong>From SharePoint:</strong> {current.source}</p>
<p><strong>To ACC:</strong> {current.target}</p>
<p class="small muted">
These folders are locked because the project has already synced. Reset the project to change
them.
</p>
</div>
{:else}
<div class="field">
<label for="sourceInput">SharePoint folder</label>
<input
id="sourceInput"
name="sourceInput"
type="text"
required={!current}
value={values.sourceInput ?? ''}
placeholder={current?.source}
/>
<span class="hint">
Open the folder in SharePoint and paste the address from your browser. Everything inside it is
synced.
{#if current}Leave blank to keep the current folder.{/if}
</span>
</div>
<div class="field">
<label for="targetInput">ACC folder</label>
<input
id="targetInput"
name="targetInput"
type="text"
required={!current}
value={values.targetInput ?? ''}
placeholder={current?.target}
/>
<span class="hint">
Open the destination folder in ACC Docs and paste the address from your browser.
{#if current}Leave blank to keep the current folder.{/if}
</span>
</div>
{/if}

View File

@@ -0,0 +1,81 @@
<script lang="ts">
import { enhance } from '$app/forms';
import type { RunRequestResult } from '#lib/server/sync/coordinator.ts';
let {
running,
cooldownSeconds,
unavailable = null
}: {
running: boolean;
/** Matches the server's per-project cooldown, so the button disables in step with it. */
cooldownSeconds: number;
/** Why a run can't start (disabled or paused project), if it can't. */
unavailable?: string | null;
} = $props();
let cooldownUntil = $state(0);
let tick = $state(Date.now());
let message = $state<string | null>(null);
const remaining = $derived(Math.max(0, Math.ceil((cooldownUntil - tick) / 1000)));
$effect(() => {
const until = cooldownUntil;
if (until <= Date.now()) return;
const timer = setInterval(() => (tick = Date.now()), 250);
return () => clearInterval(timer);
});
function startCooldown(seconds: number) {
tick = Date.now();
cooldownUntil = tick + seconds * 1000;
}
const MESSAGES: Record<RunRequestResult['status'], (r: RunRequestResult) => string> = {
started: () => 'Sync started.',
'already-running': () => 'A sync is already running for this project.',
cooldown: () => 'Run now was used moments ago. It will be available again shortly.',
unavailable: (r) => (r.status === 'unavailable' ? r.reason : '')
};
</script>
<form
method="POST"
action="?/run"
class="run-now"
use:enhance={() =>
async ({ result, update }) => {
if (result.type === 'success' && result.data?.run) {
const run = result.data.run as RunRequestResult;
message = MESSAGES[run.status](run);
if (run.status === 'started') startCooldown(cooldownSeconds);
if (run.status === 'cooldown') startCooldown(run.retryAfterSeconds);
}
await update({ reset: false });
}}
>
<button class="button primary" disabled={running || remaining > 0 || !!unavailable}>
{#if running}
Syncing…
{:else if remaining > 0}
Run now ({remaining}s)
{:else}
Run now
{/if}
</button>
<p class="small muted" role="status">{unavailable ?? message ?? ''}</p>
</form>
<style>
.run-now {
display: grid;
justify-items: end;
gap: 0.3rem;
}
.run-now p {
max-width: 22rem;
text-align: right;
min-height: 1.2em;
}
</style>

View File

@@ -0,0 +1,14 @@
<script lang="ts">
import { formatDateTime, timeAgo } from '#lib/format.ts';
import { now } from '#lib/now.svelte.ts';
let { date, empty = 'Never' }: { date: Date | null; empty?: string } = $props();
</script>
{#if date}
<time datetime={date.toISOString()} title={formatDateTime(date)}
>{timeAgo(date, now.current)}</time
>
{:else}
<span class="muted">{empty}</span>
{/if}

80
src/lib/format.ts Normal file
View File

@@ -0,0 +1,80 @@
import type { ProjectHealth } from '#lib/server/status/status-service.ts';
import type {
EventAction,
ItemStatus,
RunCounts,
RunOutcome
} from '#lib/server/sync/core/model.ts';
/** Visual tone for a badge; maps to a colour token in app.css. */
export type Tone = 'ok' | 'info' | 'warn' | 'danger' | 'muted';
export const HEALTH: Record<ProjectHealth, { label: string; tone: Tone }> = {
healthy: { label: 'Healthy', tone: 'ok' },
running: { label: 'Syncing…', tone: 'info' },
pending: { label: 'Changes pending', tone: 'info' },
issues: { label: 'Needs attention', tone: 'danger' },
paused: { label: 'Paused', tone: 'warn' },
disabled: { label: 'Disabled', tone: 'muted' },
'never-run': { label: 'Not synced yet', tone: 'muted' }
};
export const ITEM_STATUS: Record<ItemStatus, { label: string; tone: Tone }> = {
synced: { label: 'Synced', tone: 'ok' },
pending: { label: 'Pending', tone: 'info' },
failed: { label: 'Failed', tone: 'danger' },
deleted: { label: 'Deleted', tone: 'muted' }
};
export const OUTCOME: Record<RunOutcome, { label: string; tone: Tone }> = {
success: { label: 'Success', tone: 'ok' },
partial: { label: 'Partial', tone: 'warn' },
failed: { label: 'Failed', tone: 'danger' }
};
export const EVENT: Record<EventAction, { label: string; tone: Tone }> = {
created: { label: 'Created', tone: 'ok' },
updated: { label: 'New version', tone: 'ok' },
renamed: { label: 'Renamed', tone: 'info' },
moved: { label: 'Moved', tone: 'info' },
deleted: { label: 'Deleted', tone: 'muted' },
restored: { label: 'Restored', tone: 'ok' },
failed: { label: 'Failed', tone: 'danger' }
};
/** "3 created, 1 updated" — only non-zero counts, or "No changes". */
export function describeCounts(counts: RunCounts): string {
const parts = (Object.keys(EVENT) as EventAction[])
.filter((action) => counts[action] > 0)
.map((action) => `${counts[action]} ${EVENT[action].label.toLowerCase()}`);
return parts.length > 0 ? parts.join(', ') : 'No changes';
}
const relative = new Intl.RelativeTimeFormat(undefined, { numeric: 'auto' });
const UNITS: Array<[Intl.RelativeTimeFormatUnit, number]> = [
['day', 86_400_000],
['hour', 3_600_000],
['minute', 60_000],
['second', 1000]
];
/** "3 minutes ago", "just now". */
export function timeAgo(date: Date | null, now: Date = new Date()): string {
if (!date) return 'Never';
const diff = date.getTime() - now.getTime();
if (Math.abs(diff) < 10_000) return 'just now';
const [unit, ms] = UNITS.find(([, size]) => Math.abs(diff) >= size) ?? UNITS.at(-1)!;
return relative.format(Math.round(diff / ms), unit);
}
const dateTime = new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' });
export function formatDateTime(date: Date | null): string {
return date ? dateTime.format(date) : '—';
}
export function formatDuration(start: Date, end: Date | null): string {
if (!end) return 'Running';
const seconds = Math.max(0, Math.round((end.getTime() - start.getTime()) / 1000));
return seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m ${seconds % 60}s`;
}

19
src/lib/now.svelte.ts Normal file
View File

@@ -0,0 +1,19 @@
import { browser } from '$app/env';
/**
* A shared "now" for relative times. In the browser it is reactive and ticks
* every few seconds; on the server it is simply the current time.
*/
class Now {
#tick = $state(new Date());
constructor(intervalMs: number) {
if (browser) setInterval(() => (this.#tick = new Date()), intervalMs);
}
get current(): Date {
return browser ? this.#tick : new Date();
}
}
export const now = new Now(5000);

View File

@@ -132,7 +132,11 @@ export class FakeDrive implements ChangeSource {
/** The node followed by its ancestors up to the drive root. */
private *lineage(node: DriveNode): Generator<DriveNode> {
for (let n: DriveNode | undefined = node; n; n = n.parentId ? this.nodes.get(n.parentId) : undefined) {
for (
let n: DriveNode | undefined = node;
n;
n = n.parentId ? this.nodes.get(n.parentId) : undefined
) {
yield n;
}
}

View File

@@ -0,0 +1,42 @@
import { describe, expect, it } from 'vitest';
import { REJECTED_FILE, SimulatedBackend } from './simulated-backend.ts';
describe('SimulatedBackend', () => {
it('resolves the last segment of a pasted URL and reuses the folder', async () => {
const backend = new SimulatedBackend();
const url = 'https://contoso.sharepoint.com/sites/A/Shared%20Documents/Tower%20B?web=1';
const first = await backend.resolveSourceRoot(url);
const second = await backend.resolveSourceRoot('Tower B');
expect(first.displayPath).toBe('Simulated SharePoint / Tower B');
expect(second.root).toEqual(first.root);
});
it('seeds new SharePoint folders with sample files', async () => {
const backend = new SimulatedBackend();
const { root } = await backend.resolveSourceRoot('Demo');
const names = backend.drive.filesUnder(root.rootItemId).map((id) => backend.drive.nameOf(id));
expect(names).toContain('A-101 Floor Plan.pdf');
expect(names).toContain(REJECTED_FILE);
});
it('rejects a blank location', async () => {
await expect(new SimulatedBackend().resolveTargetRoot(' / ')).rejects.toThrow(
'Enter a folder path or URL.'
);
});
it('simulates activity as new change-feed entries', async () => {
const backend = new SimulatedBackend(() => 0.5);
const { root } = await backend.resolveSourceRoot('Demo');
const { cursor } = await backend.drive.getChanges(root, null);
backend.simulateActivity();
const { changes } = await backend.drive.getChanges(root, cursor);
expect(changes).toHaveLength(1);
});
});

View File

@@ -65,7 +65,9 @@ export class SimulatedBackend implements SourceRootResolver, TargetRootResolver
const roots = [...this.sourceFolders.values()];
if (roots.length === 0) return;
const root = this.pick(roots);
const files = this.drive.filesUnder(root).filter((id) => this.drive.nameOf(id) !== REJECTED_FILE);
const files = this.drive
.filesUnder(root)
.filter((id) => this.drive.nameOf(id) !== REJECTED_FILE);
const roll = this.random();
if (files.length === 0 || roll < 0.25) {

View File

@@ -3,7 +3,7 @@ import { drizzle, type BetterSQLite3Database } from 'drizzle-orm/better-sqlite3'
import { migrate } from 'drizzle-orm/better-sqlite3/migrator';
import * as schema from './schema.ts';
export type Db = BetterSQLite3Database<typeof schema>;
export type Db = BetterSQLite3Database<typeof schema> & { $client: Database.Database };
/** Opens (or creates) the database and brings its schema up to date. */
export function openDatabase(path: string, migrationsFolder = 'drizzle'): Db {

View File

@@ -73,11 +73,7 @@ export class SqliteProjectRepository implements ProjectRepository {
private set(id: string, values: Partial<ProjectRow>): void {
const defined = Object.entries(values).filter(([, value]) => value !== undefined);
if (defined.length === 0) return;
this.db
.update(projects)
.set(Object.fromEntries(defined))
.where(eq(projects.id, id))
.run();
this.db.update(projects).set(Object.fromEntries(defined)).where(eq(projects.id, id)).run();
}
}

View File

@@ -25,4 +25,23 @@ describe('SqliteRunRepository', () => {
expect(run).toMatchObject({ runId, outcome: null, finishedAt: null });
});
it('fails runs left unfinished, leaving finished ones alone', async () => {
const h = await createHarness();
const finished = await h.sync();
const unfinished = await h.runs.start(h.project.id, 'schedule', new Date());
const at = new Date();
expect(await h.runs.failUnfinished(at, 'Interrupted')).toBe(1);
const byId = new Map(
(await h.runs.listSince(h.project.id, new Date(0))).map((r) => [r.runId, r])
);
expect(byId.get(unfinished)).toMatchObject({
outcome: 'failed',
error: 'Interrupted',
finishedAt: at
});
expect(byId.get(finished.runId)).toMatchObject({ outcome: 'success', error: null });
});
});

View File

@@ -1,4 +1,4 @@
import { and, asc, desc, eq, gte, lt } from 'drizzle-orm';
import { and, asc, desc, eq, gte, isNull, lt } from 'drizzle-orm';
import type {
RunCounts,
RunEvent,
@@ -71,6 +71,14 @@ export class SqliteRunRepository implements RunRepository {
async pruneBefore(cutoff: Date): Promise<number> {
return this.db.delete(runs).where(lt(runs.startedAt, cutoff)).run().changes;
}
async failUnfinished(at: Date, error: string): Promise<number> {
return this.db
.update(runs)
.set({ finishedAt: at, outcome: 'failed', error })
.where(isNull(runs.outcome))
.run().changes;
}
}
function toRunRecord(row: RunRow): RunRecord {

24
src/lib/server/app.ts Normal file
View File

@@ -0,0 +1,24 @@
import { createServices, type AppConfig, type AppServices } from './container.ts';
// Kept on globalThis so a dev-server reload of this module can still find and
// stop the previous instance instead of leaking its timers and DB handle.
const holder = globalThis as typeof globalThis & { __syncApp?: AppServices };
export async function startApp(config: AppConfig): Promise<void> {
await stopApp();
const services = createServices(config);
holder.__syncApp = services;
await services.start();
}
export async function stopApp(): Promise<void> {
const current = holder.__syncApp;
holder.__syncApp = undefined;
await current?.stop();
}
/** The running app's services. Only valid after `startApp` (the server `init` hook). */
export function services(): AppServices {
if (!holder.__syncApp) throw new Error('The sync app has not been started.');
return holder.__syncApp;
}

View File

@@ -4,10 +4,10 @@ import type { Clock } from '#lib/server/sync/core/ports.ts';
export const SESSION_COOKIE = 'admin_session';
export interface AdminAuthConfig {
username: string | undefined;
password: string | undefined;
username?: string;
password?: string;
/** Signs session tokens. If omitted, a random one is used and sessions end on restart. */
sessionSecret: string | undefined;
sessionSecret?: string;
sessionTtlMs: number;
clock: Clock;
}
@@ -24,6 +24,10 @@ export class AdminAuth {
return Boolean(this.config.username && this.config.password);
}
get sessionTtlSeconds(): number {
return Math.floor(this.config.sessionTtlMs / 1000);
}
checkCredentials(username: string, password: string): boolean {
if (!this.enabled) return false;
// Evaluate both so timing doesn't reveal which one was wrong.

View File

@@ -0,0 +1,23 @@
import type { Cookies } from '@sveltejs/kit';
import { SESSION_COOKIE, type AdminAuth } from './admin-auth.ts';
export function startSession(cookies: Cookies, url: URL, auth: AdminAuth): void {
cookies.set(SESSION_COOKIE, auth.issueToken(), {
path: '/',
httpOnly: true,
sameSite: 'strict',
// Behind the VPN the app may be served over plain HTTP.
secure: url.protocol === 'https:',
maxAge: auth.sessionTtlSeconds
});
}
export function endSession(cookies: Cookies): void {
cookies.delete(SESSION_COOKIE, { path: '/' });
}
/** The `next` query parameter if it's a same-site path, otherwise the admin home. */
export function safeNext(url: URL): string {
const next = url.searchParams.get('next');
return next && next.startsWith('/') && !next.startsWith('//') ? next : '/admin';
}

177
src/lib/server/container.ts Normal file
View File

@@ -0,0 +1,177 @@
import { NotConnectedBackend } from '#lib/server/adapters/not-connected.ts';
import { SimulatedBackend } from '#lib/server/adapters/simulated/simulated-backend.ts';
import { openDatabase } from '#lib/server/adapters/sqlite/database.ts';
import { SqliteItemRepository } from '#lib/server/adapters/sqlite/item-repository.ts';
import { SqliteProjectRepository } from '#lib/server/adapters/sqlite/project-repository.ts';
import { SqliteRunRepository } from '#lib/server/adapters/sqlite/run-repository.ts';
import { AdminAuth } from '#lib/server/auth/admin-auth.ts';
import { consoleLogger } from '#lib/server/logger.ts';
import { StatusService } from '#lib/server/status/status-service.ts';
import { SyncCoordinator } from '#lib/server/sync/coordinator.ts';
import { SyncEngine } from '#lib/server/sync/core/engine.ts';
import { PatternIgnorePolicy } from '#lib/server/sync/core/ignore.ts';
import type {
ChangeSource,
DocumentTarget,
Logger,
SourceRootResolver,
TargetRootResolver
} from '#lib/server/sync/core/ports.ts';
import { Reconciler } from '#lib/server/sync/core/reconciler.ts';
import { ProjectService } from '#lib/server/sync/project-service.ts';
import { IntervalScheduler } from '#lib/server/sync/scheduler.ts';
export interface AppConfig {
backend: 'live' | 'simulated';
databasePath: string;
pollIntervalSeconds: number;
manualRunCooldownSeconds: number;
maxAttempts: number;
historyRetentionDays: number;
admin: { username?: string; password?: string; sessionSecret?: string };
}
export interface AppServices {
coordinator: SyncCoordinator;
status: StatusService;
projectService: ProjectService;
auth: AdminAuth;
config: AppConfig;
start(): Promise<void>;
stop(): Promise<void>;
}
interface Connection {
source: ChangeSource;
target: DocumentTarget;
sourceResolver: SourceRootResolver;
targetResolver: TargetRootResolver;
}
const DAY_MS = 86_400_000;
const PRUNE_INTERVAL_MS = 6 * 3_600_000;
const SIMULATED_ACTIVITY_MS = 45_000;
const ADMIN_SESSION_TTL_MS = 12 * 3_600_000;
const INTERRUPTED_RUN =
'The server stopped before this sync finished. Anything left over is picked up by the next sync.';
/** The composition root: the only place concrete adapters are chosen and wired. */
export function createServices(config: AppConfig, logger: Logger = consoleLogger): AppServices {
const clock = () => new Date();
const simulated = config.backend === 'simulated' ? new SimulatedBackend() : null;
const connection = simulated ? simulatedConnection(simulated) : notConnected();
// Simulated SharePoint/ACC live in memory, so their sync state must too.
const db = openDatabase(simulated ? ':memory:' : config.databasePath);
const projects = new SqliteProjectRepository(db, clock);
const items = new SqliteItemRepository(db);
const runs = new SqliteRunRepository(db);
const { maxAttempts } = config;
const reconciler = new Reconciler({ ...connection, items, runs, clock, maxAttempts });
const engine = new SyncEngine({
source: connection.source,
projects,
items,
runs,
reconciler,
ignore: new PatternIgnorePolicy(),
clock,
logger,
maxAttempts
});
const coordinator = new SyncCoordinator({
runner: engine,
projects,
clock,
logger,
manualCooldownMs: config.manualRunCooldownSeconds * 1000
});
const projectService = new ProjectService({
projects,
items,
sourceResolver: connection.sourceResolver,
targetResolver: connection.targetResolver,
activity: coordinator,
maxAttempts
});
const status = new StatusService({
projects,
items,
runs,
activity: coordinator,
clock,
retentionDays: config.historyRetentionDays
});
const auth = new AdminAuth({
...config.admin,
sessionTtlMs: ADMIN_SESSION_TTL_MS,
clock
});
const scheduler = new IntervalScheduler(logger);
return {
coordinator,
status,
projectService,
auth,
config,
async start() {
const interrupted = await runs.failUnfinished(clock(), INTERRUPTED_RUN);
if (interrupted > 0) logger.warn('Closed syncs interrupted by a restart', { interrupted });
if (simulated && (await projects.list()).length === 0) {
await projectService.create({
name: 'Demo project',
sourceInput: 'Demo Project',
targetInput: 'Demo Project'
});
}
scheduler.every(
'sync',
config.pollIntervalSeconds * 1000,
() => coordinator.runScheduledPass(),
{
immediate: true
}
);
scheduler.every(
'prune-history',
PRUNE_INTERVAL_MS,
() => runs.pruneBefore(new Date(clock().getTime() - config.historyRetentionDays * DAY_MS)),
{ immediate: true }
);
if (simulated) {
scheduler.every('simulated-activity', SIMULATED_ACTIVITY_MS, async () =>
simulated.simulateActivity()
);
}
logger.info('Sync server started', {
backend: config.backend,
pollIntervalSeconds: config.pollIntervalSeconds,
adminEnabled: auth.enabled
});
},
async stop() {
scheduler.stop();
await coordinator.drain();
db.$client.close();
}
};
}
function simulatedConnection(backend: SimulatedBackend): Connection {
return {
source: backend.drive,
target: backend.acc,
sourceResolver: backend,
targetResolver: backend
};
}
function notConnected(): Connection {
const backend = new NotConnectedBackend();
return { source: backend, target: backend, sourceResolver: backend, targetResolver: backend };
}

27
src/lib/server/forms.ts Normal file
View File

@@ -0,0 +1,27 @@
import { fail, type ActionFailure } from '@sveltejs/kit';
import { InvalidRequestError } from '#lib/server/sync/core/errors.ts';
/**
* Runs a form action's work, turning user-facing errors into a 400 with
* `{ error, ...echo }` so the form can show the message and keep what was
* typed. Anything else still throws.
*/
export async function attempt<T, E extends object = object>(
work: () => Promise<T>,
echo?: E
): Promise<T | ActionFailure<{ error: string } & E>> {
try {
return await work();
} catch (error) {
if (error instanceof InvalidRequestError) {
return fail(400, { error: error.message, ...(echo as E) });
}
throw error;
}
}
/** A form field as a string (empty if missing or a file). */
export function field(data: FormData, name: string): string {
const value = data.get(name);
return typeof value === 'string' ? value : '';
}

View File

@@ -0,0 +1,70 @@
import { describe, expect, it } from 'vitest';
import { createHarness } from '#lib/server/sync/testing/harness.ts';
import type { TreeNode } from './tree-view.ts';
const outline = (nodes: TreeNode[], depth = 0): string[] =>
nodes.flatMap((node) => [
`${' '.repeat(depth)}${node.name}${node.isFolder ? '/' : ''} [${node.status}${node.problems ? `, ${node.problems} problem` : ''}]`,
...outline(node.children, depth + 1)
]);
describe('StatusService', () => {
it('reports a never-run project', async () => {
const h = await createHarness();
const [summary] = await h.status.listProjects();
expect(summary).toMatchObject({ health: 'never-run', issueCount: 0, lastRun: null });
});
it('builds a sorted tree with folder problem counts and lists item issues', async () => {
const h = await createHarness({ maxAttempts: 1 });
const docs = h.drive.addFolder(h.rootId, 'Docs');
h.drive.addFile(docs, 'b.pdf');
h.drive.addFile(docs, 'a 10.pdf');
h.drive.addFile(docs, 'a 9.pdf');
h.drive.addFile(h.rootId, 'readme.txt');
h.drive.addFile(h.rootId, '~$readme.txt');
h.acc.failOn('b.pdf', new Error('Rejected'));
await h.sync();
const detail = (await h.status.getProject(h.project.id))!;
expect(outline(detail.tree)).toEqual([
'Docs/ [synced, 1 problem]',
' a 9.pdf [synced]',
' a 10.pdf [synced]',
' b.pdf [failed]',
'readme.txt [synced]'
]);
expect(detail).toMatchObject({ health: 'issues', issueCount: 1 });
expect(detail.issues).toEqual([
expect.objectContaining({ path: 'Docs/b.pdf', message: 'Rejected', attempts: 1 })
]);
});
it('surfaces a paused project as a project-level issue', async () => {
const h = await createHarness();
await h.projects.pause(h.project.id, 'Root deleted');
const detail = (await h.status.getProject(h.project.id))!;
expect(detail.health).toBe('paused');
expect(detail.issues).toEqual([
expect.objectContaining({ sourceId: null, message: 'Paused: Root deleted' })
]);
});
it('reports running projects as running', async () => {
const h = await createHarness();
h.running.add(h.project.id);
expect((await h.status.listProjects())[0]).toMatchObject({ running: true, health: 'running' });
});
it('only shows events for runs of the requested project', async () => {
const h = await createHarness();
h.drive.addFile(h.rootId, 'a.txt');
const run = await h.sync();
expect(await h.status.runEvents(h.project.id, run.runId)).toHaveLength(1);
expect(await h.status.runEvents('other-project', run.runId)).toEqual([]);
});
});

View File

@@ -1,9 +1,4 @@
import type {
Project,
RunEvent,
RunRecord,
StatusCounts
} from '#lib/server/sync/core/model.ts';
import type { Project, RunEvent, RunRecord, StatusCounts } from '#lib/server/sync/core/model.ts';
import type {
Clock,
ItemRepository,
@@ -14,13 +9,7 @@ import { ItemTree } from '#lib/server/sync/core/tree.ts';
import { buildTree, type TreeNode } from './tree-view.ts';
export type ProjectHealth =
| 'disabled'
| 'paused'
| 'running'
| 'issues'
| 'pending'
| 'never-run'
| 'healthy';
'disabled' | 'paused' | 'running' | 'issues' | 'pending' | 'never-run' | 'healthy';
export interface ProjectSummary {
project: Project;
@@ -63,6 +52,11 @@ export class StatusService {
return Promise.all(projects.map((project) => this.summarize(project)));
}
async getSummary(id: string): Promise<ProjectSummary | null> {
const project = await this.deps.projects.get(id);
return project ? this.summarize(project) : null;
}
async getProject(id: string): Promise<ProjectDetail | null> {
const project = await this.deps.projects.get(id);
if (!project) return null;

View File

@@ -108,6 +108,8 @@ export interface RunRepository {
listEvents(runId: string): Promise<RunEvent[]>;
/** Delete runs (and their events) started before `cutoff`; returns how many runs were removed. */
pruneBefore(cutoff: Date): Promise<number>;
/** Close every run left unfinished (e.g. by a restart) as failed; returns how many were closed. */
failUnfinished(at: Date, error: string): Promise<number>;
}
export type Clock = () => Date;

View File

@@ -0,0 +1,96 @@
import { describe, expect, it } from 'vitest';
import { createHarness } from './testing/harness.ts';
import { BUSY, ROOTS_LOCKED } from './project-service.ts';
describe('ProjectService', () => {
it('creates a project from pasted locations', async () => {
const h = await createHarness();
const project = await h.projectService.create({
name: ' Tower B ',
sourceInput: 'Tower B',
targetInput: 'Tower B Docs'
});
expect(project).toMatchObject({
name: 'Tower B',
enabled: true,
sourceDisplayPath: 'SharePoint/Tower B',
targetDisplayPath: 'ACC/Tower B Docs'
});
});
it('rejects blank names and locations', async () => {
const h = await createHarness();
await expect(
h.projectService.create({ name: ' ', sourceInput: 'a', targetInput: 'b' })
).rejects.toThrow('Name is required.');
await expect(
h.projectService.create({ name: 'x', sourceInput: '', targetInput: 'b' })
).rejects.toThrow('SharePoint folder is required.');
});
it('lets roots change before the first sync but locks them afterwards', async () => {
const h = await createHarness();
const edit = { name: 'Project X', enabled: true, sourceInput: 'Elsewhere' };
await h.projectService.update(h.project.id, edit);
expect((await h.projects.get(h.project.id))!.sourceDisplayPath).toBe('SharePoint/Elsewhere');
await h.engine.runProject(h.project.id, 'manual');
await expect(h.projectService.update(h.project.id, edit)).rejects.toThrow(ROOTS_LOCKED);
await h.projectService.update(h.project.id, { name: 'Renamed', enabled: false });
expect(await h.projects.get(h.project.id)).toMatchObject({ name: 'Renamed', enabled: false });
});
it('unlocks roots and forgets sync state on reset', async () => {
const h = await createHarness();
h.drive.addFile(h.rootId, 'a.txt');
await h.sync();
await h.projectService.reset(h.project.id);
expect(await h.projects.get(h.project.id)).toMatchObject({
firstSyncedAt: null,
deltaCursor: null
});
expect(await h.items.listByProject(h.project.id)).toEqual([]);
});
it('refuses to reset, delete or retry while a run is in progress', async () => {
const h = await createHarness();
h.running.add(h.project.id);
await expect(h.projectService.reset(h.project.id)).rejects.toThrow(BUSY);
await expect(h.projectService.delete(h.project.id)).rejects.toThrow(BUSY);
await expect(h.projectService.retryItem(h.project.id, 'x')).rejects.toThrow(BUSY);
});
it('deletes a project with its items and history', async () => {
const h = await createHarness();
h.drive.addFile(h.rootId, 'a.txt');
const run = await h.sync();
await h.projectService.delete(h.project.id);
expect(await h.projects.get(h.project.id)).toBeNull();
expect(await h.items.listByProject(h.project.id)).toEqual([]);
expect(await h.runs.listEvents(run.runId)).toEqual([]);
});
it('gives a failed item fresh attempts on retry', async () => {
const h = await createHarness({ maxAttempts: 1 });
h.drive.addFile(h.rootId, 'bad.dwg');
h.acc.failOn('bad.dwg', new Error('nope'), 1);
await h.sync();
const failed = await h.itemNamed('bad.dwg');
expect(failed.status).toBe('failed');
await h.projectService.retryItem(h.project.id, failed.sourceId);
expect(await h.itemNamed('bad.dwg')).toMatchObject({ status: 'pending', attemptCount: 0 });
await h.sync();
expect((await h.itemNamed('bad.dwg')).status).toBe('synced');
});
});

View File

@@ -4,8 +4,14 @@ import { SqliteProjectRepository } from '#lib/server/adapters/sqlite/project-rep
import { SqliteRunRepository } from '#lib/server/adapters/sqlite/run-repository.ts';
import { SyncEngine } from '#lib/server/sync/core/engine.ts';
import { PatternIgnorePolicy } from '#lib/server/sync/core/ignore.ts';
import type { Logger } from '#lib/server/sync/core/ports.ts';
import type {
Logger,
SourceRootResolver,
TargetRootResolver
} from '#lib/server/sync/core/ports.ts';
import { Reconciler } from '#lib/server/sync/core/reconciler.ts';
import { ProjectService } from '#lib/server/sync/project-service.ts';
import { StatusService } from '#lib/server/status/status-service.ts';
import { FakeAcc } from '#lib/server/adapters/simulated/fake-acc.ts';
import { FakeDrive } from '#lib/server/adapters/simulated/fake-drive.ts';
@@ -53,6 +59,40 @@ export async function createHarness({ maxAttempts = 3 } = {}) {
targetDisplayPath: 'Project X/Project Files'
});
/** Stands in for the coordinator: tests add project IDs to mark them as running. */
const running = new Set<string>();
const activity = { isRunning: (id: string) => running.has(id) };
/** Resolves any input to a new folder of that name on each side. */
const resolver: SourceRootResolver & TargetRootResolver = {
resolveSourceRoot: async (input) => ({
root: {
siteId: 'site',
driveId: 'drive',
rootItemId: drive.addFolder(drive.driveRootId, input)
},
displayPath: `SharePoint/${input}`
}),
resolveTargetRoot: async (input) => ({
root: {
hubId: 'hub',
projectId: 'acc-project',
rootFolderId: acc.addFolderByHand(acc.rootFolderId, input)
},
displayPath: `ACC/${input}`
})
};
const projectService = new ProjectService({
projects,
items,
sourceResolver: resolver,
targetResolver: resolver,
activity,
maxAttempts
});
const status = new StatusService({ projects, items, runs, activity, clock, retentionDays: 7 });
return {
db,
drive,
@@ -62,6 +102,9 @@ export async function createHarness({ maxAttempts = 3 } = {}) {
items,
runs,
engine,
projectService,
status,
running,
project,
sync: () => engine.runProject(project.id, 'schedule'),
itemNamed: async (name: string) =>

316
src/lib/styles/app.css Normal file
View File

@@ -0,0 +1,316 @@
/*
* Drafting-room palette: paper, graphite and rule lines, one marker blue for
* actions, and signal colours reserved for status.
*/
:root {
--paper: #fafaf7;
--sheet: #ffffff;
--graphite: #23272c;
--pencil: #5d6670;
--rule: #d3d7dc;
--rule-strong: #23272c;
--marker: #1d5ba6;
--marker-ink: #ffffff;
--ok: #1f7a4d;
--info: #1d5ba6;
--warn: #a86a12;
--danger: #bf3a30;
--muted: #6b737c;
--tint: 12%;
--font-ui: 'Barlow', system-ui, sans-serif;
--font-display: 'Barlow Semi Condensed', 'Barlow', system-ui, sans-serif;
--step--1: 0.8125rem;
--step-0: 0.9375rem;
--step-1: 1.125rem;
--step-2: 1.5rem;
--step-3: 2.25rem;
--radius: 3px;
--gutter: clamp(1rem, 3vw, 2rem);
color-scheme: light;
}
@media (prefers-color-scheme: dark) {
:root {
--paper: #181b1f;
--sheet: #202429;
--graphite: #e4e7ea;
--pencil: #a3abb4;
--rule: #363c43;
--rule-strong: #8b949e;
--marker: #7fb0ec;
--marker-ink: #10243c;
--ok: #5cc28d;
--info: #7fb0ec;
--warn: #e0a64a;
--danger: #f07c72;
--muted: #8b949e;
--tint: 18%;
color-scheme: dark;
}
}
*,
*::before,
*::after {
box-sizing: border-box;
}
html {
-webkit-text-size-adjust: 100%;
}
body {
margin: 0;
background: var(--paper);
color: var(--graphite);
font-family: var(--font-ui);
font-size: var(--step-0);
line-height: 1.5;
}
h1,
h2,
h3 {
font-family: var(--font-display);
font-weight: 600;
line-height: 1.15;
margin: 0;
}
h1 {
font-size: var(--step-3);
letter-spacing: -0.01em;
}
h2 {
font-size: var(--step-2);
}
h3 {
font-size: var(--step-1);
}
p {
margin: 0;
}
a {
color: var(--marker);
text-underline-offset: 0.2em;
}
:focus-visible {
outline: 2px solid var(--marker);
outline-offset: 2px;
}
.page {
max-width: 76rem;
margin: 0 auto;
padding: var(--gutter);
display: grid;
gap: 2rem;
}
.section {
display: grid;
gap: 0.75rem;
}
.section-head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 1rem;
flex-wrap: wrap;
}
.muted {
color: var(--pencil);
}
.small {
font-size: var(--step--1);
}
/* Buttons */
.button {
display: inline-flex;
align-items: center;
gap: 0.4rem;
min-height: 2.25rem;
padding: 0.35rem 0.9rem;
border: 1px solid var(--rule-strong);
border-radius: var(--radius);
background: var(--sheet);
color: var(--graphite);
font: 500 var(--step-0) / 1 var(--font-ui);
text-decoration: none;
cursor: pointer;
}
.button:hover {
background: color-mix(in srgb, var(--graphite) 6%, var(--sheet));
}
.button.primary {
background: var(--marker);
border-color: var(--marker);
color: var(--marker-ink);
}
.button.primary:hover {
background: color-mix(in srgb, var(--marker) 88%, black);
}
.button.danger {
color: var(--danger);
border-color: var(--danger);
}
.button.compact {
min-height: 1.75rem;
padding: 0.2rem 0.6rem;
font-size: var(--step--1);
}
.button:disabled {
opacity: 0.55;
cursor: not-allowed;
}
/* Status badges: a tinted chip with a solid dot, colour from --tone. */
.badge {
--tone: var(--muted);
display: inline-flex;
align-items: center;
gap: 0.4em;
padding: 0.1em 0.55em;
border-radius: 999px;
background: color-mix(in srgb, var(--tone) var(--tint), transparent);
color: var(--tone);
font-size: var(--step--1);
font-weight: 600;
white-space: nowrap;
}
.badge::before {
content: '';
width: 0.5em;
height: 0.5em;
border-radius: 50%;
background: currentColor;
}
.tone-ok {
--tone: var(--ok);
}
.tone-info {
--tone: var(--info);
}
.tone-warn {
--tone: var(--warn);
}
.tone-danger {
--tone: var(--danger);
}
.tone-muted {
--tone: var(--muted);
}
/* Register tables: the drawing-index look used for lists. */
.register {
width: 100%;
border-collapse: collapse;
background: var(--sheet);
border: 1px solid var(--rule);
}
.register th {
text-align: left;
font-weight: 600;
font-size: var(--step--1);
color: var(--pencil);
padding: 0.5rem 0.75rem;
border-bottom: 1px solid var(--rule-strong);
}
.register td {
padding: 0.55rem 0.75rem;
border-bottom: 1px solid var(--rule);
vertical-align: top;
}
.register tr:last-child td {
border-bottom: 0;
}
.table-wrap {
overflow-x: auto;
}
/* Forms */
.form {
display: grid;
gap: 1.1rem;
max-width: 40rem;
}
.field {
display: grid;
gap: 0.3rem;
}
.field label {
font-weight: 600;
}
.field input[type='text'],
.field input[type='password'],
.field input[type='url'] {
width: 100%;
padding: 0.5rem 0.65rem;
border: 1px solid var(--rule-strong);
border-radius: var(--radius);
background: var(--sheet);
color: var(--graphite);
font: inherit;
}
.field .hint {
font-size: var(--step--1);
color: var(--pencil);
}
.check {
display: flex;
align-items: center;
gap: 0.5rem;
}
.notice {
--tone: var(--info);
padding: 0.65rem 0.9rem;
border-left: 3px solid var(--tone);
background: color-mix(in srgb, var(--tone) var(--tint), var(--sheet));
}
.actions {
display: flex;
gap: 0.6rem;
flex-wrap: wrap;
align-items: center;
}
@media (prefers-reduced-motion: reduce) {
* {
animation: none !important;
transition: none !important;
}
}