offgit 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,140 @@
1
+ """Server-side settings (``/etc/offgit/server.toml``, overridable by ``OFFGIT_SERVER_CONFIG``).
2
+
3
+ The RPC never accepts filesystem paths, commands or credentials from callers;
4
+ everything path-like comes from this root-owned file.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import tomllib
11
+ from dataclasses import dataclass, field
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from offgit.protocol import clamp_limits
16
+
17
+ DEFAULT_CONFIG_PATH = "/etc/offgit/server.toml"
18
+ DEFAULT_DATA_DIR = "/var/lib/offgit"
19
+
20
+
21
+ class SettingsError(Exception):
22
+ pass
23
+
24
+
25
+ @dataclass
26
+ class BackupSettings:
27
+ restic_bin: str = "restic"
28
+ repository: str = "rclone:gdrive:offgit/restic"
29
+ password_file: str | None = None # default: <data_dir>/secrets/restic-password
30
+ rclone_config: str | None = None # passed as RCLONE_CONFIG when set
31
+ host_tag: str = "offgit"
32
+ tag: str = "offgit"
33
+ timeout_seconds: int = 3600
34
+ keep_hourly: int = 24
35
+ keep_daily: int = 14
36
+ keep_weekly: int = 8
37
+ keep_monthly: int = 6
38
+
39
+
40
+ @dataclass
41
+ class ServerSettings:
42
+ data_dir: Path = Path(DEFAULT_DATA_DIR)
43
+ limits: dict[str, int] = field(default_factory=lambda: clamp_limits({}))
44
+ busy_timeout_ms: int = 5000
45
+ lock_timeout_seconds: float = 15.0
46
+ backup: BackupSettings = field(default_factory=BackupSettings)
47
+ config_path: Path | None = None
48
+
49
+ @property
50
+ def store_path(self) -> Path:
51
+ return self.data_dir / "store.sqlite3"
52
+
53
+ @property
54
+ def locks_dir(self) -> Path:
55
+ return self.data_dir / "locks"
56
+
57
+ @property
58
+ def stage_dir(self) -> Path:
59
+ return self.data_dir / "backup-stage"
60
+
61
+ @property
62
+ def health_path(self) -> Path:
63
+ return self.data_dir / "backup-health.json"
64
+
65
+ @property
66
+ def repo_id_path(self) -> Path:
67
+ return self.data_dir / "backup-repository-id"
68
+
69
+ @property
70
+ def pre_restore_dir(self) -> Path:
71
+ return self.data_dir / "pre-restore"
72
+
73
+ @property
74
+ def password_file(self) -> Path:
75
+ if self.backup.password_file:
76
+ return Path(self.backup.password_file)
77
+ return self.data_dir / "secrets" / "restic-password"
78
+
79
+
80
+ def _check_abs(value: Any, name: str) -> str:
81
+ if not isinstance(value, str) or not value.startswith("/") or "\0" in value:
82
+ raise SettingsError(f"{name} must be an absolute path")
83
+ return value
84
+
85
+
86
+ def load_settings(path: str | None = None) -> ServerSettings:
87
+ path = path or os.environ.get("OFFGIT_SERVER_CONFIG") or DEFAULT_CONFIG_PATH
88
+ p = Path(path)
89
+ settings = ServerSettings(config_path=p if p.exists() else None)
90
+ if not p.exists():
91
+ if os.environ.get("OFFGIT_SERVER_CONFIG"):
92
+ raise SettingsError(f"server config {p} does not exist")
93
+ return settings
94
+ try:
95
+ raw = tomllib.loads(p.read_text(encoding="utf-8"))
96
+ except (OSError, tomllib.TOMLDecodeError, UnicodeDecodeError) as exc:
97
+ raise SettingsError(f"cannot read server config {p}: {exc}") from exc
98
+ allowed = {"data_dir", "limits", "busy_timeout_ms", "lock_timeout_seconds", "backup"}
99
+ unknown = set(raw) - allowed
100
+ if unknown:
101
+ raise SettingsError(f"unknown keys in {p}: {sorted(unknown)}")
102
+ if "data_dir" in raw:
103
+ settings.data_dir = Path(_check_abs(raw["data_dir"], "data_dir"))
104
+ if "limits" in raw:
105
+ if not isinstance(raw["limits"], dict):
106
+ raise SettingsError("[limits] must be a table")
107
+ try:
108
+ settings.limits = clamp_limits(raw["limits"])
109
+ except ValueError as exc:
110
+ raise SettingsError(str(exc)) from exc
111
+ if "busy_timeout_ms" in raw:
112
+ val = raw["busy_timeout_ms"]
113
+ if not isinstance(val, int) or not 1 <= val <= 120_000:
114
+ raise SettingsError("busy_timeout_ms must be 1..120000")
115
+ settings.busy_timeout_ms = val
116
+ if "lock_timeout_seconds" in raw:
117
+ val = raw["lock_timeout_seconds"]
118
+ if not isinstance(val, int | float) or not 0 <= val <= 600:
119
+ raise SettingsError("lock_timeout_seconds must be 0..600")
120
+ settings.lock_timeout_seconds = float(val)
121
+ if "backup" in raw:
122
+ b = raw["backup"]
123
+ if not isinstance(b, dict):
124
+ raise SettingsError("[backup] must be a table")
125
+ known = set(BackupSettings.__dataclass_fields__)
126
+ unknown_b = set(b) - known
127
+ if unknown_b:
128
+ raise SettingsError(f"unknown [backup] keys: {sorted(unknown_b)}")
129
+ for key in ("password_file", "rclone_config"):
130
+ if key in b:
131
+ _check_abs(b[key], f"backup.{key}")
132
+ if "restic_bin" in b and not (
133
+ isinstance(b["restic_bin"], str) and b["restic_bin"] and "\0" not in b["restic_bin"]
134
+ ):
135
+ raise SettingsError("backup.restic_bin invalid")
136
+ for key in ("keep_hourly", "keep_daily", "keep_weekly", "keep_monthly", "timeout_seconds"):
137
+ if key in b and (not isinstance(b[key], int) or b[key] < 0):
138
+ raise SettingsError(f"backup.{key} must be a non-negative integer")
139
+ settings.backup = BackupSettings(**b)
140
+ return settings