Skip to content

prefect.events.clients

AssertingEventsClient

Bases: EventsClient

A Prefect Events client that records all events sent to it for inspection during tests.

Source code in src/prefect/events/clients.py
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
class AssertingEventsClient(EventsClient):
    """A Prefect Events client that records all events sent to it for inspection during
    tests."""

    last: ClassVar["Optional[AssertingEventsClient]"] = None
    all: ClassVar[List["AssertingEventsClient"]] = []

    args: Tuple
    kwargs: Dict[str, Any]
    events: List[Event]

    def __init__(self, *args, **kwargs):
        AssertingEventsClient.last = self
        AssertingEventsClient.all.append(self)
        self.args = args
        self.kwargs = kwargs

    @classmethod
    def reset(cls) -> None:
        """Reset all captured instances and their events. For use between
        tests"""
        cls.last = None
        cls.all = []

    def pop_events(self) -> List[Event]:
        events = self.events
        self.events = []
        return events

    async def _emit(self, event: Event) -> None:
        self.events.append(event)

    async def __aenter__(self) -> Self:
        await super().__aenter__()
        self.events = []
        return self

reset() classmethod

Reset all captured instances and their events. For use between tests

Source code in src/prefect/events/clients.py
206
207
208
209
210
211
@classmethod
def reset(cls) -> None:
    """Reset all captured instances and their events. For use between
    tests"""
    cls.last = None
    cls.all = []

AssertingPassthroughEventsClient

Bases: PrefectEventsClient

A Prefect Events client that BOTH records all events sent to it for inspection during tests AND sends them to a Prefect server.

Source code in src/prefect/events/clients.py
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
class AssertingPassthroughEventsClient(PrefectEventsClient):
    """A Prefect Events client that BOTH records all events sent to it for inspection
    during tests AND sends them to a Prefect server."""

    last: ClassVar["Optional[AssertingPassthroughEventsClient]"] = None
    all: ClassVar[List["AssertingPassthroughEventsClient"]] = []

    args: Tuple
    kwargs: Dict[str, Any]
    events: List[Event]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        AssertingPassthroughEventsClient.last = self
        AssertingPassthroughEventsClient.all.append(self)
        self.args = args
        self.kwargs = kwargs

    @classmethod
    def reset(cls) -> None:
        cls.last = None
        cls.all = []

    def pop_events(self) -> List[Event]:
        events = self.events
        self.events = []
        return events

    async def _emit(self, event: Event) -> None:
        # actually send the event to the server
        await super()._emit(event)

        # record the event for inspection
        self.events.append(event)

    async def __aenter__(self) -> Self:
        await super().__aenter__()
        self.events = []
        return self

EventsClient

Bases: ABC

The abstract interface for all Prefect Events clients

Source code in src/prefect/events/clients.py
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
class EventsClient(abc.ABC):
    """The abstract interface for all Prefect Events clients"""

    @property
    def client_name(self) -> str:
        return self.__class__.__name__

    async def emit(self, event: Event) -> None:
        """Emit a single event"""
        if not hasattr(self, "_in_context"):
            raise TypeError(
                "Events may only be emitted while this client is being used as a "
                "context manager"
            )

        try:
            return await self._emit(event)
        finally:
            EVENTS_EMITTED.labels(self.client_name).inc()

    @abc.abstractmethod
    async def _emit(self, event: Event) -> None:  # pragma: no cover
        ...

    async def __aenter__(self) -> Self:
        self._in_context = True
        return self

    async def __aexit__(
        self,
        exc_type: Optional[Type[Exception]],
        exc_val: Optional[Exception],
        exc_tb: Optional[TracebackType],
    ) -> None:
        del self._in_context
        return None

emit(event) async

Emit a single event

Source code in src/prefect/events/clients.py
151
152
153
154
155
156
157
158
159
160
161
162
async def emit(self, event: Event) -> None:
    """Emit a single event"""
    if not hasattr(self, "_in_context"):
        raise TypeError(
            "Events may only be emitted while this client is being used as a "
            "context manager"
        )

    try:
        return await self._emit(event)
    finally:
        EVENTS_EMITTED.labels(self.client_name).inc()

