|
| 1 | +from datetime import datetime |
| 2 | +from collections.abc import AsyncIterable |
| 3 | + |
| 4 | +import aiorun |
| 5 | + |
| 6 | +from pynumaflow.sourcer import ( |
| 7 | + ReadRequest, |
| 8 | + Message, |
| 9 | + AckRequest, |
| 10 | + PendingResponse, |
| 11 | + Offset, |
| 12 | + AsyncSourcer, |
| 13 | +) |
| 14 | + |
| 15 | + |
| 16 | +class AsyncSource: |
| 17 | + """ |
| 18 | + AsyncSource is a class for User Defined Source implementation. |
| 19 | + """ |
| 20 | + |
| 21 | + def __init__(self): |
| 22 | + """ |
| 23 | + to_ack_set: Set to maintain a track of the offsets yet to be acknowledged |
| 24 | + read_idx : the offset idx till where the messages have been read |
| 25 | + """ |
| 26 | + self.to_ack_set = set() |
| 27 | + self.read_idx = 0 |
| 28 | + |
| 29 | + async def read_handler(self, datum: ReadRequest) -> AsyncIterable[Message]: |
| 30 | + """ |
| 31 | + read_handler is used to read the data from the source and send the data forward |
| 32 | + for each read request we process num_records and increment the read_idx to indicate that |
| 33 | + the message has been read and the same is added to the ack set |
| 34 | + """ |
| 35 | + if self.to_ack_set: |
| 36 | + return |
| 37 | + |
| 38 | + for x in range(datum.num_records): |
| 39 | + yield Message( |
| 40 | + payload=str(self.read_idx).encode(), |
| 41 | + offset=Offset(offset=str(self.read_idx).encode(), partition_id="0"), |
| 42 | + event_time=datetime.now(), |
| 43 | + ) |
| 44 | + self.to_ack_set.add(str(self.read_idx)) |
| 45 | + self.read_idx += 1 |
| 46 | + |
| 47 | + async def ack_handler(self, ack_request: AckRequest): |
| 48 | + """ |
| 49 | + The ack handler is used acknowledge the offsets that have been read, and remove them |
| 50 | + from the to_ack_set |
| 51 | + """ |
| 52 | + for offset in ack_request.offset: |
| 53 | + self.to_ack_set.remove(str(offset.offset, "utf-8")) |
| 54 | + |
| 55 | + async def pending_handler(self) -> PendingResponse: |
| 56 | + """ |
| 57 | + The simple source always returns zero to indicate there is no pending record. |
| 58 | + """ |
| 59 | + return PendingResponse(count=0) |
| 60 | + |
| 61 | + |
| 62 | +if __name__ == "__main__": |
| 63 | + ud_source = AsyncSource() |
| 64 | + grpc_server = AsyncSourcer( |
| 65 | + read_handler=ud_source.read_handler, |
| 66 | + ack_handler=ud_source.ack_handler, |
| 67 | + pending_handler=ud_source.pending_handler, |
| 68 | + ) |
| 69 | + aiorun.run(grpc_server.start()) |
0 commit comments