agoralar-source-http 0.2.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.
@@ -0,0 +1,310 @@
1
+ """HTTP JSON как источник объектов AxisLar.
2
+
3
+ Источник забирает JSON по URL и превращает записи в объекты по тем же
4
+ правилам, что SQL-источник: `key` даёт естественный ключ (`entity_id_for`),
5
+ `axes`/`measurable`/`reference`/`scalars` раскладывают поля, `multi`
6
+ разрешает несколько значений на объект.
7
+
8
+ Три вещи зафиксированы жёстко:
9
+
10
+ - `null` (и отсутствующее поле) — **не значение**, а отсутствие: фасет не
11
+ создаётся, объект остаётся разреженным (ADR-0010 ядра);
12
+ - `content_hash` считается по каноническому JSON **сопоставленных** полей,
13
+ поэтому лишние поля ответа не выдают себя за изменение объекта;
14
+ - раскладка задаётся явно: адаптер не угадывает, что станет осью.
15
+
16
+ Источник только читает: `GET` без тела, без ретраев и без записи на сервер.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import asyncio
22
+ import hashlib
23
+ import json
24
+ import urllib.error
25
+ import urllib.request
26
+ from collections.abc import AsyncIterator, Iterable, Mapping
27
+ from dataclasses import dataclass, field
28
+ from typing import Any
29
+
30
+ from axislar_core.contracts import (
31
+ CategoricalValue,
32
+ Entity,
33
+ EntityId,
34
+ FacetOwner,
35
+ FacetValue,
36
+ IEntitySource,
37
+ MeasurableValue,
38
+ Origin,
39
+ ReferenceValue,
40
+ entity_id_for,
41
+ )
42
+
43
+ #: Контракт ядра, с которым совместим плагин.
44
+ REQUIRES_CONTRACT = ">=5,<6"
45
+
46
+ #: Вид объекта, если он не задан в настройках.
47
+ DEFAULT_KIND = "record"
48
+
49
+ #: Поле естественного ключа по умолчанию.
50
+ DEFAULT_KEY = ("id",)
51
+
52
+ #: Разделитель частей естественного ключа (unit separator).
53
+ KEY_SEPARATOR = "\x1f"
54
+
55
+ #: Таймаут запроса по умолчанию, секунды.
56
+ DEFAULT_TIMEOUT = 10.0
57
+
58
+ #: Алгоритм хэша содержимого записи.
59
+ HASH_ALGO = "sha256-record-json"
60
+
61
+
62
+ class HttpSourceError(RuntimeError):
63
+ """Источник не может прочитать данные: сеть, статус, JSON, форма."""
64
+
65
+
66
+ @dataclass(slots=True)
67
+ class HttpSource(IEntitySource):
68
+ """Источник поверх JSON-API."""
69
+
70
+ url: str
71
+ source_id: str
72
+ kind: str = DEFAULT_KIND
73
+ key: tuple[str, ...] = DEFAULT_KEY
74
+ axes: tuple[str, ...] = ()
75
+ measurable: tuple[str, ...] = ()
76
+ reference: Mapping[str, str] = field(default_factory=dict)
77
+ scalars: tuple[str, ...] = ()
78
+ multi: Mapping[str, str] = field(default_factory=dict)
79
+ hash_fields: tuple[str, ...] = ()
80
+ items: str = ""
81
+ headers: Mapping[str, str] = field(default_factory=dict)
82
+ timeout: float = DEFAULT_TIMEOUT
83
+ warnings: list[str] = field(default_factory=list)
84
+
85
+ def describe(self) -> str:
86
+ return f"http:{self.url} (source_id={self.source_id})"
87
+
88
+ async def scan(self) -> AsyncIterator[Entity]:
89
+ self.warnings = []
90
+ payload = await asyncio.to_thread(self._fetch)
91
+ for index, record in enumerate(self._records(payload)):
92
+ entity = self._build(record, index)
93
+ if entity is not None:
94
+ yield entity
95
+
96
+ # ---------------------------------------------------------------- чтение
97
+
98
+ def _fetch(self) -> object:
99
+ request = urllib.request.Request(self.url, headers=dict(self.headers))
100
+ try:
101
+ with urllib.request.urlopen(request, timeout=self.timeout) as response:
102
+ body = response.read()
103
+ except urllib.error.HTTPError as error:
104
+ raise HttpSourceError(f"http {error.code} on {self.url}") from error
105
+ except urllib.error.URLError as error:
106
+ raise HttpSourceError(f"cannot reach {self.url}: {error.reason}") from error
107
+ try:
108
+ return json.loads(body)
109
+ except json.JSONDecodeError as error:
110
+ raise HttpSourceError(f"{self.url}: invalid JSON: {error}") from error
111
+
112
+ def _records(self, payload: object) -> list[Mapping[str, object]]:
113
+ current: object = payload
114
+ for part in self.items.split(".") if self.items else ():
115
+ if not isinstance(current, Mapping) or part not in current:
116
+ raise HttpSourceError(f"{self.url}: no {self.items!r} in response")
117
+ current = current[part]
118
+ if not isinstance(current, list):
119
+ raise HttpSourceError(f"{self.url}: expected a JSON array of records")
120
+ records: list[Mapping[str, object]] = []
121
+ for index, item in enumerate(current):
122
+ if not isinstance(item, Mapping):
123
+ raise HttpSourceError(f"{self.url}: record {index} is not an object")
124
+ records.append(item)
125
+ return records
126
+
127
+ # ------------------------------------------------------------- построение
128
+
129
+ def _build(self, record: Mapping[str, object], index: int) -> Entity | None:
130
+ key_parts: list[str] = []
131
+ for name in self.key:
132
+ raw = record.get(name)
133
+ if raw is None:
134
+ self.warnings.append(f"запись {index} пропущена: нет ключевого поля {name!r}")
135
+ return None
136
+ key_parts.append(text(raw))
137
+ key = KEY_SEPARATOR.join(key_parts)
138
+
139
+ facets: dict[str, tuple[FacetValue, ...]] = {}
140
+ for name in self.axes:
141
+ values = self._categorical(record, name)
142
+ if values:
143
+ facets[name] = values
144
+ for name in self.measurable:
145
+ value = self._measurable(record, name, key)
146
+ if value is not None:
147
+ facets[name] = (value,)
148
+ for name in self.reference:
149
+ raw = record.get(name)
150
+ if raw is None:
151
+ continue
152
+ facets[name] = (ReferenceValue(target=EntityId(text(raw))),)
153
+
154
+ scalars: dict[str, str] = {}
155
+ for name in self.scalars:
156
+ raw = record.get(name)
157
+ if raw is not None:
158
+ scalars[name] = text(raw)
159
+
160
+ return Entity(
161
+ id=entity_id_for(self.source_id, key),
162
+ kind=self.kind,
163
+ scalars=scalars,
164
+ facets=facets,
165
+ owners=dict.fromkeys(facets, FacetOwner.SOURCE),
166
+ origin=Origin(
167
+ source_id=self.source_id,
168
+ key=key,
169
+ content_hash=self._content_hash(record),
170
+ hash_algo=HASH_ALGO,
171
+ ),
172
+ )
173
+
174
+ def _categorical(self, record: Mapping[str, object], name: str) -> tuple[FacetValue, ...]:
175
+ raw = record.get(name)
176
+ if raw is None:
177
+ return ()
178
+ separator = self.multi.get(name)
179
+ if separator is None:
180
+ return (CategoricalValue(value=text(raw)),)
181
+ pieces: Iterable[object] = raw if isinstance(raw, list) else text(raw).split(separator)
182
+ values = [text(piece).strip() for piece in pieces]
183
+ return tuple(CategoricalValue(value=piece) for piece in values if piece)
184
+
185
+ def _measurable(self, record: Mapping[str, object], name: str, key: str) -> FacetValue | None:
186
+ raw = record.get(name)
187
+ if raw is None:
188
+ return None
189
+ if isinstance(raw, bool) or not isinstance(raw, str | int | float):
190
+ self.warnings.append(f"{key}: поле {name!r} не число ({raw!r}), фасет пропущен")
191
+ return None
192
+ try:
193
+ number = float(raw)
194
+ except ValueError:
195
+ self.warnings.append(f"{key}: поле {name!r} не число ({raw!r}), фасет пропущен")
196
+ return None
197
+ return MeasurableValue(value=number)
198
+
199
+ def _content_hash(self, record: Mapping[str, object]) -> str:
200
+ fields = self.hash_fields or tuple(sorted(self._mapped_fields()))
201
+ payload = {name: record.get(name) for name in fields}
202
+ blob = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
203
+ return hashlib.sha256(blob.encode("utf-8")).hexdigest()
204
+
205
+ def _mapped_fields(self) -> set[str]:
206
+ return (
207
+ set(self.key)
208
+ | set(self.axes)
209
+ | set(self.measurable)
210
+ | set(self.scalars)
211
+ | set(self.reference)
212
+ )
213
+
214
+
215
+ # ------------------------------------------------------------------- утилиты
216
+
217
+
218
+ def text(value: object) -> str:
219
+ """Значение поля как текст (числа и bool — по `str`, списки — JSON)."""
220
+ if isinstance(value, str):
221
+ return value
222
+ if isinstance(value, bool):
223
+ return "true" if value else "false"
224
+ if isinstance(value, int | float):
225
+ return str(value)
226
+ return json.dumps(value, ensure_ascii=False, sort_keys=True)
227
+
228
+
229
+ def _as_tuple(value: object, *, name: str) -> tuple[str, ...]:
230
+ if value is None:
231
+ return ()
232
+ if isinstance(value, str):
233
+ return (value,)
234
+ if not isinstance(value, list | tuple):
235
+ raise ValueError(f"http source: {name} must be a list of field names")
236
+ return tuple(str(item) for item in value)
237
+
238
+
239
+ def _as_mapping(value: object, *, name: str) -> dict[str, str]:
240
+ if value is None:
241
+ return {}
242
+ if not isinstance(value, Mapping):
243
+ raise ValueError(f"http source: {name} must be a table")
244
+ return {str(key): str(item) for key, item in value.items()}
245
+
246
+
247
+ def create(options: Mapping[str, Any]) -> HttpSource:
248
+ """Фабрика из настроек плагина (конфиг + CLI)."""
249
+ url = options.get("url")
250
+ source_id = options.get("source_id")
251
+ if not url:
252
+ raise ValueError("http source requires 'url'")
253
+ if not source_id:
254
+ raise ValueError("http source requires 'source_id'")
255
+
256
+ axes = _as_tuple(options.get("axes"), name="axes")
257
+ measurable = _as_tuple(options.get("measurable"), name="measurable")
258
+ scalars = _as_tuple(options.get("scalars"), name="scalars")
259
+ reference = _as_mapping(options.get("reference"), name="reference")
260
+ multi = _as_mapping(options.get("multi"), name="multi")
261
+
262
+ mapped = list(axes) + list(measurable) + list(scalars) + list(reference)
263
+ duplicated = sorted({name for name in mapped if mapped.count(name) > 1})
264
+ if duplicated:
265
+ raise ValueError("http source: field mapped more than once: " + ", ".join(duplicated))
266
+ unknown_multi = sorted(set(multi) - set(axes))
267
+ if unknown_multi:
268
+ raise ValueError(
269
+ "http source: 'multi' is allowed only for categorical axes: " + ", ".join(unknown_multi)
270
+ )
271
+
272
+ timeout = options.get("timeout", DEFAULT_TIMEOUT)
273
+ if not isinstance(timeout, int | float) or timeout <= 0:
274
+ raise ValueError("http source: 'timeout' must be a positive number")
275
+
276
+ return HttpSource(
277
+ url=str(url),
278
+ source_id=str(source_id),
279
+ kind=str(options.get("kind") or DEFAULT_KIND),
280
+ key=_as_tuple(options.get("key"), name="key") or DEFAULT_KEY,
281
+ axes=axes,
282
+ measurable=measurable,
283
+ reference=reference,
284
+ scalars=scalars,
285
+ multi=multi,
286
+ hash_fields=_as_tuple(options.get("hash"), name="hash"),
287
+ items=str(options.get("items") or ""),
288
+ headers=_as_mapping(options.get("headers"), name="headers"),
289
+ timeout=float(timeout),
290
+ )
291
+
292
+
293
+ def plugin() -> dict[str, Any]:
294
+ """Манифест плагина обычными данными (ADR-0013)."""
295
+ return {"requires_contract": REQUIRES_CONTRACT, "factory": create}
296
+
297
+
298
+ __all__ = [
299
+ "DEFAULT_KIND",
300
+ "DEFAULT_KEY",
301
+ "DEFAULT_TIMEOUT",
302
+ "HASH_ALGO",
303
+ "KEY_SEPARATOR",
304
+ "REQUIRES_CONTRACT",
305
+ "HttpSource",
306
+ "HttpSourceError",
307
+ "create",
308
+ "plugin",
309
+ "text",
310
+ ]
@@ -0,0 +1,65 @@
1
+ Metadata-Version: 2.4
2
+ Name: agoralar-source-http
3
+ Version: 0.2.1
4
+ Summary: HTTP JSON API как источник объектов для AxisLar (плагин AgoraLar)
5
+ License-Expression: MIT
6
+ Project-URL: Source, https://github.com/authorlarciss/AgoraLar/tree/HEAD/plugins/source_http
7
+ Project-URL: Kernel, https://github.com/authorlarciss/AxisLar
8
+ Requires-Python: <3.15,>=3.13
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: axislar-core<0.11,>=0.10
12
+ Provides-Extra: dev
13
+ Requires-Dist: pytest>=8; extra == "dev"
14
+ Requires-Dist: pytest-asyncio>=0.24; extra == "dev"
15
+ Requires-Dist: mypy>=1.10; extra == "dev"
16
+ Requires-Dist: ruff>=0.6; extra == "dev"
17
+ Dynamic: license-file
18
+
19
+ # agoralar-source-http
20
+
21
+ Источник объектов для [AxisLar](https://github.com/authorlarciss/AxisLar):
22
+ JSON-API отдаёт массив записей, плагин раскладывает поля по осям и
23
+ скалярам.
24
+
25
+ Плагин продукта [AgoraLar](https://github.com/authorlarciss/AgoraLar).
26
+ Источник только читает: `GET` без тела, без ретраев.
27
+
28
+ ```toml
29
+ [plugins.http]
30
+ url = "https://api.example.net/edits" # источник данных
31
+ source_id = "api-edits" # стабильный id источника, не URL
32
+ kind = "edit"
33
+ key = ["id"] # естественный ключ → entity_id_for
34
+ items = "data.items" # путь к массиву в ответе ('' — корень)
35
+
36
+ axes = ["author", "genre"] # категориальные оси
37
+ multi = { genre = "," } # список или строка через запятую
38
+ measurable = ["year"] # измеримые оси
39
+ reference = { editor = "person" } # ссылочные оси: поле → вид цели
40
+ scalars = ["title"] # текстовые поля
41
+ hash = ["title", "author", "year"] # по умолчанию — все сопоставленные
42
+
43
+ headers = { Authorization = "Bearer ..." }
44
+ timeout = 10.0
45
+ ```
46
+
47
+ Правила те же, что у `agoralar-source-sql` (это намеренно: у источников
48
+ одна семантика, разные транспорты):
49
+
50
+ - `null` и отсутствующее поле — **не значение**, а отсутствие: фасет не
51
+ создаётся, объект разреженный (ADR-0010 ядра);
52
+ - `multi`-поле принимает и JSON-массив, и строку с разделителем;
53
+ - bool в `measurable` — предупреждение, а не `1`/`0`;
54
+ - запись без значения в ключевом поле пропускается с предупреждением;
55
+ - `content_hash` — по каноническому JSON **сопоставленных** полей, поэтому
56
+ прочие поля ответа не считаются изменением объекта;
57
+ - `id` = `entity_id_for(source_id, key)`, `key` — значения ключевых полей
58
+ через unit separator (`\x1f`).
59
+
60
+ Ошибки транспорта — `HttpSourceError` (подкласс `RuntimeError`): статус
61
+ `>= 400`, недоступный хост, невалидный JSON, ответ не массив объектов.
62
+ Продукт печатает причину и завершает прогон, не трогая хранилище.
63
+
64
+ Проверки — `run_source_sync_contract` из ядра, тот же набор, что у
65
+ `filesystem` и `sql`.
@@ -0,0 +1,7 @@
1
+ agora_source_http/__init__.py,sha256=T17rXGXg4uSW5MJsKga7NxGmF8rCxxktdPg5gQf9_qw,11980
2
+ agoralar_source_http-0.2.1.dist-info/licenses/LICENSE,sha256=Yu5isJQWAEfcgXgtHntFHNSDWzXKIDmrsBOqoO07wlc,1070
3
+ agoralar_source_http-0.2.1.dist-info/METADATA,sha256=YTXMeUrSiZaCNf16zm91dF_a6ussYDcS7nduiGtwUF4,3613
4
+ agoralar_source_http-0.2.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
5
+ agoralar_source_http-0.2.1.dist-info/entry_points.txt,sha256=b146_OQVTgLjAnOZo1ivg3YmeQQ3zzUrECWyH2pEnTo,50
6
+ agoralar_source_http-0.2.1.dist-info/top_level.txt,sha256=qGiXJ062HEyc_9y0Dvjoggq7DWM1TR-pE8h38ULv62A,18
7
+ agoralar_source_http-0.2.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [agoralar.source]
2
+ http = agora_source_http:plugin
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 authorlarciss
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ agora_source_http