NullEventsClient

Bases: EventsClient

A Prefect Events client implementation that does nothing

Source code in src/prefect/events/clients.py
182
183
184
185
186
class NullEventsClient(EventsClient):
    """A Prefect Events client implementation that does nothing"""

    async def _emit(self, event: Event) -> None:
        pass

PrefectCloudAccountEventSubscriber

Bases: PrefectCloudEventSubscriber

Source code in src/prefect/events/clients.py
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
class PrefectCloudAccountEventSubscriber(PrefectCloudEventSubscriber):
    def __init__(
        self,
        api_url: Optional[str] = None,
        api_key: Optional[str] = None,
        filter: Optional["EventFilter"] = None,
        reconnection_attempts: int = 10,
    ):
        """
        Args:
            api_url: The base URL for a Prefect Cloud workspace
            api_key: The API of an actor with the manage_events scope
            reconnection_attempts: When the client is disconnected, how many times
                the client should attempt to reconnect
        """
        api_url, api_key = _get_api_url_and_key(api_url, api_key)

        account_api_url, _, _ = api_url.partition("/workspaces/")

        super().__init__(
            api_url=account_api_url,
            filter=filter,
            reconnection_attempts=reconnection_attempts,
        )

        self._api_key = api_key

__init__(api_url=None, api_key=None, filter=None, reconnection_attempts=10)

Parameters:

Name Type Description Default
api_url Optional[str]

The base URL for a Prefect Cloud workspace

None
api_key Optional[str]

The API of an actor with the manage_events scope

None
reconnection_attempts int

When the client is disconnected, how many times the client should attempt to reconnect

10
Source code in src/prefect/events/clients.py
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
def __init__(
    self,
    api_url: Optional[str] = None,
    api_key: Optional[str] = None,
    filter: Optional["EventFilter"] = None,
    reconnection_attempts: int = 10,
):
    """
    Args:
        api_url: The base URL for a Prefect Cloud workspace
        api_key: The API of an actor with the manage_events scope
        reconnection_attempts: When the client is disconnected, how many times
            the client should attempt to reconnect
    """
    api_url, api_key = _get_api_url_and_key(api_url, api_key)

    account_api_url, _, _ = api_url.partition("/workspaces/")

    super().__init__(
        api_url=account_api_url,
        filter=filter,
        reconnection_attempts=reconnection_attempts,
    )

    self._api_key = api_key

PrefectCloudEventSubscriber

Bases: PrefectEventSubscriber

Source code in src/prefect/events/clients.py
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
class PrefectCloudEventSubscriber(PrefectEventSubscriber):
    def __init__(
        self,
        api_url: Optional[str] = None,
        api_key: Optional[str] = None,
        filter: Optional["EventFilter"] = None,
        reconnection_attempts: int = 10,
    ):
        """
        Args:
            api_url: The base URL for a Prefect Cloud workspace
            api_key: The API of an actor with the manage_events scope
            reconnection_attempts: When the client is disconnected, how many times
                the client should attempt to reconnect
        """
        api_url, api_key = _get_api_url_and_key(api_url, api_key)

        super().__init__(
            api_url=api_url,
            filter=filter,
            reconnection_attempts=reconnection_attempts,
        )

        self._api_key = api_key

__init__(api_url=None, api_key=None, filter=None, reconnection_attempts=10)

Parameters:

Name Type Description Default
api_url Optional[str]

The base URL for a Prefect Cloud workspace

None
api_key Optional[str]

The API of an actor with the manage_events scope

None
reconnection_attempts int

When the client is disconnected, how many times the client should attempt to reconnect

10
Source code in src/prefect/events/clients.py
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
def __init__(
    self,
    api_url: Optional[str] = None,
    api_key: Optional[str] = None,
    filter: Optional["EventFilter"] = None,
    reconnection_attempts: int = 10,
):
    """
    Args:
        api_url: The base URL for a Prefect Cloud workspace
        api_key: The API of an actor with the manage_events scope
        reconnection_attempts: When the client is disconnected, how many times
            the client should attempt to reconnect
    """
    api_url, api_key = _get_api_url_and_key(api_url, api_key)

    super().__init__(
        api_url=api_url,
        filter=filter,
        reconnection_attempts=reconnection_attempts,
    )

    self._api_key = api_key

