libbeachcomber 0.10.0__tar.gz → 0.11.0__tar.gz

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 (19) hide show
  1. {libbeachcomber-0.10.0 → libbeachcomber-0.11.0}/.gitignore +3 -0
  2. {libbeachcomber-0.10.0 → libbeachcomber-0.11.0}/PKG-INFO +5 -4
  3. {libbeachcomber-0.10.0 → libbeachcomber-0.11.0}/README.md +4 -3
  4. {libbeachcomber-0.10.0 → libbeachcomber-0.11.0}/libbeachcomber/__init__.py +2 -0
  5. {libbeachcomber-0.10.0 → libbeachcomber-0.11.0}/libbeachcomber/_native.py +12 -2
  6. {libbeachcomber-0.10.0 → libbeachcomber-0.11.0}/libbeachcomber/client.py +117 -13
  7. {libbeachcomber-0.10.0 → libbeachcomber-0.11.0}/libbeachcomber/exceptions.py +8 -0
  8. {libbeachcomber-0.10.0 → libbeachcomber-0.11.0}/pyproject.toml +1 -1
  9. {libbeachcomber-0.10.0 → libbeachcomber-0.11.0}/tests/conftest.py +4 -0
  10. {libbeachcomber-0.10.0 → libbeachcomber-0.11.0}/tests/test_exceptions.py +2 -0
  11. {libbeachcomber-0.10.0 → libbeachcomber-0.11.0}/tests/test_integration.py +23 -5
  12. {libbeachcomber-0.10.0 → libbeachcomber-0.11.0}/conformance_runner.py +0 -0
  13. {libbeachcomber-0.10.0 → libbeachcomber-0.11.0}/libbeachcomber/discovery.py +0 -0
  14. {libbeachcomber-0.10.0 → libbeachcomber-0.11.0}/libbeachcomber/types.py +0 -0
  15. {libbeachcomber-0.10.0 → libbeachcomber-0.11.0}/tests/__init__.py +0 -0
  16. {libbeachcomber-0.10.0 → libbeachcomber-0.11.0}/tests/test_api_surface.py +0 -0
  17. {libbeachcomber-0.10.0 → libbeachcomber-0.11.0}/tests/test_client_options.py +0 -0
  18. {libbeachcomber-0.10.0 → libbeachcomber-0.11.0}/tests/test_closed.py +0 -0
  19. {libbeachcomber-0.10.0 → libbeachcomber-0.11.0}/tests/test_discovery.py +0 -0
@@ -44,3 +44,6 @@ sdks/c/conformance_runner
44
44
 
45
45
  # Nix
46
46
  flake.lock
47
+
48
+ # hush secret-set refs (local to this machine)
49
+ .shuhi.sh
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: libbeachcomber
3
- Version: 0.10.0
3
+ Version: 0.11.0
4
4
  Summary: Python client SDK for the beachcomber (comb) shell-state daemon
5
5
  Project-URL: Homepage, https://github.com/NavistAu/beachcomber
6
6
  Project-URL: Repository, https://github.com/NavistAu/beachcomber
@@ -119,10 +119,10 @@ with client.session() as session:
119
119
  stored nowhere — the same value `comb eval` prints; `eval("{{ p.f }}")` and
120
120
  `get("p.f")` agree. The template accepts a single `{{ expr }}` tag, or
121
121
  literal text/several tags — the former keeps the expression's natural type,
