holon-sh 0.0.1.dev17__tar.gz → 0.0.1.dev19__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 (27) hide show
  1. {holon_sh-0.0.1.dev17 → holon_sh-0.0.1.dev19}/PKG-INFO +1 -1
  2. {holon_sh-0.0.1.dev17 → holon_sh-0.0.1.dev19}/holon/ext/events/_server.py +72 -82
  3. {holon_sh-0.0.1.dev17 → holon_sh-0.0.1.dev19}/pyproject.toml +1 -1
  4. {holon_sh-0.0.1.dev17 → holon_sh-0.0.1.dev19}/tests/test_events.py +57 -69
  5. {holon_sh-0.0.1.dev17 → holon_sh-0.0.1.dev19}/tests/test_package.py +1 -1
  6. {holon_sh-0.0.1.dev17 → holon_sh-0.0.1.dev19}/.gitignore +0 -0
  7. {holon_sh-0.0.1.dev17 → holon_sh-0.0.1.dev19}/LICENSE +0 -0
  8. {holon_sh-0.0.1.dev17 → holon_sh-0.0.1.dev19}/README.md +0 -0
  9. {holon_sh-0.0.1.dev17 → holon_sh-0.0.1.dev19}/holon/client.py +0 -0
  10. {holon_sh-0.0.1.dev17 → holon_sh-0.0.1.dev19}/holon/context.py +0 -0
  11. {holon_sh-0.0.1.dev17 → holon_sh-0.0.1.dev19}/holon/ext/__init__.py +0 -0
  12. {holon_sh-0.0.1.dev17 → holon_sh-0.0.1.dev19}/holon/ext/events/__init__.py +0 -0
  13. {holon_sh-0.0.1.dev17 → holon_sh-0.0.1.dev19}/holon/ext/events/_client.py +0 -0
  14. {holon_sh-0.0.1.dev17 → holon_sh-0.0.1.dev19}/holon/ext/events/_wire.py +0 -0
  15. {holon_sh-0.0.1.dev17 → holon_sh-0.0.1.dev19}/holon/ext/files/__init__.py +0 -0
  16. {holon_sh-0.0.1.dev17 → holon_sh-0.0.1.dev19}/holon/ext/files/_client.py +0 -0
  17. {holon_sh-0.0.1.dev17 → holon_sh-0.0.1.dev19}/holon/ext/files/_server.py +0 -0
  18. {holon_sh-0.0.1.dev17 → holon_sh-0.0.1.dev19}/holon/ext/files/_wire.py +0 -0
  19. {holon_sh-0.0.1.dev17 → holon_sh-0.0.1.dev19}/holon/py.typed +0 -0
  20. {holon_sh-0.0.1.dev17 → holon_sh-0.0.1.dev19}/holon/serve.py +0 -0
  21. {holon_sh-0.0.1.dev17 → holon_sh-0.0.1.dev19}/scripts/verify_distribution.py +0 -0
  22. {holon_sh-0.0.1.dev17 → holon_sh-0.0.1.dev19}/tests/fixtures/caller/holon/apps/__init__.py +0 -0
  23. {holon_sh-0.0.1.dev17 → holon_sh-0.0.1.dev19}/tests/test_context.py +0 -0
  24. {holon_sh-0.0.1.dev17 → holon_sh-0.0.1.dev19}/tests/test_elicit.py +0 -0
  25. {holon_sh-0.0.1.dev17 → holon_sh-0.0.1.dev19}/tests/test_files.py +0 -0
  26. {holon_sh-0.0.1.dev17 → holon_sh-0.0.1.dev19}/tests/test_runtime.py +0 -0
  27. {holon_sh-0.0.1.dev17 → holon_sh-0.0.1.dev19}/tests/test_serve.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: holon-sh
3
- Version: 0.0.1.dev17
3
+ Version: 0.0.1.dev19
4
4
  Summary: Typed MCP clients and the caller of an MCP request
5
5
  Project-URL: Repository, https://github.com/holon-sh/sdk-py
6
6
  License-Expression: Apache-2.0
@@ -12,13 +12,15 @@ import secrets
12
12
  import time
13
13
  import uuid
