streamcast 0.28.2__tar.gz → 0.28.3__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 (54) hide show
  1. {streamcast-0.28.2 → streamcast-0.28.3}/PKG-INFO +1 -1
  2. {streamcast-0.28.2 → streamcast-0.28.3}/pyproject.toml +1 -1
  3. {streamcast-0.28.2 → streamcast-0.28.3}/pyproject.toml.orig +1 -1
  4. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_outbox.py +64 -12
  5. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_store.py +66 -9
  6. {streamcast-0.28.2 → streamcast-0.28.3}/LICENSE +0 -0
  7. {streamcast-0.28.2 → streamcast-0.28.3}/NOTICE +0 -0
  8. {streamcast-0.28.2 → streamcast-0.28.3}/README.md +0 -0
  9. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/__init__.py +0 -0
  10. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/__main__.py +0 -0
  11. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_application.py +0 -0
  12. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_asgi.py +0 -0
  13. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_broker/__init__.py +0 -0
  14. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_broker/api.py +0 -0
  15. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_broker/model.py +0 -0
  16. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_broker/registry.py +0 -0
  17. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_broker/runtime.py +0 -0
  18. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_broker/transitions.py +0 -0
  19. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_broker/upgrade.py +0 -0
  20. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_catchup.py +0 -0
  21. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_children.py +0 -0
  22. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_client.py +0 -0
  23. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_codec.py +0 -0
  24. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_cursor.py +0 -0
  25. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_dedupe.py +0 -0
  26. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_errors.py +0 -0
  27. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_filter.py +0 -0
  28. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_inbox.py +0 -0
  29. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_ingest.py +0 -0
  30. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_limits.py +0 -0
  31. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_live.py +0 -0
  32. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_log.py +0 -0
  33. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_maintain.py +0 -0
  34. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_manifest.py +0 -0
  35. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_metadata.py +0 -0
  36. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_metrics.py +0 -0
  37. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_process.py +0 -0
  38. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_protocol.py +0 -0
  39. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_publish.py +0 -0
  40. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_published.py +0 -0
  41. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_remote.py +0 -0
  42. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_replicate.py +0 -0
  43. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_retention.py +0 -0
  44. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_schema.py +0 -0
  45. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_snapshot.py +0 -0
  46. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_spec.py +0 -0
  47. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_stats.py +0 -0
  48. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_stream.py +0 -0
  49. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_subscriber.py +0 -0
  50. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_tasks.py +0 -0
  51. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_transport.py +0 -0
  52. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_versions.py +0 -0
  53. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/_writer.py +0 -0
  54. {streamcast-0.28.2 → streamcast-0.28.3}/src/streamcast/py.typed +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: streamcast
3
- Version: 0.28.2
3
+ Version: 0.28.3
4
4
  Summary: A JSON WebSocket pubsub framework for structured data. Every message lands in an Iceberg table: no ETL, no second copy.
5
5
  Keywords: websocket,multicast,broadcast,tickerplant,market-data
6
6
  Author: Nico Bautista Hobin
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "streamcast"
3
- version = "0.28.2"
3
+ version = "0.28.3"
4
4
  description = "A JSON WebSocket pubsub framework for structured data. Every message lands in an Iceberg table: no ETL, no second copy."
5
5
  readme = "README.md"
6
6
  license = "Apache-2.0"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "streamcast"
3
- version = "0.28.2"
3
+ version = "0.28.3"
4
4
  description = "A JSON WebSocket pubsub framework for structured data. Every message lands in an Iceberg table: no ETL, no second copy."
5
5
  readme = "README.md"