PrefectCloudEventsClient

Bases: PrefectEventsClient

A Prefect Events client that streams events to a Prefect Cloud Workspace

Source code in src/prefect/events/clients.py
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
class PrefectCloudEventsClient(PrefectEventsClient):
    """A Prefect Events client that streams events to a Prefect Cloud Workspace"""

    def __init__(
        self,
        api_url: Optional[str] = None,
        api_key: Optional[str] = None,
        reconnection_attempts: int = 10,
        checkpoint_every: int = 700,
    ):
        """
        Args:
            api_url: The base URL for a Prefect Cloud workspace
            api_key: The API of an actor with the manage_events scope
            reconnection_attempts: When the client is disconnected, how many times
                the client should attempt to reconnect
            checkpoint_every: How often the client should sync with the server to
                confirm receipt of all previously sent events
        """
        api_url, api_key = _get_api_url_and_key(api_url, api_key)
        super().__init__(
            api_url=api_url,
            reconnection_attempts=reconnection_attempts,
            checkpoint_every=checkpoint_every,
        )
        self._connect = connect(
            self._events_socket_url,
            extra_headers={"Authorization": f"bearer {api_key}"},
        )

__init__(api_url=None, api_key=None, reconnection_attempts=10, checkpoint_every=700)

Parameters:

Name Type Description Default
api_url Optional[str]

The base URL for a Prefect Cloud workspace

None
api_key Optional[str]

The API of an actor with the manage_events scope

None
reconnection_attempts int

When the client is disconnected, how many times the client should attempt to reconnect

10
checkpoint_every int

How often the client should sync with the server to confirm receipt of all previously sent events

700
Source code in src/prefect/events/clients.py
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
def __init__(
    self,
    api_url: Optional[str] = None,
    api_key: Optional[str] = None,
    reconnection_attempts: int = 10,
    checkpoint_every: int = 700,
):
    """
    Args:
        api_url: The base URL for a Prefect Cloud workspace
        api_key: The API of an actor with the manage_events scope
        reconnection_attempts: When the client is disconnected, how many times
            the client should attempt to reconnect
        checkpoint_every: How often the client should sync with the server to
            confirm receipt of all previously sent events
    """
    api_url, api_key = _get_api_url_and_key(api_url, api_key)
    super().__init__(
        api_url=api_url,
        reconnection_attempts=reconnection_attempts,
        checkpoint_every=checkpoint_every,
    )
    self._connect = connect(
        self._events_socket_url,
        extra_headers={"Authorization": f"bearer {api_key}"},
    )

PrefectEventSubscriber

Subscribes to a Prefect event stream, yielding events as they occur.

Example:

from prefect.events.clients import PrefectEventSubscriber
from prefect.events.filters import EventFilter, EventNameFilter

filter = EventFilter(event=EventNameFilter(prefix=["prefect.flow-run."]))

async with PrefectEventSubscriber(filter=filter) as subscriber:
    async for event in subscriber:
        print(event.occurred, event.resource.id, event.event)
