Skip to content

Rebroadcasting data

nebra.rebroadcast(target, args=(), kwargs=None, max_retries=7, initial_retry_delay=1.0, send_function=send, **send_kwargs)

Rebroadcast events from a producer function onto the AT Protocol. Includes threading for speed, robust error handling that automatically reboots clients that crash, a Queue system to deal with busy networks or rate limited PDSs, and more!

This function is the recommended way to rebroadcast events onto the AT Protocol from an existing source in a robust way.

Parameters:

Name Type Description Default
target Callable

A function that produces events and adds them to the data source. This function should take a DataSource as its first argument, followed by any additional arguments specified in args and kwargs.

required
args tuple

Positional arguments to pass to the producer function. Defaults to ().

()
kwargs dict

Keyword arguments to pass to the producer function. Defaults to None.

None
max_retries int

Maximum number of retry attempts for failed sends. Defaults to 7.

7
initial_retry_delay float

Initial delay in seconds for retry attempts (exponential backoff). Defaults to 1.0.

1.0
send_function Callable

Function to use for sending events. Defaults to nebra.client.send.

send
**send_kwargs dict

Additional keyword arguments to pass to the send function.

{}
Source code in nebra/broadcast.py
def rebroadcast(
    target: t.Callable,
    args: tuple = (),
    kwargs: dict | None = None,
    max_retries: int = 7,
    initial_retry_delay: float = 1.0,
    send_function=send,
    **send_kwargs,
):
    """Rebroadcast events from a producer function onto the AT Protocol.
    Includes threading for speed, robust error handling that automatically reboots
    clients that crash, a Queue system to deal with busy networks or rate limited PDSs,
    and more!

    This function is the recommended way to rebroadcast events onto the AT Protocol from
    an existing source in a robust way.

    Parameters
    ----------
    target : Callable
        A function that produces events and adds them to the data source.
        This function should take a DataSource as its first argument, followed by
        any additional arguments specified in args and kwargs.
    args : tuple, optional
        Positional arguments to pass to the producer function. Defaults to ().
    kwargs : dict, optional
        Keyword arguments to pass to the producer function. Defaults to None.
    max_retries : int, optional
        Maximum number of retry attempts for failed sends. Defaults to 7.
    initial_retry_delay : float, optional
        Initial delay in seconds for retry attempts (exponential backoff). Defaults to 1.0.
    send_function : Callable, optional
        Function to use for sending events. Defaults to nebra.client.send.
    **send_kwargs : dict
        Additional keyword arguments to pass to the send function.
    """
    client = RebroadcastClient(
        producer_function=target,
        producer_args=args,
        producer_kwargs=kwargs,
        max_retries=max_retries,
        initial_retry_delay=initial_retry_delay,
        send_function=send_function,
        **send_kwargs,
    )
    client.start()

nebra.DataSource

Class for managing event sources with thread-safe queue operations.

This class provides a thread-safe queue for communication between event producers and consumers, along with methods for monitoring the producer's activity.

Attributes:

Name Type Description
stop_event Event

An event to signal when the data source should stop.

Methods:

Name Description
add_event

Add an event to the queue.

get_event

Get an event from the queue, with optional timeout.

is_active

Check if the data source is active (not stopped).

mark_producer_running

Mark the producer as running by recording the current time. This method is thread-safe.

producer_last_signal

Get the number of seconds since mark_producer_running() was last called.

Examples:

The following example shows how to use a DataSource with a callable:

import time
import nebra

def post_producer(data_source: nebra.DataSource):
    counter = 1
    while data_source.is_active():
        # Mark that the producer is running
        data_source.mark_producer_running()

        new_post = {
            "$type": "app.bsky.feed.post",
            "text": f"This is test post {counter}.",
            "createdAt": nebra.get_atproto_utc_time()
        }
        data_source.add_event(new_post)
        counter += 1
        time.sleep(1)

    # Producer has been stopped
    print(f"Producer last signal was {data_source.producer_last_signal():.2f} seconds ago")

class PostConsumer:
    def __init__(self, data_source: nebra.DataSource):
        self.data_source = data_source

    def process_events(self):
        while self.data_source.is_active():
            try:
                # Get an event with a 1-second timeout
                event = self.data_source.get_event(timeout=1.0)
                print(f"Processing event: {event}")
            except queue.Empty:
                # No event available, continue checking if active
                continue
