Live
This commit is contained in:
@@ -0,0 +1,336 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One-way V1 to V2 merge. Dry-run unless --apply is supplied."""
|
||||
|
||||
import argparse
|
||||
from collections import Counter
|
||||
from contextlib import contextmanager, nullcontext
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import sqlite3
|
||||
import tempfile
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from snapshot import snapshot
|
||||
|
||||
|
||||
TABLES = ("Users", "Categories", "Videos", "Workouts", "CrossfitWorkouts")
|
||||
|
||||
|
||||
@contextmanager
|
||||
def exclusive_lock(filename):
|
||||
with Path(filename).open("a+b") as lock:
|
||||
if os.name == "nt":
|
||||
import msvcrt
|
||||
if lock.seek(0, os.SEEK_END) == 0:
|
||||
lock.write(b"0")
|
||||
lock.flush()
|
||||
lock.seek(0)
|
||||
msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
lock.seek(0)
|
||||
msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1)
|
||||
else:
|
||||
import fcntl
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
fcntl.flock(lock, fcntl.LOCK_UN)
|
||||
|
||||
|
||||
def connect(filename):
|
||||
db = sqlite3.connect(Path(filename).resolve().as_uri() + "?mode=rw", uri=True, timeout=30)
|
||||
db.row_factory = sqlite3.Row
|
||||
db.execute("PRAGMA foreign_keys=ON")
|
||||
return db
|
||||
|
||||
|
||||
def now():
|
||||
return datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S.%f +00:00")
|
||||
|
||||
|
||||
def digest_file(filename):
|
||||
digest = hashlib.sha256()
|
||||
with open(filename, "rb") as stream:
|
||||
for block in iter(lambda: stream.read(1024 * 1024), b""):
|
||||
digest.update(block)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def stage_videos(rows, source_dir, stage_dir):
|
||||
"""Copy while hashing; changes during a copy abort the whole database merge."""
|
||||
source_dir = Path(source_dir).resolve(strict=True)
|
||||
staged = {}
|
||||
for row in rows:
|
||||
name = row["filename"]
|
||||
if not name or Path(name).name != name or "/" in name or "\\" in name:
|
||||
raise ValueError("Invalid V1 video filename")
|
||||
source = (source_dir / name).resolve(strict=True)
|
||||
if source.parent != source_dir or not source.is_file():
|
||||
raise ValueError("V1 video must be a regular file inside its uploads directory")
|
||||
temporary = Path(stage_dir) / str(row["id"])
|
||||
with source.open("rb") as src, temporary.open("wb") as dst:
|
||||
before = os.fstat(src.fileno())
|
||||
shutil.copyfileobj(src, dst, 1024 * 1024)
|
||||
after = os.fstat(src.fileno())
|
||||
current = source.stat()
|
||||
if (before.st_size, before.st_mtime_ns, before.st_ino) != (
|
||||
after.st_size, after.st_mtime_ns, after.st_ino) or (
|
||||
before.st_size, before.st_mtime_ns, before.st_ino) != (
|
||||
current.st_size, current.st_mtime_ns, current.st_ino):
|
||||
raise ValueError("V1 video changed during copy; retry the sync")
|
||||
digest = digest_file(temporary)
|
||||
suffix = source.suffix.lower()
|
||||
if suffix not in (".mp4", ".mov", ".m4v"):
|
||||
raise ValueError("Unsupported V1 video extension")
|
||||
filename = f"v1-{row['id']}-{digest}{suffix}"
|
||||
staged[row["id"]] = {
|
||||
"filename": filename, "temporary": temporary, "digest": digest,
|
||||
"fileSizeBytes": before.st_size,
|
||||
"mimeType": {".mp4": "video/mp4", ".mov": "video/quicktime", ".m4v": "video/x-m4v"}[suffix],
|
||||
}
|
||||
return staged
|
||||
|
||||
|
||||
def publish_videos(staged, uploads):
|
||||
"""Publish immutable filenames before DB commit; never replace a V2 file."""
|
||||
for entry in staged.values():
|
||||
target = Path(uploads) / entry["filename"]
|
||||
try:
|
||||
os.link(entry["temporary"], target)
|
||||
except FileExistsError:
|
||||
if target.is_symlink() or digest_file(target) != entry["digest"]:
|
||||
raise ValueError("Imported media filename collision or damaged file")
|
||||
# Files unreferenced after a rollback are harmless and reusable on retry.
|
||||
|
||||
|
||||
def merge(db, source, media, organization_id, creator_id, source_identity, apply=False, user_role_overrides=None):
|
||||
"""All row changes and ID mappings commit together. Never write source DB."""
|
||||
user_role_overrides = user_role_overrides or {}
|
||||
if any(not str(key).isdigit() or value != 'SystemAdmin' for key, value in user_role_overrides.items()):
|
||||
raise ValueError('Role overrides must map explicit V1 user IDs to SystemAdmin')
|
||||
counts = Counter()
|
||||
timestamp = now()
|
||||
db.execute("BEGIN IMMEDIATE")
|
||||
try:
|
||||
org = db.execute('SELECT id FROM Organizations WHERE id=?', (organization_id,)).fetchone()
|
||||
creator = db.execute('SELECT * FROM Users WHERE id=?', (creator_id,)).fetchone() if creator_id is not None else None
|
||||
if not org or (creator_id is not None and (not creator or creator["organizationId"] != organization_id or not creator["isActive"])):
|
||||
raise ValueError("Select an existing organization and active creator in that organization")
|
||||
db.execute('''CREATE TABLE IF NOT EXISTS V1SyncConfig (
|
||||
id INTEGER PRIMARY KEY CHECK(id=1), source TEXT NOT NULL, organizationId INTEGER NOT NULL)''')
|
||||
settings = db.execute('SELECT * FROM V1SyncConfig WHERE id=1').fetchone()
|
||||
if settings and (settings["source"] != source_identity or settings["organizationId"] != organization_id):
|
||||
raise ValueError("This database is already mapped to a different V1 source or organization")
|
||||
db.execute('INSERT OR IGNORE INTO V1SyncConfig VALUES (1, ?, ?)', (source_identity, organization_id))
|
||||
db.execute('''CREATE TABLE IF NOT EXISTS V1SyncMap (
|
||||
entity TEXT NOT NULL, sourceId INTEGER NOT NULL, targetId INTEGER NOT NULL,
|
||||
PRIMARY KEY(entity, sourceId), UNIQUE(entity, targetId))''')
|
||||
|
||||
def mapped(table, sid):
|
||||
row = db.execute('SELECT targetId FROM V1SyncMap WHERE entity=? AND sourceId=?', (table, sid)).fetchone()
|
||||
return row[0] if row else None
|
||||
|
||||
def upsert(table, row, values, extra=None):
|
||||
tid = mapped(table, row["id"])
|
||||
target = db.execute(f'SELECT * FROM "{table}" WHERE id=?', (tid,)).fetchone() if tid else None
|
||||
if target and (target["organizationId"] != organization_id or
|
||||
(table == "Users" and target["role"] == "SystemAdmin" and
|
||||
user_role_overrides.get(str(row["id"])) != "SystemAdmin")):
|
||||
raise ValueError("Mapped record changed organization or became SystemAdmin; review mapping")
|
||||
if target is None:
|
||||
# Do not guess that a matching username or numeric ID is the same account.
|
||||
if table == "Users" and db.execute('SELECT 1 FROM Users WHERE username=?', (values["username"],)).fetchone():
|
||||
raise ValueError(f"Unmapped username collision for V1 user ID {row['id']}; resolve before import")
|
||||
record = {"organizationId": organization_id, **(extra or {}), **values,
|
||||
"createdAt": row.get("createdAt") or timestamp, "updatedAt": timestamp}
|
||||
# Recreate the mapped ID if V2 deleted an imported object. Keep references stable.
|
||||
if tid is not None:
|
||||
record["id"] = tid
|
||||
columns = ', '.join(f'"{key}"' for key in record)
|
||||
cursor = db.execute(f'INSERT INTO "{table}" ({columns}) VALUES ({",".join("?" for _ in record)})', tuple(record.values()))
|
||||
tid = cursor.lastrowid
|
||||
db.execute('INSERT OR REPLACE INTO V1SyncMap VALUES (?, ?, ?)', (table, row["id"], tid))
|
||||
counts[f"{table}.inserted"] += 1
|
||||
else:
|
||||
changed = {key: value for key, value in values.items() if target[key] != value}
|
||||
if table == "Users" and ("password" in changed or "role" in changed or "isActive" in changed):
|
||||
changed["passwordChangedAt"] = timestamp
|
||||
db.execute('UPDATE DeviceTokens SET isRevoked=1, updatedAt=? WHERE userId=? AND isRevoked=0', (timestamp, tid))
|
||||
if changed:
|
||||
changed["updatedAt"] = timestamp
|
||||
columns = ', '.join(f'"{key}"=?' for key in changed)
|
||||
db.execute(f'UPDATE "{table}" SET {columns} WHERE id=?', (*changed.values(), tid))
|
||||
counts[f"{table}.updated"] += 1
|
||||
return tid
|
||||
|
||||
for row in source["Users"]:
|
||||
role = {"Admin": "Owner", "Coach": "Coach"}.get(row["role"])
|
||||
if role is None:
|
||||
raise ValueError("Unexpected V1 role; define its V2 mapping before import")
|
||||
role = user_role_overrides.get(str(row["id"]), role)
|
||||
upsert("Users", row, {"username": row["username"], "password": row["password"],
|
||||
"role": role, "isActive": 1})
|
||||
|
||||
if creator_id is None:
|
||||
candidate = next((row for row in source["Users"] if row["role"] == "Admin"),
|
||||
next(iter(source["Users"]), None))
|
||||
if candidate is None:
|
||||
raise ValueError("V1 needs at least one account to own imported workouts")
|
||||
creator_id = mapped("Users", candidate["id"])
|
||||
|
||||
# Categories are supporting video metadata, identified by name within this org.
|
||||
categories = {r["name"] for r in source["Categories"]}
|
||||
categories.update(r["category"] for r in source["Videos"] if r["category"])
|
||||
for name in sorted(categories):
|
||||
if not db.execute('SELECT 1 FROM Categories WHERE organizationId=? AND name=?', (organization_id, name)).fetchone():
|
||||
db.execute('INSERT INTO Categories (organizationId,name,createdAt,updatedAt) VALUES (?,?,?,?)',
|
||||
(organization_id, name, timestamp, timestamp))
|
||||
counts["Categories.inserted"] += 1
|
||||
|
||||
for row in source["Videos"]:
|
||||
entry = media[row["id"]]
|
||||
upsert("Videos", row, {"description": row["description"], "category": row["category"],
|
||||
**{key: entry[key] for key in ("filename", "mimeType", "fileSizeBytes")}})
|
||||
|
||||
video_ids = {r["id"] for r in source["Videos"]}
|
||||
for row in source["Workouts"]:
|
||||
values = {key: row[key] for key in ("name", "workoutDate", "number1", "number2", "number3", "number4")}
|
||||
for key in ("video1", "video2", "video3", "video4"):
|
||||
sid = row[key]
|
||||
if sid is not None and sid not in video_ids:
|
||||
raise ValueError("V1 workout references a missing video; fix source data before syncing")
|
||||
values[key] = mapped("Videos", sid) if sid is not None else None
|
||||
upsert("Workouts", row, values, {"createdByUserId": creator_id})
|
||||
|
||||
for row in source["CrossfitWorkouts"]:
|
||||
items = json.loads(row["workoutItems"])
|
||||
if not isinstance(items, list) or any(not isinstance(item, str) for item in items):
|
||||
raise ValueError("Expected V1 Crossfit workoutItems to be a list of text lines")
|
||||
upsert("CrossfitWorkouts", row, {"name": row["name"], "workoutDate": row["workoutDate"],
|
||||
"workoutItems": json.dumps(items, ensure_ascii=False)},
|
||||
{"createdByUserId": creator_id})
|
||||
|
||||
# Apply deletions only to mapped data, children first. Media files are retained.
|
||||
for table in ("Workouts", "CrossfitWorkouts", "Videos", "Users"):
|
||||
live = {r["id"] for r in source[table]}
|
||||
for mapping in db.execute('SELECT * FROM V1SyncMap WHERE entity=?', (table,)).fetchall():
|
||||
if mapping["sourceId"] in live:
|
||||
continue
|
||||
tid = mapping["targetId"]
|
||||
target = db.execute(f'SELECT * FROM "{table}" WHERE id=?', (tid,)).fetchone()
|
||||
if target is None:
|
||||
continue
|
||||
if target["organizationId"] != organization_id or (table == "Users" and target["role"] == "SystemAdmin" and
|
||||
user_role_overrides.get(str(mapping["sourceId"])) != "SystemAdmin"):
|
||||
raise ValueError("Cannot retire a mapped record whose ownership changed")
|
||||
if table == "Users":
|
||||
if target["isActive"]:
|
||||
db.execute('UPDATE Users SET isActive=0,passwordChangedAt=?,updatedAt=? WHERE id=?', (timestamp, timestamp, tid))
|
||||
db.execute('UPDATE DeviceTokens SET isRevoked=1,updatedAt=? WHERE userId=?', (timestamp, tid))
|
||||
counts["Users.deactivated"] += 1
|
||||
continue
|
||||
if table == "Videos":
|
||||
referenced = db.execute('SELECT 1 FROM Workouts WHERE video1=? OR video2=? OR video3=? OR video4=? LIMIT 1', (tid,) * 4).fetchone()
|
||||
for assignment in db.execute('SELECT items FROM ClientWorkouts'):
|
||||
items = json.loads(assignment[0] or '[]')
|
||||
if any(isinstance(item, dict) and str(item.get("videoId")) == str(tid) for item in items):
|
||||
referenced = True
|
||||
if referenced:
|
||||
counts["Videos.retained_referenced"] += 1
|
||||
continue
|
||||
db.execute(f'DELETE FROM "{table}" WHERE id=?', (tid,))
|
||||
counts[f"{table}.deleted"] += 1
|
||||
|
||||
if db.execute('PRAGMA foreign_key_check').fetchone():
|
||||
raise ValueError("Foreign-key check failed; transaction rolled back")
|
||||
if apply:
|
||||
db.commit()
|
||||
else:
|
||||
db.rollback()
|
||||
return dict(counts)
|
||||
except BaseException:
|
||||
db.rollback()
|
||||
raise
|
||||
|
||||
|
||||
def run(config, apply=False, scheduled=False):
|
||||
paths = {key: Path(config[key]).resolve(strict=True) for key in
|
||||
("v1_db", "v1_uploads", "v2_db", "v2_uploads", "backup_dir")}
|
||||
if os.path.samefile(paths["v1_db"], paths["v2_db"]):
|
||||
raise ValueError("V1 and V2 must use separate databases")
|
||||
for a, b in (("v1_uploads", "v2_uploads"), ("backup_dir", "v1_uploads"), ("backup_dir", "v2_uploads")):
|
||||
if paths[a] == paths[b] or paths[a] in paths[b].parents or paths[b] in paths[a].parents:
|
||||
raise ValueError("Uploads and backup directories must be separate and non-nested")
|
||||
# Cron and manual runs use the same advisory lock.
|
||||
with exclusive_lock(paths["backup_dir"] / "sync.lock"):
|
||||
zone_name = config.get("timezone", "America/New_York")
|
||||
local_time = datetime.now(timezone.utc if zone_name == "UTC" else ZoneInfo(zone_name))
|
||||
last_success = paths["backup_dir"] / "last-success.json"
|
||||
if scheduled:
|
||||
if local_time.hour != config.get("sync_hour", 5):
|
||||
return {"skipped": "outside scheduled hour"}
|
||||
if last_success.exists() and json.loads(last_success.read_text()).get("local_day") == local_time.date().isoformat():
|
||||
return {"skipped": "already synced today"}
|
||||
prefix = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ-")
|
||||
context = (nullcontext(tempfile.mkdtemp(prefix=prefix, dir=paths["backup_dir"]))
|
||||
if config.get("retain_snapshots", True) else
|
||||
tempfile.TemporaryDirectory(prefix=prefix, dir=paths["backup_dir"]))
|
||||
with context as directory:
|
||||
report = run_batch(config, paths, Path(directory), apply)
|
||||
if apply:
|
||||
report["local_day"] = local_time.date().isoformat()
|
||||
temporary = last_success.with_suffix('.tmp')
|
||||
temporary.write_text(json.dumps(report) + "\n")
|
||||
os.replace(temporary, last_success)
|
||||
print(json.dumps(report))
|
||||
return report
|
||||
|
||||
|
||||
def run_batch(config, paths, batch, apply):
|
||||
snapshot(paths["v1_db"], batch / "v1.sqlite")
|
||||
snapshot(paths["v2_db"], batch / "v2-before.sqlite")
|
||||
source_db = connect(batch / "v1.sqlite")
|
||||
try:
|
||||
source = {table: [dict(row) for row in source_db.execute(f'SELECT * FROM "{table}" ORDER BY id')] for table in TABLES}
|
||||
finally:
|
||||
source_db.close()
|
||||
# Dry-runs merge into a disposable backup, never acquire a write lock on live V2.
|
||||
target = paths["v2_db"] if apply else batch / "v2-before.sqlite"
|
||||
with tempfile.TemporaryDirectory(prefix=".v1-stage-", dir=paths["v2_uploads"]) as stage:
|
||||
media = stage_videos(source["Videos"], paths["v1_uploads"], stage)
|
||||
# Validate the whole merge against the backup before publishing any files.
|
||||
preview = connect(batch / "v2-before.sqlite")
|
||||
try:
|
||||
counts = merge(preview, source, media, config["organization_id"], config["creator_id"], str(paths["v1_db"]),
|
||||
user_role_overrides=config.get("user_role_overrides"))
|
||||
finally:
|
||||
preview.close()
|
||||
if apply:
|
||||
publish_videos(media, paths["v2_uploads"])
|
||||
db = connect(target)
|
||||
try:
|
||||
counts = merge(db, source, media, config["organization_id"], config["creator_id"], str(paths["v1_db"]), apply=True,
|
||||
user_role_overrides=config.get("user_role_overrides"))
|
||||
finally:
|
||||
db.close()
|
||||
report = {"applied": apply, "finished_at": now(), "counts": counts}
|
||||
(batch / "result.json").write_text(json.dumps(report, indent=2) + "\n")
|
||||
return report
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--config", required=True)
|
||||
parser.add_argument("--apply", action="store_true")
|
||||
parser.add_argument("--scheduled", action="store_true", help="Run only once daily during configured local hour")
|
||||
args = parser.parse_args()
|
||||
os.umask(0o077)
|
||||
with open(args.config) as stream:
|
||||
run(json.load(stream), apply=args.apply, scheduled=args.scheduled)
|
||||
Reference in New Issue
Block a user