@ansible-flow/assets 1.1.0-rc.3 → 1.2.0-rc.1

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.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Ansible Flow Designer files a host passes by path: the Python probe, the run events callback, the JSON schemas, the contract with Ansible Flow Server and the sample projects.
4
4
 
5
- Built from [Ansible Flow Designer](https://github.com/ChistokhinSV/ansible-flow-designer) 1.1.0-rc.3
5
+ Built from [Ansible Flow Designer](https://github.com/ChistokhinSV/ansible-flow-designer) 1.2.0-rc.1
6
6
  and released with it. The folders are found by path: `import { probeDir, schemaDir, contractDir, samplesDir } from '@ansible-flow/assets'`.
7
7
 
8
8
  What is in the package, which entry points are documented and what may change:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ansible-flow/assets",
3
- "version": "1.1.0-rc.3",
3
+ "version": "1.2.0-rc.1",
4
4
  "description": "Ansible Flow Designer files a host passes by path: the Python probe, the run events callback, the JSON schemas, the contract with Ansible Flow Server and the sample projects.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://github.com/ChistokhinSV/ansible-flow-designer/blob/main/docs/packages.md",
@@ -0,0 +1,4 @@
1
+ # Ansible Flow Designer debugger library (ADR-0040): masking (mask), capture (capture), safe render
2
+ # (render) and the debugger's side of a paused run (debug). Stdlib and ansible-core 2.19+ only.
3
+ # Imported by the afd_step strategy in debug runs (AFD_DEBUG=1): the probe folder goes on sys.path,
4
+ # so a run that is not a debug run never loads it.
@@ -0,0 +1,316 @@
1
+ # Capture at a pause (ADR-0040 §3, AFD-361): a host's variables by scope, masked, as JSON-safe
2
+ # values, with a size per value and per answer. Only at a pause, only when asked, from one
3
+ # variable_manager.get_vars(play, host) per host per pause.
4
+ #
5
+ # Scopes:
6
+ # - inputs: the step's inputs (its play vars, ADR-0011), as written: a template stays text;
7
+ # - host: inventory variables, set_fact values and registers;
8
+ # - flow: the run's extra vars (the flow's inputs and carried data);
9
+ # - facts: ansible_facts, only when asked for (expensive).
10
+ # Never sent: `vars` (2.19+: every variable again), `hostvars` (walking it renders every variable
11
+ # of every host and runs their lookups) and the other magic variables.
12
+ from __future__ import annotations
13
+
14
+ import contextlib
15
+ import datetime
16
+ import json
17
+ import math
18
+ import re
19
+ from collections.abc import Mapping
20
+
21
+ from .mask import Masked, Masker
22
+
23
+ try:
24
+ from ansible._internal._datatag._tags import TrustedAsTemplate
25
+ from ansible.module_utils._internal._datatag import AnsibleTagHelper
26
+ from ansible.parsing.vault import EncryptedString
27
+
28
+ TAGS = True
29
+ except ImportError: # pragma: no cover
30
+ TAGS = False
31
+
32
+ VALUE_LIMIT = 64 * 1024
33
+ ANSWER_LIMIT = 1024 * 1024
34
+ PAGE = 100
35
+ DEPTH = 40
36
+ SCOPES = ("inputs", "host", "flow", "facts")
37
+ SCOPE_NAMES = {
38
+ "inputs": "Step inputs",
39
+ "host": "Host variables",
40
+ "flow": "Flow data",
41
+ "facts": "Facts",
42
+ }
43
+
44
+ MAGIC = {
45
+ "hostvars", "groups", "group_names", "inventory_hostname", "inventory_hostname_short",
46
+ "inventory_dir", "inventory_file", "play_hosts", "playbook_dir", "role_names", "omit",
47
+ "environment", "ansible_play_hosts", "ansible_play_hosts_all", "ansible_play_batch",
48
+ "ansible_play_name", "ansible_play_role_names", "ansible_role_names", "ansible_version",
49
+ "ansible_check_mode", "ansible_diff_mode", "ansible_forks", "ansible_inventory_sources",
50
+ "ansible_playbook_python", "ansible_config_file", "ansible_verbosity", "ansible_run_tags",
51
+ "ansible_skip_tags", "ansible_dependent_role_names", "ansible_collection_name",
52
+ "ansible_search_path", "ansible_loop_var", "ansible_index_var", "ansible_parent_role_names",
53
+ "ansible_parent_role_paths", "ansible_role_name", "ansible_vault_id", "vars",
54
+ } # fmt: skip
55
+ # The generator's own play variables: not inputs of the step.
56
+ OWN_PLAY_VARS = {"flow_node_id", "afd_sim"}
57
+ # The record inputs task marks an input the flow knows is secret with this constant (AFD-341).
58
+ SECRET_MARK = "__afd_secret__"
59
+ _MARKED = re.compile(r"'([A-Za-z_][A-Za-z0-9_]*)'\s*:\s*'" + SECRET_MARK + "'")
60
+
61
+
62
+ def plain(value: object, depth: int = 0) -> object:
63
+ """A JSON-safe copy: masked parts as markers, vaulted values never decrypted, a template as
64
+ its text (flagged), odd types described."""
65
+ if isinstance(value, Masked):
66
+ return {"__afd__": "masked", "masked": value.kind}
67
+ if depth > DEPTH:
68
+ return {"__afd__": "deep"}
69
+ if TAGS and isinstance(value, EncryptedString):
70
+ return {"__afd__": "masked", "masked": "vault"}
71
+ if type(value).__name__ in ("HostVars", "HostVarsVars"):
72
+ return {"__afd__": "lazy", "type": "hostvars"}
73
+ if isinstance(value, bool) or value is None:
74
+ return value
75
+ if isinstance(value, int):
76
+ return int(value)
77
+ if isinstance(value, float):
78
+ return float(value) if math.isfinite(value) else str(value)
79
+ if isinstance(value, str):
80
+ text = str.__str__(value)
81
+ if "{{" in text or "{%" in text:
82
+ try:
83
+ if not TAGS or TrustedAsTemplate in AnsibleTagHelper.tag_types(value):
84
+ return {"__afd__": "template", "text": text}
85
+ except Exception: # noqa: BLE001
86
+ pass
87
+ return text
88
+ if isinstance(value, Mapping):
89
+ return {str(k): plain(v, depth + 1) for k, v in value.items()}
90
+ if isinstance(value, (list, tuple, set, frozenset)):
91
+ return [plain(v, depth + 1) for v in value]
92
+ if isinstance(value, bytes):
93
+ return {"__afd__": "bytes", "size": len(value)}
94
+ if isinstance(value, (datetime.date, datetime.time)):
95
+ return value.isoformat()
96
+ try:
97
+ shown = repr(value)[:200]
98
+ except Exception as ex: # noqa: BLE001 - an Undefined's repr may raise
99
+ shown = f"<{type(ex).__name__}>"
100
+ return {"__afd__": type(value).__name__, "repr": shown}
101
+
102
+
103
+ def type_of(value: object) -> str:
104
+ """The type a client shows: a marker's kind, or the JSON type."""
105
+ if isinstance(value, dict):
106
+ marker = value.get("__afd__")
107
+ if isinstance(marker, str):
108
+ return marker
109
+ return "dict"
110
+ if isinstance(value, list):
111
+ return "list"
112
+ if isinstance(value, bool):
113
+ return "bool"
114
+ if value is None:
115
+ return "null"
116
+ if isinstance(value, int):
117
+ return "int"
118
+ if isinstance(value, float):
119
+ return "float"
120
+ return "str"
121
+
122
+
123
+ def to_json(value: object) -> str:
124
+ return json.dumps(value, ensure_ascii=False, separators=(",", ":"), default=str)
125
+
126
+
127
+ def entry(name: str | int, value: object) -> dict:
128
+ """One variable or item, as a list shows it: name, type, size; a scalar's value (cut at
129
+ VALUE_LIMIT), a container's count. A masked value says why, never its size."""
130
+ kind = type_of(value)
131
+ out: dict[str, object] = {"name": name, "type": kind}
132
+ if kind == "masked":
133
+ out["masked"] = value["masked"] # type: ignore[index]
134
+ return out
135
+ if kind == "dict" or kind == "list":
136
+ out["count"] = len(value) # type: ignore[arg-type]
137
+ out["size"] = len(to_json(value))
138
+ return out
139
+ text = to_json(value)
140
+ out["size"] = len(text)
141
+ if kind == "str" and len(value) > VALUE_LIMIT: # type: ignore[arg-type]
142
+ out["value"] = value[:VALUE_LIMIT] # type: ignore[index]
143
+ out["cut"] = len(value) # type: ignore[arg-type]
144
+ elif len(text) > VALUE_LIMIT:
145
+ out["value"] = text[:VALUE_LIMIT]
146
+ out["cut"] = len(text)
147
+ else:
148
+ out["value"] = value
149
+ return out
150
+
151
+
152
+ def _walk_tasks(items: list, visit, depth: int = 0) -> None:
153
+ for item in items or []:
154
+ if depth < 8 and hasattr(item, "block"):
155
+ for part in ("block", "rescue", "always"):
156
+ _walk_tasks(getattr(item, part, None) or [], visit, depth + 1)
157
+ continue
158
+ visit(item)
159
+
160
+
161
+ def nolog_registers(play) -> set[str]:
162
+ """The variables a no_log task of the play registers: from 2.19 a register keeps the task's
163
+ whole result, without the _ansible_no_log flag."""
164
+ found: set[str] = set()
165
+
166
+ def visit(task) -> None:
167
+ register = getattr(task, "register", None)
168
+ no_log = getattr(task, "no_log", None)
169
+ if not register or no_log in (None, False, "false", "False", "no"):
170
+ return
171
+ # 2.21: a mapping of names to what each registers; before: one name.
172
+ names = list(register) if isinstance(register, Mapping) else [register]
173
+ found.update(str(n) for n in names)
174
+
175
+ with contextlib.suppress(Exception):
176
+ for part in ("pre_tasks", "tasks", "post_tasks", "handlers"):
177
+ _walk_tasks(list(getattr(play, part, None) or []), visit)
178
+ return found
179
+
180
+
181
+ def secret_inputs(play) -> set[str]:
182
+ """The inputs the flow knows are secret: the record inputs task writes them as a constant."""
183
+ found: set[str] = set()
184
+
185
+ def visit(task) -> None:
186
+ if str(getattr(task, "name", "") or "").endswith("] record inputs"):
187
+ for v in (getattr(task, "args", None) or {}).values():
188
+ found.update(_MARKED.findall(str.__str__(str(v))))
189
+
190
+ with contextlib.suppress(Exception): # nothing more known: the other checks still run
191
+ _walk_tasks(list(play.tasks or []), visit)
192
+ return found
193
+
194
+
195
+ class HostView:
196
+ """A host's variables at one pause: masked and made plain once, then listed and paged."""
197
+
198
+ def __init__(
199
+ self,
200
+ all_vars: Mapping,
201
+ *,
202
+ play_vars: set[str],
203
+ extra: set[str],
204
+ secret: set[str],
205
+ masker: Masker,
206
+ nolog: set[str] | None = None,
207
+ ) -> None:
208
+ self._vars = all_vars
209
+ self._play_vars = play_vars - OWN_PLAY_VARS
210
+ self._extra = extra
211
+ self._secret = secret
212
+ self._nolog = nolog or set()
213
+ self._masker = masker
214
+ self._scopes: dict[str, dict[str, object]] = {}
215
+ for v in all_vars.values():
216
+ masker.learn(v)
217
+
218
+ def scope_of(self, name: str) -> str | None:
219
+ if name in MAGIC or name in OWN_PLAY_VARS or name.startswith("ansible_facts"):
220
+ return None
221
+ if name in self._extra:
222
+ return "flow"
223
+ if name in self._play_vars:
224
+ return "inputs"
225
+ facts = self._vars.get("ansible_facts")
226
+ if isinstance(facts, Mapping) and name.startswith("ansible_") and name[8:] in facts:
227
+ return None # a fact again, as a variable (INJECT_FACTS_AS_VARS)
228
+ if name == "ansible_local":
229
+ return None
230
+ return "host"
231
+
232
+ def scope(self, scope: str) -> dict[str, object]:
233
+ """The scope's values by name, plain and masked."""
234
+ if scope in self._scopes:
235
+ return self._scopes[scope]
236
+ out: dict[str, object] = {}
237
+ if scope == "facts":
238
+ facts = self._vars.get("ansible_facts")
239
+ if isinstance(facts, Mapping):
240
+ for name in sorted(facts, key=str):
241
+ out[str(name)] = plain(self._masker.mask(str(name), facts[name]))
242
+ else:
243
+ for name in sorted(self._vars, key=str):
244
+ if self.scope_of(str(name)) != scope:
245
+ continue
246
+ if scope == "inputs" and name in self._secret:
247
+ out[name] = plain(Masked("credential"))
248
+ continue
249
+ if scope == "host" and name in self._nolog:
250
+ out[name] = plain(Masked("no_log"))
251
+ continue
252
+ out[name] = plain(self._masker.mask(str(name), self._vars[name]))
253
+ self._scopes[scope] = out
254
+ return out
255
+
256
+ def scopes(self, facts: bool = False) -> list[dict]:
257
+ """Every scope with its variables' names, types and sizes, no values."""
258
+ out = []
259
+ for scope in SCOPES:
260
+ item: dict[str, object] = {"id": scope, "name": SCOPE_NAMES[scope]}
261
+ if scope == "facts":
262
+ item["expensive"] = True
263
+ if not facts:
264
+ out.append(item)
265
+ continue
266
+ names = []
267
+ for name, value in self.scope(scope).items():
268
+ e = entry(name, value)
269
+ e.pop("value", None)
270
+ e.pop("cut", None)
271
+ names.append(e)
272
+ item["vars"] = names
273
+ out.append(item)
274
+ return out
275
+
276
+ def page(self, scope: str, path: list, start: int = 0, count: int = PAGE) -> dict:
277
+ """The value at `path` in a scope: a scalar whole (cut), a container's items paged."""
278
+ node: object = self.scope(scope)
279
+ for i, key in enumerate(path):
280
+ if isinstance(node, dict) and type_of(node) == "dict" and str(key) in node:
281
+ node = node[str(key)]
282
+ elif isinstance(node, list) and isinstance(key, int) and 0 <= key < len(node):
283
+ node = node[key]
284
+ else:
285
+ where = "/".join(str(p) for p in path[: i + 1])
286
+ return {"error": f"no such variable: {where}"}
287
+ kind = type_of(node)
288
+ if path and kind not in ("dict", "list"):
289
+ return entry(path[-1], node)
290
+ items: list[tuple[str | int, object]] = (
291
+ list(node.items()) if isinstance(node, dict) else list(enumerate(node)) # type: ignore[union-attr]
292
+ )
293
+ start = max(0, int(start))
294
+ count = max(1, min(int(count), 1000))
295
+ children = []
296
+ used = 0
297
+ more = False
298
+ for name, value in items[start : start + count]:
299
+ e = entry(name, value)
300
+ size = len(to_json(e))
301
+ if children and used + size > ANSWER_LIMIT:
302
+ more = True
303
+ break
304
+ used += size
305
+ children.append(e)
306
+ if start + len(children) < len(items):
307
+ more = True
308
+ out: dict[str, object] = {
309
+ "type": kind if path else "scope",
310
+ "total": len(items),
311
+ "start": start,
312
+ "children": children,
313
+ }
314
+ if more:
315
+ out["more"] = True
316
+ return out