Source code in nebra/broadcast.py
class DataSource:
    """Class for managing event sources with thread-safe queue operations.

    This class provides a thread-safe queue for communication between event producers
    and consumers, along with methods for monitoring the producer's activity.

    Attributes
    ----------
    stop_event : threading.Event
        An event to signal when the data source should stop.

    Methods
    -------
    add_event(event: dict[str, Any]) -> bool
        Add an event to the queue.

    get_event(timeout: float | None = None) -> dict[str, Any]
        Get an event from the queue, with optional timeout.

    is_active() -> bool
        Check if the data source is active (not stopped).

    mark_producer_running() -> None
        Mark the producer as running by recording the current time.
        This method is thread-safe.

    producer_last_signal() -> float
        Get the number of seconds since mark_producer_running() was last called.

    Examples
    --------
    The following example shows how to use a DataSource with a callable:

    ```python
    import time
    import nebra

    def post_producer(data_source: nebra.DataSource):
        counter = 1
        while data_source.is_active():
            # Mark that the producer is running
            data_source.mark_producer_running()

            new_post = {
                "$type": "app.bsky.feed.post",
                "text": f"This is test post {counter}.",
                "createdAt": nebra.get_atproto_utc_time()
            }
            data_source.add_event(new_post)
            counter += 1
            time.sleep(1)

        # Producer has been stopped
        print(f"Producer last signal was {data_source.producer_last_signal():.2f} seconds ago")

    class PostConsumer:
        def __init__(self, data_source: nebra.DataSource):
            self.data_source = data_source

        def process_events(self):
            while self.data_source.is_active():
                try:
                    # Get an event with a 1-second timeout
                    event = self.data_source.get_event(timeout=1.0)
                    print(f"Processing event: {event}")
                except queue.Empty:
                    # No event available, continue checking if active
                    continue
    ```
    """

    def __init__(self, max_queue_size: int = 1000):
        """Initialize the DataSource with an event queue.

        Parameters
        ----------
        max_queue_size : int, optional
            Maximum size of the event queue. Defaults to 1000.
        """
        self._event_queue = queue.Queue(maxsize=max_queue_size)
        self.stop_event = threading.Event()
        self._producer_last_active = time.time()
        self._producer_active_lock = threading.Lock()

    def add_event(self, event: dict[str, Any]) -> bool:
        """Add an event to the queue.

        Parameters
        ----------
        event : dict[str, Any]
            The event to add to the queue.

        Returns
        -------
        bool
            True if the event was added, False if the queue was full.
        """
        try:
            self._event_queue.put_nowait(event)
            return True
        except queue.Full:
            print("Event queue full, dropping oldest event")
            try:
                # Remove oldest event and try again
                self._event_queue.get_nowait()
                self._event_queue.put_nowait(event)
                return True
            except queue.Empty:
                # Queue was empty after all, just put the event
                self._event_queue.put_nowait(event)
                return True

    def get_event(self, timeout: float | None = None) -> dict[str, Any]:
        """Get an event from the queue.

        Parameters
        ----------
        timeout : float | None, optional
            Maximum time to wait for an event, in seconds. If None, waits indefinitely.

        Returns
        -------
        dict[str, Any]
            The event from the queue.

        Raises
        ------
        queue.Empty
            If no event is available within the specified timeout.
        """
        return self._event_queue.get(timeout=timeout)

    def stop(self) -> None:
        """Signal the data source to stop.

        This method sets the stop_event, which should be checked periodically
        in the producer function to allow for clean shutdown.
        """
        self.stop_event.set()

    def is_active(self) -> bool:
        """Check if the data source is active (not stopped).

        Returns
        -------
        bool
            True if the data source is active (stop_event is not set), False otherwise.
        """
        return not self.stop_event.is_set()

    def mark_producer_running(self) -> None:
        """Mark the producer as running by recording the current time.

        This method is thread-safe and can be called from any thread.
        The time since this was last called can be accessed with producer_last_signal().
        """
        with self._producer_active_lock:
            self._producer_last_active = time.time()

    def producer_last_signal(self) -> float:
        """Get the number of seconds since mark_producer_running() was last called.

        Returns
        -------
        float
            The number of seconds since mark_producer_running() was last called.
            If mark_producer_running() has never been called, returns the time since
            the DataSource was initialized.
        """
        with self._producer_active_lock:
            return time.time() - self._producer_last_active

