intelligence-cloud 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.
- intelligence_cloud/__init__.py +62 -0
- intelligence_cloud/_base.py +75 -0
- intelligence_cloud/_generated.py +533 -0
- intelligence_cloud/_spec.py +334 -0
- intelligence_cloud/_version.py +1 -0
- intelligence_cloud/auth.py +142 -0
- intelligence_cloud/client.py +433 -0
- intelligence_cloud/data/spec.json +6391 -0
- intelligence_cloud/errors.py +179 -0
- intelligence_cloud/intelligence.py +292 -0
- intelligence_cloud/py.typed +0 -0
- intelligence_cloud/receiver.py +197 -0
- intelligence_cloud/resources.py +358 -0
- intelligence_cloud/workflows.py +791 -0
- intelligence_cloud-0.1.0.dist-info/METADATA +410 -0
- intelligence_cloud-0.1.0.dist-info/RECORD +18 -0
- intelligence_cloud-0.1.0.dist-info/WHEEL +4 -0
- intelligence_cloud-0.1.0.dist-info/licenses/LICENSE +22 -0
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
"""Operation registry, request checks and response projection, driven by the bundled spec data."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import re
|
|
6
|
+
import uuid
|
|
7
|
+
from datetime import date, datetime, timedelta, timezone
|
|
8
|
+
from functools import lru_cache
|
|
9
|
+
from typing import Any, Dict, List, Mapping, Optional
|
|
10
|
+
|
|
11
|
+
from .errors import InvalidRequestError
|
|
12
|
+
|
|
13
|
+
from importlib.resources import files as _files
|
|
14
|
+
|
|
15
|
+
MAX_LOCATION_IDS = 50 # longer query strings are refused before they reach the API
|
|
16
|
+
MAX_NUMBERS = 25
|
|
17
|
+
|
|
18
|
+
_RFC3339 = re.compile(
|
|
19
|
+
r"^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}:\d{2}(\.\d+)?([Zz]|[+-]\d{2}:\d{2})$"
|
|
20
|
+
)
|
|
21
|
+
_RFC3339_PARTS = re.compile(
|
|
22
|
+
r"^(\d{4})-(\d{2})-(\d{2})[Tt ](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?([Zz]|[+-]\d{2}:\d{2})$"
|
|
23
|
+
)
|
|
24
|
+
_DATE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
|
|
25
|
+
_NUMBER_OK = re.compile(r"^[A-Za-z0-9@#]+$")
|
|
26
|
+
_NUMBER_STRIP = re.compile(r"[\s+\-().]")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@lru_cache(maxsize=None)
|
|
30
|
+
def spec() -> Dict[str, Any]:
|
|
31
|
+
text = _files("intelligence_cloud").joinpath("data/spec.json").read_text(encoding="utf-8")
|
|
32
|
+
return json.loads(text)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def operation(op_id: str) -> Dict[str, Any]:
|
|
36
|
+
try:
|
|
37
|
+
return spec()["operations"][op_id]
|
|
38
|
+
except KeyError: # pragma: no cover - programming error
|
|
39
|
+
raise KeyError(f"unknown operation {op_id}") from None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
# ------------------------------------------------------------------ schema helpers
|
|
43
|
+
|
|
44
|
+
def _resolve(schema: Any) -> Any:
|
|
45
|
+
seen = 0
|
|
46
|
+
while isinstance(schema, dict) and "$ref" in schema:
|
|
47
|
+
schema = spec()["schemas"][schema["$ref"].split("/")[-1]]
|
|
48
|
+
seen += 1
|
|
49
|
+
if seen > 50: # pragma: no cover
|
|
50
|
+
break
|
|
51
|
+
return schema
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _object_props(schema: Any) -> Optional[Dict[str, Any]]:
|
|
55
|
+
"""Known properties of an object schema (merging allOf/oneOf/anyOf), or None when anything goes."""
|
|
56
|
+
schema = _resolve(schema)
|
|
57
|
+
if not isinstance(schema, dict):
|
|
58
|
+
return None
|
|
59
|
+
if schema.get("additionalProperties") is True:
|
|
60
|
+
return None
|
|
61
|
+
props: Dict[str, Any] = {}
|
|
62
|
+
found = False
|
|
63
|
+
if "properties" in schema:
|
|
64
|
+
props.update(schema["properties"])
|
|
65
|
+
found = True
|
|
66
|
+
for key in ("allOf", "oneOf", "anyOf"):
|
|
67
|
+
for part in schema.get(key, []) or []:
|
|
68
|
+
sub = _object_props(part)
|
|
69
|
+
if sub is None:
|
|
70
|
+
return None
|
|
71
|
+
found = True
|
|
72
|
+
for k, v in sub.items():
|
|
73
|
+
props.setdefault(k, v)
|
|
74
|
+
return props if found else None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _items_schema(schema: Any) -> Any:
|
|
78
|
+
schema = _resolve(schema)
|
|
79
|
+
if isinstance(schema, dict) and "items" in schema:
|
|
80
|
+
return schema["items"]
|
|
81
|
+
return None
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def project(value: Any, schema: Any) -> Any:
|
|
85
|
+
"""Drop every field the published schema does not list. Unknown shapes pass through."""
|
|
86
|
+
if schema is None or value is None:
|
|
87
|
+
return value
|
|
88
|
+
if isinstance(value, dict):
|
|
89
|
+
props = _object_props(schema)
|
|
90
|
+
if props is None:
|
|
91
|
+
return value
|
|
92
|
+
return {k: project(v, props[k]) for k, v in value.items() if k in props}
|
|
93
|
+
if isinstance(value, list):
|
|
94
|
+
items = _items_schema(schema)
|
|
95
|
+
if items is None:
|
|
96
|
+
return value
|
|
97
|
+
return [project(v, items) for v in value]
|
|
98
|
+
return value
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def response_schema(op_id: str, status: int) -> Any:
|
|
102
|
+
responses = operation(op_id)["responses"]
|
|
103
|
+
if str(status) in responses:
|
|
104
|
+
return responses[str(status)]
|
|
105
|
+
for key in sorted(responses):
|
|
106
|
+
if key.startswith("2") and responses[key] is not None:
|
|
107
|
+
return responses[key]
|
|
108
|
+
return None
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
# Inside the call detail's vcon object only the recording link and its expiry are ever passed on,
|
|
112
|
+
# whatever the schema lists.
|
|
113
|
+
RECORDING_FIELDS = ("recording_url", "recording_url_expires_at")
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
# Never passed on, even with keep_unknown_fields: one-time links and secret references (any "*_ref" field).
|
|
117
|
+
DENIED_FIELDS = frozenset({"invitation_link"})
|
|
118
|
+
# Always projected to the published schema, whatever the client option says: the signed-in user,
|
|
119
|
+
# sign-in, and every conversation-data read (calls, transcripts, alerts, tasks, insights).
|
|
120
|
+
ALWAYS_PROJECTED = frozenset({"getMe", "login", "refresh"})
|
|
121
|
+
ALWAYS_PROJECTED_NAMESPACES = frozenset({"calls", "alerts", "tasks", "insights"})
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def drop_denied(value: Any) -> Any:
|
|
125
|
+
if isinstance(value, dict):
|
|
126
|
+
return {k: drop_denied(v) for k, v in value.items()
|
|
127
|
+
if k not in DENIED_FIELDS and not str(k).endswith("_ref")}
|
|
128
|
+
if isinstance(value, list):
|
|
129
|
+
return [drop_denied(v) for v in value]
|
|
130
|
+
return value
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def project_response(op_id: str, status: int, body: Any, keep_unknown: bool = False) -> Any:
|
|
134
|
+
schema = response_schema(op_id, status)
|
|
135
|
+
if (keep_unknown and op_id not in ALWAYS_PROJECTED
|
|
136
|
+
and operation(op_id).get("namespace") not in ALWAYS_PROJECTED_NAMESPACES):
|
|
137
|
+
out = drop_denied(body)
|
|
138
|
+
else:
|
|
139
|
+
out = body if schema is None else drop_denied(project(body, schema))
|
|
140
|
+
if op_id == "getCall" and isinstance(out, dict) and isinstance(out.get("data"), dict):
|
|
141
|
+
vcon = out["data"].get("vcon")
|
|
142
|
+
if isinstance(vcon, dict):
|
|
143
|
+
out["data"]["vcon"] = {k: vcon[k] for k in RECORDING_FIELDS if k in vcon}
|
|
144
|
+
return out
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def recording_link(body: Any) -> Optional[Dict[str, Any]]:
|
|
148
|
+
"""The recording link and expiry from a raw call-detail body, or None."""
|
|
149
|
+
data = body.get("data") if isinstance(body, dict) else None
|
|
150
|
+
vcon = data.get("vcon") if isinstance(data, dict) else None
|
|
151
|
+
if not isinstance(vcon, dict) or not vcon.get("recording_url"):
|
|
152
|
+
return None
|
|
153
|
+
return {k: vcon.get(k) for k in RECORDING_FIELDS}
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def webhook_schema(name: str) -> Any:
|
|
157
|
+
return spec()["webhooks"][name]
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def schema_by_name(name: str) -> Any:
|
|
161
|
+
return spec()["schemas"][name]
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
# ------------------------------------------------------------------ request checks
|
|
165
|
+
|
|
166
|
+
def check_body(op_id: str, body: Mapping[str, Any]) -> None:
|
|
167
|
+
op = operation(op_id)
|
|
168
|
+
if op["body"] is None:
|
|
169
|
+
raise InvalidRequestError(f"{op_id} takes no body")
|
|
170
|
+
if not isinstance(body, Mapping):
|
|
171
|
+
raise InvalidRequestError(f"{op_id}: body must be a mapping")
|
|
172
|
+
schema = _resolve(op["body"]["schema"])
|
|
173
|
+
props = _object_props(schema)
|
|
174
|
+
if props is None:
|
|
175
|
+
return
|
|
176
|
+
unknown = sorted(set(body) - set(props))
|
|
177
|
+
if unknown:
|
|
178
|
+
raise InvalidRequestError(
|
|
179
|
+
f"{op_id}: unknown field(s) {unknown}. Allowed: {sorted(props)}"
|
|
180
|
+
)
|
|
181
|
+
missing = [k for k in schema.get("required", []) if k not in body]
|
|
182
|
+
if missing:
|
|
183
|
+
raise InvalidRequestError(f"{op_id}: missing required field(s) {missing}")
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def is_uuid(value: Any) -> bool:
|
|
187
|
+
if not isinstance(value, str):
|
|
188
|
+
return False
|
|
189
|
+
try:
|
|
190
|
+
uuid.UUID(value)
|
|
191
|
+
except ValueError:
|
|
192
|
+
return False
|
|
193
|
+
return len(value) == 36
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def format_datetime(value: Any, name: str) -> str:
|
|
197
|
+
"""Full RFC 3339 in UTC. Naive datetimes and date-only values are refused."""
|
|
198
|
+
if isinstance(value, datetime):
|
|
199
|
+
if value.tzinfo is None or value.tzinfo.utcoffset(value) is None:
|
|
200
|
+
raise InvalidRequestError(
|
|
201
|
+
f"{name}: a datetime without a time zone is refused. Pass an aware datetime, "
|
|
202
|
+
"e.g. datetime.now(timezone.utc)"
|
|
203
|
+
)
|
|
204
|
+
value = value.astimezone(timezone.utc)
|
|
205
|
+
frac = f".{value.microsecond:06d}" if value.microsecond else ""
|
|
206
|
+
return value.strftime("%Y-%m-%dT%H:%M:%S") + frac + "Z"
|
|
207
|
+
if isinstance(value, date):
|
|
208
|
+
raise InvalidRequestError(
|
|
209
|
+
f"{name}: a date alone is refused. Pass a datetime, e.g. 2026-11-01T00:00:00Z"
|
|
210
|
+
)
|
|
211
|
+
if isinstance(value, str):
|
|
212
|
+
v = value.strip()
|
|
213
|
+
if _DATE.match(v):
|
|
214
|
+
raise InvalidRequestError(
|
|
215
|
+
f"{name}: {v!r} is a date only. Use a full timestamp, e.g. {v}T00:00:00Z"
|
|
216
|
+
)
|
|
217
|
+
if not _RFC3339.match(v):
|
|
218
|
+
raise InvalidRequestError(
|
|
219
|
+
f"{name}: {v!r} is not a full RFC 3339 timestamp (e.g. 2026-11-01T00:00:00Z)"
|
|
220
|
+
)
|
|
221
|
+
m = _RFC3339_PARTS.match(v)
|
|
222
|
+
frac = (m.group(7) or "")[:6].ljust(6, "0") if m.group(7) else "0"
|
|
223
|
+
off = m.group(8)
|
|
224
|
+
if off in ("Z", "z"):
|
|
225
|
+
tz = timezone.utc
|
|
226
|
+
else:
|
|
227
|
+
sign = 1 if off[0] == "+" else -1
|
|
228
|
+
tz = timezone(sign * timedelta(hours=int(off[1:3]), minutes=int(off[4:6])))
|
|
229
|
+
parsed = datetime(int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4)),
|
|
230
|
+
int(m.group(5)), int(m.group(6)), int(frac), tzinfo=tz)
|
|
231
|
+
return format_datetime(parsed, name)
|
|
232
|
+
raise InvalidRequestError(f"{name}: expected a datetime or RFC 3339 string")
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def format_date(value: Any, name: str) -> str:
|
|
236
|
+
if isinstance(value, datetime):
|
|
237
|
+
raise InvalidRequestError(f"{name}: pass a date (YYYY-MM-DD), not a datetime")
|
|
238
|
+
if isinstance(value, date):
|
|
239
|
+
return value.isoformat()
|
|
240
|
+
if isinstance(value, str) and _DATE.match(value.strip()):
|
|
241
|
+
return value.strip()
|
|
242
|
+
raise InvalidRequestError(f"{name}: expected YYYY-MM-DD")
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def clean_number(entry: str, name: str = "numbers") -> str:
|
|
246
|
+
"""Strip formatting. A North American number written with its leading 1 (11 digits) is sent as its
|
|
247
|
+
last 10 digits, so it also matches records stored without the 1."""
|
|
248
|
+
v = _NUMBER_STRIP.sub("", str(entry))
|
|
249
|
+
if not _NUMBER_OK.match(v):
|
|
250
|
+
raise InvalidRequestError(f"{name}: {entry!r} must be digits (letters, @ and # are also allowed)")
|
|
251
|
+
if len(v) == 11 and v.isdigit() and v.startswith("1"):
|
|
252
|
+
v = v[1:]
|
|
253
|
+
return v
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _as_list(value: Any) -> List[str]:
|
|
257
|
+
if isinstance(value, str):
|
|
258
|
+
return [p.strip() for p in value.split(",") if p.strip()]
|
|
259
|
+
return [str(v).strip() for v in value]
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def encode_query(op_id: str, query: Mapping[str, Any]) -> Dict[str, str]:
|
|
263
|
+
op = operation(op_id)
|
|
264
|
+
allowed = op["query"]
|
|
265
|
+
out: Dict[str, str] = {}
|
|
266
|
+
for name, value in query.items():
|
|
267
|
+
if name not in allowed:
|
|
268
|
+
raise InvalidRequestError(f"{op_id}: unknown filter {name!r}. Allowed: {sorted(allowed)}")
|
|
269
|
+
q = allowed[name]
|
|
270
|
+
if value is None:
|
|
271
|
+
if q.get("required"):
|
|
272
|
+
raise InvalidRequestError(f"{op_id}: {name} is required")
|
|
273
|
+
continue
|
|
274
|
+
out[name] = _encode_one(op_id, name, q, value)
|
|
275
|
+
for name, q in allowed.items():
|
|
276
|
+
if q.get("required") and name not in out:
|
|
277
|
+
raise InvalidRequestError(f"{op_id}: {name} is required")
|
|
278
|
+
return out
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def _encode_one(op_id: str, name: str, q: Mapping[str, Any], value: Any) -> str:
|
|
282
|
+
typ = q.get("type")
|
|
283
|
+
fmt = q.get("format")
|
|
284
|
+
if q.get("enum") == ["true"]:
|
|
285
|
+
if value is True:
|
|
286
|
+
return "true"
|
|
287
|
+
raise InvalidRequestError(f"{name}: only True is supported (leave it out otherwise)")
|
|
288
|
+
if typ == "boolean":
|
|
289
|
+
if not isinstance(value, bool):
|
|
290
|
+
raise InvalidRequestError(f"{name}: expected True or False")
|
|
291
|
+
return "true" if value else "false"
|
|
292
|
+
if typ == "integer":
|
|
293
|
+
if isinstance(value, bool) or not isinstance(value, int):
|
|
294
|
+
raise InvalidRequestError(f"{name}: expected an integer")
|
|
295
|
+
if "minimum" in q and value < q["minimum"]:
|
|
296
|
+
raise InvalidRequestError(f"{name}: must be >= {q['minimum']}")
|
|
297
|
+
if "maximum" in q and value > q["maximum"]:
|
|
298
|
+
raise InvalidRequestError(f"{name}: must be <= {q['maximum']}")
|
|
299
|
+
return str(value)
|
|
300
|
+
if typ == "array":
|
|
301
|
+
items = _as_list(value)
|
|
302
|
+
item_fmt = (q.get("items") or {}).get("format")
|
|
303
|
+
if name == "numbers":
|
|
304
|
+
items = [clean_number(i) for i in items]
|
|
305
|
+
limit = min(q.get("maxItems", MAX_NUMBERS), MAX_NUMBERS)
|
|
306
|
+
else:
|
|
307
|
+
limit = q.get("maxItems", 100)
|
|
308
|
+
if name == "location_id":
|
|
309
|
+
limit = MAX_LOCATION_IDS
|
|
310
|
+
deduped: List[str] = []
|
|
311
|
+
for i in items:
|
|
312
|
+
if i not in deduped:
|
|
313
|
+
deduped.append(i)
|
|
314
|
+
if not deduped:
|
|
315
|
+
raise InvalidRequestError(f"{name}: empty list")
|
|
316
|
+
if len(deduped) > limit:
|
|
317
|
+
raise InvalidRequestError(f"{name}: at most {limit} entries per request (got {len(deduped)})")
|
|
318
|
+
if item_fmt == "uuid":
|
|
319
|
+
bad = [i for i in deduped if not is_uuid(i)]
|
|
320
|
+
if bad:
|
|
321
|
+
raise InvalidRequestError(f"{name}: not a UUID: {bad[0]!r}")
|
|
322
|
+
return ",".join(deduped)
|
|
323
|
+
# strings
|
|
324
|
+
if fmt == "date-time":
|
|
325
|
+
return format_datetime(value, name)
|
|
326
|
+
if fmt == "date":
|
|
327
|
+
return format_date(value, name)
|
|
328
|
+
if not isinstance(value, str):
|
|
329
|
+
raise InvalidRequestError(f"{name}: expected a string")
|
|
330
|
+
if "enum" in q and value not in q["enum"]:
|
|
331
|
+
raise InvalidRequestError(f"{name}: {value!r} is not one of {q['enum']}")
|
|
332
|
+
if fmt == "uuid" and not is_uuid(value):
|
|
333
|
+
raise InvalidRequestError(f"{name}: not a UUID: {value!r}")
|
|
334
|
+
return value
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""Token storage. The SDK keeps tokens in memory unless you pass your own ``token_store``."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import contextlib
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import tempfile
|
|
8
|
+
import threading
|
|
9
|
+
import time
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from typing import Iterator, Optional, Protocol
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class Tokens:
|
|
16
|
+
"""An access token and its single-use refresh token."""
|
|
17
|
+
|
|
18
|
+
access_token: str = field(repr=False)
|
|
19
|
+
refresh_token: str = field(repr=False)
|
|
20
|
+
expires_at: float = 0.0 # epoch seconds; 0 = unknown
|
|
21
|
+
|
|
22
|
+
def expired(self, skew: float = 30.0) -> bool:
|
|
23
|
+
return bool(self.expires_at) and time.time() >= self.expires_at - skew
|
|
24
|
+
|
|
25
|
+
def __repr__(self) -> str:
|
|
26
|
+
return f"Tokens(access_token='***', refresh_token='***', expires_at={self.expires_at:.0f})"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class TokenStore(Protocol):
|
|
30
|
+
"""Where the client keeps its tokens. Implement ``get`` and ``set`` to share tokens between runs.
|
|
31
|
+
|
|
32
|
+
Refresh tokens rotate: ``set`` is called with the new pair before it is used, and the old refresh
|
|
33
|
+
token is never sent again. Store it somewhere private (it is a credential).
|
|
34
|
+
|
|
35
|
+
**Several processes sharing one integration user** (workers, serverless, a cron next to a web app):
|
|
36
|
+
also implement ``lock()``, returning a context manager that holds a lock across processes. The
|
|
37
|
+
client signs in and renews inside that lock and re-reads the store first, so two processes never
|
|
38
|
+
send the same refresh token (a replayed refresh token ends the session everywhere).
|
|
39
|
+
:class:`FileTokenStore` does this with a lock file; with a shared cache or a database, use its own lock.
|
|
40
|
+
Without ``lock()`` a store is safe only within one process.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
def get(self) -> Optional[Tokens]: ...
|
|
44
|
+
|
|
45
|
+
def set(self, tokens: Optional[Tokens]) -> None: ...
|
|
46
|
+
|
|
47
|
+
# Optional: def lock(self) -> ContextManager[Any]: ...
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class MemoryTokenStore:
|
|
51
|
+
"""The default store: tokens live in this process only."""
|
|
52
|
+
|
|
53
|
+
def __init__(self, tokens: Optional[Tokens] = None):
|
|
54
|
+
self._tokens = tokens
|
|
55
|
+
self._lock = threading.Lock()
|
|
56
|
+
|
|
57
|
+
def get(self) -> Optional[Tokens]:
|
|
58
|
+
with self._lock:
|
|
59
|
+
return self._tokens
|
|
60
|
+
|
|
61
|
+
def set(self, tokens: Optional[Tokens]) -> None:
|
|
62
|
+
with self._lock:
|
|
63
|
+
self._tokens = tokens
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class FileTokenStore:
|
|
67
|
+
"""Tokens in a private file (mode 0600), shared by every process on this machine.
|
|
68
|
+
|
|
69
|
+
``lock()`` takes an exclusive lock on ``<path>.lock`` (``fcntl.flock``; ``msvcrt.locking`` on
|
|
70
|
+
Windows), so processes sharing the file renew one at a time. Writes are atomic.
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
def __init__(self, path: str):
|
|
74
|
+
self.path = os.path.abspath(path)
|
|
75
|
+
self._thread_lock = threading.RLock()
|
|
76
|
+
|
|
77
|
+
def get(self) -> Optional[Tokens]:
|
|
78
|
+
try:
|
|
79
|
+
with open(self.path, "r", encoding="utf-8") as fh:
|
|
80
|
+
data = json.load(fh)
|
|
81
|
+
except (FileNotFoundError, ValueError):
|
|
82
|
+
return None
|
|
83
|
+
if not isinstance(data, dict) or not data.get("access_token") or not data.get("refresh_token"):
|
|
84
|
+
return None
|
|
85
|
+
return Tokens(access_token=data["access_token"], refresh_token=data["refresh_token"],
|
|
86
|
+
expires_at=float(data.get("expires_at") or 0.0))
|
|
87
|
+
|
|
88
|
+
def set(self, tokens: Optional[Tokens]) -> None:
|
|
89
|
+
directory = os.path.dirname(self.path) or "."
|
|
90
|
+
if tokens is None:
|
|
91
|
+
with contextlib.suppress(FileNotFoundError):
|
|
92
|
+
os.remove(self.path)
|
|
93
|
+
return
|
|
94
|
+
payload = json.dumps({"access_token": tokens.access_token, "refresh_token": tokens.refresh_token,
|
|
95
|
+
"expires_at": tokens.expires_at})
|
|
96
|
+
fd, tmp = tempfile.mkstemp(prefix=".tokens-", dir=directory)
|
|
97
|
+
try:
|
|
98
|
+
os.chmod(tmp, 0o600)
|
|
99
|
+
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
|
100
|
+
fh.write(payload)
|
|
101
|
+
os.replace(tmp, self.path)
|
|
102
|
+
except BaseException:
|
|
103
|
+
with contextlib.suppress(FileNotFoundError):
|
|
104
|
+
os.remove(tmp)
|
|
105
|
+
raise
|
|
106
|
+
|
|
107
|
+
@contextlib.contextmanager
|
|
108
|
+
def lock(self) -> Iterator[None]:
|
|
109
|
+
with self._thread_lock:
|
|
110
|
+
fd = os.open(self.path + ".lock", os.O_RDWR | os.O_CREAT, 0o600)
|
|
111
|
+
try:
|
|
112
|
+
_lock_fd(fd)
|
|
113
|
+
try:
|
|
114
|
+
yield
|
|
115
|
+
finally:
|
|
116
|
+
_unlock_fd(fd)
|
|
117
|
+
finally:
|
|
118
|
+
os.close(fd)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _lock_fd(fd: int) -> None:
|
|
122
|
+
try:
|
|
123
|
+
import fcntl
|
|
124
|
+
except ImportError: # pragma: no cover - Windows
|
|
125
|
+
import msvcrt
|
|
126
|
+
while True:
|
|
127
|
+
try:
|
|
128
|
+
msvcrt.locking(fd, msvcrt.LK_LOCK, 1)
|
|
129
|
+
return
|
|
130
|
+
except OSError:
|
|
131
|
+
time.sleep(0.05)
|
|
132
|
+
fcntl.flock(fd, fcntl.LOCK_EX)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _unlock_fd(fd: int) -> None:
|
|
136
|
+
try:
|
|
137
|
+
import fcntl
|
|
138
|
+
except ImportError: # pragma: no cover - Windows
|
|
139
|
+
import msvcrt
|
|
140
|
+
msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
|
|
141
|
+
return
|
|
142
|
+
fcntl.flock(fd, fcntl.LOCK_UN)
|