122
- the latter is always a string (a source with no tags at all is its literal
122
+ the latter is a string, absent when its tags print only whitespace (a source with no tags at all is its literal
123
123
  text).
124
124
 
125
- `exec()` inside a template runs only on a client created with
125
+ `_.exec()` inside a template runs only on a client created with
126
126
  `Client(exec=True)`; it is off by default, and a template that calls it
127
127
  then fails with `exec() is disabled in this context`.
128
128
 
@@ -160,7 +160,7 @@ client = Client(socket_path="/tmp/beachcomber-1000/sock", timeout_ms=500, connec
160
160
  | `timeout_ms` | 250 | How long one read or write on the socket may take; at least 1. |
161
161
  | `connect_timeout_ms` | 1500 | How long connecting keeps retrying before it gives up; 0 is one attempt. |
162
162
  | `autostart` | on | Start a daemon when none answers an auto-discovered socket. |
163
- | `exec` | off | Whether a template this client renders may call `exec()`. |
163
+ | `exec` | off | Whether a template this client renders may call `_.exec()`. |
164
164
 
165
165
  The defaults are the library's (`bc_client_new`): this SDK passes on the
166
166
  options you give and adds none of its own.
@@ -213,6 +213,7 @@ not need to string-match `str(exc)`.
213
213
  | `ParseError` | `parse_error` | A request, a response or a template could not be read |
214
214
  | `ServerError` | `server_error` | The daemon refused the request, or a template failed to render |
215
215
  | `TimeoutError` | `timeout` | A read or write ran out `timeout_ms`, or `next_event` ran out its `timeout_ms` |
216
+ | `ProtocolMismatchError` | `protocol_mismatch` | The daemon speaks a protocol whose major is not the library's; restart the daemon (`comb kill`) or upgrade the library |
216
217
  | `BusyError` | `busy` | A session or watch is in use by another caller |
217
218
  | `PanicError` | `panic` | The library panicked; the panic was caught at the boundary |
218
219
  | `LibraryNotFoundError` | `library_not_found` | No `libbeachcomber` was found where discovery looks |
@@ -95,10 +95,10 @@ with client.session() as session:
95
95
  stored nowhere — the same value `comb eval` prints; `eval("{{ p.f }}")` and
96
96
  `get("p.f")` agree. The template accepts a single `{{ expr }}` tag, or
97
97
  literal text/several tags — the former keeps the expression's natural type,
98
- the latter is always a string (a source with no tags at all is its literal
98
+ the latter is a string, absent when its tags print only whitespace (a source with no tags at all is its literal
99
99
  text).
100
100
 
101
- `exec()` inside a template runs only on a client created with
101
+ `_.exec()` inside a template runs only on a client created with
102
102
  `Client(exec=True)`; it is off by default, and a template that calls it
103
103
  then fails with `exec() is disabled in this context`.
104
104
 
@@ -136,7 +136,7 @@ client = Client(socket_path="/tmp/beachcomber-1000/sock", timeout_ms=500, connec
136
136
  | `timeout_ms` | 250 | How long one read or write on the socket may take; at least 1. |
137
137
  | `connect_timeout_ms` | 1500 | How long connecting keeps retrying before it gives up; 0 is one attempt. |
138
138
  | `autostart` | on | Start a daemon when none answers an auto-discovered socket. |
139
- | `exec` | off | Whether a template this client renders may call `exec()`. |
139
+ | `exec` | off | Whether a template this client renders may call `_.exec()`. |
140
140
 
141
141
  The defaults are the library's (`bc_client_new`): this SDK passes on the
142
142
  options you give and adds none of its own.
@@ -189,6 +189,7 @@ not need to string-match `str(exc)`.
189
189
  | `ParseError` | `parse_error` | A request, a response or a template could not be read |
190
190
  | `ServerError` | `server_error` | The daemon refused the request, or a template failed to render |
191
191
  | `TimeoutError` | `timeout` | A read or write ran out `timeout_ms`, or `next_event` ran out its `timeout_ms` |
192
+ | `ProtocolMismatchError` | `protocol_mismatch` | The daemon speaks a protocol whose major is not the library's; restart the daemon (`comb kill`) or upgrade the library |
192
193
  | `BusyError` | `busy` | A session or watch is in use by another caller |
193
194
  | `PanicError` | `panic` | The library panicked; the panic was caught at the boundary |
194
195
  | `LibraryNotFoundError` | `library_not_found` | No `libbeachcomber` was found where discovery looks |
@@ -39,6 +39,7 @@ from .exceptions import (
39
39
  LibrarySymbolError,
40
40
  PanicError,
41
41
  ParseError,
42
+ ProtocolMismatchError,
42
43
  ServerError,
43
44
  TimeoutError,
44
45
  UnsupportedError,
@@ -66,6 +67,7 @@ __all__ = [
66
67
  "ServerError",
67
68
  "TimeoutError",
68
69
  "BusyError",
70
+ "ProtocolMismatchError",
69
71
  "PanicError",
70
72
  "LibraryNotFoundError",
71
73
  "LibrarySymbolError",
@@ -41,6 +41,10 @@ _SYMBOLS: dict = {
41
41
  [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_bool],
42
42
  ctypes.c_void_p,
43
43
  ),
44
+ "bc_io": (
45
+ [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p],
46
+ ctypes.c_void_p,
47
+ ),
44
48
  "bc_refresh": ([ctypes.c_void_p, ctypes.c_char_p, ctypes.c_char_p], ctypes.c_void_p),
45
49
  "bc_status": ([ctypes.c_void_p], ctypes.c_void_p),
46
50
  "bc_introspect": (
@@ -62,6 +66,10 @@ _SYMBOLS: dict = {
62
66
  [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_bool],
63
67
  ctypes.c_void_p,
64
68
  ),
69
+ "bc_session_io": (
70
+ [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p],
71
+ ctypes.c_void_p,
72
+ ),
65
73
  "bc_session_refresh": (
66
74
  [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_char_p],
67
75
  ctypes.c_void_p,
@@ -132,8 +140,10 @@ class NativeLib:
132
140
  def _decode_envelope(self, ptr: Optional[int]) -> dict:
133
141
  if not ptr:
134
142
  raise ParseError("native call returned NULL", self.version)
135
- raw = ctypes.cast(ptr, ctypes.c_char_p).value
136
- self._cdll.bc_string_free(ptr)
143
+ try:
144
+ raw = ctypes.cast(ptr, ctypes.c_char_p).value
145
+ finally:
146
+ self._cdll.bc_string_free(ptr)
137
147
  if raw is None:
138
148
  raise ParseError("native call returned an empty envelope", self.version)
139
149
  try:
@@ -69,6 +69,41 @@ def _read_args(
69
69
  )
70
70
 
71
71
 
72
+ def _io_args(
73
+ put_key: str,
74
+ get_key: str,
75
+ input: Any,
76
+ cwd: Optional[str],
77
+ env: Optional[dict],
78
+ force: bool,
79
+ wait: Optional[str],
80
+ ttl: Optional[str],
81
+ persist: bool,
82
+ ) -> tuple:
83
+ """The arguments after the handle of ``bc_io`` and ``bc_session_io``:
84
+ ``input`` is JSON text as given, else the object as JSON; ``ttl`` and
85
+ ``persist`` ride in ``options_json`` beside ``force`` and ``wait``."""
86
+ text = input if isinstance(input, str) else json.dumps(input)
87
+ options: dict = {}
88
+ if force:
89
+ options["force"] = True
90
+ if wait is not None:
91
+ options["wait"] = wait
92
+ if ttl is not None:
93
+ options["ttl"] = ttl
94
+ if persist:
95
+ options["persist"] = True
96
+ cwd_b, env_b, _ = _read_args(cwd, env, False, None)
97
+ return (
98
+ put_key.encode(),
99
+ get_key.encode(),
100
+ text.encode(),
101
+ cwd_b,
102
+ env_b,
103
+ json.dumps(options).encode() if options else None,
104
+ )
105
+
106
+
72
107
  def _parse_hello(data: Optional[dict]) -> HelloInfo:
73
108
  if not isinstance(data, dict):
74
109
  data = {}
@@ -206,10 +241,11 @@ class WatchStream:
206
241
 
207
242
  def close(self) -> None:
208
243
  """End the stream and free the underlying native watch handle."""
209
- if self._ptr is not None:
210
- self._lib.call_void("bc_watch_cancel", self._ptr)
211
- self._lib.call_void("bc_watch_free", self._ptr)
212
- self._ptr = None
244
+ ptr = self._ptr
245
+ self._ptr = None
246
+ if ptr is not None:
247
+ self._lib.call_void("bc_watch_cancel", ptr)
248
+ self._lib.call_void("bc_watch_free", ptr)
213
249
 
214
250
  def __enter__(self) -> "WatchStream":
215
251
  return self
@@ -230,14 +266,14 @@ class Client:
230
266
  its per-user default).
231
267
  timeout_ms: How long one read or write on the socket may take, in
232
268
  milliseconds; at least 1. ``None`` is the library's default
233
- (100).
269
+ (250).
234
270
  connect_timeout_ms: How long connecting keeps retrying before it
235
271
  gives up, in milliseconds; ``0`` is one attempt. ``None`` is the
236
272
  library's default (1500).
237
273
  autostart: Whether to attempt starting the daemon if it isn't
238
274
  running. ``None`` is the library's default (on).
239
275
  exec: Whether a template this client renders (:meth:`get`,
240
- :meth:`eval`) may call ``exec()``. ``None`` is the library's
276
+ :meth:`eval`) may call ``_.exec()``. ``None`` is the library's
241
277
  default, off: a template that calls it then fails with
242
278
  ``exec() is disabled in this context``.
243
279
 
@@ -281,9 +317,10 @@ class Client:
281
317
 
282
318
  def close(self) -> None:
283
319
  """Free the underlying native client handle."""
284
- if self._ptr is not None:
285
- self._lib.call_void("bc_client_free", self._ptr)
286
- self._ptr = None
320
+ ptr = self._ptr
321
+ self._ptr = None
322
+ if ptr is not None:
323
+ self._lib.call_void("bc_client_free", ptr)
287
324
 
288
325
  def __del__(self) -> None:
289
326
  self.close()
@@ -384,6 +421,39 @@ class Client:
384
421
  persist,
385
422
  )
386
423
 
424
+ def io(
425
+ self,
426
+ put_key: str,
427
+ get_key: str,
428
+ input: Any,
429
+ cwd: Optional[str] = None,
430
+ env: Optional[dict] = None,
431
+ force: bool = False,
432
+ wait: Optional[str] = None,
433
+ ttl: Optional[str] = None,
434
+ persist: bool = False,
435
+ ) -> Any:
436
+ """``comb io``: put ``input``, a JSON object, at ``put_key``, then read
437
+ ``get_key`` on a connection of its own with the input bound as ``input`` in templates
438
+ (``comb io``). ``input`` is a dict or JSON text. ``{field}`` in either key is
439
+ filled from the input's top-level string or number ``field``; a missing one
440
+ raises :class:`~libbeachcomber.exceptions.ParseError` and stores nothing.
441
+ Input that is not a JSON object stores nothing and the read goes on.
442
+ ``cwd`` addresses the put as well as the read (``None``: the global entry).
443
+ ``ttl`` and ``persist`` are :meth:`put`'s; ``force`` and ``wait`` are :meth:`get`'s.
444
+
445
+ Returns:
446
+ What :meth:`get` returns.
447
+
448
+ Raises:
449
+ CombError: subclass matching the failure kind.
450
+ """
451
+ return self._lib.call(
452
+ "bc_io",
453
+ self._handle(),
454
+ *_io_args(put_key, get_key, input, cwd, env, force, wait, ttl, persist),
455
+ )
456
+
387
457
  def introspect(
388
458
  self,
389
459
  subject: IntrospectSubject,
@@ -511,7 +581,7 @@ class Session:
511
581
  # Held so the client is not freed while its session is open.
512
582
  self._client = client
513
583
  self._lib = client._lib
514
- ptr = self._lib.call_ptr("bc_session_open", client._ptr)
584
+ ptr = self._lib.call_ptr("bc_session_open", client._handle())
515
585
  if not ptr:
516
586
  raise IoError("bc_session_open returned NULL (allocation failure)", self._lib.version)
517
587
  self._ptr = ptr
@@ -526,9 +596,10 @@ class Session:
526
596
 
527
597
  def close(self) -> None:
528
598
  """Close and free the underlying native session handle."""
529
- if self._ptr is not None:
530
- self._lib.call_void("bc_session_close", self._ptr)
531
- self._ptr = None
599
+ ptr = self._ptr
600
+ self._ptr = None
601
+ if ptr is not None:
602
+ self._lib.call_void("bc_session_close", ptr)
532
603
 
533
604
  def __del__(self) -> None:
534
605
  self.close()
@@ -591,6 +662,39 @@ class Session:
591
662
  persist,
592
663
  )
593
664
 
665
+ def io(
666
+ self,
667
+ put_key: str,
668
+ get_key: str,
669
+ input: Any,
670
+ cwd: Optional[str] = None,
671
+ env: Optional[dict] = None,
672
+ force: bool = False,
673
+ wait: Optional[str] = None,
674
+ ttl: Optional[str] = None,
675
+ persist: bool = False,
676
+ ) -> Any:
677
+ """:meth:`Client.io`: put ``input``, a JSON object, at ``put_key``, then read
678
+ ``get_key`` on this session's persistent connection with the input bound as ``input`` in templates
679
+ (``comb io``). ``input`` is a dict or JSON text. ``{field}`` in either key is
680
+ filled from the input's top-level string or number ``field``; a missing one
681
+ raises :class:`~libbeachcomber.exceptions.ParseError` and stores nothing.
682
+ Input that is not a JSON object stores nothing and the read goes on.
683
+ ``cwd`` addresses the put as well as the read (``None``: this session's directory, else the global entry).
684
+ ``ttl`` and ``persist`` are :meth:`put`'s; ``force`` and ``wait`` are :meth:`get`'s.
685
+
686
+ Returns:
687
+ What :meth:`get` returns.
688
+
689
+ Raises:
690
+ CombError: subclass matching the failure kind.
691
+ """
692
+ return self._lib.call(
693
+ "bc_session_io",
694
+ self._handle(),
695
+ *_io_args(put_key, get_key, input, cwd, env, force, wait, ttl, persist),
696
+ )
697
+
594
698
  def refresh(self, key: str, path: Optional[str] = None) -> None:
595
699
  """Trigger recomputation at ``path``, else at this session's directory.
596
700
 
@@ -70,6 +70,13 @@ class TimeoutError(CombError): # noqa: A001 - deliberately mirrors the ABI's "t
70
70
  kind = "timeout"
71
71
 
72
72
 
73
+ class ProtocolMismatchError(CombError):
74
+ """The daemon speaks a protocol whose major is not this library's: restart
75
+ the daemon, or upgrade the library. The message names both versions."""
76
+
77
+ kind = "protocol_mismatch"
78
+
79
+
73
80
  class BusyError(CombError):
74
81
  """A session or watch is in use by another caller."""
75
82
 
@@ -111,6 +118,7 @@ _KIND_TO_EXCEPTION = {
111
118
  ParseError,
112
119
  ServerError,
113
120
  TimeoutError,
121
+ ProtocolMismatchError,
114
122
  BusyError,
115
123
  PanicError,
116
124
  LibraryNotFoundError,
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "libbeachcomber"
7
- version = "0.10.0"
7
+ version = "0.11.0"
8
8
  description = "Python client SDK for the beachcomber (comb) shell-state daemon"
9
9
  readme = "README.md"
10
10
  license = { text = "MIT" }
@@ -77,6 +77,10 @@ def comb_bin() -> str:
77
77
  @pytest.fixture(scope="session")
78
78
  def daemon(comb_bin: str):
79
79
  proc = DaemonProcess(comb_bin)
80
+ cfg_dir = os.path.join(proc._tmpdir, "beachcomber")
81
+ os.makedirs(cfg_dir, exist_ok=True)
82
+ with open(os.path.join(cfg_dir, "config.toml"), "w", encoding="utf-8") as f:
83
+ f.write('[client.providers.execwidget2]\ntemplate.out = "{{ _.exec([\'printf\', \'x\']) }}"\n')
80
84
  proc.start()
81
85
  yield proc
82
86
  proc.stop()
@@ -16,6 +16,7 @@ from libbeachcomber.exceptions import (
16
16
  IoError,
17
17
  PanicError,
18
18
  ParseError,
19
+ ProtocolMismatchError,
19
20
  ServerError,
20
21
  TimeoutError,
21
22
  exception_for_envelope_error,
@@ -31,6 +32,7 @@ from libbeachcomber.exceptions import (
31
32
  ("parse_error", ParseError),
32
33
  ("server_error", ServerError),
33
34
  ("timeout", TimeoutError),
35
+ ("protocol_mismatch", ProtocolMismatchError),
34
36
  ("busy", BusyError),
35
37
  ("panic", PanicError),
36
38
  ],
@@ -108,8 +108,9 @@ def test_status_returns_cache_rows(client: Client) -> None:
108
108
 
109
109
 
110
110
  def test_a_status_row_says_when_it_polls_next(client: Client) -> None:
111
- client.put("widget5ttl", {"v": 1}, ttl="1m")
112
- row = next(r for r in client.status() if r.provider == "widget5ttl")
111
+ # `hostname` polls; a put, even one with a ttl, never does.
112
+ client.get("hostname.short")
113
+ row = next(r for r in client.status() if r.provider == "hostname")
113
114
  assert isinstance(row.next_poll_in_secs, int)
114
115
 
115
116
 
@@ -188,14 +189,13 @@ def test_eval_raw_expression(client: Client) -> None:
188
189
 
189
190
 
190
191
  def test_exec_is_disabled_without_the_option(client: Client) -> None:
191
- client.put("execwidget:template", {"out": "{{ exec(['printf', 'x']) }}"})
192
+ client.put("execwidget:template", {"out": "{{ _.exec(['printf', 'x']) }}"})
192
193
  with pytest.raises(ServerError) as excinfo:
193
194
  client.get("execwidget.out", cwd="/tmp")
194
195
  assert "exec() is disabled in this context" in excinfo.value.message
195
196
 
196
197
 
197
- def test_exec_runs_on_a_client_with_the_option(client: Client, daemon) -> None:
198
- client.put("execwidget2:template", {"out": "{{ exec(['printf', 'x']) }}"})
198
+ def test_exec_runs_on_a_client_with_the_option(daemon) -> None:
199
199
  exec_client = Client(socket_path=daemon.socket_path, timeout_ms=5000, exec=True)
200
200
  try:
201
201
  assert exec_client.get("execwidget2.out", cwd="/tmp") == "x"
@@ -287,3 +287,21 @@ def test_watch_yields_the_resolved_value_and_refires_on_a_template_edit(
287
287
  second = stream.next_event(timeout_ms=5000)
288
288
  assert second is not None
289
289
  assert second.data == "v1!"
290
+
291
+
292
+ def test_io_puts_then_reads_with_the_input_bound(client: Client) -> None:
293
+ client.put("view:template.n", "{{ input.n }}")
294
+ client.put("view:template.stored", "{{ comb.sess.s1.n }}")
295
+ assert client.io("sess.{session_id}", "view.n", {"session_id": "s1", "n": 5}) == 5
296
+ # JSON text is taken as it is, and the put is visible to the read.
297
+ assert client.io("sess.{session_id}", "view.stored", '{"session_id":"s1","n":6}', ttl="1h") == 6
298
+ with pytest.raises(ParseError):
299
+ client.io("sess.{session_id}", "view.n", {"n": 1})
300
+
301
+
302
+ def test_session_io_uses_the_session(client: Client) -> None:
303
+ client.put("view:template.n", "{{ input.n }}")
304
+ with client.session() as session:
305
+ assert session.io("sess.{session_id}", "view.n", {"session_id": "s2", "n": 7}) == 7
306
+ # Not a JSON object: nothing stored, the read goes on.
307
+ assert session.io("sess.x", "view.n", "nope") is None