File size: 8,650 Bytes
f398dc5
e110d9d
 
 
 
 
 
 
 
 
 
320e776
e110d9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
320e776
e110d9d
 
 
 
 
 
 
 
7f99b73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e110d9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f99b73
 
 
 
e110d9d
 
7f99b73
e110d9d
 
7f99b73
 
 
 
 
 
e110d9d
 
06e6b8c
7f99b73
e110d9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f99b73
e110d9d
 
 
320e776
e110d9d
 
 
 
 
 
 
7f99b73
e110d9d
 
320e776
e110d9d
7f99b73
e110d9d
 
 
320e776
 
 
e110d9d
 
 
 
 
 
 
 
 
 
 
 
 
7f99b73
e110d9d
 
 
 
 
 
 
 
 
 
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
#!/usr/bin/env python3

import hashlib
import json
import os
import shutil
import signal
import subprocess
import sys
import tempfile
import time
import threading
from pathlib import Path

os.environ.setdefault("HF_HUB_DISABLE_PROGRESS_BARS", "1")

from huggingface_hub import HfApi, snapshot_download, upload_folder
from huggingface_hub.errors import RepositoryNotFoundError

N8N_HOME = Path(os.environ.get("N8N_USER_FOLDER", "/home/node/.n8n"))
STATUS_FILE = Path("/tmp/hugging8n-sync-status.json")
INTERVAL = int(os.environ.get("SYNC_INTERVAL", "180"))
HF_TOKEN = os.environ.get("HF_TOKEN", "").strip()
HF_USERNAME = (
    os.environ.get("HF_USERNAME", "").strip()
    or os.environ.get("SPACE_AUTHOR_NAME", "").strip()
)
BACKUP_DATASET_NAME = os.environ.get("BACKUP_DATASET_NAME", "hugging8n-backup").strip()
HF_API = HfApi(token=HF_TOKEN) if HF_TOKEN else None
STOP_EVENT = threading.Event()


def write_status(status: str, message: str) -> None:
    payload = {
        "status": status,
        "message": message,
        "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
    }
    tmp_path = STATUS_FILE.with_suffix(".tmp")
    tmp_path.write_text(json.dumps(payload), encoding="utf-8")
    tmp_path.replace(STATUS_FILE)


def metadata_marker(root: Path) -> tuple[int, int, int]:
    if not root.exists():
        return (0, 0, 0)

    file_count = 0
    total_size = 0
    newest_mtime = 0
    for path in root.rglob("*"):
        if not path.is_file():
            continue
        rel = path.relative_to(root).as_posix()
        if rel.startswith(".cache/"):
            continue
        try:
            stat = path.stat()
        except OSError:
            continue
        file_count += 1
        total_size += int(stat.st_size)
        newest_mtime = max(newest_mtime, int(stat.st_mtime_ns))
    return (file_count, total_size, newest_mtime)


def dataset_repo_id() -> str:
    if not HF_USERNAME:
        raise RuntimeError("HF_USERNAME or SPACE_AUTHOR_NAME is required for backup repo naming")
    return f"{HF_USERNAME}/{BACKUP_DATASET_NAME}"


def ensure_repo_exists() -> str:
    repo_id = dataset_repo_id()
    try:
        HF_API.repo_info(repo_id=repo_id, repo_type="dataset")
    except RepositoryNotFoundError:
        HF_API.create_repo(repo_id=repo_id, repo_type="dataset", private=True)
    return repo_id


def fingerprint_dir(root: Path) -> str:
    hasher = hashlib.sha256()
    if not root.exists():
        return hasher.hexdigest()

    for path in sorted(p for p in root.rglob("*") if p.is_file()):
        rel = path.relative_to(root).as_posix()
        if rel.startswith(".cache/"):
            continue
        hasher.update(rel.encode("utf-8"))
        with path.open("rb") as handle:
            for chunk in iter(lambda: handle.read(1024 * 1024), b""):
                hasher.update(chunk)
    return hasher.hexdigest()


def create_snapshot_dir(source_root: Path) -> Path:
    staging_root = Path(tempfile.mkdtemp(prefix="hugging8n-sync-"))
    database_path = source_root / "database.sqlite"

    for path in sorted(source_root.rglob("*")):
        rel = path.relative_to(source_root)
        rel_posix = rel.as_posix()
        if rel_posix.startswith(".cache/"):
            continue
        target = staging_root / rel
        if path.is_dir():
            target.mkdir(parents=True, exist_ok=True)
            continue
        if rel_posix in {"database.sqlite", "database.sqlite-shm", "database.sqlite-wal"}:
            continue
        target.parent.mkdir(parents=True, exist_ok=True)
        shutil.copy2(path, target)

    if database_path.exists():
        target_db = staging_root / "database.sqlite"
        target_db.parent.mkdir(parents=True, exist_ok=True)
        try:
            subprocess.run(
                ["sqlite3", str(database_path), f".backup {target_db}"],
                check=True,
                stdout=subprocess.DEVNULL,
                stderr=subprocess.DEVNULL,
            )
        except Exception:
            shutil.copy2(database_path, target_db)
            for suffix in ("-wal", "-shm"):
                sidecar = source_root / f"database.sqlite{suffix}"
                if sidecar.exists():
                    shutil.copy2(sidecar, staging_root / sidecar.name)

    return staging_root