14
14
  from collections import Counter
15
- from collections.abc import AsyncIterator, Awaitable, Callable, Sequence
15
+ from collections.abc import AsyncIterator, Awaitable, Callable, Mapping, Sequence
16
16
  from contextlib import asynccontextmanager
17
17
  from dataclasses import dataclass, field
18
18
  from datetime import UTC, datetime
19
19
  from typing import Any, Generic, TypeAlias, TypeVar, cast
20
20
 
21
21
  import anyio
22
+ import jsonschema
23
+ from jsonschema.protocols import Validator
22
24
  from mcp.server.context import CallNext, HandlerResult, ServerRequestContext
23
25
  from mcp.server.extension import Extension, MethodBinding
24
26
  from mcp.server.lowlevel.server import Server
@@ -33,10 +35,11 @@ from mcp.types import (
33
35
  RequestParams,
34
36
  ServerNotification,
35
37
  )
36
- from pydantic import Field, StrictInt, StrictStr, TypeAdapter, ValidationError
38
+ from pydantic import Field, StrictInt, StrictStr
37
39
  from pydantic_core import to_json, to_jsonable_python
40
+ from referencing import Registry
38
41
 
39
- from holon.context import RequestContext, get_context
42
+ from holon.context import get_context
40
43
  from holon.ext.events._wire import (
41
44
  EVENTS_EXTENSION,
42
45
  FORBIDDEN,
@@ -64,16 +67,17 @@ _MAX_SUBSCRIPTIONS_PER_CALLER = 100
64
67
  _LIST_PAGE_SIZE = 100
65
68
  _SUBSCRIBE_TIMEOUT = 30.0
66
69
 
67
- A = TypeVar("A")
70
+ A = TypeVar("A", bound=Mapping[str, Any])
68
71
  T = TypeVar("T")
69
72
 
70
73
 
71
- Match: TypeAlias = Callable[[RequestContext, Event[D], A], bool]
72
- Transform: TypeAlias = Callable[[RequestContext, Event[D], A], object]
73
- Authorize: TypeAlias = Callable[[RequestContext, A], bool | Awaitable[bool]]
74
+ Context: TypeAlias = ServerRequestContext[Any, Any]
75
+ Match: TypeAlias = Callable[[Context, Event[D], A], bool]
76
+ Transform: TypeAlias = Callable[[Context, Event[D], A], object]
77
+ Authorize: TypeAlias = Callable[[Context, A], bool | Awaitable[bool]]
74
78
  Cleanup: TypeAlias = Callable[[], None | Awaitable[None]]
75
79
  SubscriptionHook: TypeAlias = Callable[
76
- [RequestContext, A, str], Cleanup | None | Awaitable[Cleanup | None]
80
+ [Context, A, str], Cleanup | None | Awaitable[Cleanup | None]
77
81
  ]
78
82
 
79
83
 
@@ -116,7 +120,6 @@ class _Request:
116
120
 
117
121
  type: EventType[Any, Any]
118
122
  id: str
119
- context: RequestContext
120
123
  caller: str
121
124
  arguments: Any
122
125
  targetable: bool
@@ -135,8 +138,8 @@ class _Kept:
135
138
  class _Entry:
136
139
  """A subscription, held by one or more streams or poll leases."""
137
140
 
138
- setup: asyncio.Future[Cleanup | None]
139
141
  holds: set[_Hold] = field(default_factory=set)
142
+ setup: asyncio.Future[Cleanup | None] | None = None
140
143
  teardown: asyncio.Future[None] | None = None
141
144
 
142
145
 
@@ -159,7 +162,7 @@ class EventType(Generic[A, D]):
159
162
 
160
163
  name: str
161
164
  _events: Events
162
- _input: TypeAdapter[A]
165
+ _input: Validator
163
166
  _descriptor: dict[str, Any]
164
167
  _match: Match[D, A] | None
165
168
  _transform: Transform[D, A] | None
@@ -295,16 +298,18 @@ class EventType(Generic[A, D]):
295
298
  return sequence, truncated
296
299
 
297
300
  # The occurrence as `request` receives it, or None when it is not for it.
298
- def _shape(self, kept: _Kept, request: _Request) -> dict[str, Any] | None:
301
+ def _shape(
302
+ self, kept: _Kept, request: _Request, ctx: Context
303
+ ) -> dict[str, Any] | None:
299
304
  if kept.target is not None:
300
305
  if not request.targetable or kept.target != request.id:
301
306
  return None
302
307
  elif self._match is not None and not self._match(
303
- request.context, kept.event, request.arguments
308
+ ctx, kept.event, request.arguments
304
309
  ):
305
310
  return None
306
311
  data = (
307
- self._transform(request.context, kept.event, request.arguments)
312
+ self._transform(ctx, kept.event, request.arguments)
308
313
  if self._transform
309
314
  else kept.event.data
310
315
  )
@@ -319,6 +324,7 @@ class EventType(Generic[A, D]):
319
324
  def _since(
320
325
  self,
321
326
  request: _Request,
327
+ ctx: Context,
322
328
  cursor: str,
323
329
  max_age_ms: int | None,
324
330
  limit: int,
@@ -329,7 +335,7 @@ class EventType(Generic[A, D]):
329
335
  while len(events) < limit and (kept := self._next(reached)) is not None:
330
336
  reached = kept.sequence
331
337
  try:
332
- occurrence = self._shape(kept, request)
338
+ occurrence = self._shape(kept, request, ctx)
333
339
  except Exception as error: # noqa: BLE001
334
340
  _described(error)
335
341
  continue
@@ -342,10 +348,8 @@ class EventType(Generic[A, D]):
342
348
  "hasMore": self._next(reached) is not None,
343
349
  }
344
350
 
345
- async def _allows(self, context: RequestContext, arguments: Any) -> bool:
346
- return self._authorize is None or await _settle(
347
- self._authorize(context, arguments)
348
- )
351
+ async def _allows(self, ctx: Context, arguments: Any) -> bool:
352
+ return self._authorize is None or await _settle(self._authorize(ctx, arguments))
349
353
 
350
354
  async def _settled(self, id: str) -> None:
351
355
  while (entry := self._subscriptions.get(id)) and entry.teardown is not None:
@@ -375,7 +379,7 @@ class Events(Extension):
375
379
  self,
376
380
  name: str,
377
381
  *,
378
- input_schema: type[A] | TypeAdapter[A],
382
+ input_schema: dict[str, Any],
379
383
  payload_schema: dict[str, Any],
380
384
  description: str | None = None,
381
385
  match: Match[D, A] | None = None,
@@ -386,10 +390,14 @@ class Events(Extension):
386
390
  ) -> EventType[A, D]:
