Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/pynumaflow-lite/manifests/source/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.venv/
73 changes: 39 additions & 34 deletions packages/pynumaflow-lite/manifests/source/Dockerfile
Original file line number Diff line number Diff line change
@@ -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"]
8 changes: 1 addition & 7 deletions packages/pynumaflow-lite/manifests/source/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"

143 changes: 53 additions & 90 deletions packages/pynumaflow-lite/manifests/source/simple_source.py
Original file line number Diff line number Diff line change
@@ -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())
8 changes: 8 additions & 0 deletions packages/pynumaflow-lite/manifests/source/uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions packages/pynumaflow-lite/pynumaflow_lite/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading