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