File size: 2,452 Bytes
5c0175e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// /api/offcloud/sync — status and configuration for the continuous auto-sync.
//
//   GET                     -> config + live state + library counts
//   POST { ...config }      -> update the auto-sync config
//   POST ?now=1             -> run one delta sync immediately
//   POST ?now=1&full=1      -> run a full reconcile immediately
import { NextRequest, NextResponse } from "next/server";
import {
  getAutoSyncConfig,
  updateAutoSyncConfig,
  getSyncState,
  getLibraryCounts,
  startAutoSync,
  syncOnce,
  type AutoSyncConfig,
} from "@/lib/sync-engine";

export const dynamic = "force-dynamic";
export const runtime = "nodejs";

async function payload() {
  const [config, counts] = await Promise.all([getAutoSyncConfig(), getLibraryCounts()]);
  return { config, state: getSyncState(), counts };
}

export async function GET() {
  try {
    // Arm the loop if this process has not started it yet (e.g. the
    // instrumentation hook was skipped in a dev reload).
    await startAutoSync();
    return NextResponse.json(await payload());
  } catch (err) {
    const msg = err instanceof Error ? err.message : "Unknown error";
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}

export async function POST(req: NextRequest) {
  const url = new URL(req.url);
  const now = url.searchParams.get("now");
  const full = url.searchParams.get("full");

  try {
    if (now) {
      const result = await syncOnce({
        mode: full ? "full" : "delta",
        trigger: "manual",
      });
      return NextResponse.json({ ok: !result.error, result, ...(await payload()) });
    }

    const body = (await req.json().catch(() => ({}))) as Partial<AutoSyncConfig>;
    const patch: Partial<AutoSyncConfig> = {};
    if (typeof body.enabled === "boolean") patch.enabled = body.enabled;
    if (body.intervalSeconds !== undefined) patch.intervalSeconds = Number(body.intervalSeconds);
    if (typeof body.fullSyncOnBoot === "boolean") patch.fullSyncOnBoot = body.fullSyncOnBoot;
    if (body.pruneAfterHours !== undefined) patch.pruneAfterHours = Number(body.pruneAfterHours);

    const config = await updateAutoSyncConfig(patch);
    return NextResponse.json({ ok: true, config, state: getSyncState() });
  } catch (err) {
    const msg = err instanceof Error ? err.message : "Unknown error";
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}