synrag 1.16.1__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.
- synrag/__init__.py +286 -0
- synrag/connectors/__init__.py +137 -0
- synrag/connectors/_http.py +64 -0
- synrag/connectors/confluence.py +86 -0
- synrag/connectors/google.py +83 -0
- synrag/connectors/local.py +92 -0
- synrag/connectors/microsoft.py +89 -0
- synrag/connectors/s3.py +114 -0
- synrag/mcp.py +220 -0
- synrag-1.16.1.dist-info/METADATA +54 -0
- synrag-1.16.1.dist-info/RECORD +16 -0
- synrag-1.16.1.dist-info/WHEEL +5 -0
- synrag-1.16.1.dist-info/entry_points.txt +2 -0
- synrag-1.16.1.dist-info/licenses/LICENSE +202 -0
- synrag-1.16.1.dist-info/licenses/NOTICE +9 -0
- synrag-1.16.1.dist-info/top_level.txt +1 -0
synrag/__init__.py
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
"""Python client for synrag (no dependencies).
|
|
2
|
+
|
|
3
|
+
from synrag import Server
|
|
4
|
+
with Server("docs.syn", build_from=["./docs"]) as rag: # starts `synrag serve`, builds the index if missing
|
|
5
|
+
ctx = rag.context("how do refunds work?", budget=800) # compressed context with [n] citations
|
|
6
|
+
print(ctx.text, ctx.sources)
|
|
7
|
+
rag.add([{"source": "faq.md", "title": "FAQ", "text": "..."}]) # live update, journaled
|
|
8
|
+
|
|
9
|
+
Or connect to a running server: `Client("http://127.0.0.1:7878")`.
|
|
10
|
+
For agents: `rag.tool()` gives an OpenAI-style function definition and `rag.call_tool(arguments)` runs it.
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import os
|
|
16
|
+
import shutil
|
|
17
|
+
import socket
|
|
18
|
+
import subprocess
|
|
19
|
+
import tempfile
|
|
20
|
+
import time
|
|
21
|
+
import urllib.error
|
|
22
|
+
import urllib.parse
|
|
23
|
+
import urllib.request
|
|
24
|
+
from dataclasses import dataclass, field
|
|
25
|
+
from typing import Any, Dict, Iterable, List, Optional, Sequence
|
|
26
|
+
|
|
27
|
+
__all__ = ["Client", "Server", "Hit", "Source", "Context", "SynragError"]
|
|
28
|
+
__version__ = "1.16.1"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class SynragError(RuntimeError):
|
|
32
|
+
pass
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass
|
|
36
|
+
class Hit:
|
|
37
|
+
rank: int
|
|
38
|
+
score: float
|
|
39
|
+
source: str
|
|
40
|
+
title: str
|
|
41
|
+
heading: str
|
|
42
|
+
page: int
|
|
43
|
+
text: str
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass
|
|
47
|
+
class Source:
|
|
48
|
+
cite: int
|
|
49
|
+
source: str
|
|
50
|
+
title: str
|
|
51
|
+
heading: str
|
|
52
|
+
page: int
|
|
53
|
+
score: float
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass
|
|
57
|
+
class Context:
|
|
58
|
+
text: str
|
|
59
|
+
tokens: int
|
|
60
|
+
source_tokens: int
|
|
61
|
+
sources: List[Source] = field(default_factory=list)
|
|
62
|
+
took_ms: float = 0.0
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class Client:
|
|
66
|
+
"""HTTP client for `synrag serve`."""
|
|
67
|
+
|
|
68
|
+
def __init__(self, url: str = "http://127.0.0.1:7878", timeout: float = 60.0, *,
|
|
69
|
+
api_key: Optional[str] = None, collection: Optional[str] = None):
|
|
70
|
+
"""`api_key`: an API key or an SSO token (sent as `Authorization: Bearer`).
|
|
71
|
+
`collection`: work in this collection (`/c/<name>/...`); None = the server's `default`."""
|
|
72
|
+
self.url = url.rstrip("/")
|
|
73
|
+
self.timeout = timeout
|
|
74
|
+
self.api_key = api_key
|
|
75
|
+
self.collection = collection
|
|
76
|
+
|
|
77
|
+
def using(self, collection: str) -> "Client":
|
|
78
|
+
"""A client for another collection on the same server (same credentials)."""
|
|
79
|
+
return Client(self.url, self.timeout, api_key=self.api_key, collection=collection)
|
|
80
|
+
|
|
81
|
+
# -- transport --
|
|
82
|
+
def _headers(self, extra: Optional[Dict[str, str]] = None) -> Dict[str, str]:
|
|
83
|
+
h = dict(extra or {})
|
|
84
|
+
if self.api_key:
|
|
85
|
+
h["Authorization"] = f"Bearer {self.api_key}"
|
|
86
|
+
return h
|
|
87
|
+
|
|
88
|
+
def _p(self, op: str) -> str:
|
|
89
|
+
return f"/c/{urllib.parse.quote(self.collection)}/{op}" if self.collection else f"/{op}"
|
|
90
|
+
|
|
91
|
+
def _get(self, path: str, **params: Any) -> Dict[str, Any]:
|
|
92
|
+
q = urllib.parse.urlencode({k: v for k, v in params.items() if v is not None})
|
|
93
|
+
return self._open(urllib.request.Request(f"{self.url}{path}?{q}" if q else f"{self.url}{path}", headers=self._headers()))
|
|
94
|
+
|
|
95
|
+
def _post(self, path: str, body: Dict[str, Any], method: str = "POST") -> Dict[str, Any]:
|
|
96
|
+
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
|
97
|
+
return self._open(urllib.request.Request(f"{self.url}{path}", data=data, method=method,
|
|
98
|
+
headers=self._headers({"Content-Type": "application/json"})))
|
|
99
|
+
|
|
100
|
+
def _open(self, req: urllib.request.Request) -> Dict[str, Any]:
|
|
101
|
+
try:
|
|
102
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as f:
|
|
103
|
+
return json.loads(f.read() or b"{}")
|
|
104
|
+
except urllib.error.HTTPError as e:
|
|
105
|
+
raise SynragError(f"{e.code}: {e.read()[:300].decode('utf-8', 'replace')}") from None
|
|
106
|
+
except urllib.error.URLError as e:
|
|
107
|
+
raise SynragError(f"synrag server not reachable at {self.url}: {e.reason}") from None
|
|
108
|
+
|
|
109
|
+
# -- API --
|
|
110
|
+
def health(self) -> Dict[str, Any]:
|
|
111
|
+
return self._get("/health")
|
|
112
|
+
|
|
113
|
+
def search(self, query: str, k: int = 10) -> List[Hit]:
|
|
114
|
+
r = self._get(self._p("search"), q=query, k=k)
|
|
115
|
+
return [Hit(h["rank"], h["score"], h["source"], h["title"], h["heading"], h["page"], h["text"]) for h in r["hits"]]
|
|
116
|
+
|
|
117
|
+
def context(self, query: str, budget: int = 1500) -> Context:
|
|
118
|
+
"""Agent-ready context: the sentences that answer the query, under a token budget, with [n] citations."""
|
|
119
|
+
r = self._get(self._p("context"), q=query, budget=budget)
|
|
120
|
+
srcs = [Source(s["cite"], s["source"], s["title"], s["heading"], s["page"], s["score"]) for s in r["sources"]]
|
|
121
|
+
return Context(r["context"], r["tokens"], r["source_tokens"], srcs, r.get("took_us", 0) / 1000)
|
|
122
|
+
|
|
123
|
+
def add(self, docs: Iterable[Dict[str, Any]]) -> Dict[str, Any]:
|
|
124
|
+
"""Add or replace documents: [{"source": id, "title": ..., "text": ..., "acl": ["group:x", ...]}].
|
|
125
|
+
Same source = new version. `acl` (optional): who may see the document; none = everyone with access
|
|
126
|
+
to the collection."""
|
|
127
|
+
out = []
|
|
128
|
+
for d in docs:
|
|
129
|
+
x = {"source": d["source"], "title": d.get("title", ""), "text": d.get("text", "")}
|
|
130
|
+
if d.get("acl"):
|
|
131
|
+
x["acl"] = list(d["acl"])
|
|
132
|
+
out.append(x)
|
|
133
|
+
return self._post(self._p("add"), {"docs": out})
|
|
134
|
+
|
|
135
|
+
def upload(self, source: str, data: bytes, *, title: Optional[str] = None,
|
|
136
|
+
acl: Optional[Sequence[str]] = None) -> Dict[str, Any]:
|
|
137
|
+
"""Upload a file (PDF, DOCX, XLSX, PPTX, HTML, ...): parsed on the server. Same source = new version."""
|
|
138
|
+
q = {"source": source}
|
|
139
|
+
if title:
|
|
140
|
+
q["title"] = title
|
|
141
|
+
if acl:
|
|
142
|
+
q["acl"] = ",".join(acl)
|
|
143
|
+
url = f"{self.url}{self._p('upload')}?{urllib.parse.urlencode(q)}"
|
|
144
|
+
return self._open(urllib.request.Request(url, data=data, method="POST",
|
|
145
|
+
headers=self._headers({"Content-Type": "application/octet-stream"})))
|
|
146
|
+
|
|
147
|
+
def delete(self, sources: Sequence[str]) -> Dict[str, Any]:
|
|
148
|
+
return self._post(self._p("delete"), {"sources": list(sources)})
|
|
149
|
+
|
|
150
|
+
def save(self) -> Dict[str, Any]:
|
|
151
|
+
"""Write a snapshot of the index (and empty the update journal)."""
|
|
152
|
+
return self._post(self._p("save"), {})
|
|
153
|
+
|
|
154
|
+
# -- collections (server started with --data <dir>) --
|
|
155
|
+
def collections(self) -> List[Dict[str, Any]]:
|
|
156
|
+
return self._get("/collections")["collections"]
|
|
157
|
+
|
|
158
|
+
def create_collection(self, name: str) -> Dict[str, Any]:
|
|
159
|
+
return self._post(f"/collections/{urllib.parse.quote(name)}", {})
|
|
160
|
+
|
|
161
|
+
def drop_collection(self, name: str) -> Dict[str, Any]:
|
|
162
|
+
return self._post(f"/collections/{urllib.parse.quote(name)}", {}, method="DELETE")
|
|
163
|
+
|
|
164
|
+
# -- agents --
|
|
165
|
+
def tool(self, name: str = "search_documents", description: Optional[str] = None) -> Dict[str, Any]:
|
|
166
|
+
"""OpenAI / OpenAI-compatible function-calling definition of the search tool."""
|
|
167
|
+
return {
|
|
168
|
+
"type": "function",
|
|
169
|
+
"function": {
|
|
170
|
+
"name": name,
|
|
171
|
+
"description": description or "Search the document collection and return the passages that answer the "
|
|
172
|
+
"question, with numbered citations [n]. Use it before answering questions about the documents.",
|
|
173
|
+
"parameters": {
|
|
174
|
+
"type": "object",
|
|
175
|
+
"properties": {
|
|
176
|
+
"query": {"type": "string", "description": "What to look for, in the user's language."},
|
|
177
|
+
"budget": {"type": "integer", "description": "Maximum tokens of context to return (default 800)."},
|
|
178
|
+
},
|
|
179
|
+
"required": ["query"],
|
|
180
|
+
},
|
|
181
|
+
},
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
def call_tool(self, arguments: Any, default_budget: int = 800) -> str:
|
|
185
|
+
"""Run the tool for an agent: arguments as dict or JSON string → context text with a source list."""
|
|
186
|
+
if isinstance(arguments, str):
|
|
187
|
+
arguments = json.loads(arguments or "{}")
|
|
188
|
+
ctx = self.context(str(arguments.get("query", "")), int(arguments.get("budget") or default_budget))
|
|
189
|
+
if not ctx.text.strip():
|
|
190
|
+
return "No relevant passages found."
|
|
191
|
+
refs = "\n".join(f"[{s.cite}] {s.title or s.source}" + (f" — {s.heading}" if s.heading else "") +
|
|
192
|
+
(f" (p. {s.page})" if s.page else "") for s in ctx.sources)
|
|
193
|
+
return f"{ctx.text}\n\nSources:\n{refs}"
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _installed(kind: str, name: str) -> Optional[str]:
|
|
197
|
+
"""A file put in place by the installer (curl -fsSL https://ai.synlabs.pro/install.sh | sh): the binary in
|
|
198
|
+
$SYNRAG_PREFIX/bin or ~/.local/bin, the models in ~/.synrag/models — found even when that is not on PATH
|
|
199
|
+
(MCP clients often start servers with a minimal environment)."""
|
|
200
|
+
if kind == "bin":
|
|
201
|
+
dirs = [os.path.join(os.environ.get("SYNRAG_PREFIX", ""), "bin"), os.path.expanduser("~/.local/bin")]
|
|
202
|
+
else:
|
|
203
|
+
dirs = [os.environ.get("SYNRAG_MODELS", ""), os.path.expanduser("~/.synrag/models")]
|
|
204
|
+
for d in dirs:
|
|
205
|
+
p = os.path.join(d, name) if d else ""
|
|
206
|
+
if p and os.path.exists(p):
|
|
207
|
+
return p
|
|
208
|
+
return None
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def default_student() -> Optional[str]:
|
|
212
|
+
"""The Synapse model installed by the installer, if any."""
|
|
213
|
+
return _installed("models", "synapse.synm")
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _free_port() -> int:
|
|
217
|
+
with socket.socket() as s:
|
|
218
|
+
s.bind(("127.0.0.1", 0))
|
|
219
|
+
return s.getsockname()[1]
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
class Server(Client):
|
|
223
|
+
"""Runs a local `synrag serve` process (the single binary) and connects to it.
|
|
224
|
+
|
|
225
|
+
index: path of the index file (created from `build_from` if it does not exist)
|
|
226
|
+
build_from: files / directories to index (PDF, Office, HTML, Markdown, CSV, JSON, ZIP, text)
|
|
227
|
+
student: Synapse model file (multilingual semantic channel); rerank: reranker head (needs student)
|
|
228
|
+
"""
|
|
229
|
+
|
|
230
|
+
def __init__(self, index: str, build_from: Optional[Sequence[str]] = None, *, binary: Optional[str] = None,
|
|
231
|
+
student: Optional[str] = None, rerank: Optional[str] = None, port: Optional[int] = None,
|
|
232
|
+
extra_args: Sequence[str] = (), startup_timeout: float = 120.0):
|
|
233
|
+
self.binary = binary or os.environ.get("SYNRAG_BIN") or shutil.which("synrag") or _installed("bin", "synrag") or "synrag"
|
|
234
|
+
self.index = index
|
|
235
|
+
if not os.path.exists(index):
|
|
236
|
+
src = list(build_from or [])
|
|
237
|
+
tmp = None
|
|
238
|
+
if not src: # start with an empty collection
|
|
239
|
+
tmp = tempfile.mkdtemp(prefix="synrag-empty-")
|
|
240
|
+
src = [tmp]
|
|
241
|
+
subprocess.run([self.binary, "index", *src, "-o", index], check=True, stdout=subprocess.DEVNULL)
|
|
242
|
+
if tmp:
|
|
243
|
+
shutil.rmtree(tmp, ignore_errors=True)
|
|
244
|
+
self.port = port or _free_port()
|
|
245
|
+
args = [self.binary, "serve", index, "--port", str(self.port)]
|
|
246
|
+
if student:
|
|
247
|
+
args += ["--student", student]
|
|
248
|
+
if rerank:
|
|
249
|
+
args += ["--rerank", rerank]
|
|
250
|
+
args += list(extra_args)
|
|
251
|
+
# server log to a temp file (a pipe nobody reads could fill up and block the server)
|
|
252
|
+
self._log = tempfile.TemporaryFile()
|
|
253
|
+
self.proc = subprocess.Popen(args, stdout=subprocess.DEVNULL, stderr=self._log)
|
|
254
|
+
super().__init__(f"http://127.0.0.1:{self.port}")
|
|
255
|
+
t0 = time.time()
|
|
256
|
+
while True:
|
|
257
|
+
if self.proc.poll() is not None:
|
|
258
|
+
self._log.seek(0)
|
|
259
|
+
msg = self._log.read().decode("utf-8", "replace")[-500:]
|
|
260
|
+
self._log.close()
|
|
261
|
+
raise SynragError(f"synrag serve exited: {msg}")
|
|
262
|
+
try:
|
|
263
|
+
self.health()
|
|
264
|
+
break
|
|
265
|
+
except SynragError:
|
|
266
|
+
if time.time() - t0 > startup_timeout:
|
|
267
|
+
self.close()
|
|
268
|
+
raise
|
|
269
|
+
time.sleep(0.05)
|
|
270
|
+
|
|
271
|
+
def close(self) -> None:
|
|
272
|
+
if self.proc.poll() is None:
|
|
273
|
+
self.proc.terminate()
|
|
274
|
+
try:
|
|
275
|
+
self.proc.wait(10)
|
|
276
|
+
except subprocess.TimeoutExpired:
|
|
277
|
+
self.proc.kill()
|
|
278
|
+
self.proc.wait()
|
|
279
|
+
if not self._log.closed:
|
|
280
|
+
self._log.close()
|
|
281
|
+
|
|
282
|
+
def __enter__(self) -> "Server":
|
|
283
|
+
return self
|
|
284
|
+
|
|
285
|
+
def __exit__(self, *exc: Any) -> None:
|
|
286
|
+
self.close()
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""Connectors: keep a synrag collection in sync with an external source (standard library only).
|
|
2
|
+
|
|
3
|
+
Every connector lists the source's items with a version (ETag, modification time, version number) and
|
|
4
|
+
their access list; `sync()` uploads new and changed items, deletes the ones that disappeared, and remembers
|
|
5
|
+
versions in a small JSON state file, so repeated runs only move what changed. Run it from cron / a
|
|
6
|
+
Kubernetes CronJob / an Airflow task.
|
|
7
|
+
|
|
8
|
+
from synrag import Client
|
|
9
|
+
from synrag.connectors import sync
|
|
10
|
+
from synrag.connectors.s3 import S3Connector
|
|
11
|
+
c = Client("http://synrag:7878", api_key="sk_...", collection="kb")
|
|
12
|
+
print(sync(S3Connector("docs-bucket", prefix="policies/", region="eu-central-1"), c, "s3_state.json"))
|
|
13
|
+
|
|
14
|
+
Document ACLs: connectors map the source's permissions to principals (`user:<id>`, `group:<id>`) that match
|
|
15
|
+
the claims of the company's SSO tokens (see the server's --jwt-groups-claim / --jwt-user-claim).
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import json
|
|
21
|
+
import os
|
|
22
|
+
import time
|
|
23
|
+
from dataclasses import dataclass, field
|
|
24
|
+
from typing import Callable, Iterator, List, Optional
|
|
25
|
+
|
|
26
|
+
__all__ = ["Item", "Connector", "SyncReport", "sync"]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class Item:
|
|
31
|
+
"""One document of a source."""
|
|
32
|
+
|
|
33
|
+
source: str
|
|
34
|
+
"""stable id; keep the file extension in it (format detection), e.g. s3://bucket/a/report.pdf"""
|
|
35
|
+
version: str
|
|
36
|
+
"""changes whenever the content (or ACL) changes"""
|
|
37
|
+
title: str = ""
|
|
38
|
+
acl: Optional[List[str]] = None
|
|
39
|
+
"""principals allowed to see it; None = everyone with access to the collection"""
|
|
40
|
+
fetch: Optional[Callable[[], bytes]] = None
|
|
41
|
+
"""lazy download of the file bytes (parsed by the server: PDF, DOCX, HTML, ...)"""
|
|
42
|
+
text: Optional[str] = None
|
|
43
|
+
"""or the text itself (database rows, wiki pages already in text form)"""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class Connector:
|
|
47
|
+
name = "connector"
|
|
48
|
+
|
|
49
|
+
def items(self) -> Iterator[Item]: # pragma: no cover - interface
|
|
50
|
+
raise NotImplementedError
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass
|
|
54
|
+
class SyncReport:
|
|
55
|
+
seen: int = 0
|
|
56
|
+
added: int = 0
|
|
57
|
+
updated: int = 0
|
|
58
|
+
unchanged: int = 0
|
|
59
|
+
deleted: int = 0
|
|
60
|
+
failed: List[str] = field(default_factory=list)
|
|
61
|
+
seconds: float = 0.0
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _load(path: str) -> dict:
|
|
65
|
+
try:
|
|
66
|
+
with open(path, encoding="utf-8") as f:
|
|
67
|
+
return json.load(f)
|
|
68
|
+
except FileNotFoundError:
|
|
69
|
+
return {}
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _save(path: str, state: dict) -> None:
|
|
73
|
+
tmp = path + ".tmp"
|
|
74
|
+
with open(tmp, "w", encoding="utf-8") as f:
|
|
75
|
+
json.dump(state, f)
|
|
76
|
+
os.replace(tmp, path)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def sync(connector: Connector, client, state_path: str, *, delete_missing: bool = True,
|
|
80
|
+
batch: int = 100, save_every: int = 200) -> SyncReport:
|
|
81
|
+
"""Bring `client`'s collection in line with the connector's items. Idempotent; safe to rerun after a crash."""
|
|
82
|
+
t0 = time.time()
|
|
83
|
+
state = _load(state_path)
|
|
84
|
+
versions = state.get("versions", {})
|
|
85
|
+
rep = SyncReport()
|
|
86
|
+
seen = set()
|
|
87
|
+
pending_text: List[dict] = []
|
|
88
|
+
pending_versions: dict = {}
|
|
89
|
+
|
|
90
|
+
def flush():
|
|
91
|
+
if pending_text:
|
|
92
|
+
client.add(pending_text)
|
|
93
|
+
versions.update(pending_versions)
|
|
94
|
+
pending_text.clear()
|
|
95
|
+
pending_versions.clear()
|
|
96
|
+
|
|
97
|
+
for it in connector.items():
|
|
98
|
+
rep.seen += 1
|
|
99
|
+
seen.add(it.source)
|
|
100
|
+
ver = it.version + "|" + ",".join(sorted(it.acl or []))
|
|
101
|
+
if versions.get(it.source) == ver:
|
|
102
|
+
rep.unchanged += 1
|
|
103
|
+
continue
|
|
104
|
+
is_new = it.source not in versions
|
|
105
|
+
try:
|
|
106
|
+
if it.text is not None:
|
|
107
|
+
pending_text.append({"source": it.source, "title": it.title, "text": it.text, "acl": it.acl or []})
|
|
108
|
+
pending_versions[it.source] = ver
|
|
109
|
+
if len(pending_text) >= batch:
|
|
110
|
+
flush()
|
|
111
|
+
else:
|
|
112
|
+
data = it.fetch() if it.fetch else b""
|
|
113
|
+
if not data:
|
|
114
|
+
raise ValueError("empty content")
|
|
115
|
+
client.upload(it.source, data, title=it.title or None, acl=it.acl)
|
|
116
|
+
versions[it.source] = ver
|
|
117
|
+
if is_new:
|
|
118
|
+
rep.added += 1
|
|
119
|
+
else:
|
|
120
|
+
rep.updated += 1
|
|
121
|
+
except Exception as e: # keep going; the item is retried on the next run
|
|
122
|
+
rep.failed.append(f"{it.source}: {e}")
|
|
123
|
+
if (rep.added + rep.updated) % save_every == 0:
|
|
124
|
+
flush()
|
|
125
|
+
_save(state_path, {"versions": versions, "connector": connector.name})
|
|
126
|
+
flush()
|
|
127
|
+
if delete_missing:
|
|
128
|
+
gone = [s for s in versions if s not in seen]
|
|
129
|
+
for i in range(0, len(gone), batch):
|
|
130
|
+
part = gone[i:i + batch]
|
|
131
|
+
client.delete(part)
|
|
132
|
+
for s in part:
|
|
133
|
+
versions.pop(s, None)
|
|
134
|
+
rep.deleted += len(part)
|
|
135
|
+
_save(state_path, {"versions": versions, "connector": connector.name, "synced_at": int(time.time())})
|
|
136
|
+
rep.seconds = round(time.time() - t0, 3)
|
|
137
|
+
return rep
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Small HTTP helpers for connectors (urllib, retries with backoff on 429 / 5xx)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import time
|
|
7
|
+
import urllib.error
|
|
8
|
+
import urllib.parse
|
|
9
|
+
import urllib.request
|
|
10
|
+
from typing import Any, Dict, Optional, Tuple
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class HTTPFailure(RuntimeError):
|
|
14
|
+
pass
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def request(url: str, *, method: str = "GET", headers: Optional[Dict[str, str]] = None, data: Optional[bytes] = None,
|
|
18
|
+
timeout: float = 60.0, retries: int = 4) -> Tuple[int, Dict[str, str], bytes]:
|
|
19
|
+
last: Any = None
|
|
20
|
+
for attempt in range(retries + 1):
|
|
21
|
+
req = urllib.request.Request(url, data=data, method=method, headers=headers or {})
|
|
22
|
+
try:
|
|
23
|
+
with urllib.request.urlopen(req, timeout=timeout) as f:
|
|
24
|
+
return f.status, dict(f.headers), f.read()
|
|
25
|
+
except urllib.error.HTTPError as e:
|
|
26
|
+
body = e.read()
|
|
27
|
+
if e.code in (429, 500, 502, 503, 504) and attempt < retries:
|
|
28
|
+
wait = float(e.headers.get("Retry-After", "0") or 0) or min(30.0, 0.5 * 2 ** attempt)
|
|
29
|
+
time.sleep(wait)
|
|
30
|
+
last = e
|
|
31
|
+
continue
|
|
32
|
+
raise HTTPFailure(f"{method} {url}: {e.code} {body[:300].decode('utf-8', 'replace')}") from None
|
|
33
|
+
except urllib.error.URLError as e:
|
|
34
|
+
if attempt < retries:
|
|
35
|
+
time.sleep(min(30.0, 0.5 * 2 ** attempt))
|
|
36
|
+
last = e
|
|
37
|
+
continue
|
|
38
|
+
raise HTTPFailure(f"{method} {url}: {e.reason}") from None
|
|
39
|
+
raise HTTPFailure(f"{method} {url}: {last}")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def get_json(url: str, headers: Optional[Dict[str, str]] = None, **kw: Any) -> Any:
|
|
43
|
+
return json.loads(request(url, headers=headers, **kw)[2] or b"null")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def post_form(url: str, form: Dict[str, str], headers: Optional[Dict[str, str]] = None) -> Any:
|
|
47
|
+
h = {"Content-Type": "application/x-www-form-urlencoded", **(headers or {})}
|
|
48
|
+
return json.loads(request(url, method="POST", headers=h, data=urllib.parse.urlencode(form).encode())[2])
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class OAuthToken:
|
|
52
|
+
"""Caches an OAuth2 access token and refreshes it shortly before expiry."""
|
|
53
|
+
|
|
54
|
+
def __init__(self, fetch):
|
|
55
|
+
self._fetch = fetch
|
|
56
|
+
self._tok: Optional[str] = None
|
|
57
|
+
self._exp = 0.0
|
|
58
|
+
|
|
59
|
+
def __call__(self) -> str:
|
|
60
|
+
if not self._tok or time.time() > self._exp - 60:
|
|
61
|
+
r = self._fetch()
|
|
62
|
+
self._tok = r["access_token"]
|
|
63
|
+
self._exp = time.time() + float(r.get("expires_in", 3600))
|
|
64
|
+
return self._tok
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""Atlassian Confluence (Cloud: e-mail + API token; Data Center / Server: personal access token)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import urllib.parse
|
|
7
|
+
from typing import Dict, Iterator, List, Optional, Sequence
|
|
8
|
+
|
|
9
|
+
from . import Connector, Item
|
|
10
|
+
from ._http import get_json
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class ConfluenceConnector(Connector):
|
|
14
|
+
"""Pages (and optionally blog posts) of the given spaces, with their read restrictions as ACLs.
|
|
15
|
+
|
|
16
|
+
ACL mapping: page read restrictions → `group:<group name>` / `user:<accountId or username>`. A page
|
|
17
|
+
without its own restrictions gets `space_acl` (None = visible to everyone with access to the collection).
|
|
18
|
+
Restrictions inherited from ancestor pages are applied when `inherit=True` (one extra request per page
|
|
19
|
+
whose ancestors are restricted)."""
|
|
20
|
+
|
|
21
|
+
name = "confluence"
|
|
22
|
+
|
|
23
|
+
def __init__(self, base_url: str, spaces: Sequence[str], *, email: Optional[str] = None, api_token: Optional[str] = None,
|
|
24
|
+
pat: Optional[str] = None, space_acl: Optional[Dict[str, List[str]]] = None, types: Sequence[str] = ("page",),
|
|
25
|
+
inherit: bool = True, page_size: int = 50):
|
|
26
|
+
self.base = base_url.rstrip("/")
|
|
27
|
+
self.spaces = list(spaces)
|
|
28
|
+
if pat:
|
|
29
|
+
self.auth = f"Bearer {pat}"
|
|
30
|
+
elif email and api_token:
|
|
31
|
+
self.auth = "Basic " + base64.b64encode(f"{email}:{api_token}".encode()).decode()
|
|
32
|
+
else:
|
|
33
|
+
raise ValueError("Confluence: give email + api_token (Cloud) or pat (Data Center)")
|
|
34
|
+
self.space_acl = space_acl or {}
|
|
35
|
+
self.types = types
|
|
36
|
+
self.inherit = inherit
|
|
37
|
+
self.page_size = page_size
|
|
38
|
+
|
|
39
|
+
def _get(self, path: str) -> dict:
|
|
40
|
+
url = path if path.startswith("http") else f"{self.base}{path}"
|
|
41
|
+
return get_json(url, headers={"Authorization": self.auth, "Accept": "application/json"})
|
|
42
|
+
|
|
43
|
+
@staticmethod
|
|
44
|
+
def _restrictions(obj: dict) -> List[str]:
|
|
45
|
+
r = ((obj.get("restrictions") or {}).get("read") or {}).get("restrictions") or {}
|
|
46
|
+
out = [f"group:{g.get('name')}" for g in (r.get("group") or {}).get("results", []) if g.get("name")]
|
|
47
|
+
for u in (r.get("user") or {}).get("results", []):
|
|
48
|
+
uid = u.get("accountId") or u.get("username") or u.get("userKey")
|
|
49
|
+
if uid:
|
|
50
|
+
out.append(f"user:{uid}")
|
|
51
|
+
return out
|
|
52
|
+
|
|
53
|
+
def _acl(self, page: dict, space: str) -> Optional[List[str]]:
|
|
54
|
+
own = self._restrictions(page)
|
|
55
|
+
if own:
|
|
56
|
+
return own
|
|
57
|
+
if self.inherit:
|
|
58
|
+
for anc in reversed(page.get("ancestors") or []):
|
|
59
|
+
a = self._get(f"/rest/api/content/{anc['id']}?expand=restrictions.read.restrictions.user,restrictions.read.restrictions.group")
|
|
60
|
+
r = self._restrictions(a)
|
|
61
|
+
if r:
|
|
62
|
+
return r
|
|
63
|
+
return self.space_acl.get(space)
|
|
64
|
+
|
|
65
|
+
def items(self) -> Iterator[Item]:
|
|
66
|
+
expand = "body.storage,version,ancestors,restrictions.read.restrictions.user,restrictions.read.restrictions.group"
|
|
67
|
+
for space in self.spaces:
|
|
68
|
+
for typ in self.types:
|
|
69
|
+
path = f"/rest/api/content?{urllib.parse.urlencode({'spaceKey': space, 'type': typ, 'limit': self.page_size, 'expand': expand})}"
|
|
70
|
+
while path:
|
|
71
|
+
r = self._get(path)
|
|
72
|
+
for p in r.get("results", []):
|
|
73
|
+
html = ((p.get("body") or {}).get("storage") or {}).get("value", "")
|
|
74
|
+
title = p.get("title", "")
|
|
75
|
+
doc = f"<html><head><title>{title}</title></head><body><h1>{title}</h1>{html}</body></html>"
|
|
76
|
+
yield Item(
|
|
77
|
+
source=f"confluence:{space}:{p['id']}.html",
|
|
78
|
+
version=str((p.get("version") or {}).get("number", "")),
|
|
79
|
+
title=title,
|
|
80
|
+
acl=self._acl(p, space),
|
|
81
|
+
fetch=lambda d=doc: d.encode("utf-8"),
|
|
82
|
+
)
|
|
83
|
+
links = r.get("_links") or {}
|
|
84
|
+
nxt = links.get("next")
|
|
85
|
+
# Cloud: base = https://<site>/wiki, next = /rest/api/content?...
|
|
86
|
+
path = f"{(links.get('base') or self.base).rstrip('/')}{nxt}" if nxt else None
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""Google Drive (OAuth refresh token of a user or of a domain-wide delegated admin).
|
|
2
|
+
|
|
3
|
+
Google Docs / Sheets / Slides are exported (HTML / CSV / plain text); other files are downloaded as is.
|
|
4
|
+
ACLs: permissions → `user:<email>`, `group:<email>`, `domain:<domain>`; "anyone" → public. Configure the
|
|
5
|
+
server with `--jwt-user-claim email` (Google ID tokens) so users match `user:<email>`; group membership must
|
|
6
|
+
come from your IdP's groups claim (e.g. Google Workspace groups mapped by Keycloak / Okta).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import urllib.parse
|
|
12
|
+
from typing import Iterator, List, Optional
|
|
13
|
+
|
|
14
|
+
from . import Connector, Item
|
|
15
|
+
from ._http import OAuthToken, get_json, post_form, request
|
|
16
|
+
|
|
17
|
+
API = "https://www.googleapis.com/drive/v3"
|
|
18
|
+
EXPORT = {
|
|
19
|
+
"application/vnd.google-apps.document": ("text/html", ".html"),
|
|
20
|
+
"application/vnd.google-apps.spreadsheet": ("text/csv", ".csv"),
|
|
21
|
+
"application/vnd.google-apps.presentation": ("text/plain", ".txt"),
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class GoogleDriveConnector(Connector):
|
|
26
|
+
name = "gdrive"
|
|
27
|
+
|
|
28
|
+
def __init__(self, client_id: str, client_secret: str, refresh_token: str, *, query: str = "trashed = false",
|
|
29
|
+
api: str = API, token_url: str = "https://oauth2.googleapis.com/token", max_bytes: int = 256 << 20):
|
|
30
|
+
self.api = api.rstrip("/")
|
|
31
|
+
self.query = query
|
|
32
|
+
self.max_bytes = max_bytes
|
|
33
|
+
self.token = OAuthToken(lambda: post_form(token_url, {
|
|
34
|
+
"grant_type": "refresh_token", "client_id": client_id, "client_secret": client_secret,
|
|
35
|
+
"refresh_token": refresh_token}))
|
|
36
|
+
|
|
37
|
+
def _h(self) -> dict:
|
|
38
|
+
return {"Authorization": f"Bearer {self.token()}"}
|
|
39
|
+
|
|
40
|
+
@staticmethod
|
|
41
|
+
def _acl(perms: list) -> Optional[List[str]]:
|
|
42
|
+
out = []
|
|
43
|
+
for p in perms or []:
|
|
44
|
+
t = p.get("type")
|
|
45
|
+
if t == "anyone":
|
|
46
|
+
return None
|
|
47
|
+
if t in ("user", "group") and p.get("emailAddress"):
|
|
48
|
+
out.append(f"{t}:{p['emailAddress'].lower()}")
|
|
49
|
+
elif t == "domain" and p.get("domain"):
|
|
50
|
+
out.append(f"domain:{p['domain'].lower()}")
|
|
51
|
+
return sorted(set(out)) or None
|
|
52
|
+
|
|
53
|
+
def items(self) -> Iterator[Item]:
|
|
54
|
+
fields = "nextPageToken,files(id,name,mimeType,modifiedTime,md5Checksum,size,permissions(type,emailAddress,domain))"
|
|
55
|
+
token = None
|
|
56
|
+
while True:
|
|
57
|
+
q = {"q": self.query, "fields": fields, "pageSize": "200", "supportsAllDrives": "true", "includeItemsFromAllDrives": "true"}
|
|
58
|
+
if token:
|
|
59
|
+
q["pageToken"] = token
|
|
60
|
+
r = get_json(f"{self.api}/files?{urllib.parse.urlencode(q)}", headers=self._h())
|
|
61
|
+
for f in r.get("files", []):
|
|
62
|
+
mt = f.get("mimeType", "")
|
|
63
|
+
if mt == "application/vnd.google-apps.folder" or (mt.startswith("application/vnd.google-apps") and mt not in EXPORT):
|
|
64
|
+
continue
|
|
65
|
+
if int(f.get("size", 0) or 0) > self.max_bytes:
|
|
66
|
+
continue
|
|
67
|
+
fid, name = f["id"], f.get("name", "")
|
|
68
|
+
if mt in EXPORT:
|
|
69
|
+
em, ext = EXPORT[mt]
|
|
70
|
+
url = f"{self.api}/files/{fid}/export?{urllib.parse.urlencode({'mimeType': em})}"
|
|
71
|
+
name = name + ext
|
|
72
|
+
else:
|
|
73
|
+
url = f"{self.api}/files/{fid}?alt=media&supportsAllDrives=true"
|
|
74
|
+
yield Item(
|
|
75
|
+
source=f"gdrive:{fid}/{name}",
|
|
76
|
+
version=f.get("md5Checksum") or f.get("modifiedTime", ""),
|
|
77
|
+
title=f.get("name", ""),
|
|
78
|
+
acl=self._acl(f.get("permissions")),
|
|
79
|
+
fetch=lambda u=url: request(u, headers=self._h())[2],
|
|
80
|
+
)
|
|
81
|
+
token = r.get("nextPageToken")
|
|
82
|
+
if not token:
|
|
83
|
+
return
|