hosteday-python 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.
Files changed (50) hide show
  1. hosteday/__init__.py +111 -0
  2. hosteday/_version.py +3 -0
  3. hosteday/auth/__init__.py +34 -0
  4. hosteday/auth/hosteday_auth.py +444 -0
  5. hosteday/auth/hosteday_auth_storage.py +130 -0
  6. hosteday/auth/hosteday_session.py +184 -0
  7. hosteday/auth/hosteday_token_provider.py +82 -0
  8. hosteday/auth/hosteday_user.py +223 -0
  9. hosteday/cli/__init__.py +5 -0
  10. hosteday/cli/setup.py +163 -0
  11. hosteday/config/__init__.py +15 -0
  12. hosteday/config/hosteday_config.py +576 -0
  13. hosteday/config/hosteday_option_keys.py +60 -0
  14. hosteday/config/hosteday_url_resolver.py +255 -0
  15. hosteday/connectivity/__init__.py +5 -0
  16. hosteday/connectivity/hosteday_connectivity.py +147 -0
  17. hosteday/exceptions.py +233 -0
  18. hosteday/features/__init__.py +5 -0
  19. hosteday/features/hosteday_features.py +78 -0
  20. hosteday/hosteday.py +346 -0
  21. hosteday/hosteday_client.py +579 -0
  22. hosteday/http/__init__.py +18 -0
  23. hosteday/http/hosteday_http_client.py +340 -0
  24. hosteday/http/hosteday_response_reader.py +171 -0
  25. hosteday/http/query_builder.py +204 -0
  26. hosteday/jobs/__init__.py +9 -0
  27. hosteday/jobs/hosteday_job_response.py +76 -0
  28. hosteday/jobs/hosteday_jobs_client.py +109 -0
  29. hosteday/notifications/__init__.py +13 -0
  30. hosteday/notifications/hosteday_notification_client.py +290 -0
  31. hosteday/notifications/hosteday_notification_response.py +79 -0
  32. hosteday/py.typed +1 -0
  33. hosteday/reactive/__init__.py +5 -0
  34. hosteday/reactive/observable_state.py +67 -0
  35. hosteday/realtime/__init__.py +31 -0
  36. hosteday/realtime/connection_state.py +14 -0
  37. hosteday/realtime/hosteday_channel.py +258 -0
  38. hosteday/realtime/hosteday_channel_auth.py +163 -0
  39. hosteday/realtime/hosteday_channel_type.py +68 -0
  40. hosteday/realtime/hosteday_realtime_client.py +790 -0
  41. hosteday/realtime/hosteday_realtime_event.py +130 -0
  42. hosteday/web/__init__.py +5 -0
  43. hosteday/web/server.py +637 -0
  44. hosteday_python/__init__.py +6 -0
  45. hosteday_python/py.typed +1 -0
  46. hosteday_python-0.1.0.dist-info/METADATA +205 -0
  47. hosteday_python-0.1.0.dist-info/RECORD +50 -0
  48. hosteday_python-0.1.0.dist-info/WHEEL +4 -0
  49. hosteday_python-0.1.0.dist-info/entry_points.txt +2 -0
  50. hosteday_python-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,340 @@
