Without using Kafka or any other external queue/streaming system, you can simulate a real-time streaming process in Python by collecting incoming data streams (via sockets, HTTP requests, or simply reading from a file in a loop) and processing them as they arrive. To deal with out-of-order (late) data, you need to maintain a buffer or window of data that you're willing to keep open for updates before finalizing a session's "valid to read" status.
Here's a simplified approach using Python's asyncio for asynchronous processing, assuming data comes in as a stream of JSON-like dictionaries from some source (async_data_source()), and we simulate late data handling by keeping sessions open for a certain late_window period.
Python-Only Approach with Asynchronous Processing
import asyncio
from datetime import datetime, timedelta
# Example incoming data format
example_data = [
{"session_id": "1", "post_id": "101", "time_stamp": "2023-04-01T12:30:00", "event_type": "start", "percentage": 85},
# Imagine more events, including late arrivals and end events
]
# Assuming this simulates your incoming data stream
async def async_data_source():
for data in example_data:
await asyncio.sleep(1) # Simulate delay between data arrivals
yield data
# Parser for the time_stamp strings
def parse_time_stamp(time_stamp):
return datetime.strptime(time_stamp, "%Y-%m-%dT%H:%M:%S")
# Process each event
async def process_event(event, sessions):
session_id = event["session_id"]
event_type = event["event_type"]
time_stamp = parse_time_stamp(event["time_stamp"])
percentage = event["percentage"]
# Check if this is the first time we see this session_id
if session_id not in sessions:
sessions[session_id] = {"start": None, "end": None, "percentages": []}
# Update session data based on event type
if event_type == "start":
sessions[session_id]["start"] = time_stamp
elif event_type == "end":
sessions[session_id]["end"] = time_stamp
# Assume percentage is relevant for both start and end
sessions[session_id]["percentages"].append(percentage)
# Check if the session can be closed (conditions met and enough time passed)
await check_and_finalize_session(session_id, sessions)
# Check and finalize sessions that are complete and valid
async def check_and_finalize_session(session_id, sessions, late_window=timedelta(seconds=10)):
session = sessions[session_id]
now = datetime.now()
if session["start"] and session["end"] and min(session["percentages"]) >= 80:
duration = session["end"] - session["start"]
# Conditions: Duration at least 5 seconds, percentage >= 80, and either not late or grace period passed
if duration >= timedelta(seconds=5) and (now - session["end"] > late_window):
print(f"Session {session_id} is valid and closed.")
del sessions[session_id] # Remove it from active sessions
# Main async processing loop
async def main():
sessions = {}
async for event in async_data_source():
await process_event(event, sessions)
# Run the async main loop
asyncio.run(main())
Key Components Explained:
async_data_source(): Simulates an asynchronous stream of data. Replace this with your actual data source, e.g., reading from a file in real-time or receiving data over the network.
process_event(): Processes incoming events by updating session information or creating new session entries as needed.
check_and_finalize_session(): After each event, checks if the session can be considered complete and valid, based on your criteria (duration and screen proportion). It keeps a "late window" to account for potential late data affecting the session validity.
Handling Late-Arriving Data:
To efficiently manage late-arriving data, this setup includes a late window (late_window in check_and_finalize_session()) which dictates how long to wait after the last known event in a session before finalizing its status. Adjust this window based on your expected latency and tolerance for late data.
Keep in mind, this is a simplified example. In a production environment, you'd need to handle more complexities, such as error handling, efficient state storage (e.g., using an in-memory database if the volume of sessions is large), and scaling the solution.