@capagents/forgeqe 2.10.4 → 3.0.0

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 (162) hide show
  1. package/HOW_TO_USE.md +119 -16
  2. package/README.md +1 -1
  3. package/THIRD_PARTY_NOTICES.md +1 -0
  4. package/dist/docs-site/docs/architecture/index.html +1 -0
  5. package/dist/docs-site/docs/cost-architecture/index.html +1 -1
  6. package/dist/docs-site/docs/index.html +158 -19
  7. package/dist/docs-site/docs/mobile/index.html +38 -2
  8. package/dist/docs-site/docs/search.js +1 -1
  9. package/dist/forgeqe.js +2121 -1947
  10. package/dist/web/assets/Agent-DISh0THc.js +8 -0
  11. package/dist/web/assets/ApiTests-CK0HqEH4.js +10 -0
  12. package/dist/web/assets/Browse-WylAQZvD.js +2 -0
  13. package/dist/web/assets/Chat-B7IOg3I3.js +5 -0
  14. package/dist/web/assets/CommandPalette-CkreEJ8R.js +1 -0
  15. package/dist/web/assets/Compare-CgOfZofk.js +1 -0
  16. package/dist/web/assets/Cost-Dl5-viu4.js +1 -0
  17. package/dist/web/assets/Data-Bv2S5wkW.js +6 -0
  18. package/dist/web/assets/Desktop-CifPwy5u.js +1 -0
  19. package/dist/web/assets/DesktopReview-fpGdtU4r.js +1 -0
  20. package/dist/web/assets/Evidence-hOZDzfKt.js +1 -0
  21. package/dist/web/assets/Explore-c85VGE9Q.js +2 -0
  22. package/dist/web/assets/Features-DXL_vSjn.js +1 -0
  23. package/dist/web/assets/Flags-B7x2pDud.js +2 -0
  24. package/dist/web/assets/Flaky-BM3syqCt.js +1 -0
  25. package/dist/web/assets/Impact-BUCh8OAI.js +3 -0
  26. package/dist/web/assets/Jobs-B8sBDYRI.js +5 -0
  27. package/dist/web/assets/KindPage-yVmpQm7L.js +6 -0
  28. package/dist/web/assets/Migration-BOLN1duU.js +2 -0
  29. package/dist/web/assets/Product-C0FeEaJg.js +7 -0
  30. package/dist/web/assets/Production-BSMQyWKd.js +1 -0
  31. package/dist/web/assets/Quality-DsM9gWZb.js +1 -0
  32. package/dist/web/assets/Readiness-BhqkAJYN.js +1 -0
  33. package/dist/web/assets/Record-CPx-lK53.js +2 -0
  34. package/dist/web/assets/Regression-BXbX46nO.js +5 -0
  35. package/dist/web/assets/{RelationGraph-D_ZVeOBh.js → RelationGraph-eoGXXz5t.js} +1 -1
  36. package/dist/web/assets/Reports-36YQzVhA.js +2 -0
  37. package/dist/web/assets/Response-DplUOsue.js +4 -0
  38. package/dist/web/assets/RunDiff-D0fDhRmK.js +1 -0
  39. package/dist/web/assets/Runs-Bv1Ef8zq.js +2 -0
  40. package/dist/web/assets/Steps-Cm-atRtk.js +2 -0
  41. package/dist/web/assets/TestCases-B9x9W3zJ.js +1 -0
  42. package/dist/web/assets/TestData-DsJ6Z2YI.js +2 -0
  43. package/dist/web/assets/TestDebt-B_FUbMOb.js +1 -0
  44. package/dist/web/assets/Tosca-nxVCubA5.js +3 -0
  45. package/dist/web/assets/WhatsNew-CdnbMvrr.js +1 -0
  46. package/dist/web/assets/agentLink-BGKAF6xd.js +1 -0
  47. package/dist/web/assets/capture.worklet-C2TjBQ56.js +11 -0
  48. package/dist/web/assets/capture.worklet-UcNywATd.js +1 -0
  49. package/dist/web/assets/dataParts-Bn-tzbKg.js +3 -0
  50. package/dist/web/assets/{families-zlLgApNV.js → families-DPlFfKf2.js} +1 -1
  51. package/dist/web/assets/filters-Bj5K1WaL.js +1 -0
  52. package/dist/web/assets/fold-BhRpA0sy.js +1 -0
  53. package/dist/web/assets/frame-D_TPoUTD.js +16 -0
  54. package/dist/web/assets/index-BRB-oAMd.js +67 -0
  55. package/dist/web/assets/index-CIw5WfL8.css +2 -0
  56. package/dist/web/assets/{line-icons-CQ-3V8ax.js → line-icons-DBwNPSmu.js} +1 -1
  57. package/dist/web/assets/{logos-DfCytw3-.js → logos-839CfoKx.js} +1 -1
  58. package/dist/web/assets/{markdown-nTIj9lyp.js → markdown-6z0km3hN.js} +7 -7
  59. package/dist/web/assets/paletteCommands-CZFdKGhh.js +1 -0
  60. package/dist/web/assets/parts-VPcxh6Jc.js +1 -0
  61. package/dist/web/assets/{productParts-DK3ULNpv.js → productParts-BjfWgMtq.js} +1 -1
  62. package/dist/web/assets/qualityParts-PGN65yfI.js +1 -0
  63. package/dist/web/assets/{recordTest-CqxnF953.js → recordTest-EkxSMWbe.js} +1 -1
  64. package/dist/web/assets/rows-uLoguIo5.js +1 -0
  65. package/dist/web/assets/segmented-DphDskQz.js +1 -0
  66. package/dist/web/assets/{usePageChat-Dl2aUtHP.js → usePageChat-DqEwGcyO.js} +1 -1
  67. package/dist/web/index.html +6 -6
  68. package/docs/ARCHITECTURE.md +1 -0
  69. package/docs/COST_ARCHITECTURE.md +1 -1
  70. package/docs/MOBILE.md +40 -0
  71. package/docs/user-guide.html +158 -19
  72. package/evals/prompts/brain/browser-narrow-with-filters.yaml +20 -0
  73. package/forgeqe.example.yaml +11 -1
  74. package/package.json +4 -1
  75. package/prompts/brain.md +4 -0
  76. package/prompts/browser-goal-verification.md +2 -0
  77. package/prompts/refine.md +2 -0
  78. package/prompts/requests-rule.md +1 -1
  79. package/prompts/talk-summary.md +43 -0
  80. package/prompts/talk.md +49 -0
  81. package/prompts/test-agent.md +1 -0
  82. package/prompts/test-reviewer.md +2 -1
  83. package/prompts/test-rules.md +3 -0
  84. package/py/forgeqe_data/__init__.py +1 -0
  85. package/py/forgeqe_data/__main__.py +12 -0
  86. package/py/forgeqe_data/connect.py +290 -0
  87. package/py/forgeqe_data/connstr.py +169 -0
  88. package/py/forgeqe_data/flows.py +603 -0
  89. package/py/forgeqe_data/guard.py +214 -0
  90. package/py/forgeqe_data/mongo.py +219 -0
  91. package/py/forgeqe_data/schema.py +431 -0
  92. package/py/forgeqe_data/service.py +651 -0
  93. package/py/forgeqe_data/streams.py +400 -0
  94. package/py/forgeqe_data/subset.py +299 -0
  95. package/py/forgeqe_data/testdata.py +861 -0
  96. package/py/forgeqe_data/vector.py +113 -0
  97. package/py/forgeqe_desktop/workflow.py +6 -4
  98. package/py/forgeqe_engine/capture.py +5 -4
  99. package/py/forgeqe_engine/diagnostics.py +2 -2
  100. package/py/forgeqe_engine/lenient_json.py +96 -0
  101. package/py/forgeqe_engine/llm.py +4 -0
  102. package/py/forgeqe_engine/network.py +93 -15
  103. package/py/forgeqe_engine/neutral_log.py +16 -1
  104. package/py/forgeqe_engine/recordsession.py +54 -1
  105. package/py/forgeqe_engine/service.py +22 -3
  106. package/py/forgeqe_mobile/appium_driver.py +9 -0
  107. package/py/forgeqe_mobile/apps.py +4 -0
  108. package/py/forgeqe_mobile/maestro.py +3 -0
  109. package/py/forgeqe_mobile/record.py +610 -0
  110. package/py/forgeqe_mobile/service.py +37 -7
  111. package/py/forgeqe_talk/__init__.py +1 -0
  112. package/py/forgeqe_talk/__main__.py +65 -0
  113. package/py/forgeqe_voice/worker.py +141 -0
  114. package/skills/dotnet-nunit-playwright/SKILL.md +1 -0
  115. package/skills/playwright-typescript/SKILL.md +1 -1
  116. package/dist/web/assets/Agent-DaA5WhAY.js +0 -8
  117. package/dist/web/assets/ApiTests-B7xsTGyo.js +0 -10
  118. package/dist/web/assets/Browse-ByYCyAwd.js +0 -2
  119. package/dist/web/assets/Chat-D1-cYNBr.js +0 -3
  120. package/dist/web/assets/CommandPalette-DbxKJJJB.js +0 -1
  121. package/dist/web/assets/Compare-CYLFEtJl.js +0 -1
  122. package/dist/web/assets/Cost-Csz0jMHo.js +0 -1
  123. package/dist/web/assets/Data-BWTme_Yw.js +0 -6
  124. package/dist/web/assets/Desktop-rZ0vB6Ie.js +0 -1
  125. package/dist/web/assets/DesktopReview-_Xha22_d.js +0 -1
  126. package/dist/web/assets/Evidence-DmUyZy9F.js +0 -1
  127. package/dist/web/assets/Explore-2wzgwz3J.js +0 -2
  128. package/dist/web/assets/Features-DazEWqYu.js +0 -1
  129. package/dist/web/assets/Flags-BTt0-pqd.js +0 -2
  130. package/dist/web/assets/Flaky-CjkQp73T.js +0 -1
  131. package/dist/web/assets/Impact-De87sv5J.js +0 -3
  132. package/dist/web/assets/Jobs-aiNGBVHL.js +0 -5
  133. package/dist/web/assets/KindPage-CrGoFeSa.js +0 -6
  134. package/dist/web/assets/Migration-BAhQ1DZO.js +0 -2
  135. package/dist/web/assets/Product-DpK-PIxV.js +0 -7
  136. package/dist/web/assets/Production-D6A89rZZ.js +0 -1
  137. package/dist/web/assets/Quality-Bc5wCsog.js +0 -1
  138. package/dist/web/assets/Readiness-CoVgZw2X.js +0 -1
  139. package/dist/web/assets/Record-DcgBatJJ.js +0 -2
  140. package/dist/web/assets/Regression-BJLYrqST.js +0 -5
  141. package/dist/web/assets/Reports-DYfyfEDy.js +0 -2
  142. package/dist/web/assets/Response-CNLi9Dqu.js +0 -4
  143. package/dist/web/assets/RunDiff-BMTdRhii.js +0 -1
  144. package/dist/web/assets/Runs-lb78rvPV.js +0 -2
  145. package/dist/web/assets/Steps-BDSeIznj.js +0 -2
  146. package/dist/web/assets/TestCases-CfUwd67O.js +0 -1
  147. package/dist/web/assets/TestData-DP7cvW48.js +0 -2
  148. package/dist/web/assets/TestDebt-CqARxL7k.js +0 -1
  149. package/dist/web/assets/Tosca-CLAz9tWT.js +0 -3
  150. package/dist/web/assets/WhatsNew-1lhTRE5Z.js +0 -1
  151. package/dist/web/assets/dataParts-DI_OJhy5.js +0 -3
  152. package/dist/web/assets/filters-CflRmNDz.js +0 -1
  153. package/dist/web/assets/fold-pOBiaSlF.js +0 -1
  154. package/dist/web/assets/frame-CYYiRu5P.js +0 -4
  155. package/dist/web/assets/index-CNDoTeRV.css +0 -2
  156. package/dist/web/assets/index-D4a0w3Vl.js +0 -67
  157. package/dist/web/assets/palette-Cj4CUs0K.js +0 -1
  158. package/dist/web/assets/parts-C53RxMcR.js +0 -1
  159. package/dist/web/assets/qualityParts-C9FItsTg.js +0 -1
  160. package/dist/web/assets/rows-D6rPRkHl.js +0 -1
  161. package/dist/web/assets/segmented-CAf_qz5Z.js +0 -1
  162. package/dist/web/assets/thread-DQdyL3Sv.js +0 -5
