selfprivacy-rest-api/selfprivacy_api/graphql/subscriptions/jobs.py

71 lines
2.1 KiB
Python
Raw Normal View History

2022-08-02 19:50:16 +00:00
import asyncio
2022-08-02 19:58:39 +00:00
import datetime
2022-08-02 19:50:16 +00:00
from typing import AsyncGenerator
import typing
import strawberry
from selfprivacy_api.graphql import IsAuthenticated
from selfprivacy_api.jobs import Job, Jobs
2022-08-02 20:12:48 +00:00
2022-08-02 19:58:39 +00:00
@strawberry.type
class ApiJob:
name: str
description: str
status: str
status_text: typing.Optional[str]
progress: typing.Optional[int]
created_at: datetime.datetime
updated_at: datetime.datetime
finished_at: typing.Optional[datetime.datetime]
error: typing.Optional[str]
result: typing.Optional[str]
2022-08-02 20:12:48 +00:00
2022-08-02 19:50:16 +00:00
@strawberry.type
class JobSubscription:
2022-08-02 20:08:32 +00:00
@strawberry.subscription()
2022-08-02 19:58:39 +00:00
async def job_subscription(self) -> AsyncGenerator[typing.List[ApiJob], None]:
2022-08-02 19:50:16 +00:00
is_updated = True
2022-08-02 20:12:48 +00:00
2022-08-02 19:50:16 +00:00
def callback(jobs: typing.List[Job]):
nonlocal is_updated
is_updated = True
2022-08-02 20:12:48 +00:00
print("Subscribing to job updates...")
2022-08-02 19:50:16 +00:00
Jobs().add_observer(callback)
2022-08-02 20:12:48 +00:00
yield [
ApiJob(
name=job.name,
description=job.description,
status=job.status.name,
status_text=job.status_text,
progress=job.progress,
created_at=job.created_at,
updated_at=job.updated_at,
finished_at=job.finished_at,
error=job.error,
result=job.result,
)
for job in Jobs().get_jobs()
]
2022-08-02 20:08:32 +00:00
while True:
if is_updated:
is_updated = False
2022-08-02 20:12:48 +00:00
yield [
ApiJob(
name=job.name,
description=job.description,
status=job.status.name,
status_text=job.status_text,
progress=job.progress,
created_at=job.created_at,
updated_at=job.updated_at,
finished_at=job.finished_at,
error=job.error,
result=job.result,
)
for job in Jobs().get_jobs()
]