__init__(max_queue_size=1000)

Initialize the DataSource with an event queue.

Parameters:

Name Type Description Default
max_queue_size int

Maximum size of the event queue. Defaults to 1000.

1000
Source code in nebra/broadcast.py
def __init__(self, max_queue_size: int = 1000):
    """Initialize the DataSource with an event queue.

    Parameters
    ----------
    max_queue_size : int, optional
        Maximum size of the event queue. Defaults to 1000.
    """
    self._event_queue = queue.Queue(maxsize=max_queue_size)
    self.stop_event = threading.Event()
    self._producer_last_active = time.time()
    self._producer_active_lock = threading.Lock()

add_event(event)

Add an event to the queue.

Parameters:

Name Type Description Default
event dict[str, Any]

The event to add to the queue.

required

Returns:

Type Description
bool

True if the event was added, False if the queue was full.

Source code in nebra/broadcast.py
def add_event(self, event: dict[str, Any]) -> bool:
    """Add an event to the queue.

    Parameters
    ----------
    event : dict[str, Any]
        The event to add to the queue.

    Returns
    -------
    bool
        True if the event was added, False if the queue was full.
    """
    try:
        self._event_queue.put_nowait(event)
        return True
    except queue.Full:
        print("Event queue full, dropping oldest event")
        try:
            # Remove oldest event and try again
            self._event_queue.get_nowait()
            self._event_queue.put_nowait(event)
            return True
        except queue.Empty:
            # Queue was empty after all, just put the event
            self._event_queue.put_nowait(event)
            return True

get_event(timeout=None)

Get an event from the queue.

Parameters:

Name Type Description Default
timeout float | None

Maximum time to wait for an event, in seconds. If None, waits indefinitely.

None

Returns:

Type Description
dict[str, Any]

The event from the queue.

Raises:

Type Description
Empty

If no event is available within the specified timeout.

Source code in nebra/broadcast.py
def get_event(self, timeout: float | None = None) -> dict[str, Any]:
    """Get an event from the queue.

    Parameters
    ----------
    timeout : float | None, optional
        Maximum time to wait for an event, in seconds. If None, waits indefinitely.

    Returns
    -------
    dict[str, Any]
        The event from the queue.

    Raises
    ------
    queue.Empty
        If no event is available within the specified timeout.
    """
    return self._event_queue.get(timeout=timeout)

is_active()

Check if the data source is active (not stopped).

Returns:

Type Description
bool

True if the data source is active (stop_event is not set), False otherwise.

Source code in nebra/broadcast.py
def is_active(self) -> bool:
    """Check if the data source is active (not stopped).

    Returns
    -------
    bool
        True if the data source is active (stop_event is not set), False otherwise.
    """
    return not self.stop_event.is_set()

mark_producer_running()

Mark the producer as running by recording the current time.

This method is thread-safe and can be called from any thread. The time since this was last called can be accessed with producer_last_signal().

Source code in nebra/broadcast.py
def mark_producer_running(self) -> None:
    """Mark the producer as running by recording the current time.

    This method is thread-safe and can be called from any thread.
    The time since this was last called can be accessed with producer_last_signal().
    """
    with self._producer_active_lock:
        self._producer_last_active = time.time()

producer_last_signal()

Get the number of seconds since mark_producer_running() was last called.

Returns:

Type Description
float

The number of seconds since mark_producer_running() was last called. If mark_producer_running() has never been called, returns the time since the DataSource was initialized.

Source code in nebra/broadcast.py
def producer_last_signal(self) -> float:
    """Get the number of seconds since mark_producer_running() was last called.

    Returns
    -------
    float
        The number of seconds since mark_producer_running() was last called.
        If mark_producer_running() has never been called, returns the time since
        the DataSource was initialized.
    """
    with self._producer_active_lock:
        return time.time() - self._producer_last_active

stop()

Signal the data source to stop.

This method sets the stop_event, which should be checked periodically in the producer function to allow for clean shutdown.

Source code in nebra/broadcast.py
def stop(self) -> None:
    """Signal the data source to stop.

    This method sets the stop_event, which should be checked periodically
    in the producer function to allow for clean shutdown.
    """
    self.stop_event.set()