387
391
  """Declare an event type.
388
392
 
389
- Annotate the result as ``EventType[Arguments, Data]`` to type ``emit``.
393
+ Annotate the result as ``EventType[Arguments, Data]`` to type the hooks and ``emit``. Hooks receive the
394
+ arguments as the subscription sent them, so ``Arguments`` is a ``TypedDict`` or ``dict[str, Any]``. Each
395
+ hook's ``context`` is the server's context of the request it runs in. A subscription outlives the first
396
+ request to name it, where ``on_subscribe`` runs, and other requests may share it: keep what the hook reads
397
+ from ``context``, not ``context``.
390
398
 
391
399
  Args:
392
- input_schema: Type of a subscription's arguments.
400
+ input_schema: JSON Schema of a subscription's arguments. Arguments that do not match are refused.
393
401
  payload_schema: JSON Schema of each occurrence's data.
394
402
  match: ``(context, event, arguments)``: whether a subscription receives an event. Defaults to all.
395
403
  transform: ``(context, event, arguments)``: the data a subscription receives.
@@ -402,21 +410,18 @@ class Events(Extension):
402
410
  raise ValueError(f"Event {name} is already declared.")
403
411
  if not delivery:
404
412
  raise ValueError(f"Event {name} must be delivered by poll, push or both.")
405
- arguments = (
406
- input_schema
407
- if isinstance(input_schema, TypeAdapter)
408
- else TypeAdapter(input_schema)
409
- )
413
+ checker = jsonschema.validators.validator_for(input_schema)
414
+ checker.check_schema(input_schema)
410
415
  descriptor = {
411
416
  "name": name,
412
417
  **({"description": description} if description else {}),
413
- "inputSchema": arguments.json_schema(),
418
+ "inputSchema": input_schema,
414
419
  "payloadSchema": payload_schema,
415
420
  }
416
421
  declared = EventType(
417
422
  name,
418
423
  self,
419
- arguments,
424
+ checker(input_schema, registry=Registry()),
420
425
  descriptor,
421
426
  match,
422
427
  transform,
@@ -479,13 +484,11 @@ class Events(Extension):
479
484
  result["nextCursor"] = str(start + _LIST_PAGE_SIZE)
480
485
  return result
481
486
 
482
- async def _poll(
483
- self, ctx: ServerRequestContext[Any, Any], params: _SubscribeParams
484
- ) -> HandlerResult:
485
- request = await self._subscription(params, "poll")
487
+ async def _poll(self, ctx: Context, params: _SubscribeParams) -> HandlerResult:
488
+ request = await self._subscription(ctx, params, "poll")
486
489
  declared = request.type
487
490
  opened = declared._sequence
488
- await self._lease(request)
491
+ await self._lease(request, ctx)
489
492
  if params.cursor is None:
490
493
  answer = {
491
494
  "events": [],
@@ -496,6 +499,7 @@ class Events(Extension):
496
499
  else:
497
500
  answer = declared._since(
498
501
  request,
502
+ ctx,
499
503
  params.cursor,
500
504
  params.max_age_ms,
501
505
  params.max_events or _MAX_POLL_EVENTS,
@@ -518,7 +522,7 @@ class Events(Extension):
518
522
 
519
523
  # Checked in the order of https://github.com/modelcontextprotocol/experimental-ext-triggers-events/blob/main/docs/design-sketch-proposal.md#error-codes
520
524
  async def _subscription(
521
- self, params: _SubscribeParams, delivery: Delivery
525
+ self, ctx: Context, params: _SubscribeParams, delivery: Delivery
522
526
  ) -> _Request:
523
527
  self._loop = self._loop or asyncio.get_running_loop()
524
528
  declared = self._types.get(params.name)
@@ -530,18 +534,15 @@ class Events(Extension):
530
534
  "Unsupported",
531
535
  {"feature": "deliveryMode", "value": delivery},
532
536
  )
533
- try:
534
- arguments = declared._input.validate_python(params.arguments or {})
535
- except ValidationError as error:
536
- problems = "; ".join(
537
- f"{'.'.join(map(str, each['loc'])) or 'arguments'}: {each['msg']}"
538
- for each in error.errors()
539
- )
537
+ arguments = params.arguments or {}
538
+ if error := jsonschema.exceptions.best_match(
539
+ declared._input.iter_errors(arguments)
540
+ ):
540
541
  raise MCPError(
541
- INVALID_PARAMS, f"Invalid arguments for {params.name}: {problems}"
542
- ) from None
543
- context = get_context()
544
- principal = context.principal
542
+ INVALID_PARAMS,
543
+ f"Invalid arguments for {params.name}: {error.json_path}: {error.message}",
544
+ )
545
+ principal = get_context().principal
545
546
  caller = ""
546
547
  if principal is not None:
547
548
  who = [
@@ -555,24 +556,16 @@ class Events(Extension):
555
556
  if principal is None and delivery == "push":
556
557
  id = f"sub_{uuid.uuid4().hex}"
557
558
  else:
558
- canonical = json.dumps(
559
- [
560
- caller,
561
- declared.name,
562
- declared._input.dump_python(arguments, mode="json"),
563
- ],
564
- sort_keys=True,
565
- )
559
+ canonical = json.dumps([caller, declared.name, arguments], sort_keys=True)
566
560
  id = f"sub_{hashlib.sha256(canonical.encode()).hexdigest()[:32]}"
567
561
  request = _Request(
568
562
  declared,
569
563
  id,
570
- context,
571
564
  caller,
572
565
  arguments,
573
566
  targetable=principal is not None or delivery == "push",
574
567
  )
575
- if not await declared._allows(context, arguments):
568
+ if not await declared._allows(ctx, arguments):
576
569
  declared.terminate(id, _FORBIDDEN)
577
570
  if lease := self._leases.get(id):
578
571
  self._stop(lease)
@@ -597,27 +590,26 @@ class Events(Extension):
597
590
  },
598
591
  )
599
592
  self._held[request.caller] += 1
600
- subscriptions = request.type._subscriptions
601
- entry = subscriptions.get(request.id)
602
- if entry is None:
603
- setup = asyncio.ensure_future(self._set_up(request))
604
- entry = subscriptions[request.id] = _Entry(setup)
593
+ entry = request.type._subscriptions.setdefault(request.id, _Entry())
605
594
  hold = _Hold(request, entry)
606
595
  entry.holds.add(hold)
607
596
  return hold
608
597
 
609
- async def _set_up(self, request: _Request) -> Cleanup | None:
598
+ async def _set_up(self, request: _Request, ctx: Context) -> Cleanup | None:
610
599
  if request.type._on_subscribe is None:
611
600
  return None
612
601
  async with asyncio.timeout(_SUBSCRIBE_TIMEOUT):
613
602
  return await _settle(
614
- request.type._on_subscribe(
615
- request.context, request.arguments, request.id
616
- )
603
+ request.type._on_subscribe(ctx, request.arguments, request.id)
617
604
  )
618
605
 
619
- async def _ready(self, hold: _Hold) -> None:
620
- await asyncio.shield(hold.entry.setup)
606
+ async def _ready(self, hold: _Hold, ctx: Context) -> None:
607
+ entry = hold.entry
608
+ while entry.setup is not None and not entry.setup.done():
609
+ await asyncio.wait([entry.setup])
610
+ if entry.setup is None or entry.setup.cancelled():
611
+ entry.setup = asyncio.ensure_future(self._set_up(hold.request, ctx))
612
+ await entry.setup
621
613
  if hold.ended is not None:
622
614
  raise MCPError.from_error_data(hold.ended)
623
615
 
@@ -632,18 +624,20 @@ class Events(Extension):
632
624
 
633
625
  # Cleanup follows only a setup that succeeded; a failing hook is logged.
634
626
  async def _tear_down(self, hold: _Hold) -> None:
635
- request = hold.request
627
+ request, setup = hold.request, hold.entry.setup
636
628
  try:
637
- cleanup = await hold.entry.setup
638
- if cleanup is not None:
639
- await _settle(cleanup())
629
+ if setup is not None:
630
+ await asyncio.wait([setup])
631
+ cleanup = None if setup.cancelled() else setup.result()
632
+ if cleanup is not None:
633
+ await _settle(cleanup())
640
634
  except Exception:
641
635
  logger.exception("An event subscription's setup or cleanup failed")
642
636
  finally:
643
637
  del request.type._subscriptions[request.id]
644
638
 
645
639
  # A poll lease begins with the first poll, is renewed by each, and lapses when polls stop.
646
- async def _lease(self, request: _Request) -> None:
640
+ async def _lease(self, request: _Request, ctx: Context) -> None:
647
641
  await request.type._settled(request.id)
648
642
  hold = self._leases.get(request.id)
649
643
  if hold is None:
@@ -655,7 +649,7 @@ class Events(Extension):
655
649
  _POLL_SUBSCRIPTION_TTL, self._stop, hold
656
650
  )
657
651
  try:
658
- await self._ready(hold)
652
+ await self._ready(hold, ctx)
659
653
  except Exception:
660
654
  self._stop(hold)
661
655
  raise
@@ -684,16 +678,14 @@ class Events(Extension):
684
678
  self._sent.set()
685
679
  self._sent = asyncio.Event()
686
680
 
687
- async def _stream(
688
- self, ctx: ServerRequestContext[Any, Any], params: _SubscribeParams
689
- ) -> HandlerResult:
690
- request = await self._subscription(params, "push")
681
+ async def _stream(self, ctx: Context, params: _SubscribeParams) -> HandlerResult:
682
+ request = await self._subscription(ctx, params, "push")
691
683
  declared = request.type
692
684
  await declared._settled(request.id)
693
685
  hold = self._open(request)
694
686
  hold.seen = declared._sequence
695
687
  try:
696
- await self._ready(hold)
688
+ await self._ready(hold, ctx)
697
689
 
698
690
  async def say(method: str, body: dict[str, Any], size: int = 0) -> None:
699
691
  body["_meta"] = {SUBSCRIPTION_ID_META_KEY: ctx.request_id}
@@ -717,7 +709,7 @@ class Events(Extension):
717
709
  async def send(kept: _Kept) -> None:
718
710
  hold.seen = kept.sequence
719
711
  try:
720
- shaped = declared._shape(kept, request)
712
+ shaped = declared._shape(kept, request, ctx)
721
713
  except Exception as error: # noqa: BLE001
722
714
  await say("error", {"error": _described(error)})
723
715
  return
@@ -732,9 +724,7 @@ class Events(Extension):
732
724
  if time.monotonic() >= beat:
733
725
  beat = time.monotonic() + _HEARTBEAT
734
726
  try:
735
- allowed = await declared._allows(
736
- request.context, request.arguments
737
- )
727
+ allowed = await declared._allows(ctx, request.arguments)
738
728
  except Exception as error: # noqa: BLE001
739
729
  await say("error", {"error": _described(error)})
740
730
  continue
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "holon-sh"
7
- version = "0.0.1.dev17"
7
+ version = "0.0.1.dev19"
8
8
  description = "Typed MCP clients and the caller of an MCP request"
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
@@ -52,11 +52,11 @@ def asynchronous(test):
52
52
  return run
53
53
 
54
54
 
55
- def declare(events=None, **hooks) -> tuple[Events, EventType[Board, Change]]:
55
+ def declare(events=None, **hooks) -> tuple[Events, EventType[dict[str, str], Change]]:
56
56
  events = events or Events()
57
57
  return events, events.event(
58
58
  "board.changed",
59
- input_schema=Board,
59
+ input_schema=Board.model_json_schema(),
60
60
  payload_schema=Change.model_json_schema(),
61
61
  **hooks,
62
62
  )
@@ -166,7 +166,7 @@ async def test_a_subscription_hears_what_its_arguments_match_as_shaped_across_a_
166
166
  delivery,
167
167
  ):
168
168
  events, changed = declare(
169
- match=lambda context, event, arguments: event.data.board == arguments.board,
169
+ match=lambda context, event, arguments: event.data.board == arguments["board"],
170
170
  transform=lambda context, event, arguments: {
171
171
  "board": event.data.board,
172
172
  "text": event.data.text.upper(),
@@ -207,6 +207,22 @@ async def test_targeted_events_follow_shared_identity_but_isolate_anonymous_read
207
207
  assert (await anext(second)).event_id == expected
208
208
 
209
209
 
210
+ @asynchronous
211
+ async def test_a_subscription_is_named_by_its_arguments_as_sent():
212
+ subscribed = []
213
+ events, _ = declare(on_subscribe=lambda context, args, id: subscribed.append(args))
214
+ ann = {"x-holon-context": signed_in("ann")}
215
+ async with served(events) as port, httpx2.AsyncClient(headers=ann) as http:
216
+ for arguments in [
217
+ {"board": "b"},
218
+ {"n": 1, "board": "b"},
219
+ {"board": "b", "n": 1},
220
+ ]:
221
+ params = {"name": "board.changed", "arguments": arguments}
222
+ assert "result" in await call(http, port, "events/poll", params)
223
+ assert subscribed == [{"board": "b"}, {"n": 1, "board": "b"}]
224
+
225
+
210
226
  @pytest.mark.parametrize("targeted", [False, True])
211
227
  @pytest.mark.parametrize("delivery", ["push", "poll"])
212
228
  @asynchronous
@@ -236,28 +252,21 @@ async def test_a_subscription_behind_what_is_kept_is_told_of_the_gap_and_carries
236
252
 
237
253
 
238
254
  @asynchronous
239
- async def test_what_a_subscribe_hook_emits_reaches_its_subscription_first_and_a_cursor_from_before_a_restart_is_a_gap():
240
- events, changed = declare(
241
- on_subscribe=lambda context, arguments, id: say(
242
- changed, arguments.board, "welcome", to=id
243
- )
244
- )
245
- restarted = declare()[1].cursor()
246
- gaps = []
255
+ async def test_a_cursor_from_before_a_restart_is_a_gap():
256
+ events, changed = declare()
257
+ restarted, gaps = declare()[1].cursor(), []
247
258
  async with served(events) as port:
248
- for cursor in [None, restarted]:
249
- for delivery in ["push", "poll"]:
250
- board = f"{delivery} {'resumed' if cursor else 'fresh'}"
251
- async with client(port, user="ann").subscribe(
252
- "board.changed",
253
- {"board": board},
254
- delivery=delivery,
255
- cursor=cursor,
256
- on_gap=partial(gaps.append, board),
257
- ) as changes:
258
- say(changed, board, "hello")
259
- assert await take(changes, 2) == ["welcome", "hello"]
260
- assert gaps == ["push resumed", "poll resumed"]
259
+ for delivery in ["push", "poll"]:
260
+ async with client(port, user="ann").subscribe(
261
+ "board.changed",
262
+ {"board": delivery},
263
+ delivery=delivery,
264
+ cursor=restarted,
265
+ on_gap=partial(gaps.append, delivery),
266
+ ) as changes:
267
+ say(changed, delivery, "hello")
268
+ assert await take(changes, 1) == ["hello"]
269
+ assert gaps == ["push", "poll"]
261
270
 
262
271
 
263
272
  @asynchronous
@@ -265,7 +274,7 @@ async def test_a_subscription_the_app_ends_is_sent_what_was_emitted_to_it_unless
265
274
  ids = {}
266
275
 
267
276
  def on_subscribe(context, arguments, id):
268
- ids[arguments.board] = id
277
+ ids[arguments["board"]] = id
269
278
 
270
279
  events, changed = declare(on_subscribe=on_subscribe)
271
280
  async with served(events) as port:
@@ -297,16 +306,6 @@ async def test_a_subscription_the_app_ends_is_sent_what_was_emitted_to_it_unless
297
306
 
298
307
  @asynchronous
299
308
  async def test_the_messages_on_the_wire_are_the_sketchs():
300
- recursive = {
301
- "$ref": "#/$defs/Node",
302
- "$defs": {
303
- "Node": {
304
- "type": "object",
305
- "properties": {"child": {"$ref": "#/$defs/Node"}},
306
- }
307
- },
308
- }
309
-
310
309
  def shaped(context, event, arguments):
311
310
  if event.data.text == "bad":
312
311
  raise ValueError("cannot be shaped")
@@ -319,10 +318,10 @@ async def test_the_messages_on_the_wire_are_the_sketchs():
319
318
  )
320
319
  events.event(
321
320
  "board.locked",
322
- input_schema=Board,
323
- payload_schema=recursive,
321
+ input_schema=Board.model_json_schema(),
322
+ payload_schema=Change.model_json_schema(),
324
323
  delivery=["poll"],
325
- authorize=lambda context, arguments: arguments.board != "secret",
324
+ authorize=lambda context, arguments: arguments["board"] != "secret",
326
325
  )
327
326
  async with served(events) as port, httpx2.AsyncClient(timeout=10) as http:
328
327
  discovered = await call(http, port, "server/discover", {})
@@ -331,7 +330,6 @@ async def test_the_messages_on_the_wire_are_the_sketchs():
331
330
  event["name"]: event
332
331
  for event in (await call(http, port, "events/list", {}))["result"]["events"]
333
332
  }
334
- assert listed["board.locked"]["payloadSchema"] == recursive
335
333
  assert set(listed["board.changed"]["delivery"]) == {"poll", "push"}
336
334
  expected = {
337
335
  "description": "A board changed",
@@ -424,53 +422,46 @@ async def test_the_messages_on_the_wire_are_the_sketchs():
424
422
 
425
423
 
426
424
  @asynchronous
427
- async def test_a_poll_that_gives_up_while_it_is_set_up_holds_its_place_until_its_lease_lapses(
425
+ async def test_a_poll_that_gives_up_while_it_is_set_up_stops_its_setup_and_holds_its_place_until_its_lease_lapses(
428
426
  monkeypatch,
429
427
  ):
430
- monkeypatch.setattr(_server, "_POLL_SUBSCRIPTION_TTL", 0.1)
428
+ monkeypatch.setattr(_server, "_POLL_SUBSCRIPTION_TTL", 0.5)
431
429
  monkeypatch.setattr(_server, "_MAX_SUBSCRIPTIONS", 1)
432
- setting_up, release, ended = asyncio.Event(), asyncio.Event(), asyncio.Event()
430
+ ended, seen = asyncio.Event(), []
433
431
 
434
432
  async def on_subscribe(context, arguments, id):
435
- setting_up.set()
436
- await release.wait()
433
+ seen.append(context.request.headers.get("x-leaving"))
434
+ try:
435
+ if seen[-1]:
436
+ await asyncio.Event().wait()
437
+ except asyncio.CancelledError:
438
+ seen.append("stopped")
439
+ raise
437
440
 
438
441
  async def cleanup():
439
442
  ended.set()
440
443
 
441
444
  return cleanup
442
445
 
443
- events, _ = declare(on_subscribe=on_subscribe)
444
- app, left = mounted(events), asyncio.Event()
445
-
446
- # Tells when the server sees the poll that gives up disconnect.
447
- async def noticing(scope, receive, send):
448
- async def receiving():
449
- message = await receive()
450
- if message["type"] == "http.disconnect":
451
- left.set()
452
- return message
453
-
454
- leaving = (b"x-leaving", b"1") in scope.get("headers", [])
455
- await app(scope, receiving if leaving else receive, send)
456
-
457
446
  async def give_up():
458
447
  async with httpx2.AsyncClient(headers={"x-leaving": "1"}) as http:
459
448
  await call(http, port, "events/poll", changed_on("b1"))
460
449
 
461
- port, stop = await serve(noticing)
462
- giving_up = asyncio.ensure_future(give_up())
463
- await setting_up.wait()
464
- async with httpx2.AsyncClient(timeout=10) as http:
450
+ async with (
451
+ served(declare(on_subscribe=on_subscribe)[0]) as port,
452
+ httpx2.AsyncClient(timeout=10) as http,
453
+ ):
454
+ giving_up = asyncio.ensure_future(give_up())
455
+ await until(lambda: seen)
465
456
  exhausted = await call(http, port, "events/poll", changed_on("b2"))
466
457
  limit = exhausted["error"]["data"]
467
458
  assert (limit["limit"], limit["max"]) == ("subscriptions", 1)
468
459
  giving_up.cancel()
469
- await left.wait()
470
- release.set()
460
+ await until(lambda: "stopped" in seen)
461
+ assert "result" in await call(http, port, "events/poll", changed_on("b1"))
462
+ assert seen == ["1", "stopped", None]
471
463
  await ended.wait()
472
464
  assert "result" in await call(http, port, "events/poll", changed_on("b2"))
473
- await stop()
474
465
 
475
466
 
476
467
  @asynchronous
@@ -493,10 +484,7 @@ async def test_a_subscription_can_be_retried_after_setup_times_out(
493
484
 
494
485
  @asynchronous
495
486
  async def test_a_subscription_from_the_cursor_read_with_a_snapshot_hears_every_change_after_it():
496
- events, said = Events(), []
497
- changed: EventType[Board, Change] = events.event(
498
- "board.changed", input_schema=Board, payload_schema=Change.model_json_schema()
499
- )
487
+ (events, changed), said = declare(), []
500
488
 
501
489
  def tell(text):
502
490
  said.append(text)
@@ -20,7 +20,7 @@ from holon.ext.events import Events, EventType
20
20
 
21
21
  def emit() -> None:
22
22
  changed: EventType[dict[str, str], dict[str, str]] = Events().event(
23
- "board.changed", input_schema=dict[str, str],
23
+ "board.changed", input_schema={"type": "object"},
24
24
  payload_schema={"type": "object", "additionalProperties": {"type": "string"}},
25
25
  )
26
26
  changed.emit({"text": "hello"})
File without changes
File without changes