remotessd 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.
remotessd/__init__.py
ADDED
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
"""Python SDK for remoteSSD drives.
|
|
2
|
+
|
|
3
|
+
from remotessd import Drive
|
|
4
|
+
d = Drive(key="rssd_...") # or Drive() to read REMOTESSD_KEY (and REMOTESSD_URL / REMOTESSD_DRIVE)
|
|
5
|
+
d.write("/notes.md", "hello\\n")
|
|
6
|
+
text, version = d.read_text("/notes.md", with_version=True)
|
|
7
|
+
d.update("/notes.md", lambda old: old + "one more line\\n") # safe write with retries
|
|
8
|
+
old = d.read_version("/notes.md", version=1) # history: versions, revert, undelete
|
|
9
|
+
|
|
10
|
+
Every method makes one or a few HTTPS requests to the drive. Errors are raised as
|
|
11
|
+
subclasses of RemoteSSDError (NotFound, Conflict, AuthError, QuotaExceeded, ...).
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
import random
|
|
18
|
+
import re
|
|
19
|
+
import time
|
|
20
|
+
from urllib.parse import quote
|
|
21
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
22
|
+
from dataclasses import dataclass, field
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import BinaryIO, Callable, Iterator, Optional, Union
|
|
25
|
+
|
|
26
|
+
import httpx
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
"Drive", "Entry", "SearchHit", "RemoteSSDError", "NotFound", "Conflict", "AuthError",
|
|
30
|
+
"QuotaExceeded", "ServerError", "CHUNK", "DEFAULT_URL",
|
|
31
|
+
]
|
|
32
|
+
__version__ = "0.1.0"
|
|
33
|
+
|
|
34
|
+
DEFAULT_URL = "https://app.remotessd.com"
|
|
35
|
+
CHUNK = 4 * 1024 * 1024 # upload pieces and download ranges; the drive takes chunks of up to 4 MB, listed as [key, size]
|
|
36
|
+
SMALL = 8 * 1024 * 1024 # up to this size a file goes up or down in one request
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class RemoteSSDError(Exception):
|
|
40
|
+
def __init__(self, message: str, status: int = 0, errno: str = "", body: Optional[dict] = None):
|
|
41
|
+
super().__init__(message)
|
|
42
|
+
self.status, self.errno, self.body = status, errno, body or {}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class NotFound(RemoteSSDError):
|
|
46
|
+
pass
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class Conflict(RemoteSSDError):
|
|
50
|
+
"""A safe write was refused (the file changed, or already exists), or a folder isn't empty.
|
|
51
|
+
|
|
52
|
+
`current_version` is the file's version now, when the drive reported it."""
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def current_version(self) -> Optional[int]:
|
|
56
|
+
return self.body.get("version")
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class AuthError(RemoteSSDError):
|
|
60
|
+
pass
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class QuotaExceeded(RemoteSSDError):
|
|
64
|
+
pass
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class ServerError(RemoteSSDError):
|
|
68
|
+
pass
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass
|
|
72
|
+
class Entry:
|
|
73
|
+
path: str
|
|
74
|
+
kind: str # "file", "dir" or "link"
|
|
75
|
+
size: int
|
|
76
|
+
version: int
|
|
77
|
+
mode: int
|
|
78
|
+
mtime: float # seconds since the epoch
|
|
79
|
+
raw: dict = field(repr=False, default_factory=dict)
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def name(self) -> str:
|
|
83
|
+
return self.path.rsplit("/", 1)[-1] or "/"
|
|
84
|
+
|
|
85
|
+
@property
|
|
86
|
+
def is_dir(self) -> bool:
|
|
87
|
+
return self.kind == "dir"
|
|
88
|
+
|
|
89
|
+
@classmethod
|
|
90
|
+
def _from(cls, d: dict) -> "Entry":
|
|
91
|
+
return cls(path=d["path"], kind={"f": "file", "d": "dir", "l": "link"}.get(d["kind"], d["kind"]),
|
|
92
|
+
size=d["size"], version=d["version"], mode=d.get("mode", 0), mtime=d.get("mtime", 0) / 1000, raw=d)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@dataclass
|
|
96
|
+
class SearchHit:
|
|
97
|
+
path: str
|
|
98
|
+
match: str # "name" or "content"
|
|
99
|
+
version: int
|
|
100
|
+
size: int
|
|
101
|
+
lines: list # [(line_number, text)] for content matches
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _norm(path: str) -> str:
|
|
105
|
+
return "/" + "/".join(p for p in str(path).split("/") if p)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class Drive:
|
|
109
|
+
"""A connection to one remoteSSD drive.
|
|
110
|
+
|
|
111
|
+
url: the drive service (env REMOTESSD_URL, default https://app.remotessd.com)
|
|
112
|
+
key: an agent key (env REMOTESSD_KEY). Sent as `Authorization: Bearer <key>`.
|
|
113
|
+
drive: the drive name (env REMOTESSD_DRIVE, default "-", the key's own drive). An account key
|
|
114
|
+
(rssd_<drive>_...) names its own drive, which is then used instead.
|
|
115
|
+
"""
|
|
116
|
+
|
|
117
|
+
def __init__(self, url: Optional[str] = None, key: Optional[str] = None, drive: Optional[str] = None,
|
|
118
|
+
timeout: float = 60.0, client: Optional[httpx.Client] = None):
|
|
119
|
+
self.url = (url or os.environ.get("REMOTESSD_URL") or DEFAULT_URL).rstrip("/")
|
|
120
|
+
self.key = key or os.environ.get("REMOTESSD_KEY", "")
|
|
121
|
+
self.drive = drive or os.environ.get("REMOTESSD_DRIVE") or "-"
|
|
122
|
+
m = re.match(r"rssd_([0-9a-f]{20})_", self.key)
|
|
123
|
+
if m:
|
|
124
|
+
self.drive = m.group(1)
|
|
125
|
+
if not self.url or not self.key:
|
|
126
|
+
raise ValueError("Drive needs a key (pass key= or set REMOTESSD_KEY)")
|
|
127
|
+
self._http = client or httpx.Client(timeout=timeout, http2=False)
|
|
128
|
+
self._http.headers.update({"authorization": f"Bearer {self.key}", "x-client": "python"})
|
|
129
|
+
|
|
130
|
+
def close(self) -> None:
|
|
131
|
+
self._http.close()
|
|
132
|
+
|
|
133
|
+
def __enter__(self) -> "Drive":
|
|
134
|
+
return self
|
|
135
|
+
|
|
136
|
+
def __exit__(self, *exc) -> None:
|
|
137
|
+
self.close()
|
|
138
|
+
|
|
139
|
+
# ---------- low level ----------
|
|
140
|
+
def _url(self, op: str) -> str:
|
|
141
|
+
return f"{self.url}/d/{quote(self.drive, safe='')}/{op}"
|
|
142
|
+
|
|
143
|
+
def _req(self, method: str, op: str, params: dict, what: str = "", **kw) -> httpx.Response:
|
|
144
|
+
params = {k: v for k, v in params.items() if v is not None}
|
|
145
|
+
for attempt in range(3):
|
|
146
|
+
try:
|
|
147
|
+
r = self._http.request(method, self._url(op), params=params, **kw)
|
|
148
|
+
except httpx.TransportError as e:
|
|
149
|
+
if method == "GET" and attempt < 2:
|
|
150
|
+
time.sleep(0.3 * (attempt + 1))
|
|
151
|
+
continue
|
|
152
|
+
raise ServerError(f"network error: {e}") from e
|
|
153
|
+
if r.status_code >= 500 and method == "GET" and attempt < 2:
|
|
154
|
+
time.sleep(0.3 * (attempt + 1))
|
|
155
|
+
continue
|
|
156
|
+
break
|
|
157
|
+
if r.is_success:
|
|
158
|
+
return r
|
|
159
|
+
try:
|
|
160
|
+
body = r.json()
|
|
161
|
+
except ValueError:
|
|
162
|
+
body = {"error": r.text[:200]}
|
|
163
|
+
errno = body.get("errno", "")
|
|
164
|
+
what = what or params.get("path", op)
|
|
165
|
+
msg = f"{what}: {errno or r.status_code} {body.get('error', '')}".strip()
|
|
166
|
+
if r.status_code in (401, 403):
|
|
167
|
+
raise AuthError("key refused", r.status_code, errno, body)
|
|
168
|
+
if r.status_code == 404:
|
|
169
|
+
raise NotFound(f"{what}: not found", 404, errno, body)
|
|
170
|
+
if r.status_code == 409:
|
|
171
|
+
raise Conflict(msg + (f" (current version {body['version']})" if "version" in body else ""), 409, errno, body)
|
|
172
|
+
if r.status_code == 429:
|
|
173
|
+
raise QuotaExceeded("request limit reached", 429, errno, body)
|
|
174
|
+
if r.status_code >= 500:
|
|
175
|
+
raise ServerError(msg, r.status_code, errno, body)
|
|
176
|
+
raise RemoteSSDError(msg, r.status_code, errno, body)
|
|
177
|
+
|
|
178
|
+
# ---------- reading ----------
|
|
179
|
+
def stat(self, path: str) -> Entry:
|
|
180
|
+
return Entry._from(self._req("GET", "stat", {"path": _norm(path)}).json())
|
|
181
|
+
|
|
182
|
+
def exists(self, path: str) -> bool:
|
|
183
|
+
try:
|
|
184
|
+
self.stat(path)
|
|
185
|
+
return True
|
|
186
|
+
except NotFound:
|
|
187
|
+
return False
|
|
188
|
+
|
|
189
|
+
def list(self, path: str = "/") -> list[Entry]:
|
|
190
|
+
b = self._req("GET", "list", {"path": _norm(path)}).json()
|
|
191
|
+
return sorted((Entry._from(e) for e in b["entries"]), key=lambda e: e.path)
|
|
192
|
+
|
|
193
|
+
def read(self, path: str, offset: int = 0, length: Optional[int] = None, with_version: bool = False):
|
|
194
|
+
"""Bytes of a file, or of the range [offset, offset+length). Big files are fetched in 4 MB parts."""
|
|
195
|
+
path = _norm(path)
|
|
196
|
+
if offset == 0 and length is None:
|
|
197
|
+
r = self._req("GET", "read", {"path": path}, headers={"range": f"bytes=0-{SMALL - 1}"})
|
|
198
|
+
md = json.loads(r.headers.get("x-meta", "{}"))
|
|
199
|
+
if md.get("size", 0) <= SMALL:
|
|
200
|
+
return (r.content, md["version"]) if with_version else r.content
|
|
201
|
+
length = md["size"]
|
|
202
|
+
if length is not None and length <= 0:
|
|
203
|
+
return (b"", self.stat(path).version) if with_version else b""
|
|
204
|
+
if length is not None and length <= SMALL:
|
|
205
|
+
r = self._range(path, offset, offset + length - 1)
|
|
206
|
+
data, ver = (r.content, json.loads(r.headers["x-meta"])["version"]) if r is not None else (b"", None)
|
|
207
|
+
return (data, ver) if with_version else data
|
|
208
|
+
st = self.stat(path)
|
|
209
|
+
end = st.size if length is None else min(st.size, offset + length)
|
|
210
|
+
parts = list(range(offset, end, CHUNK))
|
|
211
|
+
|
|
212
|
+
def get(a: int) -> bytes:
|
|
213
|
+
r = self._range(path, a, min(end, a + CHUNK) - 1)
|
|
214
|
+
if r is None:
|
|
215
|
+
return b""
|
|
216
|
+
if json.loads(r.headers["x-meta"])["version"] != st.version:
|
|
217
|
+
raise Conflict(f"{path}: changed while reading; try again", 409, "ECONFLICT", {})
|
|
218
|
+
return r.content
|
|
219
|
+
|
|
220
|
+
with ThreadPoolExecutor(4) as ex:
|
|
221
|
+
data = b"".join(ex.map(get, parts))
|
|
222
|
+
return (data, st.version) if with_version else data
|
|
223
|
+
|
|
224
|
+
def _range(self, path: str, a: int, b: int, sel: Optional[dict] = None) -> Optional[httpx.Response]:
|
|
225
|
+
try:
|
|
226
|
+
return self._req("GET", "read", {"path": path, **(sel or {})}, headers={"range": f"bytes={a}-{b}"})
|
|
227
|
+
except RemoteSSDError as e:
|
|
228
|
+
if e.status == 416:
|
|
229
|
+
return None
|
|
230
|
+
raise
|
|
231
|
+
|
|
232
|
+
def read_text(self, path: str, encoding: str = "utf-8", with_version: bool = False):
|
|
233
|
+
data, v = self.read(path, with_version=True)
|
|
234
|
+
return (data.decode(encoding), v) if with_version else data.decode(encoding)
|
|
235
|
+
|
|
236
|
+
def download(self, path: str, dest: Union[str, Path]) -> Entry:
|
|
237
|
+
"""Copy a drive file to a local file, in 4 MB parts for big files, without holding it all in memory."""
|
|
238
|
+
path, dest = _norm(path), Path(dest)
|
|
239
|
+
st = self.stat(path)
|
|
240
|
+
tmp = dest.with_name(f".{dest.name}.remotessd-{os.getpid()}")
|
|
241
|
+
try:
|
|
242
|
+
with open(tmp, "wb") as f:
|
|
243
|
+
f.truncate(st.size)
|
|
244
|
+
|
|
245
|
+
def get(a: int) -> None:
|
|
246
|
+
r = self._range(path, a, min(st.size, a + CHUNK) - 1)
|
|
247
|
+
if r is None:
|
|
248
|
+
return
|
|
249
|
+
if json.loads(r.headers["x-meta"])["version"] != st.version:
|
|
250
|
+
raise Conflict(f"{path}: changed while copying; try again", 409, "ECONFLICT", {})
|
|
251
|
+
with open(tmp, "r+b") as g:
|
|
252
|
+
g.seek(a)
|
|
253
|
+
g.write(r.content)
|
|
254
|
+
|
|
255
|
+
with ThreadPoolExecutor(4) as ex:
|
|
256
|
+
list(ex.map(get, range(0, st.size, CHUNK)))
|
|
257
|
+
os.replace(tmp, dest)
|
|
258
|
+
finally:
|
|
259
|
+
if tmp.exists():
|
|
260
|
+
tmp.unlink()
|
|
261
|
+
return st
|
|
262
|
+
|
|
263
|
+
def search(self, query: str, path: str = "/", where: str = "both", limit: int = 50) -> list[SearchHit]:
|
|
264
|
+
"""Find files by name and by text inside files up to 64 KB. `where`: both, name or content."""
|
|
265
|
+
b = self._req("GET", "search", {"q": query, "path": _norm(path), "in": None if where == "both" else where,
|
|
266
|
+
"limit": limit}, what="search").json()
|
|
267
|
+
return [SearchHit(path=x["path"], match=x["match"], version=x["version"], size=x["size"],
|
|
268
|
+
lines=[(l["line"], l["text"]) for l in x.get("lines", [])]) for x in b["results"]]
|
|
269
|
+
|
|
270
|
+
# ---------- history ----------
|
|
271
|
+
def versions(self, path: str, limit: Optional[int] = None, before: Optional[int] = None) -> dict:
|
|
272
|
+
"""A file's saved versions, newest first; history is kept 30 days after a version stops being current.
|
|
273
|
+
|
|
274
|
+
Returns {"path", "current", "versions", "next"}. "current" is the file's meta now (None if it is
|
|
275
|
+
deleted). Each entry in "versions" has vid, version, saved, ended (ms since the epoch), size,
|
|
276
|
+
by/byName (the key that saved it), how (None, "merge", "restore" or "delete") and deleted.
|
|
277
|
+
Pass before=next to get the page after this one."""
|
|
278
|
+
return self._req("GET", "versions", {"path": _norm(path), "limit": limit, "before": before}).json()
|
|
279
|
+
|
|
280
|
+
def read_version(self, path: str, vid: Optional[int] = None, version: Optional[int] = None) -> bytes:
|
|
281
|
+
"""Bytes of an old version, picked by vid (from versions()) or by version number."""
|
|
282
|
+
if (vid is None) == (version is None):
|
|
283
|
+
raise ValueError("pass exactly one of vid and version")
|
|
284
|
+
path, sel = _norm(path), {"vid": vid, "version": version}
|
|
285
|
+
r = self._req("GET", "read", {"path": path, **sel}, headers={"range": f"bytes=0-{SMALL - 1}"})
|
|
286
|
+
size = json.loads(r.headers.get("x-meta", "{}")).get("size", 0)
|
|
287
|
+
if size <= SMALL:
|
|
288
|
+
return r.content
|
|
289
|
+
|
|
290
|
+
def get(a: int) -> bytes:
|
|
291
|
+
rr = self._range(path, a, min(size, a + CHUNK) - 1, sel)
|
|
292
|
+
return rr.content if rr is not None else b""
|
|
293
|
+
|
|
294
|
+
with ThreadPoolExecutor(4) as ex:
|
|
295
|
+
return r.content + b"".join(ex.map(get, range(SMALL, size, CHUNK)))
|
|
296
|
+
|
|
297
|
+
def revert(self, path: str, vid: int, if_version: Optional[int] = None) -> Entry:
|
|
298
|
+
"""Make old version `vid` the file's content again, saved as a new version (history keeps
|
|
299
|
+
everything). Also brings back a deleted file. With if_version, raises Conflict if the file is no
|
|
300
|
+
longer at that version."""
|
|
301
|
+
return Entry._from(self._req("POST", "revert", {"path": _norm(path), "vid": vid, "ifVersion": if_version}).json())
|
|
302
|
+
|
|
303
|
+
def undelete(self, path: str) -> Entry:
|
|
304
|
+
"""Bring back a deleted file with its last content. Raises Conflict if a file is there now and
|
|
305
|
+
NotFound if there is nothing to bring back."""
|
|
306
|
+
return Entry._from(self._req("POST", "undelete", {"path": _norm(path)}).json())
|
|
307
|
+
|
|
308
|
+
def deleted(self, path: str = "/", limit: Optional[int] = None) -> list[dict]:
|
|
309
|
+
"""Files deleted in the last 30 days under the folder `path` (recursive) that do not exist now,
|
|
310
|
+
newest delete first. Each has path, deletedAt (ms), by, byName, size, and vid/version of the last
|
|
311
|
+
content (pass the vid to revert or read_version)."""
|
|
312
|
+
return self._req("GET", "deleted", {"path": _norm(path), "limit": limit}).json()["files"]
|
|
313
|
+
|
|
314
|
+
# ---------- writing ----------
|
|
315
|
+
def write(self, path: str, data: Union[bytes, str, BinaryIO], if_version: Optional[int] = None) -> Entry:
|
|
316
|
+
"""Create or replace a whole file. Last save wins unless if_version is given.
|
|
317
|
+
|
|
318
|
+
if_version=N saves only if the file is still at version N (a safe write); if_version=0 saves
|
|
319
|
+
only if the file does not exist. Raises Conflict otherwise, and nothing is written."""
|
|
320
|
+
path = _norm(path)
|
|
321
|
+
if isinstance(data, str):
|
|
322
|
+
data = data.encode()
|
|
323
|
+
if not isinstance(data, (bytes, bytearray, memoryview)):
|
|
324
|
+
data = data.read()
|
|
325
|
+
data = bytes(data)
|
|
326
|
+
if len(data) <= SMALL:
|
|
327
|
+
return Entry._from(self._req("POST", "write", {"path": path, "ifVersion": if_version}, content=data).json())
|
|
328
|
+
parts = [data[i:i + CHUNK] for i in range(0, len(data), CHUNK)]
|
|
329
|
+
return self._commit_chunks(path, len(data), parts, if_version)
|
|
330
|
+
|
|
331
|
+
def _commit_chunks(self, path: str, size: int, parts, if_version: Optional[int]) -> Entry:
|
|
332
|
+
def put(part: bytes) -> list:
|
|
333
|
+
return [self._req("PUT", "chunk", {"path": path}, content=part).json()["key"], len(part)]
|
|
334
|
+
|
|
335
|
+
with ThreadPoolExecutor(4) as ex:
|
|
336
|
+
keys = list(ex.map(put, parts))
|
|
337
|
+
return Entry._from(self._req("POST", "commit", {"path": path, "ifVersion": if_version},
|
|
338
|
+
json={"size": size, "chunks": keys}).json())
|
|
339
|
+
|
|
340
|
+
def upload(self, src: Union[str, Path], path: str, if_version: Optional[int] = None) -> Entry:
|
|
341
|
+
"""Copy a local file to the drive, in 4 MB parts for big files."""
|
|
342
|
+
src = Path(src)
|
|
343
|
+
size = src.stat().st_size
|
|
344
|
+
if size <= SMALL:
|
|
345
|
+
return self.write(path, src.read_bytes(), if_version)
|
|
346
|
+
|
|
347
|
+
def parts() -> Iterator[bytes]:
|
|
348
|
+
with open(src, "rb") as f:
|
|
349
|
+
while True:
|
|
350
|
+
b = f.read(CHUNK)
|
|
351
|
+
if not b:
|
|
352
|
+
return
|
|
353
|
+
yield b
|
|
354
|
+
|
|
355
|
+
return self._commit_chunks(_norm(path), size, parts(), if_version)
|
|
356
|
+
|
|
357
|
+
def safe_write(self, path: str, data: Union[bytes, str], expected_version: int) -> Entry:
|
|
358
|
+
"""Save only if the file is still at expected_version (0 = must not exist). Raises Conflict if not."""
|
|
359
|
+
return self.write(path, data, if_version=expected_version)
|
|
360
|
+
|
|
361
|
+
def update(self, path: str, change: Callable[[str], str], retries: int = 50, create: bool = True,
|
|
362
|
+
encoding: str = "utf-8") -> Entry:
|
|
363
|
+
"""Read-modify-write with safe writes: read the file, apply `change` to its text, save only if
|
|
364
|
+
nobody saved in between, and on a conflict read again and retry. `change` must be safe to call
|
|
365
|
+
more than once. A missing file starts as "" when create is True."""
|
|
366
|
+
path = _norm(path)
|
|
367
|
+
for attempt in range(retries):
|
|
368
|
+
try:
|
|
369
|
+
text, version = self.read_text(path, encoding, with_version=True)
|
|
370
|
+
except NotFound:
|
|
371
|
+
if not create:
|
|
372
|
+
raise
|
|
373
|
+
text, version = "", 0
|
|
374
|
+
try:
|
|
375
|
+
return self.write(path, change(text).encode(encoding), if_version=version)
|
|
376
|
+
except Conflict:
|
|
377
|
+
time.sleep(min(0.05 * (attempt + 1), 0.5) * (0.5 + random.random()))
|
|
378
|
+
raise Conflict(f"{path}: still changing after {retries} tries", 409, "ECONFLICT", {})
|
|
379
|
+
|
|
380
|
+
def append(self, path: str, text: str, **kw) -> Entry:
|
|
381
|
+
"""Append text to a file with safe writes (no other writer's change is lost)."""
|
|
382
|
+
return self.update(path, lambda old: old + text, **kw)
|
|
383
|
+
|
|
384
|
+
def mkdir(self, path: str, parents: bool = False) -> None:
|
|
385
|
+
parts = [p for p in _norm(path).split("/") if p]
|
|
386
|
+
start = 1 if parents else len(parts)
|
|
387
|
+
for i in range(start, len(parts) + 1):
|
|
388
|
+
p = "/" + "/".join(parts[:i])
|
|
389
|
+
try:
|
|
390
|
+
self._req("POST", "mkdir", {"path": p})
|
|
391
|
+
except Conflict:
|
|
392
|
+
if not parents or self.stat(p).kind != "dir":
|
|
393
|
+
raise
|
|
394
|
+
|
|
395
|
+
def move(self, src: str, dst: str) -> Entry:
|
|
396
|
+
"""Move or rename a file or folder in one atomic step. Replaces an existing file at dst."""
|
|
397
|
+
return Entry._from(self._req("POST", "mv", {"path": _norm(src), "to": _norm(dst)}).json())
|
|
398
|
+
|
|
399
|
+
def delete(self, path: str, recursive: bool = False, if_version: Optional[int] = None) -> None:
|
|
400
|
+
"""Delete a file or link, or an empty folder (or a whole tree with recursive=True)."""
|
|
401
|
+
path = _norm(path)
|
|
402
|
+
try:
|
|
403
|
+
self._req("POST", "rm", {"path": path, "ifVersion": if_version})
|
|
404
|
+
return
|
|
405
|
+
except RemoteSSDError as e:
|
|
406
|
+
if e.errno != "EISDIR":
|
|
407
|
+
raise
|
|
408
|
+
if recursive:
|
|
409
|
+
for e in self.list(path):
|
|
410
|
+
self.delete(e.path, recursive=True)
|
|
411
|
+
self._req("POST", "rmdir", {"path": path})
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: remotessd
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python client for remoteSSD, a shared drive for people and AI agents
|
|
5
|
+
Project-URL: Homepage, https://remotessd.com
|
|
6
|
+
Project-URL: Documentation, https://remotessd.com/join.txt
|
|
7
|
+
Keywords: remotessd,drive,storage,agents,sdk
|
|
8
|
+
Classifier: Development Status :: 4 - Beta
|
|
9
|
+
Classifier: Intended Audience :: Developers
|
|
10
|
+
Classifier: License :: Other/Proprietary License
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
14
|
+
Classifier: Topic :: System :: Filesystems
|
|
15
|
+
Requires-Python: >=3.9
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
Requires-Dist: httpx>=0.25
|
|
18
|
+
|
|
19
|
+
# remotessd
|
|
20
|
+
|
|
21
|
+
Python client for [remoteSSD](https://remotessd.com), a shared drive for people and AI agents.
|
|
22
|
+
Python 3.9 or later; the only dependency is [httpx](https://www.python-httpx.org/).
|
|
23
|
+
|
|
24
|
+
AI agents setting up a drive for someone: follow https://remotessd.com/join.txt.
|
|
25
|
+
|
|
26
|
+
## Install
|
|
27
|
+
|
|
28
|
+
```sh
|
|
29
|
+
pip install remotessd
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Connect with an agent key
|
|
33
|
+
|
|
34
|
+
Every request is authenticated with a key, sent as `Authorization: Bearer <key>`. Use an agent key
|
|
35
|
+
(`rssd_...`), made in the remoteSSD app or with `POST /api/keys`. An agent key can be limited to one
|
|
36
|
+
folder, made read-only and set to expire.
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
from remotessd import Drive
|
|
40
|
+
|
|
41
|
+
d = Drive(key="rssd_...")
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
`Drive()` with no arguments reads the same environment variables as the `remotessd` command-line
|
|
45
|
+
client:
|
|
46
|
+
|
|
47
|
+
| Variable | Default | Meaning |
|
|
48
|
+
| --- | --- | --- |
|
|
49
|
+
| `REMOTESSD_KEY` | (required) | The agent key. |
|
|
50
|
+
| `REMOTESSD_URL` | `https://app.remotessd.com` | The drive service. Set it to use your own deployment. |
|
|
51
|
+
| `REMOTESSD_DRIVE` | `-` | The drive name. `-` means the drive the key belongs to. |
|
|
52
|
+
|
|
53
|
+
Arguments win over environment variables: `Drive(url=..., key=..., drive=..., timeout=60.0)`. A
|
|
54
|
+
`Drive` holds an HTTP connection pool; close it with `d.close()` or use it as a context manager:
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
with Drive() as d:
|
|
58
|
+
print([e.name for e in d.list("/")])
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Reading
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
for e in d.list("/docs"): # Entry: path, name, kind ("file", "dir", "link"), size, version, mode, mtime
|
|
65
|
+
print(e.name, e.kind, e.size, e.version)
|
|
66
|
+
|
|
67
|
+
d.stat("/docs/a.txt") # one Entry; raises NotFound if missing
|
|
68
|
+
d.exists("/docs/a.txt") # True or False
|
|
69
|
+
|
|
70
|
+
data = d.read("/docs/a.txt") # bytes
|
|
71
|
+
part = d.read("/docs/a.txt", offset=100, length=50)
|
|
72
|
+
text, version = d.read_text("/docs/a.txt", with_version=True)
|
|
73
|
+
|
|
74
|
+
d.download("/isos/big.iso", "big.iso") # streamed to disk in 4 MB parts
|
|
75
|
+
for hit in d.search("TODO", path="/src"): # by name, and by text in files up to 64 KB
|
|
76
|
+
print(hit.path, hit.match, hit.lines)
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## Writing
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
d.write("/notes.md", "hello\n") # create or replace; str, bytes or a binary file object
|
|
83
|
+
d.upload("big.iso", "/isos/big.iso") # big files go up in 4 MB parts and appear all at once
|
|
84
|
+
d.mkdir("/a/b/c", parents=True)
|
|
85
|
+
d.move("/a/b", "/a/renamed") # atomic move or rename
|
|
86
|
+
d.delete("/a", recursive=True)
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
A plain `write` is last-save-wins. Each file has a `version` that goes up by one on every save, so
|
|
90
|
+
several agents can share a file without losing each other's changes.
|
|
91
|
+
|
|
92
|
+
### Safe writes
|
|
93
|
+
|
|
94
|
+
`safe_write` saves only if the file is still at the version you read. Otherwise it raises `Conflict`
|
|
95
|
+
and writes nothing; read again, redo the change and retry. Version `0` means "only if the file does not
|
|
96
|
+
exist".
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
from remotessd import Conflict
|
|
100
|
+
|
|
101
|
+
while True:
|
|
102
|
+
text, version = d.read_text("/shared/todo.md", with_version=True)
|
|
103
|
+
try:
|
|
104
|
+
d.safe_write("/shared/todo.md", text + "- new item\n", version)
|
|
105
|
+
break
|
|
106
|
+
except Conflict as e:
|
|
107
|
+
print("someone saved first; now at version", e.current_version)
|
|
108
|
+
|
|
109
|
+
d.safe_write("/shared/new.md", "first\n", 0) # create only, Conflict if it already exists
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
`update` and `append` run that loop for you:
|
|
113
|
+
|
|
114
|
+
```python
|
|
115
|
+
d.update("/shared/todo.md", lambda text: text.replace("[ ]", "[x]", 1))
|
|
116
|
+
d.append("/shared/log.md", "one more line\n")
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
The function passed to `update` may be called more than once, so it should only compute the new text.
|
|
120
|
+
|
|
121
|
+
## Versions and restore
|
|
122
|
+
|
|
123
|
+
Every saved version of every file is kept for 30 days after it stops being current, including deleted
|
|
124
|
+
files.
|
|
125
|
+
|
|
126
|
+
```python
|
|
127
|
+
h = d.versions("/notes.md") # {"current", "versions": [...], "next"}, newest first
|
|
128
|
+
for v in h["versions"]:
|
|
129
|
+
print(v["vid"], v["version"], v["saved"], v["size"], v["byName"], v["how"])
|
|
130
|
+
older = d.versions("/notes.md", before=h["next"]) # next page
|
|
131
|
+
|
|
132
|
+
old = d.read_version("/notes.md", version=3) # or vid=...
|
|
133
|
+
d.revert("/notes.md", h["versions"][1]["vid"]) # the old content becomes a new version
|
|
134
|
+
d.revert("/notes.md", vid, if_version=h["current"]["version"]) # safe: Conflict if it changed
|
|
135
|
+
|
|
136
|
+
for f in d.deleted("/docs"): # files deleted in the last 30 days that don't exist now
|
|
137
|
+
d.undelete(f["path"]) # brings back the last content; Conflict if a file is there now
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
## Errors
|
|
141
|
+
|
|
142
|
+
Every error is a subclass of `RemoteSSDError`, which carries `.status` (HTTP status), `.errno` (for
|
|
143
|
+
example `ECONFLICT`, `EEXIST`, `ENOTEMPTY`) and `.body` (the JSON response).
|
|
144
|
+
|
|
145
|
+
| Exception | When |
|
|
146
|
+
| --- | --- |
|
|
147
|
+
| `NotFound` | The path, or the old version asked for, doesn't exist. |
|
|
148
|
+
| `Conflict` | A safe write or safe delete was refused, the file already exists, or a folder isn't empty. `.current_version` is the file's version now, when known. |
|
|
149
|
+
| `AuthError` | The key is wrong, expired, or not allowed to do this (HTTP 401 or 403). |
|
|
150
|
+
| `QuotaExceeded` | The request limit was reached (HTTP 429). |
|
|
151
|
+
| `ServerError` | A network error or a 5xx response. Reads are retried twice before this is raised. |
|
|
152
|
+
|
|
153
|
+
`Drive()` raises `ValueError` when no key is given.
|
|
154
|
+
|
|
155
|
+
## Links
|
|
156
|
+
|
|
157
|
+
- Website: https://remotessd.com
|
|
158
|
+
- Agent setup: https://remotessd.com/join.txt
|
|
159
|
+
- Command-line client: `npm install -g remotessd`
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
remotessd/__init__.py,sha256=m0WZ5URNSP6034bx6Jo8QecrKtdrx6Fup3LZHy48CIM,18486
|
|
2
|
+
remotessd-0.1.0.dist-info/METADATA,sha256=NTBOKK_cj_DTowkRaZKJyBkE1CNbsnv0NnQiG6RAY2A,5971
|
|
3
|
+
remotessd-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
4
|
+
remotessd-0.1.0.dist-info/top_level.txt,sha256=2GlH7vLuIAWltvrRNhY0ByeRcH-pCUhNsVK1bDp5gQU,10
|
|
5
|
+
remotessd-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
remotessd
|