From 5df4e9a27636ea641419cf4dd8debd6d347a2925 Mon Sep 17 00:00:00 2001 From: Sreekanth Date: Thu, 19 Nov 2026 16:03:51 +0530 Subject: [PATCH] pynumaflow-lite: Pythonic APIs for Sourcer Signed-off-by: Sreekanth --- .../manifests/source/.dockerignore | 1 + .../manifests/source/Dockerfile | 73 +-- .../manifests/source/pyproject.toml | 8 +- .../manifests/source/simple_source.py | 143 ++--- .../pynumaflow-lite/manifests/source/uv.lock | 8 + .../pynumaflow_lite/__init__.py | 2 + .../pynumaflow_lite/_source_dtypes.py | 126 ++--- .../pynumaflow_lite/_source_server.py | 25 + .../pynumaflow_lite/sourcer.pyi | 202 +++---- packages/pynumaflow-lite/src/source/mod.rs | 519 +++++++----------- packages/pynumaflow-lite/src/source/server.rs | 362 ++++++------ .../tests/examples/source_simple.py | 158 ++---- .../pynumaflow-lite/tests/test_source_unit.py | 214 ++++++++ 13 files changed, 895 insertions(+), 946 deletions(-) create mode 100644 packages/pynumaflow-lite/manifests/source/.dockerignore create mode 100644 packages/pynumaflow-lite/manifests/source/uv.lock create mode 100644 packages/pynumaflow-lite/pynumaflow_lite/_source_server.py create mode 100644 packages/pynumaflow-lite/tests/test_source_unit.py diff --git a/packages/pynumaflow-lite/manifests/source/.dockerignore b/packages/pynumaflow-lite/manifests/source/.dockerignore new file mode 100644 index 00000000..21d0b898 --- /dev/null +++ b/packages/pynumaflow-lite/manifests/source/.dockerignore @@ -0,0 +1 @@ +.venv/ diff --git a/packages/pynumaflow-lite/manifests/source/Dockerfile b/packages/pynumaflow-lite/manifests/source/Dockerfile index 5bcbb6d1..302a2990 100644 --- a/packages/pynumaflow-lite/manifests/source/Dockerfile +++ b/packages/pynumaflow-lite/manifests/source/Dockerfile @@ -1,38 +1,43 @@ FROM python:3.11-slim-trixie AS builder -ENV PYTHONFAULTHANDLER=1 \ - PYTHONUNBUFFERED=1 \ - PYTHONHASHSEED=random \ - PIP_NO_CACHE_DIR=on \ - PIP_DISABLE_PIP_VERSION_CHECK=on \ - PIP_DEFAULT_TIMEOUT=100 \ - POETRY_HOME="/opt/poetry" \ - POETRY_VIRTUALENVS_IN_PROJECT=true \ - POETRY_NO_INTERACTION=1 \ - PYSETUP_PATH="/opt/pysetup" - - ENV PATH="$POETRY_HOME/bin:$PATH" - -RUN apt-get update \ - && apt-get install --no-install-recommends -y \ - curl \ - wget \ - # deps for building python deps - build-essential \ - && apt-get install -y git \ - && apt-get clean && rm -rf /var/lib/apt/lists/* \ - && curl -sSL https://install.python-poetry.org | python3 - - -FROM builder AS udf - -WORKDIR $PYSETUP_PATH -COPY ./ ./ - -RUN pip install $PYSETUP_PATH/pynumaflow_lite-0.1.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl - -RUN poetry lock -RUN poetry install --no-cache --no-root && \ - rm -rf ~/.cache/pypoetry/ +COPY --from=ghcr.io/astral-sh/uv:0.12.13 /uv /uvx /bin/ -CMD ["python", "simple_source.py"] +ENV UV_COMPILE_BYTECODE=1 \ + UV_LINK_MODE=copy \ + UV_PYTHON_DOWNLOADS=never + +WORKDIR /app + +RUN --mount=type=cache,target=/root/.cache/uv \ + --mount=type=bind,source=uv.lock,target=uv.lock \ + --mount=type=bind,source=pyproject.toml,target=pyproject.toml \ + uv sync --locked --no-install-project --no-dev + +COPY . . + +RUN --mount=type=cache,target=/root/.cache/uv \ + uv sync --locked --no-dev + +# Install the local pynumaflow-lite wheel that matches the build platform. +RUN uv pip install --no-index --find-links . pynumaflow-lite + +FROM python:3.11-slim-trixie +# Setup a non-root user +RUN groupadd --system --gid 999 nonroot \ + && useradd --system --gid 999 --uid 999 --create-home nonroot + +COPY --from=builder --chown=nonroot:nonroot /app /app + +ENV PATH="/app/.venv/bin:$PATH" + +# Keeps Python from buffering stdout and stderr to avoid situations where +# the application crashes without emitting any logs due to buffering. +ENV PYTHONUNBUFFERED=1 + +# Use the non-root user to run our application +USER nonroot + +WORKDIR /app + +CMD ["python", "simple_source.py"] diff --git a/packages/pynumaflow-lite/manifests/source/pyproject.toml b/packages/pynumaflow-lite/manifests/source/pyproject.toml index e2139497..acffef17 100644 --- a/packages/pynumaflow-lite/manifests/source/pyproject.toml +++ b/packages/pynumaflow-lite/manifests/source/pyproject.toml @@ -6,12 +6,6 @@ authors = [ { name = "Vigith Maurice", email = "vigith@gmail.com" } ] readme = "README.md" -requires-python = ">=3.11" +requires-python = "==3.11.*" dependencies = [ ] - - -[build-system] -requires = ["poetry-core>=2.0.0,<3.0.0"] -build-backend = "poetry.core.masonry.api" - diff --git a/packages/pynumaflow-lite/manifests/source/simple_source.py b/packages/pynumaflow-lite/manifests/source/simple_source.py index 9104bae6..66ad69ff 100644 --- a/packages/pynumaflow-lite/manifests/source/simple_source.py +++ b/packages/pynumaflow-lite/manifests/source/simple_source.py @@ -1,115 +1,78 @@ import asyncio import logging -import signal +from collections import deque from collections.abc import AsyncIterator from datetime import UTC, datetime -from pynumaflow_lite import sourcer -from pynumaflow_lite._source_dtypes import Sourcer +from pynumaflow_lite.sourcer import Message, NackOffset, Offset, ReadRequest, SourceAsyncServer, Sourcer -# Configure logging logging.basicConfig(level=logging.INFO) -_LOGGER = logging.getLogger(__name__) +logger = logging.getLogger(__name__) class SimpleSource(Sourcer): """ - Simple source that generates messages with incrementing numbers. - This is a class-based user-defined source implementation. - """ + A source that generates messages with incrementing numbers. - def __init__(self): - self.counter = 0 - self.partition_idx = 0 - - async def read_handler(self, datum: sourcer.ReadRequest) -> AsyncIterator[sourcer.Message]: - """ - The simple source generates messages with incrementing numbers. - """ - _LOGGER.info(f"Read request: num_records={datum.num_records}, timeout_ms={datum.timeout_ms}") - - # Generate the requested number of messages - for _ in range(datum.num_records): - # Create message payload - payload = f"message-{self.counter}".encode() - - # Create offset - offset = sourcer.Offset( - offset=str(self.counter).encode("utf-8"), - partition_id=self.partition_idx, - ) + It keeps the offsets that are read but not acked yet. A nacked offset is + read again before any new message. + """ - # Create message - message = sourcer.Message( - payload=payload, - offset=offset, - event_time=datetime.now(UTC), + def __init__(self, partition_id: int = 0) -> None: + self.partition_id = partition_id + self.next_id = 0 + self.unacked: set[Offset] = set() + self.redeliver: deque[Offset] = deque() + + def _next_offset(self) -> Offset: + if self.redeliver: + return self.redeliver.popleft() + offset = Offset(str(self.next_id).encode(), self.partition_id) + self.next_id += 1 + return offset + + async def read(self, request: ReadRequest) -> AsyncIterator[Message]: + logger.info("Read request: %r", request) + for _ in range(request.num_records): + offset = self._next_offset() + self.unacked.add(offset) + yield Message( + f"message-{offset.value.decode()}".encode(), + offset, + datetime.now(UTC), keys=["key1"], headers={"source": "simple"}, + user_metadata={ + "source_info": { + "source_name": b"simple_source", + "message_id": offset.value, + "partition": str(offset.partition_id).encode(), + } + }, ) - _LOGGER.info(f"Generated message: {self.counter}") - self.counter += 1 - - yield message - - # Small delay to simulate real source - await asyncio.sleep(0.1) - - async def ack_handler(self, request: sourcer.AckRequest) -> None: - """ - The simple source acknowledges the offsets. - """ - _LOGGER.info(f"Acknowledging {len(request.offsets)} offsets") - for offset in request.offsets: - _LOGGER.debug(f"Acked offset: {offset.offset.decode('utf-8')}, partition: {offset.partition_id}") - - async def nack_handler(self, request: sourcer.NackRequest) -> None: - """ - The simple source negatively acknowledges the offsets. - """ - _LOGGER.info(f"Negatively acknowledging {len(request.nack_offsets)} offsets") - for nack_offset in request.nack_offsets: - offset = nack_offset.offset - _LOGGER.warning( - f"Nacked offset: {offset.offset.decode('utf-8')}, " - f"partition: {offset.partition_id}, options: {nack_offset.nack_options}" - ) - - async def pending_handler(self) -> sourcer.PendingResponse: - """ - The simple source always returns zero to indicate there is no pending record. - """ - return sourcer.PendingResponse(count=0) - - async def partitions_handler(self) -> sourcer.PartitionsResponse: - """ - The simple source always returns default partitions. - """ - return sourcer.PartitionsResponse(partitions=[self.partition_idx]) + async def ack(self, offsets: list[Offset]) -> None: + logger.info("Acknowledging %d offsets", len(offsets)) + self.unacked.difference_update(offsets) + async def nack(self, offsets: list[NackOffset]) -> None: + logger.info("Negatively acknowledging %d offsets", len(offsets)) + for nack_offset in offsets: + logger.warning("Nacked %r", nack_offset) + self.unacked.discard(nack_offset.offset) + self.redeliver.append(nack_offset.offset) -async def start(): - server = sourcer.SourceAsyncServer() + async def pending(self) -> int | None: + # Only the nacked messages wait to be read: new messages are made on demand. + return len(self.redeliver) - # Create an instance of the source handler - handler = SimpleSource() + async def active_partitions(self) -> list[int] | None: + return [self.partition_id] - # Register loop-level signal handlers to request graceful shutdown - loop = asyncio.get_running_loop() - try: - loop.add_signal_handler(signal.SIGINT, lambda: server.stop()) - loop.add_signal_handler(signal.SIGTERM, lambda: server.stop()) - except (NotImplementedError, RuntimeError): - pass - try: - await server.start(handler) - print("Shutting down gracefully...") - except asyncio.CancelledError: - server.stop() - return +async def main() -> None: + await SourceAsyncServer(SimpleSource()).serve() if __name__ == "__main__": - asyncio.run(start()) + asyncio.run(main()) diff --git a/packages/pynumaflow-lite/manifests/source/uv.lock b/packages/pynumaflow-lite/manifests/source/uv.lock new file mode 100644 index 00000000..ad3ceddf --- /dev/null +++ b/packages/pynumaflow-lite/manifests/source/uv.lock @@ -0,0 +1,8 @@ +version = 1 +revision = 3 +requires-python = "==3.11.*" + +[[package]] +name = "simple-source" +version = "0.1.0" +source = { virtual = "." } diff --git a/packages/pynumaflow-lite/pynumaflow_lite/__init__.py b/packages/pynumaflow-lite/pynumaflow_lite/__init__.py index 80e5ed1b..0b0a2b22 100644 --- a/packages/pynumaflow-lite/pynumaflow_lite/__init__.py +++ b/packages/pynumaflow-lite/pynumaflow_lite/__init__.py @@ -20,6 +20,7 @@ from ._sink_dtypes import Sinker from ._sink_server import SinkAsyncServer from ._source_dtypes import Sourcer +from ._source_server import SourceAsyncServer from ._sourcetransform_server import SourceTransformAsyncServer from ._sourcetransformer_dtypes import SourceTransformer from .pynumaflow_lite import * # noqa: F403 # Rust extension; exports resolved at runtime @@ -55,6 +56,7 @@ sinker.Sinker = Sinker sinker.SinkAsyncServer = SinkAsyncServer sourcer.Sourcer = Sourcer +sourcer.SourceAsyncServer = SourceAsyncServer sourcetransformer.SourceTransformer = SourceTransformer sourcetransformer.SourceTransformAsyncServer = SourceTransformAsyncServer sideinputer.SideInput = SideInput diff --git a/packages/pynumaflow-lite/pynumaflow_lite/_source_dtypes.py b/packages/pynumaflow-lite/pynumaflow_lite/_source_dtypes.py index b719ea12..8ec92103 100644 --- a/packages/pynumaflow-lite/pynumaflow_lite/_source_dtypes.py +++ b/packages/pynumaflow-lite/pynumaflow_lite/_source_dtypes.py @@ -1,126 +1,68 @@ from abc import ABCMeta, abstractmethod from collections.abc import AsyncIterator -from pynumaflow_lite.sourcer import ( - AckRequest, - Message, - NackRequest, - PartitionsResponse, - PendingResponse, - ReadRequest, -) +from pynumaflow_lite.sourcer import Message, NackOffset, Offset, ReadRequest class Sourcer(metaclass=ABCMeta): """ Provides an interface to write a User Defined Source. - A Sourcer must implement the following handlers: - - read_handler: Read messages from the source - - ack_handler: Acknowledge processed messages - - pending_handler: Return the number of pending messages - - partitions_handler: Return the partitions this source handles - - Optionally, you can implement: - - nack_handler: Negatively acknowledge messages (default: no-op) + Subclasses must implement `read`, `ack`, `nack`, and `pending`. The + partition methods have defaults. """ - def __call__(self, *args, **kwargs): - """ - This allows to execute the handler function directly if - class instance is sent as a callable. - """ - return self.read_handler(*args, **kwargs) - @abstractmethod - async def read_handler(self, request: ReadRequest) -> AsyncIterator[Message]: + async def read(self, request: ReadRequest) -> AsyncIterator[Message]: """ - Read messages from the source. - - Args: - request: ReadRequest containing num_records and timeout - - Yields: - Message: Messages to be sent to the next vertex + Yield at most `request.num_records` messages, and return within + `request.timeout`. Example: - async def read_handler(self, request: ReadRequest) -> AsyncIterator[Message]: - for i in range(request.num_records): - yield Message( - payload=f"message-{i}".encode(), - offset=Offset(str(i).encode(), partition_id=0), - event_time=datetime.now(), - keys=["key1"], - headers={"x-txn-id": str(uuid.uuid4())} - ) + async def read(self, request: ReadRequest) -> AsyncIterator[Message]: + for _ in range(request.num_records): + offset = Offset(str(self.next_id).encode()) + self.next_id += 1 + yield Message(b"payload", offset, datetime.now(UTC)) """ - pass + raise NotImplementedError + yield # makes this an async generator, so overrides that yield type-check @abstractmethod - async def ack_handler(self, request: AckRequest) -> None: + async def ack(self, offsets: list[Offset]) -> None: """ - Acknowledge that messages have been processed. - - Args: - request: AckRequest containing the list of offsets to acknowledge - - Example: - async def ack_handler(self, request: AckRequest) -> None: - for offset in request.offsets: - # Remove from pending set, mark as processed, etc. - self.pending_offsets.remove(offset.offset) + Acknowledge that the messages with these offsets have been processed. """ - pass @abstractmethod - async def pending_handler(self) -> PendingResponse: + async def nack(self, offsets: list[NackOffset]) -> None: """ - Return the number of pending messages yet to be processed. - - Returns: - PendingResponse: Response containing the count of pending messages. - Return count=-1 if the source doesn't support detecting backlog. + Negatively acknowledge messages, so that they are read again. - Example: - async def pending_handler(self) -> PendingResponse: - return PendingResponse(count=len(self.pending_offsets)) + Each entry pairs an offset with the nack options for it. """ - pass @abstractmethod - async def partitions_handler(self) -> PartitionsResponse: + async def pending(self) -> int | None: """ - Return the partitions associated with this source. - - This is used by the platform to determine the partitions to which - the watermark should be published. If your source doesn't have the - concept of partitions, return the replica ID. - - Returns: - PartitionsResponse: Response containing the list of partition IDs - - Example: - async def partitions_handler(self) -> PartitionsResponse: - return PartitionsResponse(partitions=[self.partition_id]) + Return the number of messages that are yet to be read, or None if the + source cannot tell. """ - pass - async def nack_handler(self, request: NackRequest) -> None: + async def active_partitions(self) -> list[int] | None: """ - Negatively acknowledge messages (optional). + Return the partitions that this source currently reads from. The platform + publishes watermarks to these partitions. - This is called when messages could not be processed and should be - retried or handled differently. Default implementation is a no-op. - - Args: - request: NackRequest containing the list of nack offsets, each - pairing an offset with its optional nack options. + The default, None, makes the platform use the replica index as the only + partition. + """ + return None - Example: - async def nack_handler(self, request: NackRequest) -> None: - for nack_offset in request.nack_offsets: - # Add back to pending, mark for retry, etc. - self.nacked_offsets.add(nack_offset.offset.offset) - _ = nack_offset.nack_options + async def total_partitions(self) -> int | None: + """ + Return the total number of partitions of the source, across all + replicas, or None if the source cannot tell. The platform uses it to + know when every partition has reported a watermark. """ - _ = request + return None diff --git a/packages/pynumaflow-lite/pynumaflow_lite/_source_server.py b/packages/pynumaflow-lite/pynumaflow_lite/_source_server.py new file mode 100644 index 00000000..43134dc6 --- /dev/null +++ b/packages/pynumaflow-lite/pynumaflow_lite/_source_server.py @@ -0,0 +1,25 @@ +from __future__ import annotations + +from ._async_server import _AsyncServer +from ._source_dtypes import Sourcer +from .pynumaflow_lite import sourcer as _sourcer + + +class SourceAsyncServer(_AsyncServer): + _name = "source" + + def __init__( + self, + handler: Sourcer, + *, + sock_file: str | None = None, + server_info_file: str | None = None, + install_signal_handlers: bool = True, + ) -> None: + if not isinstance(handler, Sourcer): + raise TypeError(f"source handler must be a Sourcer instance, got {type(handler).__name__}") + super().__init__( + _sourcer._SourceAsyncServer(sock_file, server_info_file), + handler, + install_signal_handlers=install_signal_handlers, + ) diff --git a/packages/pynumaflow-lite/pynumaflow_lite/sourcer.pyi b/packages/pynumaflow-lite/pynumaflow_lite/sourcer.pyi index 46757472..44d8f8b4 100644 --- a/packages/pynumaflow-lite/pynumaflow_lite/sourcer.pyi +++ b/packages/pynumaflow-lite/pynumaflow_lite/sourcer.pyi @@ -1,103 +1,10 @@ import datetime as _dt from collections.abc import Awaitable +from types import TracebackType +from typing import Self -# Re-export the Python ABC for user convenience and typing from ._source_dtypes import Sourcer as Sourcer -class UserMetadata: - """User-defined metadata groups per message (read-write for source).""" - - def __init__(self) -> None: ... - def groups(self) -> list[str]: - """Returns the groups of the user metadata.""" - ... - - def keys(self, group: str) -> list[str]: - """Returns the keys of the user metadata for the given group.""" - ... - - def value(self, group: str, key: str) -> bytes: - """Returns the value of the user metadata for the given group and key.""" - ... - - def create_group(self, group: str) -> None: - """Creates a new group in the user metadata.""" - ... - - def add_kv(self, group: str, key: str, value: bytes) -> None: - """Adds a key-value pair to the user metadata.""" - ... - - def remove_key(self, group: str, key: str) -> None: - """Removes a key from a group in the user metadata.""" - ... - - def remove_group(self, group: str) -> None: - """Removes a group from the user metadata.""" - ... - - def __repr__(self) -> str: ... - -class Message: - """A message to be sent from the source.""" - - payload: bytes - offset: Offset - event_time: _dt.datetime - keys: list[str] - headers: dict[str, str] - user_metadata: UserMetadata | None - - def __init__( - self, - payload: bytes, - offset: Offset, - event_time: _dt.datetime, - keys: list[str] | None = ..., - headers: dict[str, str] | None = ..., - user_metadata: UserMetadata | None = ..., - ) -> None: ... - def __repr__(self) -> str: ... - def __str__(self) -> str: ... - -class Offset: - """The offset of a message.""" - - offset: bytes - partition_id: int - - def __init__( - self, - offset: bytes, - partition_id: int = ..., - ) -> None: ... - def __repr__(self) -> str: ... - def __str__(self) -> str: ... - -class ReadRequest: - """A request to read messages from the source.""" - - num_records: int - timeout_ms: int - - def __init__( - self, - num_records: int, - timeout_ms: int = ..., - ) -> None: ... - def __repr__(self) -> str: ... - -class AckRequest: - """A request to acknowledge messages.""" - - offsets: list[Offset] - - def __init__( - self, - offsets: list[Offset], - ) -> None: ... - def __repr__(self) -> str: ... - class NackOptions: """Per-message redelivery options for a nack.""" @@ -114,75 +21,106 @@ class NackOptions: nack_map: dict[str, str] | None = ..., ) -> None: ... def __repr__(self) -> str: ... + def __eq__(self, other: object) -> bool: ... -class NackOffset: - """An offset to negatively acknowledge, paired with its optional nack options.""" +class Offset: + """The offset of a message. Offsets are immutable and hashable.""" - offset: Offset - nack_options: NackOptions | None + @property + def value(self) -> bytes: ... + @property + def partition_id(self) -> int: ... + def __init__(self, value: bytes, partition_id: int = ...) -> None: ... + def __repr__(self) -> str: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... +class Message: + """A message read from the source.""" + + @property + def value(self) -> bytes: ... + @property + def offset(self) -> Offset: ... + @property + def event_time(self) -> _dt.datetime: ... + @property + def keys(self) -> list[str]: ... + @property + def headers(self) -> dict[str, str]: ... + @property + def user_metadata(self) -> dict[str, dict[str, bytes]]: ... def __init__( self, + value: bytes, offset: Offset, - nack_options: NackOptions | None = ..., + event_time: _dt.datetime, + keys: list[str] | None = ..., + headers: dict[str, str] | None = ..., + user_metadata: dict[str, dict[str, bytes]] | None = ..., ) -> None: ... def __repr__(self) -> str: ... + def __eq__(self, other: object) -> bool: ... -class NackRequest: - """A request to negatively acknowledge messages.""" - - nack_offsets: list[NackOffset] +class ReadRequest: + """A request to read messages from the source.""" - def __init__( - self, - nack_offsets: list[NackOffset], - ) -> None: ... + @property + def num_records(self) -> int: ... + @property + def timeout(self) -> _dt.timedelta: ... + def __init__(self, num_records: int, timeout: _dt.timedelta = ...) -> None: ... def __repr__(self) -> str: ... + def __eq__(self, other: object) -> bool: ... -class PendingResponse: - """Response for pending messages count.""" - - count: int +class NackOffset: + """An offset to negatively acknowledge, with the nack options for it.""" - def __init__( - self, - count: int = ..., - ) -> None: ... + @property + def offset(self) -> Offset: ... + @property + def nack_options(self) -> NackOptions | None: ... + def __init__(self, offset: Offset, nack_options: NackOptions | None = ...) -> None: ... def __repr__(self) -> str: ... + def __eq__(self, other: object) -> bool: ... -class PartitionsResponse: - """Response for partitions.""" - - partitions: list[int] - +class _SourceAsyncServer: def __init__( self, - partitions: list[int], + sock_file: str | None = ..., + server_info_file: str | None = ..., ) -> None: ... - def __repr__(self) -> str: ... + def start(self, sourcer: Sourcer) -> Awaitable[None]: ... + def wait_ready(self) -> Awaitable[None]: ... + def stop(self) -> None: ... class SourceAsyncServer: - """Async Source Server that can be started from Python code.""" - def __init__( self, + handler: Sourcer, + *, sock_file: str | None = ..., - info_file: str | None = ..., + server_info_file: str | None = ..., + install_signal_handlers: bool = ..., ) -> None: ... - def start(self, py_func: Sourcer) -> Awaitable[None]: ... + async def serve(self) -> None: ... def stop(self) -> None: ... + async def wait_ready(self) -> None: ... + async def wait_for_termination(self) -> None: ... + async def __aenter__(self) -> Self: ... + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: ... __all__ = [ - "AckRequest", "Message", "NackOffset", "NackOptions", - "NackRequest", "Offset", - "PartitionsResponse", - "PendingResponse", "ReadRequest", "SourceAsyncServer", "Sourcer", - "UserMetadata", ] diff --git a/packages/pynumaflow-lite/src/source/mod.rs b/packages/pynumaflow-lite/src/source/mod.rs index c17b836e..d7701e7e 100644 --- a/packages/pynumaflow-lite/src/source/mod.rs +++ b/packages/pynumaflow-lite/src/source/mod.rs @@ -1,118 +1,92 @@ use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::Mutex; +use std::time::Duration; use chrono::{DateTime, Utc}; - -/// Source interface managed by Python. It means Python code will start the server -/// and can pass in the Python function. -pub mod server; - +use numaflow::proto::source::source_client::SourceClient; +use numaflow::source; use pyo3::prelude::*; -use std::sync::Mutex; +use tokio::net::UnixStream; +use tonic::transport::Uri; +use tower::service_fn; use crate::nack::NackOptions; +use crate::pyrs::{bytes_literal, py_repr}; -/// UserMetadata wraps user-defined metadata groups per message. -/// Source is the origin or the first vertex in the pipeline. -/// Here, for the first time, the user metadata can be set by the user. -#[pyclass(module = "pynumaflow_lite.sourcer", from_py_object)] -#[derive(Clone, Default, Debug)] -pub struct UserMetadata { - data: HashMap>>, +/// Source interface managed by Python. It means Python code will start the server +/// and can pass in the Python Sourcer. +pub mod server; + +/// The offset of a message. Offsets are immutable and hashable, so they can be +/// kept in sets and used as dict keys to track in-flight messages. +#[pyclass( + module = "pynumaflow_lite.sourcer", + name = "Offset", + frozen, + eq, + hash, + from_py_object +)] +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct PyOffset { + /// The offset value, as defined by the source. + #[pyo3(get)] + pub value: Vec, + /// The partition the offset belongs to. + #[pyo3(get)] + pub partition_id: i32, } #[pymethods] -impl UserMetadata { +impl PyOffset { #[new] - #[pyo3(signature = () -> "UserMetadata")] - fn new() -> Self { - Self::default() - } - - /// Returns the groups of the user metadata. - /// If there are no groups, it returns an empty list. - #[pyo3(signature = () -> "list[str]")] - fn groups(&self) -> Vec { - self.data.keys().cloned().collect() - } - - /// Returns the keys of the user metadata for the given group. - /// If there are no keys or the group is not present, it returns an empty list. - #[pyo3(signature = (group: "str") -> "list[str]")] - fn keys(&self, group: &str) -> Vec { - self.data - .get(group) - .map(|kv| kv.keys().cloned().collect()) - .unwrap_or_default() - } - - /// Returns the value of the user metadata for the given group and key. - /// If there is no value or the group or key is not present, it returns an empty bytes. - #[pyo3(signature = (group: "str", key: "str") -> "bytes")] - fn value(&self, group: &str, key: &str) -> Vec { - self.data - .get(group) - .and_then(|kv| kv.get(key)) - .cloned() - .unwrap_or_default() - } - - /// Creates a new group in the user metadata. - /// If the group already exists, this is a no-op. - #[pyo3(signature = (group: "str"))] - fn create_group(&mut self, group: String) { - self.data.entry(group).or_default(); - } - - /// Adds a key-value pair to the user metadata. - /// If the group is not present, it creates a new group. - #[pyo3(signature = (group: "str", key: "str", value: "bytes"))] - fn add_kv(&mut self, group: String, key: String, value: Vec) { - self.data.entry(group).or_default().insert(key, value); - } - - /// Removes a key from a group in the user metadata. - /// If the key or group is not present, it's a no-op. - #[pyo3(signature = (group: "str", key: "str"))] - fn remove_key(&mut self, group: &str, key: &str) { - if let Some(kv) = self.data.get_mut(group) { - kv.remove(key); + #[pyo3(signature = (value: "bytes", partition_id: "int"=0) -> "Offset")] + fn new(value: Vec, partition_id: i32) -> Self { + Self { + value, + partition_id, } } - /// Removes a group from the user metadata. - /// If the group is not present, it's a no-op. - #[pyo3(signature = (group: "str"))] - fn remove_group(&mut self, group: &str) { - self.data.remove(group); + fn __repr__(&self) -> String { + format!( + "Offset(value={}, partition_id={})", + bytes_literal(&self.value), + self.partition_id + ) } +} - fn __repr__(&self) -> String { - format!("UserMetadata(groups={:?})", self.groups()) +impl From for source::Offset { + fn from(value: PyOffset) -> Self { + Self { + offset: value.value, + partition_id: value.partition_id, + } } } -impl From for numaflow::source::UserMetadata { - fn from(value: UserMetadata) -> Self { - let mut user_metadata = numaflow::source::UserMetadata::new(); - for (group, kv_map) in value.data { - for (key, val) in kv_map { - user_metadata.add_kv(group.clone(), key, val); - } +impl From for PyOffset { + fn from(value: source::Offset) -> Self { + Self { + value: value.offset, + partition_id: value.partition_id, } - user_metadata } } -/// A message to be sent from the source. -#[pyclass(module = "pynumaflow_lite.sourcer", from_py_object)] -#[derive(Clone, Debug)] +/// A message read from the source. +#[pyclass(module = "pynumaflow_lite.sourcer", frozen, eq, from_py_object)] +#[derive(Clone, Debug, PartialEq)] pub struct Message { - /// The payload of the message. + /// The value passed to the next vertex. + #[pyo3(get)] + pub value: Vec, + /// The offset of the message. The same offset is later given to ack or nack. #[pyo3(get)] - pub payload: Vec, - /// The offset of the message (not directly exposed, use offset property). - pub(crate) offset: PyOffset, - /// The event time of the message. + pub offset: PyOffset, + /// The time at which the event happened. #[pyo3(get)] pub event_time: DateTime, /// Keys of the message. @@ -121,217 +95,136 @@ pub struct Message { /// Headers of the message. #[pyo3(get)] pub headers: HashMap, - /// User metadata for the message. - pub user_metadata: Option, + /// User metadata, as {group: {key: value}}. The source is the first vertex + /// of the pipeline, so it is the first place where user metadata is set. + #[pyo3(get)] + pub user_metadata: HashMap>>, } #[pymethods] impl Message { - /// Create a new [Message] with the given payload, offset, event_time, keys, headers, and user_metadata. #[new] - #[pyo3(signature = (payload: "bytes", offset: "Offset", event_time: "datetime", keys: "list[str] | None"=None, headers: "dict[str, str] | None"=None, user_metadata: "UserMetadata | None"=None) -> "Message" - )] + #[pyo3(signature = ( + value: "bytes", + offset: "Offset", + event_time: "datetime.datetime", + keys: "list[str] | None"=None, + headers: "dict[str, str] | None"=None, + user_metadata: "dict[str, dict[str, bytes]] | None"=None, + ) -> "Message")] fn new( - payload: Vec, + value: Vec, offset: PyOffset, event_time: DateTime, keys: Option>, headers: Option>, - user_metadata: Option, + user_metadata: Option>>>, ) -> Self { Self { - payload, + value, offset, event_time, keys: keys.unwrap_or_default(), headers: headers.unwrap_or_default(), - user_metadata, + user_metadata: user_metadata.unwrap_or_default(), } } - /// Get the offset of the message. - #[getter] - fn offset(&self) -> PyOffset { - self.offset.clone() - } - - fn __repr__(&self) -> String { - format!( - "Message(payload={:?}, offset={:?}, event_time={}, keys={:?}, headers={:?}, user_metadata={:?})", - self.payload, self.offset, self.event_time, self.keys, self.headers, self.user_metadata - ) - } - - fn __str__(&self) -> String { - format!( - "Message(payload={:?}, offset={:?}, event_time={}, keys={:?}, headers={:?}, user_metadata={:?})", - String::from_utf8_lossy(&self.payload), - self.offset, - self.event_time, - self.keys, - self.headers, - self.user_metadata - ) + fn __repr__(&self, py: Python<'_>) -> PyResult { + Ok(format!( + "Message(value={}, offset={}, event_time={}, keys={}, headers={}, user_metadata={})", + bytes_literal(&self.value), + self.offset.__repr__(), + py_repr(py, self.event_time)?, + py_repr(py, &self.keys)?, + py_repr(py, &self.headers)?, + py_repr(py, &self.user_metadata)?, + )) } } -impl From for numaflow::source::Message { +impl From for source::Message { fn from(value: Message) -> Self { + let user_metadata = (!value.user_metadata.is_empty()).then(|| { + let mut umd = source::UserMetadata::new(); + for (group, kv) in value.user_metadata { + umd.create_group(group.clone()); + for (key, val) in kv { + umd.add_kv(group.clone(), key, val); + } + } + umd + }); + Self { - value: value.payload, + value: value.value, offset: value.offset.into(), event_time: value.event_time, keys: value.keys, headers: value.headers, - user_metadata: value.user_metadata.map(|m| m.into()), - } - } -} - -/// The offset of a message. -#[pyclass(module = "pynumaflow_lite.sourcer", name = "Offset", from_py_object)] // this to avoid conflict with the Offset in the source module -#[derive(Clone, Debug)] -pub struct PyOffset { - /// Offset value in bytes. - #[pyo3(get)] - pub offset: Vec, - /// Partition ID of the message. - #[pyo3(get)] - pub partition_id: i32, -} - -#[pymethods] -impl PyOffset { - /// Create a new [Offset] with the given offset bytes and partition_id. - #[new] - #[pyo3(signature = (offset: "bytes", partition_id: "int"=0) -> "Offset")] - fn new(offset: Vec, partition_id: i32) -> Self { - Self { - offset, - partition_id, - } - } - - fn __repr__(&self) -> String { - format!( - "Offset(offset={:?}, partition_id={})", - self.offset, self.partition_id - ) - } - - fn __str__(&self) -> String { - format!( - "Offset(offset={:?}, partition_id={})", - String::from_utf8_lossy(&self.offset), - self.partition_id - ) - } -} - -impl From for numaflow::source::Offset { - fn from(value: PyOffset) -> Self { - Self { - offset: value.offset, - partition_id: value.partition_id, - } - } -} - -impl From for PyOffset { - fn from(value: numaflow::source::Offset) -> Self { - Self { - offset: value.offset, - partition_id: value.partition_id, + user_metadata, } } } /// A request to read messages from the source. -#[pyclass(module = "pynumaflow_lite.sourcer", from_py_object)] -#[derive(Clone, Debug)] +#[pyclass(module = "pynumaflow_lite.sourcer", frozen, eq, from_py_object)] +#[derive(Clone, Debug, PartialEq)] pub struct ReadRequest { - /// The number of messages to read. + /// The maximum number of messages to read. #[pyo3(get)] pub num_records: u64, - /// Request timeout in milliseconds. + /// How long the read may take. Return early, with fewer messages, when it runs out. #[pyo3(get)] - pub timeout_ms: u64, + pub timeout: Duration, } #[pymethods] impl ReadRequest { - /// Create a new [ReadRequest] with the given num_records and timeout_ms. #[new] - #[pyo3(signature = (num_records: "int", timeout_ms: "int"=1000) -> "ReadRequest")] - fn new(num_records: u64, timeout_ms: u64) -> Self { + #[pyo3(signature = ( + num_records: "int", + timeout: "datetime.timedelta"=Duration::from_secs(1), + ) -> "ReadRequest")] + fn new(num_records: u64, timeout: Duration) -> Self { Self { num_records, - timeout_ms, + timeout, } } - fn __repr__(&self) -> String { - format!( - "ReadRequest(num_records={}, timeout_ms={})", - self.num_records, self.timeout_ms - ) + fn __repr__(&self, py: Python<'_>) -> PyResult { + Ok(format!( + "ReadRequest(num_records={}, timeout={})", + self.num_records, + py_repr(py, self.timeout)?, + )) } } -impl From for ReadRequest { - fn from(value: numaflow::source::SourceReadRequest) -> Self { +impl From for ReadRequest { + fn from(value: source::SourceReadRequest) -> Self { Self { num_records: value.count as u64, - timeout_ms: value.timeout.as_millis() as u64, + timeout: value.timeout, } } } -/// A request to acknowledge messages. -#[pyclass(module = "pynumaflow_lite.sourcer", from_py_object)] -#[derive(Clone, Debug)] -pub struct AckRequest { - /// The offsets to acknowledge. - #[pyo3(get)] - pub offsets: Vec, -} - -#[pymethods] -impl AckRequest { - /// Create a new [AckRequest] with the given offsets. - #[new] - #[pyo3(signature = (offsets: "list[Offset]") -> "AckRequest")] - fn new(offsets: Vec) -> Self { - Self { offsets } - } - - fn __repr__(&self) -> String { - format!("AckRequest(offsets={:?})", self.offsets) - } -} - -/// An offset to negatively acknowledge, paired with its optional nack options. -/// -/// Nack is a per-message operation: each offset carries its own (optional) -/// nack options, giving a 1:1 mapping between an offset and its options. -#[pyclass( - module = "pynumaflow_lite.sourcer", - name = "NackOffset", - from_py_object -)] -#[derive(Clone, Debug)] +/// An offset to negatively acknowledge, with the nack options for it. +#[pyclass(module = "pynumaflow_lite.sourcer", frozen, eq, from_py_object)] +#[derive(Clone, Debug, PartialEq)] pub struct NackOffset { - /// The offset to be negatively acknowledged. + /// The offset to negatively acknowledge. #[pyo3(get)] pub offset: PyOffset, - /// The options to apply when nacking this offset. + /// How the platform asks for the message to be redelivered, if it says so. #[pyo3(get)] pub nack_options: Option, } #[pymethods] impl NackOffset { - /// Create a new [NackOffset] with the given offset and nack options. #[new] #[pyo3(signature = (offset: "Offset", nack_options: "NackOptions | None"=None) -> "NackOffset")] fn new(offset: PyOffset, nack_options: Option) -> Self { @@ -341,16 +234,17 @@ impl NackOffset { } } - fn __repr__(&self) -> String { - format!( - "NackOffset(offset={:?}, nack_options={:?})", - self.offset, self.nack_options - ) + fn __repr__(&self, py: Python<'_>) -> PyResult { + Ok(format!( + "NackOffset(offset={}, nack_options={})", + self.offset.__repr__(), + py_repr(py, self.nack_options.clone())?, + )) } } -impl From for NackOffset { - fn from(value: numaflow::source::NackOffset) -> Self { +impl From for NackOffset { + fn from(value: source::NackOffset) -> Self { Self { offset: value.offset.into(), nack_options: value.options.map(Into::into), @@ -358,114 +252,88 @@ impl From for NackOffset { } } -/// A request to negatively acknowledge messages. -/// -/// It carries a list of [NackOffset] entries, each pairing an offset with its -/// own (optional) nack options. -#[pyclass(module = "pynumaflow_lite.sourcer", from_py_object)] -#[derive(Clone, Debug)] -pub struct NackRequest { - /// The offsets (with per-offset options) to negatively acknowledge. - #[pyo3(get)] - pub nack_offsets: Vec, -} - -#[pymethods] -impl NackRequest { - /// Create a new [NackRequest] with the given nack offsets. - #[new] - #[pyo3(signature = (nack_offsets: "list[NackOffset]") -> "NackRequest")] - fn new(nack_offsets: Vec) -> Self { - Self { nack_offsets } - } - - fn __repr__(&self) -> String { - format!("NackRequest(nack_offsets={:?})", self.nack_offsets) - } -} - -/// Response for pending messages count. -#[pyclass(module = "pynumaflow_lite.sourcer", from_py_object)] -#[derive(Clone, Debug)] -pub struct PendingResponse { - /// The number of pending messages. -1 if the source doesn't support detecting backlog. - #[pyo3(get)] - pub count: i64, -} - -#[pymethods] -impl PendingResponse { - /// Create a new [PendingResponse] with the given count. - #[new] - #[pyo3(signature = (count: "int"=0) -> "PendingResponse")] - fn new(count: i64) -> Self { - Self { count } - } - - fn __repr__(&self) -> String { - format!("PendingResponse(count={})", self.count) - } -} +async fn source_client(sock_file: String) -> PyResult> { + let endpoint = tonic::transport::Endpoint::try_from("http://[::]:50051") + .map_err(|e| pyo3::PyErr::new::(e.to_string()))?; + + let channel = endpoint + .connect_with_connector(service_fn(move |_: Uri| { + let sock = PathBuf::from(sock_file.clone()); + async move { + Ok::<_, std::io::Error>(hyper_util::rt::TokioIo::new( + UnixStream::connect(sock).await?, + )) + } + })) + .await + .map_err(|e| pyo3::PyErr::new::(e.to_string()))?; -/// Response for partitions. -#[pyclass(module = "pynumaflow_lite.sourcer", from_py_object)] -#[derive(Clone, Debug)] -pub struct PartitionsResponse { - /// The list of partition IDs. - #[pyo3(get)] - pub partitions: Vec, + Ok(SourceClient::new(channel)) } -#[pymethods] -impl PartitionsResponse { - /// Create a new [PartitionsResponse] with the given partitions. - #[new] - #[pyo3(signature = (partitions: "list[int]") -> "PartitionsResponse")] - fn new(partitions: Vec) -> Self { - Self { partitions } - } +// Poll the IsReady probe until it succeeds. There is no deadline: Python sets +// one with asyncio.timeout(), and cancellation drops this future. +async fn wait_for_ready(sock_file: String) { + loop { + if let Ok(mut client) = source_client(sock_file.clone()).await + && let Ok(response) = client.is_ready(()).await + && response.into_inner().ready + { + return; + } - fn __repr__(&self) -> String { - format!("PartitionsResponse(partitions={:?})", self.partitions) + tokio::time::sleep(Duration::from_millis(100)).await; } } -/// Async Source Server that can be started from Python code which will run the Python UDF function. -#[pyclass(module = "pynumaflow_lite.sourcer")] +/// Async Source Server that can be started from Python code which will run the Python Sourcer. +#[pyclass(name = "_SourceAsyncServer", module = "pynumaflow_lite.sourcer")] pub struct SourceAsyncServer { sock_file: String, - info_file: String, + server_info_file: String, shutdown_tx: Mutex>>, } #[pymethods] impl SourceAsyncServer { #[new] - #[pyo3(signature = (sock_file: "str | None"=numaflow::source::SOCK_ADDR.to_string(), info_file: "str | None"=numaflow::source::SERVER_INFO_FILE.to_string()) -> "SourceAsyncServer" - )] - fn new(sock_file: String, info_file: String) -> Self { + #[pyo3(signature = ( + sock_file: "str | None"=None, + server_info_file: "str | None"=None, + ) -> "_SourceAsyncServer")] + fn new(sock_file: Option, server_info_file: Option) -> Self { Self { - sock_file, - info_file, + sock_file: sock_file.unwrap_or_else(|| source::SOCK_ADDR.to_string()), + server_info_file: server_info_file + .unwrap_or_else(|| source::SERVER_INFO_FILE.to_string()), shutdown_tx: Mutex::new(None), } } - /// Start the server with the given Python source handler. - #[pyo3(signature = (py_func: "callable") -> "None")] - pub fn start<'a>(&self, py: Python<'a>, py_func: Py) -> PyResult> { + /// Start the server with the given Python Sourcer. + #[pyo3(signature = (sourcer: "Sourcer") -> "None")] + pub fn start<'a>(&self, py: Python<'a>, sourcer: Py) -> PyResult> { let sock_file = self.sock_file.clone(); - let info_file = self.info_file.clone(); + let server_info_file = self.server_info_file.clone(); let (tx, rx) = tokio::sync::oneshot::channel::<()>(); { let mut guard = self.shutdown_tx.lock().unwrap(); *guard = Some(tx); } + pyo3_async_runtimes::tokio::future_into_py( + py, + crate::source::server::start(sourcer, sock_file, server_info_file, rx), + ) + } + + /// Wait until the Numaflow IsReady probe succeeds over the source UDS. + #[pyo3(signature = () -> "None")] + pub fn wait_ready<'a>(&self, py: Python<'a>) -> PyResult> { + let sock_file = self.sock_file.clone(); + pyo3_async_runtimes::tokio::future_into_py(py, async move { - crate::source::server::start(py_func, sock_file, info_file, rx) - .await - .expect("server failed to start"); + wait_for_ready(sock_file).await; Ok(()) }) } @@ -482,16 +350,11 @@ impl SourceAsyncServer { /// Helper to populate a PyModule with source types/functions. pub(crate) fn populate_py_module(m: &Bound) -> PyResult<()> { - m.add_class::()?; m.add_class::()?; m.add_class::()?; m.add_class::()?; - m.add_class::()?; m.add_class::()?; m.add_class::()?; - m.add_class::()?; - m.add_class::()?; - m.add_class::()?; m.add_class::()?; Ok(()) diff --git a/packages/pynumaflow-lite/src/source/server.rs b/packages/pynumaflow-lite/src/source/server.rs index c7a5b014..8dafdf38 100644 --- a/packages/pynumaflow-lite/src/source/server.rs +++ b/packages/pynumaflow-lite/src/source/server.rs @@ -1,198 +1,235 @@ -use numaflow::shared::ServerExtras; +use std::sync::{Arc, Mutex}; +use numaflow::shared::ServerExtras; +use numaflow::source; +use pyo3::call::PyCallArgs; +use pyo3::exceptions::{PyTypeError, PyValueError}; use pyo3::prelude::*; -use std::sync::Arc; +use tokio::sync::Notify; use tokio::sync::mpsc::Sender; +use tokio_stream::StreamExt; + +use crate::pyiterables::PyAsyncIterStream; +use crate::pyrs::{combine_errors, format_error}; +use crate::source::{Message, NackOffset, PyOffset, ReadRequest}; pub(crate) struct PySourceRunner { pub(crate) event_loop: Arc>, - pub(crate) py_handler: Arc>, + pub(crate) sourcer: Arc>, + pub(crate) errors: Arc>>, + /// Notified when a handler fails, so that start() shuts the server down. + pub(crate) failed: Arc, } -#[tonic::async_trait] -impl numaflow::source::Sourcer for PySourceRunner { - /// Reads the messages from the source and sends them to the transmitter. - async fn read( - &self, - request: numaflow::source::SourceReadRequest, - transmitter: Sender, - ) { - // Convert the Rust request to Python ReadRequest - let read_request: crate::source::ReadRequest = request.into(); - - // Call the Python read_handler which returns an AsyncIterator[Message] - let py_async_iter = Python::attach(|py| { - let py_handler = self.py_handler.clone(); - - // Call read_handler(request) -> AsyncIterator[Message] - py_handler - .call_method1(py, "read_handler", (read_request,)) - .expect("failed to call read_handler") - }); - - // Create a stream from the Python AsyncIterator - let mut stream = crate::pyiterables::PyAsyncIterStream::::new( - py_async_iter, - self.event_loop.clone(), - ) - .expect("failed to create stream from Python AsyncIterator"); - - // Stream messages from Python to the transmitter - use tokio_stream::StreamExt; - while let Some(result) = stream.next().await { - match result { - Ok(py_message) => { - let rust_message: numaflow::source::Message = py_message.into(); - if transmitter.send(rust_message).await.is_err() { - // Receiver dropped, stop reading - break; - } - } - Err(e) => { - eprintln!("Error reading from Python source: {:?}", e); - break; - } - } - } - } - - /// Acknowledges the message that has been processed by the user-defined source. - async fn ack(&self, offsets: Vec) { - // Convert Rust offsets to Python Offset objects - let py_offsets: Vec = - offsets.into_iter().map(|o| o.into()).collect(); +fn type_name(obj: &Bound<'_, PyAny>) -> String { + obj.get_type() + .name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_else(|_| "".to_string()) +} - // Create AckRequest - let ack_request = crate::source::AckRequest::new(py_offsets); +impl PySourceRunner { + fn fail(&self, error: PyErr) -> ! { + // numaflow can call the handlers concurrently, so keep every error. + // start() raises them together, which lets Python format every traceback + // instead of Rust printing them by hand. + let message = Python::attach(|py| format_error(py, &error)); + self.errors.lock().unwrap().push(error); + + // numaflow shuts the server down after a panic in read or ack, but not + // after one in nack, pending, or active_partitions. Ask for the shutdown here so + // that every handler failure stops the server in the same way. + self.failed.notify_one(); + + // The panic makes the client get a gRPC error. Returning a value instead + // would look like a valid answer from the handler. + panic!("{message}"); + } - // Call the Python ack_handler - let fut = Python::attach(|py| { - let py_handler = self.py_handler.clone(); + /// Call `sourcer.(*args)`, await the coroutine, and return its result. + async fn call(&self, method: &str, args: A) -> Py + where + A: for<'py> PyCallArgs<'py> + Send, + { + let fut = match Python::attach(|py| -> PyResult<_> { let locals = pyo3_async_runtimes::TaskLocals::new(self.event_loop.bind(py).clone()); - - let coro = py_handler - .call_method1(py, "ack_handler", (ack_request,)) - .expect("failed to call ack_handler") - .into_bound(py); - - pyo3_async_runtimes::into_future_with_locals(&locals, coro) - .expect("failed to convert ack_handler to future") - }); - - // Await the Python coroutine - let _ = fut.await; + let coro = self.sourcer.bind(py).call_method1(method, args)?; + let is_awaitable: bool = py + .import("inspect")? + .call_method1("isawaitable", (&coro,))? + .extract()?; + let not_async = || { + PyErr::new::(format!( + "source {method} must be an async function (coroutine)" + )) + }; + if !is_awaitable { + return Err(not_async()); + } + pyo3_async_runtimes::into_future_with_locals(&locals, coro).map_err(|_| not_async()) + }) { + Ok(fut) => fut, + Err(error) => self.fail(error), + }; + + match fut.await { + Ok(result) => result, + Err(error) => self.fail(error), + } } - /// Negatively acknowledges the message that has been processed by the user-defined source. - async fn nack(&self, offsets: Vec) { - // Convert Rust nack offsets to Python NackOffset objects - let py_nack_offsets: Vec = - offsets.into_iter().map(|o| o.into()).collect(); - - // Create NackRequest - let nack_request = crate::source::NackRequest::new(py_nack_offsets); - - // Call the Python nack_handler - let fut = Python::attach(|py| { - let py_handler = self.py_handler.clone(); - let locals = pyo3_async_runtimes::TaskLocals::new(self.event_loop.bind(py).clone()); + /// Like `call`, then convert the result to `T`, or fail with a TypeError that + /// names `expected`. + async fn call_and_extract(&self, method: &str, args: A, expected: &str) -> T + where + T: for<'a, 'py> FromPyObject<'a, 'py>, + A: for<'py> PyCallArgs<'py> + Send, + { + let result = self.call(method, args).await; + match Python::attach(|py| { + let result = result.bind(py); + result.extract::().map_err(|_| { + PyErr::new::(format!( + "source {method} must return {expected}, got {}", + type_name(result) + )) + }) + }) { + Ok(value) => value, + Err(error) => self.fail(error), + } + } +} - let coro = py_handler - .call_method1(py, "nack_handler", (nack_request,)) - .expect("failed to call nack_handler") - .into_bound(py); +#[tonic::async_trait] +impl source::Sourcer for PySourceRunner { + async fn read(&self, request: source::SourceReadRequest, transmitter: Sender) { + let request: ReadRequest = request.into(); + + // sourcer.read(request) -> AsyncIterator[Message] + let agen = match Python::attach(|py| self.sourcer.call_method1(py, "read", (request,))) { + Ok(agen) => agen, + Err(error) => self.fail(error), + }; + + // Items stay as Py so that a wrong item type gives a clear error below. + let agen_ref = Python::attach(|py| agen.clone_ref(py)); + let mut stream = + match PyAsyncIterStream::>::new(agen_ref, self.event_loop.clone()) { + Ok(stream) => stream, + Err(_) => { + // A coroutine (async def without yield) must be closed, or Python + // warns that it was never awaited. + Python::attach(|py| { + let _ = agen.call_method0(py, "close"); + }); + self.fail(PyErr::new::( + "source read must be an async generator (yield Message)", + )) + } + }; + + while let Some(item) = stream.next().await { + let obj = match item { + Ok(obj) => obj, + Err(error) => self.fail(error), + }; + + let message: Message = match Python::attach(|py| { + let obj = obj.bind(py); + obj.extract().map_err(|_| { + PyErr::new::(format!( + "source read must yield Message, got {}", + type_name(obj) + )) + }) + }) { + Ok(message) => message, + Err(error) => self.fail(error), + }; + + // The receiver is gone, so the client does not want more messages. + if transmitter.send(message.into()).await.is_err() { + break; + } + } + } - pyo3_async_runtimes::into_future_with_locals(&locals, coro) - .expect("failed to convert nack_handler to future") - }); + async fn ack(&self, offsets: Vec) { + let offsets: Vec = offsets.into_iter().map(Into::into).collect(); + self.call("ack", (offsets,)).await; + } - // Await the Python coroutine - let _ = fut.await; + async fn nack(&self, offsets: Vec) { + let offsets: Vec = offsets.into_iter().map(Into::into).collect(); + self.call("nack", (offsets,)).await; } - /// Returns the number of messages that are yet to be processed by the user-defined source. - /// The None value can be returned if source doesn't support detecting the backlog. async fn pending(&self) -> Option { - // Call the Python pending_handler - let fut = Python::attach(|py| { - let py_handler = self.py_handler.clone(); - let locals = pyo3_async_runtimes::TaskLocals::new(self.event_loop.bind(py).clone()); - - let coro = py_handler - .call_method0(py, "pending_handler") - .expect("failed to call pending_handler") - .into_bound(py); - - pyo3_async_runtimes::into_future_with_locals(&locals, coro) - .expect("failed to convert pending_handler to future") - }); - - // Await the Python coroutine and extract the result - let result = fut.await.expect("pending_handler failed"); - - let pending_response = Python::attach(|py| { - result - .extract::(py) - .expect("failed to extract PendingResponse") - }); - - // Convert count to Option - // -1 means the source doesn't support detecting backlog - if pending_response.count < 0 { - None - } else { - Some(pending_response.count as usize) + match self + .call_and_extract::, _>("pending", (), "int or None") + .await + { + None => None, + Some(count) => match usize::try_from(count) { + Ok(count) => Some(count), + Err(_) => self.fail(PyErr::new::(format!( + "source pending must not be negative, got {count}; return None when the count is unknown" + ))), + }, } } - /// Returns the partitions associated with the source. This will be used by the platform to determine - /// the partitions to which the watermark should be published. Some sources might not have the concept of partitions. - /// Kafka is an example of source where a reader can read from multiple partitions. - /// If None is returned, Numaflow replica-id will be returned as the partition. - async fn partitions(&self) -> Option> { - // Call the Python partitions_handler - let fut = Python::attach(|py| { - let py_handler = self.py_handler.clone(); - let locals = pyo3_async_runtimes::TaskLocals::new(self.event_loop.bind(py).clone()); - - let coro = py_handler - .call_method0(py, "partitions_handler") - .expect("failed to call partitions_handler") - .into_bound(py); - - pyo3_async_runtimes::into_future_with_locals(&locals, coro) - .expect("failed to convert partitions_handler to future") - }); - - // Await the Python coroutine and extract the result - let result = fut.await.expect("partitions_handler failed"); - - let partitions_response = Python::attach(|py| { - result - .extract::(py) - .expect("failed to extract PartitionsResponse") - }); + async fn active_partitions(&self) -> Option> { + self.call_and_extract("active_partitions", (), "list[int] or None") + .await + } - Some(partitions_response.partitions) + async fn total_partitions(&self) -> Option { + self.call_and_extract("total_partitions", (), "int or None") + .await } } /// Start the source server by spinning up a dedicated Python asyncio loop and wiring shutdown. pub(super) async fn start( - py_handler: Py, + sourcer: Py, sock_file: String, info_file: String, shutdown_rx: tokio::sync::oneshot::Receiver<()>, ) -> Result<(), pyo3::PyErr> { let (tx, rx) = tokio::sync::oneshot::channel(); - let py_asyncio_loop_handle = tokio::task::spawn_blocking(move || crate::pyrs::run_asyncio(tx)); + let py_asyncio_loop_handle = tokio::task::spawn_blocking({ + println!( + "Starting Source UDF. socket={}, server_info={}", + sock_file, info_file + ); + move || crate::pyrs::run_asyncio(tx) + }); let event_loop = rx.await.unwrap(); - let (sig_handle, combined_rx) = crate::pyrs::setup_sig_handler(shutdown_rx); + let errors = Arc::new(Mutex::new(Vec::new())); + let failed = Arc::new(Notify::new()); + + // Shutdown has two sources: stop() from Python through shutdown_rx, and a + // handler failure through `failed`. + let (server_shutdown_tx, server_shutdown_rx) = tokio::sync::oneshot::channel::<()>(); + let shutdown_watcher = tokio::spawn({ + let failed = Arc::clone(&failed); + async move { + tokio::select! { + _ = shutdown_rx => {}, + _ = failed.notified() => {}, + } + let _ = server_shutdown_tx.send(()); + } + }); let py_source_runner = PySourceRunner { - py_handler: Arc::new(py_handler), + sourcer: Arc::new(sourcer), event_loop: event_loop.clone(), + errors: Arc::clone(&errors), + failed, }; let server = numaflow::source::Server::new(py_source_runner) @@ -200,10 +237,12 @@ pub(super) async fn start( .with_server_info_file(info_file); let result = server - .start_with_shutdown(combined_rx) + .start_with_shutdown(server_shutdown_rx) .await .map_err(|e| pyo3::PyErr::new::(e.to_string())); + shutdown_watcher.abort(); + // Ensure the event loop is stopped even if shutdown came from elsewhere. Python::attach(|py| { if let Ok(stop_cb) = event_loop.getattr(py, "stop") { @@ -216,10 +255,9 @@ pub(super) async fn start( // Wait for the blocking asyncio thread to finish. let _ = py_asyncio_loop_handle.await; - // if not finished, abort it - if !sig_handle.is_finished() { - println!("Aborting signal handler"); - sig_handle.abort(); + let errors = std::mem::take(&mut *errors.lock().unwrap()); + if !errors.is_empty() { + return Err(Python::attach(|py| combine_errors(py, errors))); } result diff --git a/packages/pynumaflow-lite/tests/examples/source_simple.py b/packages/pynumaflow-lite/tests/examples/source_simple.py index 118aa246..a3602dff 100644 --- a/packages/pynumaflow-lite/tests/examples/source_simple.py +++ b/packages/pynumaflow-lite/tests/examples/source_simple.py @@ -1,126 +1,82 @@ import asyncio import logging -import signal +from collections import deque from collections.abc import AsyncIterator from datetime import UTC, datetime -from pynumaflow_lite import sourcer -from pynumaflow_lite._source_dtypes import Sourcer +from pynumaflow_lite.sourcer import Message, NackOffset, Offset, ReadRequest, SourceAsyncServer, Sourcer -# Configure logging logging.basicConfig(level=logging.INFO) -_LOGGER = logging.getLogger(__name__) +logger = logging.getLogger(__name__) class SimpleSource(Sourcer): """ - Simple source that generates messages with incrementing numbers. - This is the class-based approach matching the user's example. - """ + A source that generates messages with incrementing numbers. - def __init__(self): - self.counter = 0 - self.partition_idx = 0 - - async def read_handler(self, datum: sourcer.ReadRequest) -> AsyncIterator[sourcer.Message]: - """ - The simple source generates messages with incrementing numbers. - Also demonstrates creating user metadata (source is origin, so only user metadata). - """ - _LOGGER.info(f"Read request: num_records={datum.num_records}, timeout_ms={datum.timeout_ms}") - - # Generate the requested number of messages - for _ in range(datum.num_records): - # Create message payload - payload = f"message-{self.counter}".encode() - - # Create offset - offset = sourcer.Offset( - offset=str(self.counter).encode("utf-8"), - partition_id=self.partition_idx, - ) + It keeps the offsets that are read but not acked yet. A nacked offset is + read again before any new message. + """ - # Create user metadata for the message - user_metadata = sourcer.UserMetadata() - user_metadata.create_group("source_info") - user_metadata.add_kv("source_info", "source_name", b"simple_source") - user_metadata.add_kv("source_info", "message_id", str(self.counter).encode()) - user_metadata.add_kv("source_info", "partition", str(self.partition_idx).encode()) - - # Create message - message = sourcer.Message( - payload=payload, - offset=offset, - event_time=datetime.now(UTC), + def __init__(self, partition_id: int = 0) -> None: + self.partition_id = partition_id + self.next_id = 0 + self.unacked: set[Offset] = set() + self.redeliver: deque[Offset] = deque() + + def _next_offset(self) -> Offset: + if self.redeliver: + return self.redeliver.popleft() + offset = Offset(str(self.next_id).encode(), self.partition_id) + self.next_id += 1 + return offset + + async def read(self, request: ReadRequest) -> AsyncIterator[Message]: + logger.info("Read request: %r", request) + for _ in range(request.num_records): + offset = self._next_offset() + self.unacked.add(offset) + yield Message( + f"message-{offset.value.decode()}".encode(), + offset, + datetime.now(UTC), keys=["key1"], headers={"source": "simple"}, - user_metadata=user_metadata, + user_metadata={ + "source_info": { + "source_name": b"simple_source", + "message_id": offset.value, + "partition": str(offset.partition_id).encode(), + } + }, ) - _LOGGER.info(f"Generated message: {self.counter}") - self.counter += 1 - - yield message - - # Small delay to simulate real source - await asyncio.sleep(0.1) - - async def ack_handler(self, request: sourcer.AckRequest) -> None: - """ - The simple source acknowledges the offsets. - """ - _LOGGER.info(f"Acknowledging {len(request.offsets)} offsets") - for offset in request.offsets: - _LOGGER.debug(f"Acked offset: {offset.offset.decode('utf-8')}, partition: {offset.partition_id}") - - async def nack_handler(self, request: sourcer.NackRequest) -> None: - """ - The simple source negatively acknowledges the offsets. - """ - _LOGGER.info(f"Negatively acknowledging {len(request.nack_offsets)} offsets") - for nack_offset in request.nack_offsets: - offset = nack_offset.offset - _LOGGER.warning( - f"Nacked offset: {offset.offset.decode('utf-8')}, " - f"partition: {offset.partition_id}, options: {nack_offset.nack_options}" - ) - - async def pending_handler(self) -> sourcer.PendingResponse: - """ - The simple source always returns zero to indicate there is no pending record. - """ - return sourcer.PendingResponse(count=0) - - async def partitions_handler(self) -> sourcer.PartitionsResponse: - """ - The simple source always returns default partitions. - """ - return sourcer.PartitionsResponse(partitions=[self.partition_idx]) + async def ack(self, offsets: list[Offset]) -> None: + logger.info("Acknowledging %d offsets", len(offsets)) + self.unacked.difference_update(offsets) + async def nack(self, offsets: list[NackOffset]) -> None: + logger.info("Negatively acknowledging %d offsets", len(offsets)) + for nack_offset in offsets: + logger.warning("Nacked %r", nack_offset) + self.unacked.discard(nack_offset.offset) + self.redeliver.append(nack_offset.offset) -async def start(): - sock_file = "/tmp/var/run/numaflow/source.sock" - server_info_file = "/tmp/var/run/numaflow/sourcer-server-info" - server = sourcer.SourceAsyncServer(sock_file, server_info_file) + async def pending(self) -> int | None: + # Only the nacked messages wait to be read: new messages are made on demand. + return len(self.redeliver) - # Create an instance of the source handler - handler = SimpleSource() + async def active_partitions(self) -> list[int] | None: + return [self.partition_id] - # Register loop-level signal handlers to request graceful shutdown - loop = asyncio.get_running_loop() - try: - loop.add_signal_handler(signal.SIGINT, lambda: server.stop()) - loop.add_signal_handler(signal.SIGTERM, lambda: server.stop()) - except (NotImplementedError, RuntimeError): - pass - try: - await server.start(handler) - print("Shutting down gracefully...") - except asyncio.CancelledError: - server.stop() - return +async def main() -> None: + await SourceAsyncServer( + SimpleSource(), + sock_file="/tmp/var/run/numaflow/source.sock", + server_info_file="/tmp/var/run/numaflow/sourcer-server-info", + ).serve() if __name__ == "__main__": - asyncio.run(start()) + asyncio.run(main()) diff --git a/packages/pynumaflow-lite/tests/test_source_unit.py b/packages/pynumaflow-lite/tests/test_source_unit.py new file mode 100644 index 00000000..85114360 --- /dev/null +++ b/packages/pynumaflow-lite/tests/test_source_unit.py @@ -0,0 +1,214 @@ +import asyncio +import os +import subprocess +import sys +import uuid +from collections.abc import AsyncIterator +from contextlib import suppress +from datetime import UTC, datetime, timedelta +from pathlib import Path + +import pytest + +from pynumaflow_lite import sourcer + +CARGO_ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(Path(__file__).resolve().parent / "examples")) + +from source_simple import SimpleSource # noqa: E402 + +EVENT_TIME = datetime(2023, 6, 1, tzinfo=UTC) + + +async def _read_all(source: sourcer.Sourcer, request: sourcer.ReadRequest) -> list[sourcer.Message]: + return [message async for message in source.read(request)] + + +def test_sourcer_can_be_unit_tested_without_server(): + async def scenario() -> None: + source = SimpleSource() + + messages = await _read_all(source, sourcer.ReadRequest(3)) + offsets = [message.offset for message in messages] + assert offsets == [sourcer.Offset(b"0"), sourcer.Offset(b"1"), sourcer.Offset(b"2")] + assert messages[0].user_metadata["source_info"]["message_id"] == b"0" + + await source.ack(offsets[:2]) + await source.nack([sourcer.NackOffset(offsets[2])]) + assert source.unacked == set() + assert await source.pending() == 1 + + [redelivered] = await _read_all(source, sourcer.ReadRequest(1)) + assert redelivered.offset == offsets[2] + assert await source.active_partitions() == [0] + assert await source.total_partitions() is None + + asyncio.run(scenario()) + + +def test_offset_is_hashable_value_object(): + offset = sourcer.Offset(b"7", partition_id=2) + + assert offset == sourcer.Offset(b"7", 2) + assert offset != sourcer.Offset(b"7", 3) + assert {offset, sourcer.Offset(b"7", 2)} == {offset} + assert offset.value == b"7" + assert offset.partition_id == 2 + assert repr(offset) == "Offset(value=b'7', partition_id=2)" + with pytest.raises(AttributeError): + offset.value = b"8" # type: ignore[misc] + + +def test_message_attributes_and_repr(): + message = sourcer.Message(b"value", sourcer.Offset(b"1"), EVENT_TIME, keys=["key"]) + + assert message.value == b"value" + assert message.offset == sourcer.Offset(b"1", 0) + assert message.event_time == EVENT_TIME + assert message.keys == ["key"] + assert message.headers == {} + assert message.user_metadata == {} + assert message == sourcer.Message(b"value", sourcer.Offset(b"1"), EVENT_TIME, keys=["key"]) + assert repr(message).startswith("Message(value=b'value', offset=Offset(value=b'1', partition_id=0), ") + + +def test_read_request_timeout_is_timedelta(): + request = sourcer.ReadRequest(5) + + assert request.num_records == 5 + assert request.timeout == timedelta(seconds=1) + assert sourcer.ReadRequest(5, timedelta(milliseconds=250)).timeout == timedelta(milliseconds=250) + assert repr(request) == "ReadRequest(num_records=5, timeout=datetime.timedelta(seconds=1))" + + +def test_nack_offset_attributes(): + options = sourcer.NackOptions(delay=100, reason="retry") + nack_offset = sourcer.NackOffset(sourcer.Offset(b"1"), options) + + assert nack_offset.offset == sourcer.Offset(b"1") + assert nack_offset.nack_options == options + assert sourcer.NackOffset(sourcer.Offset(b"1")).nack_options is None + + +def test_sourcer_requires_read_ack_nack_and_pending(): + class Incomplete(sourcer.Sourcer): + pass + + with pytest.raises(TypeError) as excinfo: + Incomplete() # type: ignore[abstract] + for method in ("read", "ack", "nack", "pending"): + assert method in str(excinfo.value) + + +def test_server_rejects_non_sourcer(): + with pytest.raises(TypeError, match="source handler must be a Sourcer instance"): + sourcer.SourceAsyncServer(object()) # type: ignore[arg-type] + + +async def _run_source_client(sock_path: Path) -> subprocess.CompletedProcess[str]: + return await asyncio.to_thread( + subprocess.run, + ["cargo", "run", "--quiet", "--bin", "test_source", "--", str(sock_path)], + cwd=CARGO_ROOT, + capture_output=True, + text=True, + timeout=60, + check=False, + ) + + +async def _exercise_server( + tmp_path: Path, + source: sourcer.Sourcer, + clients: list[subprocess.CompletedProcess[str]] | None = None, +) -> None: + path_id = f"{tmp_path.name[:12]}-{uuid.uuid4().hex[:12]}" + sock_path = Path(f"/tmp/pnl-{path_id}.sock") + server_info_path = Path(f"/tmp/pnl-{path_id}.info") + server = sourcer.SourceAsyncServer( + source, + sock_file=str(sock_path), + server_info_file=str(server_info_path), + ) + + try: + async with server: + client = await _run_source_client(sock_path) + if clients is not None: + clients.append(client) + finally: + for path in (sock_path, server_info_path): + with suppress(FileNotFoundError): + os.unlink(path) + + +def test_source_server_serves_rust_client(tmp_path: Path): + clients: list[subprocess.CompletedProcess[str]] = [] + source = SimpleSource() + + asyncio.run(_exercise_server(tmp_path, source, clients)) + + [client] = clients + assert client.returncode == 0, client.stderr + # 5 messages acked, then 2 read and nacked. + assert source.unacked == set() + assert list(source.redeliver) == [sourcer.Offset(b"5"), sourcer.Offset(b"6")] + + +class _FailingRead(SimpleSource): + async def read(self, request: sourcer.ReadRequest) -> AsyncIterator[sourcer.Message]: + raise RuntimeError("read exploded") + yield + + +class _ReadReturnsList(SimpleSource): + async def read(self, request: sourcer.ReadRequest): # type: ignore[override] + return [] + + +class _ReadYieldsWrongType(SimpleSource): + async def read(self, request: sourcer.ReadRequest): # type: ignore[override] + yield "not a message" + + +class _FailingAck(SimpleSource): + async def ack(self, offsets: list[sourcer.Offset]) -> None: + raise RuntimeError("ack exploded") + + +class _SyncPending(SimpleSource): + def pending(self) -> int | None: # type: ignore[override] + return 0 + + +class _NegativePending(SimpleSource): + async def pending(self) -> int | None: + return -1 + + +class _BadPartitions(SimpleSource): + async def active_partitions(self) -> list[int] | None: + return "0" # type: ignore[return-value] + + +@pytest.mark.parametrize( + ("source", "error", "match"), + [ + (_FailingRead(), RuntimeError, "read exploded"), + (_ReadReturnsList(), TypeError, r"source read must be an async generator"), + (_ReadYieldsWrongType(), TypeError, "source read must yield Message, got str"), + (_FailingAck(), RuntimeError, "ack exploded"), + (_SyncPending(), TypeError, r"source pending must be an async function"), + (_NegativePending(), ValueError, "source pending must not be negative, got -1"), + (_BadPartitions(), TypeError, r"source active_partitions must return list\[int\] or None, got str"), + ], + ids=lambda value: type(value).__name__.strip("_") if isinstance(value, sourcer.Sourcer) else None, +) +def test_source_server_propagates_handler_failure(tmp_path: Path, source, error, match): + clients: list[subprocess.CompletedProcess[str]] = [] + with pytest.raises(error, match=match): + asyncio.run(_exercise_server(tmp_path, source, clients)) + + # The client must get a gRPC error, not a silent empty or default answer. + [client] = clients + assert client.returncode != 0