def restore() -> bool:
    if not HF_TOKEN:
        write_status("disabled", "HF_TOKEN is not configured.")
        return False

    repo_id = dataset_repo_id()
    write_status("restoring", f"Restoring state from {repo_id}")

    try:
        with tempfile.TemporaryDirectory() as tmpdir:
            snapshot_download(
                repo_id=repo_id,
                repo_type="dataset",
                token=HF_TOKEN,
                local_dir=tmpdir,
            )

            tmp_path = Path(tmpdir)
            if not any(tmp_path.iterdir()):
                write_status("fresh", "Backup dataset is empty. Starting fresh.")
                return True

            N8N_HOME.mkdir(parents=True, exist_ok=True)
            for child in N8N_HOME.iterdir():
                if child.name == ".cache":
                    continue
                if child.is_dir():
                    shutil.rmtree(child, ignore_errors=True)
                else:
                    child.unlink(missing_ok=True)

            for child in tmp_path.iterdir():
                if child.name == ".cache":
                    continue
                destination = N8N_HOME / child.name
                if child.is_dir():
                    shutil.copytree(child, destination)
                else:
                    shutil.copy2(child, destination)

        write_status("restored", f"Restored state from {repo_id}")
        return True
    except RepositoryNotFoundError:
        write_status("fresh", f"Backup dataset {repo_id} does not exist yet.")
        return True
    except Exception as exc:
        write_status("error", f"Restore failed: {exc}")
        print(f"Restore failed: {exc}", file=sys.stderr)
        return False


def sync_once(
    last_fingerprint: str | None = None,
    last_marker: tuple[int, int, int] | None = None,
) -> tuple[str, tuple[int, int, int]]:
    if not HF_TOKEN:
        write_status("disabled", "HF_TOKEN is not configured.")
        return (last_fingerprint or "", last_marker or (0, 0, 0))

    repo_id = ensure_repo_exists()

    current_marker = metadata_marker(N8N_HOME)
    if last_marker is not None and current_marker == last_marker:
        write_status("synced", "No state changes detected.")
        return (last_fingerprint or "", current_marker)

    current_fingerprint = fingerprint_dir(N8N_HOME)
    if last_fingerprint is not None and current_fingerprint == last_fingerprint:
        write_status("synced", "No state changes detected.")
        return (last_fingerprint, current_marker)

    write_status("syncing", f"Uploading state to {repo_id}")
    snapshot_dir = create_snapshot_dir(N8N_HOME)
    try:
        upload_folder(
            folder_path=str(snapshot_dir),
            repo_id=repo_id,
            repo_type="dataset",
            token=HF_TOKEN,
            commit_message=f"Hugging8n sync {time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())}",
            ignore_patterns=[".cache/*"],
        )
    finally:
        shutil.rmtree(snapshot_dir, ignore_errors=True)
    write_status("success", f"Uploaded state to {repo_id}")
    return (current_fingerprint, current_marker)


def handle_signal(_sig, _frame) -> None:
    STOP_EVENT.set()


def loop() -> int:
    signal.signal(signal.SIGTERM, handle_signal)
    signal.signal(signal.SIGINT, handle_signal)

    last_fingerprint = fingerprint_dir(N8N_HOME)
    last_marker = metadata_marker(N8N_HOME)
    write_status("configured", f"Backup loop active with {INTERVAL}s interval.")

    while not STOP_EVENT.is_set():
        try:
            last_fingerprint, last_marker = sync_once(last_fingerprint, last_marker)
        except Exception as exc:
            write_status("error", f"Sync failed: {exc}")
            print(f"Sync failed: {exc}", file=sys.stderr)
        
        if STOP_EVENT.wait(INTERVAL):
            break

    return 0


def main() -> int:
    if len(sys.argv) < 2:
        print("Usage: n8n-sync.py [restore|sync-once|loop]", file=sys.stderr)
        return 1

    command = sys.argv[1]
    if command == "restore":
        return 0 if restore() else 1
    if command == "sync-once":
        sync_once(None, None)
        return 0
    if command == "loop":
        return loop()

    print(f"Unknown command: {command}", file=sys.stderr)
    return 1


if __name__ == "__main__":
    raise SystemExit(main())