6
6
  authors = [
@@ -41,8 +41,9 @@ the lowest pending seq already says it, and a second copy could disagree.
41
41
 
42
42
  **The sender:**
43
43
 
44
- * it connects only when it has rows, so a quiet process holds no idle
45
- connection for the broker's keepalive to close;
44
+ * it connects when it has rows or unresolved acknowledgement waiters, so a
45
+ final ACK with a lost COMMIT reply reconciles even after its row is gone;
46
+ a quiet process holds no idle connection for the broker to close;
46
47
  * it ships ordered batches of `SEND_BATCH` rows as one frame, pipelined up to
47
48
  `max_in_flight`;
48
49
  * a batch the broker refuses (`Rejected`) is sent again one row at a time,
@@ -57,6 +58,12 @@ the lowest pending seq already says it, and a second copy could disagree.
57
58
  stream this sender ships to;
58
59
  * it reconnects under a capped backoff (`BACKOFF`), and polls every
59
60
  `POLL_EVERY` for rows another process committed to the same database;
61
+ * database connection failures, including polling and acknowledgement
62
+ transactions, use that same backoff. Unclassified libpq errors have a
63
+ five-minute grace period because permanent connect refusals omit SQLSTATE
64
+ too; errors still unclassified after that surface and stop the sender. A
65
+ caller's enqueue still raises its current database error; the sender
66
+ never stores a transient failure or replays a caller's transaction;
60
67
  * a refusal of the connection itself -- `Superseded`, `ExactlyOnceUnavailable`,
61
68
  `StreamRetired`, `StreamMismatch`, `AcknowledgedRowsLost`,
62
69
  `StoreBehindBroker`, or a `SequenceGap` the sender did not cause -- is
@@ -96,7 +103,11 @@ from streamcast._errors import (
96
103
  from streamcast._limits import BACKOFF, MAX_IN_FLIGHT, POLL_EVERY, SEND_BATCH
97
104
  from streamcast._protocol import stream_name
98
105
  from streamcast._publish import Publication, publish
99
- from streamcast._store import sql
106
+ from streamcast._store import (
107
+ _transient_connection_error,
108
+ _unclassified_connection_error,
109
+ sql,
110
+ )
100
111
 
101
112
  if TYPE_CHECKING:
102
113
  from collections.abc import Callable, Iterable, Mapping, Sequence
@@ -112,6 +123,14 @@ _DECODE = msgspec.json.Decoder()
112
123
  LANDED_KEPT = 10_000
113
124
  """Offsets of recently acknowledged seqs kept for `landed`, oldest out first."""
114
125
 
126
+ UNCLASSIFIED_DB_RETRY_GRACE = 300.0
127
+ """Seconds of consecutive unclassified connection failures before surfacing.
128
+
129
+ libpq gives no SQLSTATE for either an outage or a permanent connect refusal.
130
+ Five minutes accommodates a brief restart without hiding bad credentials or
131
+ connection policy forever. A successful sender cycle resets the grace.
132
+ """
133
+
115
134
 
116
135
  def _now_us() -> int:
117
136
  return time.time_ns() // 1_000
@@ -612,16 +631,45 @@ class Outbox:
612
631
 
613
632
  async def _run(self) -> None:
614
633
  attempt = 0
634
+ unclassified_since: float | None = None
615
635
  try:
616
636
  while not self._closed:
617
- if not await self._has_rows():
618
- self._drained.set()
619
- await self._sleep(self._poll_every)
620
- continue
621
-
622
637
  try:
638
+ if not await self._has_rows() and not self._waiting:
639
+ self._recovered()
640
+ attempt = 0
641
+ unclassified_since = None
642
+ self._drained.set()
643
+ await self._sleep(self._poll_every)
644
+ continue
645
+
623
646
  await self._session()
624
- except (OSError, ConnectionClosed, TimeoutError, CommitFailed) as exc:
647
+ except Exception as exc:
648
+ if not (
649
+ isinstance(
650
+ exc, (OSError, ConnectionClosed, TimeoutError, CommitFailed)
651
+ )
652
+ or _transient_connection_error(exc)
653
+ ):
654
+ raise
655
+
656
+ if _unclassified_connection_error(exc):
657
+ now = time.monotonic()
658
+ if unclassified_since is None:
659
+ unclassified_since = now
660
+
661
+ if now - unclassified_since >= UNCLASSIFIED_DB_RETRY_GRACE:
662
+ msg = (
663
+ "Postgres connection failures without SQLSTATE "
664
+ f"persisted for {UNCLASSIFIED_DB_RETRY_GRACE:g} "
665
+ "seconds; check credentials, database existence "
666
+ "and connection policy, then reopen the outbox"
667
+ )
668
+ raise RuntimeError(msg) from exc
669
+
670
+ else:
671
+ unclassified_since = None
672
+
625
673
  if not self._outage:
626
674
  self._outage = True
627
675
  self._notice(
@@ -636,11 +684,17 @@ class Outbox:
636
684
  continue
637
685
 
638
686
  attempt = 0
687
+ unclassified_since = None
639
688
 
640
689
  except Exception as exc: # noqa: BLE001 — surfaced by the next call
641
690
  # Not BaseException: a cancel is `close`, not a failure to report.
642
691
  self._fail(exc)
643
692
 
693
+ def _recovered(self) -> None:
694
+ if self._outage:
695
+ self._outage = False
696
+ self._notice(f"streamcast outbox {self._stream!r}: publishing again")
697
+
644
698
  def _fail(self, exc: BaseException) -> None:
645
699
  self._failure = exc
646
700
  self._drained.set()
@@ -688,9 +742,7 @@ class Outbox:
688
742
  if not waiter.done():
689
743
  waiter.set_result(None)
690
744
 
691
- if self._outage:
692
- self._outage = False
693
- self._notice(f"streamcast outbox {self._stream!r}: publishing again")
745
+ self._recovered()
694
746
 
695
747
  await self._ship(out)
696
748
  finally:
@@ -52,6 +52,11 @@ from typing import TYPE_CHECKING, Any, Final, Literal, Protocol, TypeVar
52
52
 
53
53
  from streamcast._tasks import join
54
54
 
55
+ try:
56
+ import psycopg
57
+ except ImportError: # pragma: no cover — the postgres extra is optional
58
+ psycopg = None
59
+
55
60
  if TYPE_CHECKING:
56
61
  from collections.abc import AsyncIterator, Awaitable, Callable, Sequence
57
62
  from contextlib import AbstractAsyncContextManager
@@ -60,6 +65,35 @@ if TYPE_CHECKING:
60
65
  Dialect = Literal["sqlite", "postgres"]
61
66
  T = TypeVar("T")
62
67
 
68
+
69
+ def _unclassified_connection_error(error: BaseException) -> bool:
70
+ """libpq omits SQLSTATE for both unavailable servers and connect refusals."""
71
+ return (
72
+ psycopg is not None
73
+ and isinstance(error, psycopg.OperationalError)
74
+ and error.sqlstate is None
75
+ )
76
+
77
+
78
+ def _transient_connection_error(error: BaseException) -> bool:
79
+ """A lost/unavailable Postgres connection, including adapter exceptions.
80
+
81
+ OperationalError also includes permanent failures such as disk full.
82
+ Unclassified libpq failures need a bounded grace period: credentials and
83
+ policy refusals look like outages. Class 08 is a connection exception,
84
+ and 57P01–03 cover shutdown, crash and startup respectively.
85
+ """
86
+ return _unclassified_connection_error(error) or (
87
+ psycopg is not None
88
+ and isinstance(error, psycopg.OperationalError)
89
+ and error.sqlstate is not None
90
+ and (
91
+ error.sqlstate.startswith("08")
92
+ or error.sqlstate in {"57P01", "57P02", "57P03"}
93
+ )
94
+ )
95
+
96
+
63
97
  SCHEMA_VERSION: Final = 1
64
98
  """The version of the library's tables this build writes. A store whose
65
99
  tables are newer is refused at open rather than written in an older shape."""
@@ -405,15 +439,22 @@ class PostgresStore:
405
439
  transaction pooler. Pass libpq's keepalive and `options=-c
406
440
  statement_timeout=...` settings in the DSN so a database that vanished
407
441
  fails a transaction in bounded time rather than hanging it.
442
+
443
+ A broken connection is reopened at the next transaction using the
444
+ original DSN and keywords, resolving its hostname again. An interrupted
445
+ block is never replayed; a lost COMMIT reply may already have committed.
446
+ Explicit `close` is final.
408
447
  """
409
448
 
410
- __slots__ = ("_connection", "_lock")
449
+ __slots__ = ("_closed", "_connect", "_connection", "_lock")
411
450
 
412
451
  dialect: Final[Dialect] = "postgres"
413
452
 
414
- def __init__(self, connection: Any) -> None:
453
+ def __init__(self, connection: Any, connect: Callable[[], Awaitable[Any]]) -> None:
415
454
  self._connection = connection
455
+ self._connect = connect
416
456
  self._lock = _Lock()
457
+ self._closed = False
417
458
 
418
459
  @classmethod
419
460
  async def connect(
@@ -421,16 +462,18 @@ class PostgresStore:
421
462
  ) -> PostgresStore:
422
463
  """Connect to `dsn`, creating the library's tables unless
423
464
  `create=False`. Other keywords go to `psycopg.AsyncConnection.connect`."""
424
- try:
425
- import psycopg # noqa: PLC0415 — an optional extra
426
- except ImportError: # pragma: no cover — depends on the install
465
+ if psycopg is None: # pragma: no cover — depends on the install
427
466
  msg = "PostgresStore needs psycopg 3: install streamcast[postgres]"
428
467
  raise ImportError(msg) from None
429
468
 
430
- connection = await psycopg.AsyncConnection.connect(
431
- dsn, autocommit=True, **kwargs
432
- )
433
- store = cls(connection)
469
+ async def connect() -> Any:
470
+ assert psycopg is not None
471
+ # Keep the caller's DSN, not connection.info.dsn: psycopg may
472
+ # add the resolved hostaddr there, pinning a restart's old IP.
473
+ return await psycopg.AsyncConnection.connect(dsn, autocommit=True, **kwargs)
474
+
475
+ connection = await connect()
476
+ store = cls(connection, connect)
434
477
  try:
435
478
  await _prepare(store, create=create)
436
479
  except BaseException:
@@ -464,9 +507,22 @@ class PostgresStore:
464
507
 
465
508
  await self._run(run)
466
509
 
510
+ async def _reconnect(self) -> None:
511
+ await self._connection.close()
512
+ self._connection = await self._connect()
513
+
467
514
  @contextlib.asynccontextmanager
468
515
  async def transaction(self) -> AsyncIterator[Transaction]:
469
516
  async with self._lock.held():
517
+ if self._closed:
518
+ msg = "the Postgres store is closed"
519
+ raise RuntimeError(msg)
520
+
521
+ if self._connection.closed or self._connection.broken:
522
+ # Assign inside the joined command, so cancellation cannot
523
+ # orphan a newly opened connection. Never replay a block.
524
+ await self._run(self._reconnect)
525
+
470
526
  tx = _PostgresTransaction(self)
471
527
  try:
472
528
  # Inside the try, as for SQLite: a cancellation that lands
@@ -493,6 +549,7 @@ class PostgresStore:
493
549
 
494
550
  async def close(self) -> None:
495
551
  async with self._lock.held():
552
+ self._closed = True
496
553
  with contextlib.suppress(Exception):
497
554
  await self._connection.close()
498
555
 
File without changes
File without changes
File without changes