1
+ """Async HTTP transport for HosteDay REST APIs built on ``httpx``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections.abc import Callable, Mapping
7
+ from typing import TYPE_CHECKING, Any
8
+
9
+ import httpx
10
+
11
+ from hosteday.config.hosteday_config import HostedayConfig
12
+ from hosteday.exceptions import HostedayException
13
+ from hosteday.http.query_builder import QueryBuilder
14
+
15
+ if TYPE_CHECKING:
16
+ from hosteday.auth.hosteday_token_provider import HostedayTokenProvider
17
+
18
+ _SUPPORTED_METHODS = frozenset({"GET", "POST", "PUT", "PATCH", "DELETE"})
19
+ _BODY_METHODS = frozenset({"POST", "PUT", "PATCH", "DELETE"})
20
+
21
+
22
+ class HostedayHttpClient:
23
+ """Low-level async HTTP client for HosteDay APIs."""
24
+
25
+ def __init__(
26
+ self,
27
+ *,
28
+ config: HostedayConfig,
29
+ token_provider: HostedayTokenProvider | None = None,
30
+ client: httpx.AsyncClient | None = None,
31
+ timeout: float = 30.0,
32
+ on_network_result: Callable[[bool], None] | None = None,
33
+ ) -> None:
34
+ self.config: HostedayConfig = config
35
+ self.token_provider: HostedayTokenProvider | None = token_provider
36
+ self.timeout: float = timeout
37
+ self.on_network_result: Callable[[bool], None] | None = on_network_result
38
+ self._owns_client: bool = client is None
39
+ self._client: httpx.AsyncClient = client or httpx.AsyncClient(timeout=timeout)
40
+
41
+ async def get(
42
+ self,
43
+ path: str,
44
+ *,
45
+ id: Any = None,
46
+ search: str | None = None,
47
+ filters: Mapping[str, Any] | None = None,
48
+ relation_field: str | None = None,
49
+ relation_value: Any = None,
50
+ query_parameters: Mapping[str, Any] | None = None,
51
+ with_auth: bool = False,
52
+ headers: Mapping[str, str] | None = None,
53
+ timeout: float | None = None,
54
+ ) -> dict[str, Any]:
55
+ if id is not None and filters:
56
+ raise ValueError(
57
+ "filters are supported only for index GET requests when id is omitted."
58
+ )
59
+
60
+ return await self.request(
61
+ method="GET",
62
+ path=path,
63
+ id=id,
64
+ query_parameters=QueryBuilder.build_resource_query_parameters(
65
+ query_parameters=query_parameters,
66
+ search=search,
67
+ filters=filters,
68
+ relation_field=relation_field,
69
+ relation_value=relation_value,
70
+ ),
71
+ with_auth=with_auth,
72
+ headers=headers,
73
+ timeout=timeout,
74
+ )
75
+
76
+ async def post(
77
+ self,
78
+ path: str,
79
+ *,
80
+ body: Mapping[str, Any] | None = None,
81
+ query_parameters: Mapping[str, Any] | None = None,
82
+ with_auth: bool = False,
83
+ headers: Mapping[str, str] | None = None,
84
+ timeout: float | None = None,
85
+ ) -> dict[str, Any]:
86
+ return await self.request(
87
+ method="POST",
88
+ path=path,
89
+ body=body,
90
+ query_parameters=query_parameters,
91
+ with_auth=with_auth,
92
+ headers=headers,
93
+ timeout=timeout,
94
+ )
95
+
96
+ async def put(
97
+ self,
98
+ path: str,
99
+ *,
100
+ id: Any = None,
101
+ body: Mapping[str, Any] | None = None,
102
+ relation_field: str | None = None,
103
+ relation_value: Any = None,
104
+ query_parameters: Mapping[str, Any] | None = None,
105
+ with_auth: bool = False,
106
+ headers: Mapping[str, str] | None = None,
107
+ timeout: float | None = None,
108
+ ) -> dict[str, Any]:
109
+ return await self.request(
110
+ method="PUT",
111
+ path=path,
112
+ id=id,
113
+ body=body,
114
+ query_parameters=QueryBuilder.build_resource_query_parameters(
115
+ query_parameters=query_parameters,
116
+ relation_field=relation_field,
117
+ relation_value=relation_value,
118
+ ),
119
+ with_auth=with_auth,
120
+ headers=headers,
121
+ timeout=timeout,
122
+ )
123
+
124
+ async def patch(
125
+ self,
126
+ path: str,
127
+ *,
128
+ id: Any = None,
129
+ body: Mapping[str, Any] | None = None,
130
+ relation_field: str | None = None,
131
+ relation_value: Any = None,
132
+ query_parameters: Mapping[str, Any] | None = None,
133
+ with_auth: bool = False,
134
+ headers: Mapping[str, str] | None = None,
135
+ timeout: float | None = None,
136
+ ) -> dict[str, Any]:
137
+ return await self.request(
138
+ method="PATCH",
139
+ path=path,
140
+ id=id,
141
+ body=body,
142
+ query_parameters=QueryBuilder.build_resource_query_parameters(
143
+ query_parameters=query_parameters,
144
+ relation_field=relation_field,
145
+ relation_value=relation_value,
146
+ ),
147
+ with_auth=with_auth,
148
+ headers=headers,
149
+ timeout=timeout,
150
+ )
151
+
152
+ async def delete(
153
+ self,
154
+ path: str,
155
+ *,
156
+ id: Any = None,
157
+ body: Mapping[str, Any] | None = None,
158
+ relation_field: str | None = None,
159
+ relation_value: Any = None,
160
+ query_parameters: Mapping[str, Any] | None = None,
161
+ with_auth: bool = False,
162
+ headers: Mapping[str, str] | None = None,
163
+ timeout: float | None = None,
164
+ ) -> dict[str, Any]:
165
+ return await self.request(
166
+ method="DELETE",
167
+ path=path,
168
+ id=id,
169
+ body=body,
170
+ query_parameters=QueryBuilder.build_resource_query_parameters(
171
+ query_parameters=query_parameters,
172
+ relation_field=relation_field,
173
+ relation_value=relation_value,
174
+ ),
175
+ with_auth=with_auth,
176
+ headers=headers,
177
+ timeout=timeout,
178
+ )
179
+
180
+ async def post_form(
181
+ self,
182
+ path: str,
183
+ *,
184
+ data: Mapping[str, str],
185
+ with_auth: bool = True,
186
+ headers: Mapping[str, str] | None = None,
187
+ timeout: float | None = None,
188
+ ) -> httpx.Response:
189
+ """Sends an ``application/x-www-form-urlencoded`` POST request (used by broadcasting auth)."""
190
+ url = self.config.uri(path)
191
+ request_headers = await self._build_headers(
192
+ with_auth=with_auth,
193
+ has_json_body=False,
194
+ headers=headers,
195
+ )
196
+ request_headers["Content-Type"] = "application/x-www-form-urlencoded"
197
+ try:
198
+ response = await self._client.post(
199
+ url,
200
+ data=dict(data),
201
+ headers=request_headers,
202
+ timeout=timeout if timeout is not None else self.timeout,
203
+ )
204
+ if self.on_network_result is not None:
205
+ self.on_network_result(True)
206
+ return response
207
+ except httpx.TimeoutException as exc:
208
+ if self.on_network_result is not None:
209
+ self.on_network_result(False)
210
+ raise HostedayException("Hosteday request timed out.", error=exc) from exc
211
+ except httpx.HTTPError as exc:
212
+ if self.on_network_result is not None:
213
+ self.on_network_result(False)
214
+ raise HostedayException(f"Hosteday network error: {exc}", error=exc) from exc
215
+
216
+ async def request(
217
+ self,
218
+ *,
219
+ method: str,
220
+ path: str,
221
+ id: Any = None,
222
+ body: Mapping[str, Any] | None = None,
223
+ query_parameters: Mapping[str, Any] | None = None,
224
+ with_auth: bool = False,
225
+ headers: Mapping[str, str] | None = None,
226
+ timeout: float | None = None,
227
+ ) -> dict[str, Any]:
228
+ normalized_method = method.strip().upper()
229
+ if normalized_method not in _SUPPORTED_METHODS:
230
+ raise HostedayException(f"Unsupported HTTP method: {method}")
231
+
232
+ has_json_body = body is not None and normalized_method in _BODY_METHODS
233
+
234
+ url = self.config.uri(path)
235
+ if id is not None:
236
+ url = QueryBuilder.append_id_to_url(url, id)
237
+
238
+ base_url, params = QueryBuilder.flatten_query_parameters(url, query_parameters)
239
+
240
+ request_headers = await self._build_headers(
241
+ with_auth=with_auth,
242
+ has_json_body=has_json_body,
243
+ headers=headers,
244
+ )
245
+
246
+ effective_timeout = timeout if timeout is not None else self.timeout
247
+
248
+ try:
249
+ response = await self._client.request(
250
+ method=normalized_method,
251
+ url=base_url,
252
+ params=tuple(params) if params else None,
253
+ headers=request_headers,
254
+ content=json.dumps(dict(body)).encode("utf-8") if has_json_body and body is not None else None,
255
+ timeout=effective_timeout,
256
+ )
257
+ except httpx.TimeoutException as exc:
258
+ if self.on_network_result is not None:
259
+ self.on_network_result(False)
260
+ raise HostedayException("Hosteday request timed out.", error=exc) from exc
261
+ except httpx.HTTPError as exc:
262
+ if self.on_network_result is not None:
263
+ self.on_network_result(False)
264
+ raise HostedayException(f"Hosteday network error: {exc}", error=exc) from exc
265
+
266
+ if self.on_network_result is not None:
267
+ self.on_network_result(True)
268
+
269
+ try:
270
+ decoded = self._decode_response(response.text)
271
+ except HostedayException as err:
272
+ raise HostedayException(
273
+ f"HTTP {response.status_code}: {err.message}",
274
+ status_code=response.status_code,
275
+ response={"raw_body": response.text},
276
+ error=err.error,
277
+ ) from err
278
+
279
+ if response.status_code < 200 or response.status_code >= 300:
280
+ raise HostedayException.from_response(
281
+ decoded,
282
+ status_code=response.status_code,
283
+ )
284
+
285
+ return decoded
286
+
287
+ async def _build_headers(
288
+ self,
289
+ *,
290
+ with_auth: bool,
291
+ has_json_body: bool,
292
+ headers: Mapping[str, str] | None = None,
293
+ ) -> dict[str, str]:
294
+ result: dict[str, str] = {
295
+ "Accept": "application/json",
296
+ **self.config.default_headers,
297
+ }
298
+ if has_json_body:
299
+ result["Content-Type"] = "application/json"
300
+
301
+ if headers:
302
+ result.update(headers)
303
+
304
+ if with_auth:
305
+ token = (
306
+ await self.token_provider.get_token()
307
+ if self.token_provider is not None
308
+ else None
309
+ )
310
+ clean_token = token.strip() if token else ""
311
+ if not clean_token:
312
+ raise HostedayException(
313
+ "Missing authentication token.",
314
+ status_code=401,
315
+ )
316
+ result["Authorization"] = f"Bearer {clean_token}"
317
+
318
+ return result
319
+
320
+ @staticmethod
321
+ def _decode_response(body: str) -> dict[str, Any]:
322
+ clean = body.strip()
323
+ if not clean:
324
+ return {}
325
+ try:
326
+ decoded = json.loads(clean)
327
+ except json.JSONDecodeError as exc:
328
+ raise HostedayException(
329
+ "Hosteday returned an invalid JSON response.",
330
+ error=exc,
331
+ ) from exc
332
+
333
+ if isinstance(decoded, dict):
334
+ return decoded
335
+ return {"data": decoded}
336
+
337
+ async def close(self) -> None:
338
+ """Closes the underlying ``httpx.AsyncClient`` when owned by this instance."""
339
+ if self._owns_client:
340
+ await self._client.aclose()
@@ -0,0 +1,171 @@
1
+ """Strict HosteDay JSON envelope validator and generic ``HostedayPage`` model."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable, Mapping
6
+ from dataclasses import dataclass
7
+ from typing import Any, Generic, NoReturn, TypeVar
8
+
9
+ from hosteday.exceptions import HostedayException
10
+
11
+ T = TypeVar("T")
12
+ U = TypeVar("U")
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class HostedayPage(Generic[T]):
17
+ """One server-provided page of HosteDay records."""
18
+
19
+ items: list[T]
20
+ current_page: int
21
+ per_page: int
22
+ next_page_url: str | None = None
23
+ previous_page_url: str | None = None
24
+ from_index: int | None = None
25
+ to_index: int | None = None
26
+ total: int | None = None
27
+ last_page: int | None = None
28
+
29
+ @property
30
+ def has_next_page(self) -> bool:
31
+ """Whether the server supplied an informational next-page link."""
32
+ return self.next_page_url is not None
33
+
34
+ @property
35
+ def has_previous_page(self) -> bool:
36
+ """Whether the server supplied an informational previous-page link."""
37
+ return self.previous_page_url is not None
38
+
39
+ def map_items(self, transform: Callable[[T], U]) -> HostedayPage[U]:
40
+ """Transforms each item in the page while preserving pagination metadata."""
41
+ return HostedayPage(
42
+ items=[transform(item) for item in self.items],
43
+ current_page=self.current_page,
44
+ per_page=self.per_page,
45
+ next_page_url=self.next_page_url,
46
+ previous_page_url=self.previous_page_url,
47
+ from_index=self.from_index,
48
+ to_index=self.to_index,
49
+ total=self.total,
50
+ last_page=self.last_page,
51
+ )
52
+
53
+
54
+ class HostedayResponseReader:
55
+ """Validates and unwraps the standard HosteDay resource envelopes without coercing record fields."""
56
+
57
+ @classmethod
58
+ def index(cls, response: Mapping[str, Any]) -> HostedayPage[dict[str, Any]]:
59
+ """Reads and validates either a paginated or flat-list ``index`` response."""
60
+ success = response.get("success")
61
+ if success is False:
62
+ cls._fail(response, "index operation failed")
63
+ if "success" in response and success is not True:
64
+ cls._fail(response, "index.success must be true")
65
+
66
+ raw_data = response.get("data")
67
+
68
+ # 1) Direct unpaginated list: {"success": true, "data": [...]}
69
+ if isinstance(raw_data, list):
70
+ if any(not isinstance(item, Mapping) for item in raw_data):
71
+ cls._fail(response, "index.data must be a list of objects")
72
+ items = [dict(item) for item in raw_data]
73
+ count = len(items)
74
+ return HostedayPage(
75
+ items=items,
76
+ current_page=1,
77
+ per_page=max(count, 1),
78
+ from_index=1 if count > 0 else 0,
79
+ to_index=count,
80
+ total=count,
81
+ last_page=1,
82
+ )
83
+
84
+ # 2) Paginated envelope: {"success": true, "data": {"data": [...], "current_page": 1, ...}}
85
+ if not isinstance(raw_data, Mapping):
86
+ cls._fail(response, "index.data must be an object or a list of objects")
87
+
88
+ data = raw_data
89
+ raw_items = data.get("data")
90
+ if not isinstance(raw_items, list) or any(
91
+ not isinstance(item, Mapping) for item in raw_items
92
+ ):
93
+ cls._fail(response, "index.data.data must be a list of objects")
94
+
95
+ for key in ("current_page", "per_page"):
96
+ val = data.get(key)
97
+ if type(val) is not int or val < 1:
98
+ cls._fail(response, f"index.data.{key} must be a positive integer")
99
+
100
+ for key in ("from", "to", "total", "last_page"):
101
+ val = data.get(key)
102
+ if val is not None and (type(val) is not int or val < 0):
103
+ cls._fail(response, f"index.data.{key} must be an integer or null")
104
+
105
+ for key in ("next_page_url", "prev_page_url"):
106
+ val = data.get(key)
107
+ if val is not None and (not isinstance(val, str) or not val.strip()):
108
+ cls._fail(response, f"index.data.{key} must be a non-empty string or null")
109
+
110
+ items = [dict(item) for item in raw_items]
111
+ return HostedayPage(
112
+ items=items,
113
+ current_page=data["current_page"],
114
+ per_page=data["per_page"],
115
+ next_page_url=data.get("next_page_url"),
116
+ previous_page_url=data.get("prev_page_url"),
117
+ from_index=data.get("from"),
118
+ to_index=data.get("to"),
119
+ total=data.get("total"),
120
+ last_page=data.get("last_page"),
121
+ )
122
+
123
+ @classmethod
124
+ def show(cls, response: Mapping[str, Any]) -> dict[str, Any]:
125
+ """Reads and strictly validates a single-record ``show`` response."""
126
+ return dict(cls._extract_data(response, "show"))
127
+
128
+ @classmethod
129
+ def unwrap_record(cls, response: Mapping[str, Any]) -> dict[str, Any]:
130
+ """Unwraps ``{"success": true, "data": {...}}`` to the record dict, or returns clean dict as-is."""
131
+ if response.get("success") is False:
132
+ cls._fail(response, "record operation failed")
133
+ data = response.get("data")
134
+ if isinstance(data, Mapping):
135
+ return dict(data)
136
+ return dict(response)
137
+
138
+ @classmethod
139
+ def unwrap_delete(cls, response: Mapping[str, Any]) -> dict[str, Any]:
140
+ """Unwraps a delete response and ensures ``{"deleted": True, ...}``."""
141
+ if response.get("success") is False:
142
+ cls._fail(response, "delete operation failed")
143
+ data = response.get("data")
144
+ if isinstance(data, Mapping):
145
+ return {"deleted": True, **dict(data)}
146
+ if not response:
147
+ return {"deleted": True}
148
+ return {"deleted": True, **dict(response)}
149
+
150
+ @classmethod
151
+ def _extract_data(cls, response: Mapping[str, Any], operation: str) -> Mapping[str, Any]:
152
+ success = response.get("success")
153
+ if success is False:
154
+ cls._fail(response, f"{operation} operation failed")
155
+ if success is not True:
156
+ cls._fail(response, f"{operation}.success must be true")
157
+
158
+ data = response.get("data")
159
+ if not isinstance(data, Mapping):
160
+ cls._fail(response, f"{operation}.data must be an object")
161
+ return data
162
+
163
+ @staticmethod
164
+ def _fail(response: Mapping[str, Any], detail: str) -> NoReturn:
165
+ hosteday_error = HostedayException.from_response(response)
166
+ raise HostedayException(
167
+ f"Invalid Hosteday response: {detail}. {hosteday_error.message}",
168
+ response=response,
169
+ validation_errors=hosteday_error.validation_errors,
170
+ error=ValueError(detail),
171
+ )