Source code in src/prefect/events/clients.py
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
class PrefectEventSubscriber:
    """
    Subscribes to a Prefect event stream, yielding events as they occur.

    Example:

        from prefect.events.clients import PrefectEventSubscriber
        from prefect.events.filters import EventFilter, EventNameFilter

        filter = EventFilter(event=EventNameFilter(prefix=["prefect.flow-run."]))

        async with PrefectEventSubscriber(filter=filter) as subscriber:
            async for event in subscriber:
                print(event.occurred, event.resource.id, event.event)

    """

    _websocket: Optional[WebSocketClientProtocol]
    _filter: "EventFilter"
    _seen_events: MutableMapping[UUID, bool]

    _api_key: Optional[str]

    def __init__(
        self,
        api_url: Optional[str] = None,
        filter: Optional["EventFilter"] = None,
        reconnection_attempts: int = 10,
    ):
        """
        Args:
            api_url: The base URL for a Prefect Cloud workspace
            api_key: The API of an actor with the manage_events scope
            reconnection_attempts: When the client is disconnected, how many times
                the client should attempt to reconnect
        """
        self._api_key = None
        if not api_url:
            api_url = cast(str, PREFECT_API_URL.value())

        from prefect.events.filters import EventFilter

        self._filter = filter or EventFilter()  # type: ignore[call-arg]
        self._seen_events = TTLCache(maxsize=SEEN_EVENTS_SIZE, ttl=SEEN_EVENTS_TTL)

        socket_url = events_out_socket_from_api_url(api_url)

        logger.debug("Connecting to %s", socket_url)

        self._connect = connect(
            socket_url,
            subprotocols=[Subprotocol("prefect")],
        )
        self._websocket = None
        self._reconnection_attempts = reconnection_attempts
        if self._reconnection_attempts < 0:
            raise ValueError("reconnection_attempts must be a non-negative integer")

    @property
    def client_name(self) -> str:
        return self.__class__.__name__

    async def __aenter__(self) -> Self:
        # Don't handle any errors in the initial connection, because these are most
        # likely a permission or configuration issue that should propagate
        try:
            await self._reconnect()
        finally:
            EVENT_WEBSOCKET_CONNECTIONS.labels(self.client_name, "out", "initial")
        return self

    async def _reconnect(self) -> None:
        logger.debug("Reconnecting...")
        if self._websocket:
            self._websocket = None
            await self._connect.__aexit__(None, None, None)

        self._websocket = await self._connect.__aenter__()

        # make sure we have actually connected
        logger.debug("  pinging...")
        pong = await self._websocket.ping()
        await pong

        logger.debug("  authenticating...")
        await self._websocket.send(
            orjson.dumps({"type": "auth", "token": self._api_key}).decode()
        )

        try:
            message: Dict[str, Any] = orjson.loads(await self._websocket.recv())
            logger.debug("  auth result %s", message)
            assert message["type"] == "auth_success", message.get("reason", "")
        except AssertionError as e:
            raise Exception(
                "Unable to authenticate to the event stream. Please ensure the "
                "provided api_key you are using is valid for this environment. "
                f"Reason: {e.args[0]}"
            )
        except ConnectionClosedError as e:
            reason = getattr(e.rcvd, "reason", None)
            msg = "Unable to authenticate to the event stream. Please ensure the "
            msg += "provided api_key you are using is valid for this environment. "
            msg += f"Reason: {reason}" if reason else ""
            raise Exception(msg) from e

        from prefect.events.filters import EventOccurredFilter

        self._filter.occurred = EventOccurredFilter(
            since=pendulum.now("UTC").subtract(minutes=1),
            until=pendulum.now("UTC").add(years=1),
        )

        logger.debug("  filtering events since %s...", self._filter.occurred.since)
        filter_message = {
            "type": "filter",
            "filter": self._filter.model_dump(mode="json"),
        }
        await self._websocket.send(orjson.dumps(filter_message).decode())

    async def __aexit__(
        self,
        exc_type: Optional[Type[Exception]],
        exc_val: Optional[Exception],
        exc_tb: Optional[TracebackType],
    ) -> None:
        self._websocket = None
        await self._connect.__aexit__(exc_type, exc_val, exc_tb)

    def __aiter__(self) -> Self:
        return self

    async def __anext__(self) -> Event:
        assert self._reconnection_attempts >= 0
        for i in range(self._reconnection_attempts + 1):  # pragma: no branch
            try:
                # If we're here and the websocket is None, then we've had a failure in a
                # previous reconnection attempt.
                #
                # Otherwise, after the first time through this loop, we're recovering
                # from a ConnectionClosed, so reconnect now.
                if not self._websocket or i > 0:
                    try:
                        await self._reconnect()
                    finally:
                        EVENT_WEBSOCKET_CONNECTIONS.labels(
                            self.client_name, "out", "reconnect"
                        )
                    assert self._websocket

                while True:
                    message = orjson.loads(await self._websocket.recv())
                    event: Event = Event.model_validate(message["event"])

                    if event.id in self._seen_events:
                        continue
                    self._seen_events[event.id] = True

                    try:
                        return event
                    finally:
                        EVENTS_OBSERVED.labels(self.client_name).inc()
            except ConnectionClosedOK:
                logger.debug('Connection closed with "OK" status')
                raise StopAsyncIteration
            except ConnectionClosed:
                logger.debug(
                    "Connection closed with %s/%s attempts",
                    i + 1,
                    self._reconnection_attempts,
                )
                if i == self._reconnection_attempts:
                    # this was our final chance, raise the most recent error
                    raise

                if i > 2:
                    # let the first two attempts happen quickly in case this is just
                    # a standard load balancer timeout, but after that, just take a
                    # beat to let things come back around.
                    await asyncio.sleep(1)
        raise StopAsyncIteration

