Use msgspec for messages deserialization

This commit is contained in:
Zoe Roux 2024-04-17 21:59:18 +02:00
parent 76a1b5c38f
commit d34d87957e
No known key found for this signature in database
5 changed files with 24 additions and 16 deletions

View File

@ -14,5 +14,5 @@ async def main():
async with KyooClient() as kyoo, Subscriber() as sub: async with KyooClient() as kyoo, Subscriber() as sub:
provider = Provider.get_default(kyoo.client) provider = Provider.get_default(kyoo.client)
scanner = Matcher(kyoo, provider) matcher = Matcher(kyoo, provider)
await sub.listen(scanner) await sub.listen(matcher)

View File

@ -1,7 +1,6 @@
import asyncio import asyncio
from dataclasses import dataclass from typing import Union
from dataclasses_json import DataClassJsonMixin from msgspec import Struct, json
from typing import Literal
import os import os
import logging import logging
from aio_pika import connect_robust from aio_pika import connect_robust
@ -11,12 +10,19 @@ from matcher.matcher import Matcher
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class Message(Struct, tag_field="action", tag=str.lower):
pass
@dataclass class Scan(Message):
class Message(DataClassJsonMixin):
action: Literal["scan", "delete"]
path: str path: str
class Delete(Message):
path: str
class Identify(Message):
pass
decoder = json.Decoder(Union[Scan, Delete, Identify])
class Subscriber: class Subscriber:
QUEUE = "scanner" QUEUE = "scanner"
@ -36,13 +42,15 @@ class Subscriber:
async def listen(self, scanner: Matcher): async def listen(self, scanner: Matcher):
async def on_message(message: AbstractIncomingMessage): async def on_message(message: AbstractIncomingMessage):
msg = Message.from_json(message.body) msg = decoder.decode(message.body)
ack = False ack = False
match msg.action: match msg:
case "scan": case Scan(path):
ack = await scanner.identify(msg.path) ack = await scanner.identify(path)
case "delete": case Delete(path):
ack = await scanner.delete(msg.path) ack = await scanner.delete(path)
# case Identify():
# ack = await scanner.delete(msg.path)
case _: case _:
logger.error(f"Invalid action: {msg.action}") logger.error(f"Invalid action: {msg.action}")
if ack: if ack:

View File

@ -3,4 +3,4 @@ aiohttp
jsons jsons
watchfiles watchfiles
aio-pika aio-pika
dataclasses-json msgspec

View File

@ -1 +0,0 @@
aio-pika

View File

@ -9,6 +9,7 @@
aio-pika aio-pika
requests requests
dataclasses-json dataclasses-json
msgspec
]); ]);
dotnet = with pkgs.dotnetCorePackages; dotnet = with pkgs.dotnetCorePackages;
combinePackages [ combinePackages [