@@ -0,0 +1,400 @@
1
+ """
2
+ Hops that are not tables: a Kafka topic and an HTTP API, each as a source or a target. Each reader answers
3
+ what flows.check and flows.trace ask of a table reader: keys (with when they changed) and rows by key, a row being the
4
+ message's or the response's JSON flattened to dotted names (payload.customer.email).
5
+
6
+ Kafka is read without a consumer group, so no offset is committed and no other consumer is affected; a read stops at
7
+ the end offsets taken when it began, after at most MAX_MESSAGES. An API is called with GET or POST only (never a call
8
+ that changes data), at the base URL of an API app of the environment, with the headers forgeqe.yaml's api.headers
9
+ give, and never follows a redirect; a key is put into the path URL-encoded, or into the body.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import datetime as dt
14
+ import json
15
+ import re
16
+ import time
17
+ import urllib.error
18
+ import urllib.parse
19
+ import urllib.request
20
+ from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple
21
+
22
+ from .connect import ConnectError, Target
23
+
24
+ MAX_MESSAGES = 200_000
25
+ MAX_API_KEYS = 500
26
+ MAX_RESPONSE = 2 * 1024 * 1024
27
+
28
+
29
+ def flatten(value: Any, prefix: str = "", out: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
30
+ """{"a": {"b": 1}} as {"a": {...}, "a.b": 1}: a column of a flow can name any level."""
31
+ out = {} if out is None else out
32
+ if isinstance(value, dict):
33
+ for k, v in value.items():
34
+ name = f"{prefix}.{k}" if prefix else str(k)
35
+ out[name] = v
36
+ if isinstance(v, dict):
37
+ flatten(v, name, out)
38
+ return out
39
+
40
+
41
+ # ------------------------------------------------------------------------------------------------ Kafka
42
+
43
+
44
+ def kafka_config(t: Target) -> Dict[str, Any]:
45
+ """Client settings from a databases: entry with engine: kafka (host: brokers, user/password_env for SASL)."""
46
+ brokers = t.info.host if "," in t.info.host or ":" in t.info.host else f"{t.info.host}:{t.info.port or 9092}"
47
+ cfg: Dict[str, Any] = {"bootstrap_servers": [b.strip() for b in brokers.split(",") if b.strip()], "client_id": "forgeqe", "request_timeout_ms": 30_000}
48
+ protocol = t.options.get("security_protocol") or ("SASL_SSL" if t.info.user else "PLAINTEXT")
49
+ cfg["security_protocol"] = protocol.upper()
50
+ if t.info.user:
51
+ cfg.update(sasl_mechanism=(t.options.get("sasl_mechanism") or "PLAIN").upper(), sasl_plain_username=t.info.user, sasl_plain_password=t.info.password)
52
+ if cfg["security_protocol"].endswith("SSL") and t.ssl_ca:
53
+ cfg["ssl_cafile"] = t.ssl_ca
54
+ return cfg
55
+
56
+
57
+ def _consumer(t: Target) -> Any:
58
+ try:
59
+ from kafka import KafkaConsumer
60
+ except ImportError as err:
61
+ raise ConnectError("Kafka needs kafka-python in the data engine (ForgeQE sets it up for an engine: kafka database)") from err
62
+ # No group_id: nothing is committed, and no consumer group sees this reader.
63
+ return KafkaConsumer(group_id=None, enable_auto_commit=False, consumer_timeout_ms=5000, **kafka_config(t))
64
+
65
+
66
+ def kafka_test(t: Target) -> Dict[str, Any]:
67
+ started = time.time()
68
+ c = _consumer(t)
69
+ try:
70
+ topics = sorted(x for x in c.topics() if not x.startswith("__"))
71
+ finally:
72
+ c.close()
73
+ return {"ok": True, "server_version": "kafka", "topics": len(topics), "ms": int((time.time() - started) * 1000)}
74
+
75
+
76
+ def _decode(raw: Any) -> Any:
77
+ if raw is None:
78
+ return None
79
+ try:
80
+ return json.loads(raw.decode("utf-8") if isinstance(raw, (bytes, bytearray)) else raw)
81
+ except (ValueError, UnicodeDecodeError):
82
+ return raw.decode("utf-8", "replace") if isinstance(raw, (bytes, bytearray)) else raw
83
+
84
+
85
+ def read_topic(t: Target, topic: str, since: Optional[dt.datetime] = None, limit: int = MAX_MESSAGES) -> List[Dict[str, Any]]:
86
+ """The topic's messages up to the end offsets taken now, from `since` (message time) or the beginning, flattened."""
87
+ from kafka import TopicPartition
88
+
89
+ c = _consumer(t)
90
+ try:
91
+ parts = c.partitions_for_topic(topic)
92
+ if not parts:
93
+ raise ConnectError(f"No topic {topic!r} on {t.name}")
94
+ tps = [TopicPartition(topic, p) for p in sorted(parts)]
95
+ c.assign(tps)
96
+ end = c.end_offsets(tps)
97
+ if since is not None:
98
+ starts = c.offsets_for_times({tp: int(since.replace(tzinfo=dt.timezone.utc).timestamp() * 1000) for tp in tps})
99
+ for tp in tps:
100
+ found = starts.get(tp)
101
+ c.seek(tp, found.offset if found else end[tp])
102
+ else:
103
+ c.seek_to_beginning(*tps)
104
+ out: List[Dict[str, Any]] = []
105
+ done = {tp for tp in tps if c.position(tp) >= end[tp]}
106
+ while len(done) < len(tps) and len(out) < limit:
107
+ batch = c.poll(timeout_ms=3000, max_records=2000)
108
+ if not batch:
109
+ break
110
+ for tp, msgs in batch.items():
111
+ for m in msgs:
112
+ if m.offset >= end[tp]:
113
+ done.add(tp)
114
+ continue
115
+ value = _decode(m.value)
116
+ row = flatten(value) if isinstance(value, dict) else {"$value": value}
117
+ row.update({"$key": _decode(m.key), "$timestamp": dt.datetime.fromtimestamp(m.timestamp / 1000, dt.timezone.utc).replace(tzinfo=None), "$partition": m.partition, "$offset": m.offset})
118
+ out.append(row)
119
+ if c.position(tp) >= end[tp]:
120
+ done.add(tp)
121
+ return out
122
+ finally:
123
+ c.close()
124
+
125
+
126
+ def topic_catalog(t: Target, sample: int = 50) -> Dict[str, Any]:
127
+ """Topics with the fields of a sample of their latest messages, in the catalog's shape (a topic is a table)."""
128
+ from kafka import TopicPartition
129
+
130
+ c = _consumer(t)
131
+ tables: Dict[str, Any] = {}
132
+ try:
133
+ for topic in sorted(x for x in c.topics() if not x.startswith("__")):
134
+ tps = [TopicPartition(topic, p) for p in sorted(c.partitions_for_topic(topic) or [])]
135
+ if not tps:
136
+ continue
137
+ c.assign(tps)
138
+ end = c.end_offsets(tps)
139
+ for tp in tps:
140
+ c.seek(tp, max(0, end[tp] - max(1, sample // len(tps))))
141
+ fields: Dict[str, set] = {}
142
+ batch = c.poll(timeout_ms=3000, max_records=sample)
143
+ for msgs in batch.values():
144
+ for m in msgs:
145
+ value = _decode(m.value)
146
+ for k, v in (flatten(value) if isinstance(value, dict) else {"$value": value}).items():
147
+ fields.setdefault(k, set()).add(type(v).__name__)
148
+ tables[topic] = {"kind": "topic", "columns": [{"name": k, "type": "|".join(sorted(v)), "nullable": True} for k, v in sorted(fields.items())], "pk": [], "fks": [], "comment": "", "rows": sum(end.values())}
149
+ finally:
150
+ c.close()
151
+ return {"version": 2, "schema": None, "tables": tables, "read_at": time.time(), "fingerprint": None, "checked_at": time.time()}
152
+
153
+
154
+ class TopicReader:
155
+ """A topic as a flow side: rows are messages, the latest message for a key standing for it."""
156
+
157
+ def __init__(self, target: Target, topic: str) -> None:
158
+ self.target = target
159
+ self.topic = topic
160
+ self.name = topic
161
+ self._cache: Optional[Tuple[Optional[dt.datetime], List[Dict[str, Any]]]] = None
162
+ self.conn = self # flows.trace calls conn.rollback() between waits; a new read sees new messages.
163
+
164
+ def rollback(self) -> None:
165
+ self._cache = None
166
+
167
+ def close(self) -> None:
168
+ self._cache = None
169
+
170
+ def _messages(self, since: Optional[dt.datetime]) -> List[Dict[str, Any]]:
171
+ if self._cache is None or self._cache[0] != since:
172
+ self._cache = (since, read_topic(self.target, self.topic, since))
173
+ return self._cache[1]
174
+
175
+ def keys(self, key: str, changed: str = "", since: Optional[dt.datetime] = None, limit: int = MAX_MESSAGES) -> List[Tuple[Any, Any]]:
176
+ from .flows import _key
177
+
178
+ latest: Dict[Any, Any] = {}
179
+ for m in self._messages(since):
180
+ k = m.get(key)
181
+ if k is not None:
182
+ latest[_key(k)] = m.get(changed or "$timestamp")
183
+ return sorted(latest.items(), key=lambda kv: str(kv[0]))[: limit + 1]
184
+
185
+ def rows(self, key: str, values: Sequence[Any]) -> Dict[Any, List[Dict[str, Any]]]:
186
+ from .flows import _key
187
+
188
+ wanted = {_key(v) for v in values}
189
+ out: Dict[Any, List[Dict[str, Any]]] = {}
190
+ for m in self._messages(None):
191
+ k = m.get(key)
192
+ if k is not None and _key(k) in wanted:
193
+ # Every message for the key counts toward duplicates; the latest is first, so it is the one compared.
194
+ out.setdefault(_key(k), []).insert(0, m)
195
+ return out
196
+
197
+ def find(self, key: str, where: Mapping[str, Any]) -> Any:
198
+ from .flows import _key
199
+
200
+ for m in reversed(self._messages(None)):
201
+ if all(str(m.get(c)) == str(v) for c, v in where.items()):
202
+ return _key(m.get(key))
203
+ return None
204
+
205
+ def scalar(self, sql: str) -> Any:
206
+ raise ValueError("ready: is a query on a database; a Kafka topic has none")
207
+
208
+
209
+ # ------------------------------------------------------------------------------------------------ API
210
+
211
+
212
+ READ_METHODS = ("GET", "POST")
213
+ MAX_PAGES = 100
214
+ LIST_FIELDS = ("items", "data", "results", "value", "records", "content")
215
+
216
+
217
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
218
+ """A redirect is not followed: it could carry the API's headers (a token) to another host."""
219
+
220
+ def redirect_request(self, *args: Any, **kwargs: Any) -> None: # type: ignore[override]
221
+ return None
222
+
223
+
224
+ _opener = urllib.request.build_opener(_NoRedirect)
225
+
226
+
227
+ def _fill(value: Any, key: Any) -> Any:
228
+ """A request body with {key} filled in: a string that is only {key} becomes the key itself (a number stays one)."""
229
+ if isinstance(value, str):
230
+ return key if value == "{key}" else value.replace("{key}", str(key))
231
+ if isinstance(value, dict):
232
+ return {k: _fill(v, key) for k, v in value.items()}
233
+ if isinstance(value, list):
234
+ return [_fill(v, key) for v in value]
235
+ return value
236
+
237
+
238
+ def _at(value: Any, path: str) -> Any:
239
+ """data.items, or results.0.contact: a field of a response by its dotted path."""
240
+ for part in path.split(".") if path else []:
241
+ if isinstance(value, dict):
242
+ value = value.get(part)
243
+ elif isinstance(value, list) and part.isdigit() and int(part) < len(value):
244
+ value = value[int(part)]
245
+ else:
246
+ return None
247
+ return value
248
+
249
+
250
+ def _when(v: Any) -> Optional[dt.datetime]:
251
+ """When a record changed, from an API's JSON: an ISO date and time, or seconds (or milliseconds) since 1970; UTC, naive."""
252
+ if isinstance(v, (int, float)) and not isinstance(v, bool):
253
+ return dt.datetime.utcfromtimestamp(v / 1000 if v > 1e11 else v)
254
+ if isinstance(v, str) and v.strip():
255
+ try:
256
+ t = dt.datetime.fromisoformat(v.strip().replace("Z", "+00:00"))
257
+ except ValueError:
258
+ return None
259
+ return t.replace(tzinfo=None) if t.tzinfo is None else t.astimezone(dt.timezone.utc).replace(tzinfo=None)
260
+ return None
261
+
262
+
263
+ class ApiReader:
264
+ """
265
+ An API as a flow's side, at the base URL of an API app of the environment.
266
+
267
+ As a target it answers for one key: {key} in its path (/contacts/{key}) or its body (a search or a GraphQL query),
268
+ one call a key, a 404 meaning the record is not there. As a source it is a list endpoint (/contacts, no {key}),
269
+ read page by page through the response's next link. `items` is where the records are in a response (data.items);
270
+ without it, the response itself, or its first list among items, data, results, value, records and content. Calls
271
+ are GET or POST (a lookup or a search): a check never changes data, so no other method is made.
272
+ """
273
+
274
+ def __init__(self, name: str, base: str, path: str, headers: Mapping[str, str], timeout: int = 30, *, method: str = "GET",
275
+ body: Any = None, items: str = "", next_: str = "") -> None:
276
+ if not re.match(r"^https?://", base or ""):
277
+ raise ValueError(f"API {name}: its base URL must be http(s)")
278
+ if not path.startswith("/") or "://" in path or ".." in path:
279
+ raise ValueError(f"API {name}: path is a path on the API, for example /contacts/{{key}} or /contacts")
280
+ method = (method or "GET").upper()
281
+ if method not in READ_METHODS:
282
+ raise ValueError(f"API {name}: {method} could change data; a check calls GET or POST (a lookup or a search)")
283
+ self.name, self.base, self.path, self.headers, self.timeout = name, base.rstrip("/"), path, dict(headers), timeout
284
+ self.method, self.body, self.items, self.next = method, body, items, next_
285
+ self.by_key = "{key}" in path or "{key}" in json.dumps(body, default=str)
286
+ parsed = urllib.parse.urlparse(self.base)
287
+ self.scheme, self.host = parsed.scheme, parsed.netloc
288
+ self.conn = self
289
+ self._listed: Optional[Dict[Any, List[Dict[str, Any]]]] = None
290
+
291
+ def rollback(self) -> None:
292
+ # A wait for a record to arrive reads the list again.
293
+ self._listed = None
294
+
295
+ def close(self) -> None:
296
+ return None
297
+
298
+ def _call(self, target: str, key: Any = None) -> Optional[Any]:
299
+ url = target if re.match(r"^https?://", target) else self.base + target
300
+ u = urllib.parse.urlparse(url)
301
+ if u.netloc != self.host or u.scheme != self.scheme:
302
+ raise ValueError(f"API {self.name}: a call left its base URL")
303
+ headers = {"Accept": "application/json", **self.headers}
304
+ data = None
305
+ if self.method == "POST":
306
+ body = _fill(self.body, key) if self.body is not None else {}
307
+ data = (body if isinstance(body, str) else json.dumps(body, default=str)).encode("utf-8")
308
+ headers.setdefault("Content-Type", "application/json")
309
+ req = urllib.request.Request(url, data=data, headers=headers, method=self.method)
310
+ try:
311
+ with _opener.open(req, timeout=self.timeout) as res:
312
+ raw = res.read(MAX_RESPONSE + 1)
313
+ except urllib.error.HTTPError as err:
314
+ if err.code == 404:
315
+ return None
316
+ moved = " (redirects are not followed)" if 300 <= err.code < 400 else ""
317
+ raise ConnectError(f"API {self.name}: {self.method} {self.path} answered {err.code}{moved}") from None
318
+ if len(raw) > MAX_RESPONSE:
319
+ raise ConnectError(f"API {self.name}: a response is larger than {MAX_RESPONSE // 1024 // 1024} MB")
320
+ return json.loads(raw.decode("utf-8")) if raw.strip() else None
321
+
322
+ def _records(self, body: Any) -> List[Dict[str, Any]]:
323
+ value = _at(body, self.items) if self.items else body
324
+ if not self.items and isinstance(body, dict):
325
+ value = next((body[f] for f in LIST_FIELDS if isinstance(body.get(f), list)), body)
326
+ return [flatten(x) for x in (value if isinstance(value, list) else [value]) if isinstance(x, dict)]
327
+
328
+ def _list(self, key: str) -> Dict[Any, List[Dict[str, Any]]]:
329
+ """Every record of the list endpoint, by key, through its pages (at most MAX_PAGES pages, and about MAX_KEYS records)."""
330
+ from .flows import MAX_KEYS, _key
331
+
332
+ if self._listed is not None:
333
+ return self._listed
334
+ out: Dict[Any, List[Dict[str, Any]]] = {}
335
+ target: Optional[str] = self.path
336
+ pages = count = 0
337
+ while target and pages < MAX_PAGES and count <= MAX_KEYS:
338
+ body = self._call(target)
339
+ pages += 1
340
+ for row in self._records(body):
341
+ k = _key(row.get(key))
342
+ if k is not None:
343
+ out.setdefault(k, []).append(row)
344
+ count += 1
345
+ nxt = _at(body, self.next) if self.next else None
346
+ target = nxt if isinstance(nxt, str) and nxt.strip() else None
347
+ self._listed = out
348
+ return out
349
+
350
+ def keys(self, key: str, changed: str = "", since: Optional[dt.datetime] = None, limit: int = 0) -> List[Tuple[Any, Any]]:
351
+ if self.by_key:
352
+ raise ValueError(f"API {self.name} answers for one key ({{key}} in its path or body): it can be a flow's target; a source is a list endpoint, without extra: true on a target")
353
+ out = []
354
+ for k, rows in self._list(key).items():
355
+ when = _when(rows[0].get(changed)) if changed else None
356
+ if since is not None and changed and (when is None or when < since):
357
+ continue
358
+ out.append((k, when))
359
+ out.sort(key=lambda p: (isinstance(p[0], str), p[0]))
360
+ return out[: limit + 1] if limit else out
361
+
362
+ def rows(self, key: str, values: Sequence[Any]) -> Dict[Any, List[Dict[str, Any]]]:
363
+ from .flows import _key
364
+
365
+ vals = [_key(v) for v in values]
366
+ if not self.by_key:
367
+ listed = self._list(key)
368
+ return {v: listed[v] for v in vals if v in listed}
369
+ if len(vals) > MAX_API_KEYS:
370
+ raise ValueError(f"API {self.name}: at most {MAX_API_KEYS} keys a check, one call each; narrow the source with since:")
371
+ out: Dict[Any, List[Dict[str, Any]]] = {}
372
+ for v in vals:
373
+ path = self.path.replace("{key}", urllib.parse.quote(str(v), safe=""))
374
+ for row in self._records(self._call(path, v)):
375
+ if _key(row.get(key)) == v:
376
+ out.setdefault(v, []).append(row)
377
+ return out
378
+
379
+ def find(self, key: str, where: Mapping[str, Any]) -> Any:
380
+ """The key of the newest record (the highest key) whose fields hold these values, from the list endpoint."""
381
+ if self.by_key:
382
+ raise ValueError(f"API {self.name} answers for one key, so a record can be followed into it, not found in it")
383
+ found = [k for k, rows in self._list(key).items() if any(all(str(r.get(c)) == str(v) for c, v in where.items()) for r in rows)]
384
+ found.sort(key=lambda k: (isinstance(k, str), k))
385
+ return found[-1] if found else None
386
+
387
+ def scalar(self, sql: str) -> Any:
388
+ raise ValueError("ready: is a query on a database; an API has none")
389
+
390
+
391
+ def resolve_headers(headers: Mapping[str, str], env: Mapping[str, str]) -> Dict[str, str]:
392
+ """api.headers with ${NAME} filled from the environment; a header whose variable is not set is an error."""
393
+ out = {}
394
+ for k, v in headers.items():
395
+ def fill(m: "re.Match[str]") -> str:
396
+ if m.group(1) not in env:
397
+ raise ConnectError(f"api.headers.{k}: the environment variable {m.group(1)} is not set (save it with /auth {m.group(1)})")
398
+ return env[m.group(1)]
399
+ out[k] = re.sub(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}", fill, str(v))
400
+ return out