feat: opt-in by sync.json + per-instance ULID + restic subpath
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)
This commit is contained in:
+80
-12
@@ -30,7 +30,7 @@ import urllib.parse
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from . import restic, scope as scopemod, state as statemod
|
||||
from . import config as cfgmod, restic, scope as scopemod, state as statemod
|
||||
from .cli import Args
|
||||
from .creds import read_credentials
|
||||
from .ui import HeadlessProgress, Progress
|
||||
@@ -39,11 +39,18 @@ from .ui import HeadlessProgress, Progress
|
||||
def pull(args: Args, progress: Progress | None = None) -> int:
|
||||
ui = progress or HeadlessProgress()
|
||||
|
||||
# First-run login. If the user declines, skip cloud sync without
|
||||
# blocking the launch (return 0 — non-fatal for Prism PreLaunch).
|
||||
# Opt-in gate: no sync.json → instance isn't sync-enabled, silent no-op.
|
||||
# This is the path the global Prism PreLaunch hook takes for instances
|
||||
# the player hasn't opted into sync.
|
||||
sync_cfg = cfgmod.read(args.pack_folder)
|
||||
if sync_cfg is None:
|
||||
return 0
|
||||
|
||||
# First-run login. If the user declines, skip without blocking the
|
||||
# launch (return 0 — non-fatal for Prism PreLaunch).
|
||||
if not args.token_file.exists():
|
||||
if not _prompt_login_and_save(args, ui):
|
||||
ui.set_status("Cloud sync skipped")
|
||||
ui.set_status("Sync skipped")
|
||||
print("instance-sync: no token; skipping pull")
|
||||
return 0
|
||||
|
||||
@@ -52,8 +59,9 @@ def pull(args: Args, progress: Progress | None = None) -> int:
|
||||
|
||||
ui.set_status("Resolving restic binary…")
|
||||
binary = restic.resolve_binary(args)
|
||||
repo = _restic_repo(args.url, discord_id, password)
|
||||
repo = _restic_repo(sync_cfg.url, discord_id, password, sync_cfg.instance_id)
|
||||
env = _restic_env()
|
||||
label = cfgmod.resolve_label(args.instance_label, sync_cfg.instance_id)
|
||||
|
||||
ui.set_status("Checking remote snapshots…")
|
||||
code, out = restic.run(
|
||||
@@ -99,7 +107,7 @@ def pull(args: Args, progress: Progress | None = None) -> int:
|
||||
if not modified:
|
||||
decision = "use_remote"
|
||||
else:
|
||||
decision = _ask_conflict(modified, remote_time)
|
||||
decision = _ask_conflict(modified, remote_time, label)
|
||||
if decision is None:
|
||||
# UI unavailable in headless mode → conservative: cancel
|
||||
ui.set_status("Conflict detected; no UI available")
|
||||
@@ -141,6 +149,7 @@ def pull(args: Args, progress: Progress | None = None) -> int:
|
||||
statemod.write(
|
||||
args.pack_folder,
|
||||
statemod.State(
|
||||
instance_id=sync_cfg.instance_id,
|
||||
last_pulled_snapshot_id=remote_id,
|
||||
last_pulled_at=datetime.now(timezone.utc),
|
||||
),
|
||||
@@ -153,8 +162,13 @@ def pull(args: Args, progress: Progress | None = None) -> int:
|
||||
def push(args: Args, progress: Progress | None = None) -> int:
|
||||
ui = progress or HeadlessProgress()
|
||||
|
||||
# Opt-in gate — see pull().
|
||||
sync_cfg = cfgmod.read(args.pack_folder)
|
||||
if sync_cfg is None:
|
||||
return 0
|
||||
|
||||
if not args.token_file.exists():
|
||||
ui.set_status("No network token; skipping push")
|
||||
ui.set_status("No token; skipping push")
|
||||
print("instance-sync: no token; skipping push")
|
||||
return 0
|
||||
|
||||
@@ -163,9 +177,15 @@ def push(args: Args, progress: Progress | None = None) -> int:
|
||||
|
||||
ui.set_status("Resolving restic binary…")
|
||||
binary = restic.resolve_binary(args)
|
||||
repo = _restic_repo(args.url, discord_id, password)
|
||||
repo = _restic_repo(sync_cfg.url, discord_id, password, sync_cfg.instance_id)
|
||||
env = _restic_env()
|
||||
|
||||
# First-push-on-a-new-instance: probe + init if the per-instance repo
|
||||
# doesn't exist yet. Idempotent on subsequent pushes.
|
||||
code = _ensure_repo_initialized(binary, repo, env, ui)
|
||||
if code != 0:
|
||||
return code
|
||||
|
||||
scope = scopemod.load(args.pack_folder)
|
||||
files_from, exclude_from = scopemod.materialize_for_restic(args.pack_folder, scope)
|
||||
|
||||
@@ -196,6 +216,7 @@ def push(args: Args, progress: Progress | None = None) -> int:
|
||||
statemod.write(
|
||||
args.pack_folder,
|
||||
statemod.State(
|
||||
instance_id=sync_cfg.instance_id,
|
||||
last_pulled_snapshot_id=new_id,
|
||||
last_pulled_at=datetime.now(timezone.utc),
|
||||
),
|
||||
@@ -290,6 +311,7 @@ def _matches_any(rel: Path, patterns: list[str]) -> bool:
|
||||
def _ask_conflict(
|
||||
modified: list[tuple[Path, datetime]],
|
||||
remote_time: datetime,
|
||||
label: str,
|
||||
) -> str | None:
|
||||
"""Show the conflict dialog. Returns choice or None if no UI available."""
|
||||
try:
|
||||
@@ -300,7 +322,7 @@ def _ask_conflict(
|
||||
return prompt_conflict_qt(
|
||||
local_modified=_format_dt(newest[1]),
|
||||
remote_modified=_format_dt(remote_time),
|
||||
save_label="Minecraft save",
|
||||
save_label=label,
|
||||
)
|
||||
|
||||
|
||||
@@ -394,7 +416,16 @@ def _format_dt(dt: datetime) -> str:
|
||||
return f"{weekday}, {month} {local.day}, {local.year} at {hour}:{local.minute:02d} {ampm}"
|
||||
|
||||
|
||||
def _restic_repo(base_url: str, discord_id: str, password: str) -> str:
|
||||
def _restic_repo(
|
||||
base_url: str, discord_id: str, password: str, instance_id: str
|
||||
) -> str:
|
||||
"""Build ``rest:<scheme>://<id>:<pw>@<host>/<id>/<instance_id>/``.
|
||||
|
||||
Per-instance subpath under the user's namespace. ``--private-repos``
|
||||
on restic-rest-server only enforces the FIRST path segment (the
|
||||
username); deeper segments are user-controlled, so each instance
|
||||
gets its own isolated restic repo without server-side coordination.
|
||||
"""
|
||||
raw = base_url.strip()
|
||||
if raw.startswith("rest:"):
|
||||
raw = raw[len("rest:"):]
|
||||
@@ -402,13 +433,50 @@ def _restic_repo(base_url: str, discord_id: str, password: str) -> str:
|
||||
scheme_end = raw.find("://")
|
||||
if scheme_end <= 0:
|
||||
raise ValueError(
|
||||
f"--url must include scheme (http:// or https://): {base_url!r}"
|
||||
f"url must include scheme (http:// or https://): {base_url!r}"
|
||||
)
|
||||
scheme = raw[: scheme_end + 3]
|
||||
host_and_path = raw[scheme_end + 3 :]
|
||||
u = urllib.parse.quote(discord_id, safe="")
|
||||
p = urllib.parse.quote(password, safe="")
|
||||
return f"rest:{scheme}{u}:{p}@{host_and_path}/{discord_id}/"
|
||||
iid = urllib.parse.quote(instance_id, safe="")
|
||||
return f"rest:{scheme}{u}:{p}@{host_and_path}/{discord_id}/{iid}/"
|
||||
|
||||
|
||||
def _ensure_repo_initialized(
|
||||
binary: Path, repo: str, env: dict[str, str], ui: "Progress"
|
||||
) -> int:
|
||||
"""`restic cat config` to probe; `restic init` if absent. Returns 0/1/2.
|
||||
|
||||
Cheap to call before every push — `cat config` is a single HTTP GET.
|
||||
Idempotent: if the repo already exists, init is skipped.
|
||||
"""
|
||||
code, _ = restic.run(
|
||||
binary,
|
||||
["-r", repo, "--insecure-no-password", "cat", "config"],
|
||||
env=env,
|
||||
cancel_check=ui.is_cancelled,
|
||||
)
|
||||
if code == 0:
|
||||
return 0
|
||||
if code == -1:
|
||||
return 1
|
||||
# cat config failed → assume not initialized; init it.
|
||||
ui.set_status("Initializing remote repo…")
|
||||
code, _ = restic.run(
|
||||
binary,
|
||||
["-r", repo, "--insecure-no-password", "init"],
|
||||
env=env,
|
||||
cancel_check=ui.is_cancelled,
|
||||
)
|
||||
if code == -1:
|
||||
return 1
|
||||
if code != 0:
|
||||
print(
|
||||
f"instance-sync: restic init failed (exit {code})", file=sys.stderr
|
||||
)
|
||||
return 2
|
||||
return 0
|
||||
|
||||
|
||||
def _restic_env() -> dict[str, str]:
|
||||
|
||||
Reference in New Issue
Block a user