__init__(api_url=None, filter=None, reconnection_attempts=10)

Parameters:

Name Type Description Default
api_url Optional[str]

The base URL for a Prefect Cloud workspace

None
api_key

The API of an actor with the manage_events scope

required
reconnection_attempts int

When the client is disconnected, how many times the client should attempt to reconnect

10
Source code in src/prefect/events/clients.py
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
def __init__(
    self,
    api_url: Optional[str] = None,
    filter: Optional["EventFilter"] = None,
    reconnection_attempts: int = 10,
):
    """
    Args:
        api_url: The base URL for a Prefect Cloud workspace
        api_key: The API of an actor with the manage_events scope
        reconnection_attempts: When the client is disconnected, how many times
            the client should attempt to reconnect
    """
    self._api_key = None
    if not api_url:
        api_url = cast(str, PREFECT_API_URL.value())

    from prefect.events.filters import EventFilter

    self._filter = filter or EventFilter()  # type: ignore[call-arg]
    self._seen_events = TTLCache(maxsize=SEEN_EVENTS_SIZE, ttl=SEEN_EVENTS_TTL)

    socket_url = events_out_socket_from_api_url(api_url)

    logger.debug("Connecting to %s", socket_url)

    self._connect = connect(
        socket_url,
        subprotocols=[Subprotocol("prefect")],
    )
    self._websocket = None
    self._reconnection_attempts = reconnection_attempts
    if self._reconnection_attempts < 0:
        raise ValueError("reconnection_attempts must be a non-negative integer")

PrefectEventsClient

Bases: EventsClient

A Prefect Events client that streams events to a Prefect server

