You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I have multiple streams and use middleware to record the processing status of tasks. I use the ID returned by publish, which is xadd, to distinguish each task. Since it is currently impossible to pass in a custom ID, different streams may generate the same ID when concurrent.
importjsonimporttracebackfromdatetimeimportdatetimeimportredis.asyncioasredisfromtypesimportTracebackTypefromtypingimportAny, Awaitable, CallablefromfaststreamimportBaseMiddleware, PublishCommand, StreamMessagefromconfig.settingsimportsettingsdef_convert_bytes_to_str(obj):
ifisinstance(obj, bytes):
try:
returnobj.decode('utf-8')
exceptUnicodeDecodeError:
returnobj.decode('latin-1')
elifisinstance(obj, dict):
return {k.decode('utf-8') ifisinstance(k, bytes) elsek:
_convert_bytes_to_str(v) fork, vinobj.items()}
elifisinstance(obj, list):
return [_convert_bytes_to_str(item) foriteminobj]
elifisinstance(obj, tuple):
returntuple(_convert_bytes_to_str(item) foriteminobj)
returnobjclassTaskStatusMiddleware(BaseMiddleware):
def__init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.redis_client=redis.Redis(
host=settings.redis_host,
port=settings.redis_port,
db=settings.redis_db,
password=settings.redis_password,
decode_responses=True
)
self.status_key_prefix=f"task:status:"# Use this if you want to add logic when a message is received for the first time,# such as logging incoming messages, validating headers, or setting up the context.asyncdefon_receive(self) ->Any:
message_ids=self.msg.get("message_ids", [])
msg_id=message_ids[0].decode() ifmessage_idselse"unknown"# '1767854208631-0'awaitself._update_status(msg_id, "processing", {
"raw_data": self.msg
})
returnawaitsuper().on_receive()
# Use this if you want to wrap the entire message processing process,# such as implementing retry logic, circuit breakers, rate limiting, or authentication.asyncdefconsume_scope(
self,
call_next: Callable[[StreamMessage[Any]], Awaitable[Any]],
msg: StreamMessage[Any],
) ->Any:
raw_message=msg.raw_messagemessage_ids=raw_message.get("message_ids", [])
msg_id=message_ids[0].decode() ifmessage_idselse"unknown"# '1767854208631-0'try:
raw_resp=awaitcall_next(msg)
awaitself._update_status(msg_id, "completed", {
"raw_resp": raw_resp
})
returnraw_respexceptExceptionase:
raisee# Use this if you want to customize outgoing messages before they are sent,# such as adding encryption, compression, or custom headers.asyncdefpublish_scope(
self,
call_next: Callable[[PublishCommand], Awaitable[Any]],
cmd: PublishCommand,
) ->Any:
msg_id=awaitcall_next(cmd)
awaitself._update_status(msg_id.decode(), "pending", {})
returnmsg_id# Use this if you want to perform post-processing tasks after message handling has completed,# such as cleaning up, logging errors, collecting metrics, or committing transactions.asyncdefafter_processed(
self,
exc_type: type[BaseException] |None=None,
exc_val: BaseException|None=None,
exc_tb: TracebackType|None=None,
) ->bool|None:
ifexc_val:
message_ids=self.msg.get("message_ids", [])
msg_id=message_ids[0].decode() ifmessage_idselse"unknown"# '1767854208631-0'error_details= {
"error_type": exc_type.__name__ifexc_typeelseNone,
"error_message": str(exc_val),
"traceback": traceback.format_exc()
}
awaitself._update_status(msg_id, "failed", {
"raw_error": error_details
})
returnawaitsuper().after_processed(exc_type, exc_val, exc_tb)
asyncdef_update_status(self, task_id: str, status: str, details: dict):
status_data= {
"status": status,
"updated_at": datetime.now().isoformat(),
**details
}
awaitself.redis_client.setex(
f"{self.status_key_prefix}{task_id}",
3*24*60*60,
json.dumps(_convert_bytes_to_str(status_data), ensure_ascii=False)
)
returnTrue
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I have multiple streams and use middleware to record the processing status of tasks. I use the ID returned by publish, which is xadd, to distinguish each task. Since it is currently impossible to pass in a custom ID, different streams may generate the same ID when concurrent.
Beta Was this translation helpful? Give feedback.
All reactions