20cfdf62f2
Reshapes the launcher integration around two ideas:
1. ONE global Prism PreLaunch/PostExit hook is enough for all
instances. Wire it once at Settings > Default > Custom commands:
python /opt/cloud-sync.pyz pull --pack-folder=$INST_MC_DIR
python /opt/cloud-sync.pyz push --pack-folder=$INST_MC_DIR
Instances WITHOUT .cloud-sync/sync.json are silent no-ops (rc=0,
no UI, no banner). The opt-in probe runs BEFORE the UI factory
so Prism's launch log stays clean for non-sync instances.
2. Per-instance opt-in via 'setup' / 'init' subcommands that mint a
fresh ULID-style instance_id + write sync.json (mode 644) and
token (mode 600). 'disable' removes sync.json; cloud data
untouched.
Restic URL gains an /<instance_id>/ subpath under the user's
namespace, so two Prism instances of the same Discord user no longer
share a snapshot timeline. --private-repos still gates on the first
path segment (the username); deeper segments are user-controlled,
so this works without server-side coordination. First-push-on-a-new-
instance probes via 'restic cat config' and 'init's the per-instance
repo if absent.
UI label resolution is runtime-only (NEVER stored in sync.json) so
the user renaming the Prism instance just propagates through on
next launch:
--instance-label > $INST_NAME > $INST_ID > instance_id[:8]
Schema bumps:
state.json schema: 1 -> 2, adds instance_id field. Schema-1 files
are treated as missing (existing test1 user re-pulls fresh).
sync.json schema: 1 (new file).
CLI rework:
pull / push no --url; load everything from sync.json
setup interactive: Qt login dialog for token; URL prompt
if --url omitted; falls back to stdin when headless
init non-interactive setup; for scripted callers
disable rm sync.json
Args dataclass: drops 'url', adds 'instance_label'. cli.parse() now
returns (cmd, Namespace); a separate args_from(ns) builds the Args
so each subcommand can pluck the bits it needs from the Namespace
without forcing a 'one Args fits all subcommands' shape.
73 tests green; pyz 75 KB.
Smoke-verified locally:
- pull/push on a folder without sync.json: silent rc=0, no banner
- init writes sync.json (644) + token (600) with correct contents
- disable removes sync.json, keeps token
- mint produces unique 26-char base32 instance_ids
- label resolution chain (flag > INST_NAME > INST_ID > prefix)
88 lines
2.6 KiB
Python
88 lines
2.6 KiB
Python
"""Per-instance sync state.
|
|
|
|
Tracks the snapshot id this pack was last synced to and when. Lives at
|
|
``<pack-folder>/.cloud-sync/state.json`` (mode 600).
|
|
|
|
Purpose: divergence detection. On ``pull``, if the remote latest id
|
|
differs from ``last_pulled_snapshot_id`` AND any in-scope local file
|
|
has mtime > ``last_pulled_at``, the local and remote diverged from a
|
|
common ancestor — surface the conflict dialog.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
from dataclasses import dataclass
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
|
|
|
|
SCHEMA_VERSION = 2
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class State:
|
|
instance_id: str
|
|
last_pulled_snapshot_id: str
|
|
last_pulled_at: datetime
|
|
host_tag: str = "instance-sync"
|
|
|
|
|
|
def state_path(pack_folder: Path) -> Path:
|
|
return pack_folder / ".cloud-sync" / "state.json"
|
|
|
|
|
|
def read(pack_folder: Path) -> State | None:
|
|
"""Return parsed state or None if file missing / unreadable / wrong schema."""
|
|
p = state_path(pack_folder)
|
|
if not p.exists():
|
|
return None
|
|
try:
|
|
data = json.loads(p.read_text(encoding="utf-8"))
|
|
except (OSError, json.JSONDecodeError):
|
|
return None
|
|
if data.get("schema") != SCHEMA_VERSION:
|
|
return None
|
|
try:
|
|
return State(
|
|
instance_id=data["instance_id"],
|
|
last_pulled_snapshot_id=data["last_pulled_snapshot_id"],
|
|
last_pulled_at=_parse_iso(data["last_pulled_at"]),
|
|
host_tag=data.get("host_tag", "instance-sync"),
|
|
)
|
|
except (KeyError, ValueError):
|
|
return None
|
|
|
|
|
|
def write(pack_folder: Path, state: State) -> None:
|
|
"""Persist state. Creates parent dir + sets mode 600."""
|
|
p = state_path(pack_folder)
|
|
p.parent.mkdir(parents=True, exist_ok=True)
|
|
payload = {
|
|
"schema": SCHEMA_VERSION,
|
|
"instance_id": state.instance_id,
|
|
"last_pulled_snapshot_id": state.last_pulled_snapshot_id,
|
|
"last_pulled_at": state.last_pulled_at.astimezone(timezone.utc)
|
|
.isoformat()
|
|
.replace("+00:00", "Z"),
|
|
"host_tag": state.host_tag,
|
|
}
|
|
p.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
|
|
p.chmod(0o600)
|
|
|
|
|
|
def clear(pack_folder: Path) -> None:
|
|
"""Remove state.json if present. Used when remote has zero snapshots."""
|
|
p = state_path(pack_folder)
|
|
p.unlink(missing_ok=True)
|
|
|
|
|
|
def _parse_iso(s: str) -> datetime:
|
|
"""Parse ISO-8601 with trailing Z or +HH:MM, return tz-aware UTC."""
|
|
if s.endswith("Z"):
|
|
s = s[:-1] + "+00:00"
|
|
dt = datetime.fromisoformat(s)
|
|
if dt.tzinfo is None:
|
|
dt = dt.replace(tzinfo=timezone.utc)
|
|
return dt.astimezone(timezone.utc)
|