Source code in src/prefect/events/clients.py
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
class PrefectEventsClient(EventsClient):
    """A Prefect Events client that streams events to a Prefect server"""

    _websocket: Optional[WebSocketClientProtocol]
    _unconfirmed_events: List[Event]

    def __init__(
        self,
        api_url: Optional[str] = None,
        reconnection_attempts: int = 10,
        checkpoint_every: int = 700,
    ):
        """
        Args:
            api_url: The base URL for a Prefect server
            reconnection_attempts: When the client is disconnected, how many times
                the client should attempt to reconnect
            checkpoint_every: How often the client should sync with the server to
                confirm receipt of all previously sent events
        """
        api_url = api_url or PREFECT_API_URL.value()
        if not api_url:
            raise ValueError(
                "api_url must be provided or set in the Prefect configuration"
            )

        self._events_socket_url = events_in_socket_from_api_url(api_url)
        self._connect = connect(self._events_socket_url)
        self._websocket = None
        self._reconnection_attempts = reconnection_attempts
        self._unconfirmed_events = []
        self._checkpoint_every = checkpoint_every

    async def __aenter__(self) -> Self:
        # Don't handle any errors in the initial connection, because these are most
        # likely a permission or configuration issue that should propagate
        await super().__aenter__()
        await self._reconnect()
        return self

    async def __aexit__(
        self,
        exc_type: Optional[Type[Exception]],
        exc_val: Optional[Exception],
        exc_tb: Optional[TracebackType],
    ) -> None:
        self._websocket = None
        await self._connect.__aexit__(exc_type, exc_val, exc_tb)
        return await super().__aexit__(exc_type, exc_val, exc_tb)

    async def _reconnect(self) -> None:
        if self._websocket:
            self._websocket = None
            await self._connect.__aexit__(None, None, None)

        try:
            self._websocket = await self._connect.__aenter__()
            # make sure we have actually connected
            pong = await self._websocket.ping()
            await pong
        except Exception as e:
            # The client is frequently run in a background thread
            # so we log an additional warning to ensure
            # surfacing the error to the user.
            logger.warning(
                "Unable to connect to %r. "
                "Please check your network settings to ensure websocket connections "
                "to the API are allowed. Otherwise event data (including task run data) may be lost. "
                "Reason: %s. "
                "Set PREFECT_DEBUG_MODE=1 to see the full error.",
                self._events_socket_url,
                str(e),
                exc_info=PREFECT_DEBUG_MODE,
            )
            raise

        events_to_resend = self._unconfirmed_events
        # Clear the unconfirmed events here, because they are going back through emit
        # and will be added again through the normal checkpointing process
        self._unconfirmed_events = []
        for event in events_to_resend:
            await self.emit(event)

    async def _checkpoint(self, event: Event) -> None:
        assert self._websocket

        self._unconfirmed_events.append(event)

        unconfirmed_count = len(self._unconfirmed_events)
        if unconfirmed_count < self._checkpoint_every:
            return

        pong = await self._websocket.ping()
        await pong

        # once the pong returns, we know for sure that we've sent all the messages
        # we had enqueued prior to that.  There could be more that came in after, so
        # don't clear the list, just the ones that we are sure of.
        self._unconfirmed_events = self._unconfirmed_events[unconfirmed_count:]

        EVENT_WEBSOCKET_CHECKPOINTS.labels(self.client_name).inc()

    async def _emit(self, event: Event) -> None:
        for i in range(self._reconnection_attempts + 1):
            try:
                # If we're here and the websocket is None, then we've had a failure in a
                # previous reconnection attempt.
                #
                # Otherwise, after the first time through this loop, we're recovering
                # from a ConnectionClosed, so reconnect now, resending any unconfirmed
                # events before we send this one.
                if not self._websocket or i > 0:
                    await self._reconnect()
                    assert self._websocket

                await self._websocket.send(event.model_dump_json())
                await self._checkpoint(event)

                return
            except ConnectionClosed:
                if i == self._reconnection_attempts:
                    # this was our final chance, raise the most recent error
                    raise

                if i > 2:
                    # let the first two attempts happen quickly in case this is just
                    # a standard load balancer timeout, but after that, just take a
                    # beat to let things come back around.
                    await asyncio.sleep(1)

__init__(api_url=None, reconnection_attempts=10, checkpoint_every=700)

Parameters:

Name Type Description Default
api_url Optional[str]

The base URL for a Prefect server

None
reconnection_attempts int

When the client is disconnected, how many times the client should attempt to reconnect

10
checkpoint_every int

How often the client should sync with the server to confirm receipt of all previously sent events

700
Source code in src/prefect/events/clients.py
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
def __init__(
    self,
    api_url: Optional[str] = None,
    reconnection_attempts: int = 10,
    checkpoint_every: int = 700,
):
    """
    Args:
        api_url: The base URL for a Prefect server
        reconnection_attempts: When the client is disconnected, how many times
            the client should attempt to reconnect
        checkpoint_every: How often the client should sync with the server to
            confirm receipt of all previously sent events
    """
    api_url = api_url or PREFECT_API_URL.value()
    if not api_url:
        raise ValueError(
            "api_url must be provided or set in the Prefect configuration"
        )

    self._events_socket_url = events_in_socket_from_api_url(api_url)
    self._connect = connect(self._events_socket_url)
    self._websocket = None
    self._reconnection_attempts = reconnection_attempts
    self._unconfirmed_events = []
    self._checkpoint_every = checkpoint_every