Singleton try

This commit is contained in:
Zoe Roux 2025-05-13 21:40:52 +02:00
parent e56c0ec89c
commit acb2279d61
No known key found for this signature in database
8 changed files with 24 additions and 11 deletions

View File

@ -104,7 +104,7 @@ services:
- "4389:4389" - "4389:4389"
environment: environment:
- KYOO_URL=${KYOO_URL:-http://api:3567/api} - KYOO_URL=${KYOO_URL:-http://api:3567/api}
- JWKS_URL="http://auth:4568/.well-known/jwks.json" - JWKS_URL=http://auth:4568/.well-known/jwks.json
- JWT_ISSUER=${PUBLIC_URL} - JWT_ISSUER=${PUBLIC_URL}
volumes: volumes:
- ./scanner:/app - ./scanner:/app

View File

@ -30,7 +30,6 @@ async def lifespan(_):
# creating the processor makes it listen to requests event in pg # creating the processor makes it listen to requests event in pg
async with ( async with (
get_db() as db, get_db() as db,
KyooClient() as client,
): ):
scanner = Scanner(client, RequestCreator(db)) scanner = Scanner(client, RequestCreator(db))
# there's no way someone else used the same id, right? # there's no way someone else used the same id, right?

View File

@ -4,6 +4,8 @@ from types import TracebackType
from aiohttp import ClientSession from aiohttp import ClientSession
from scanner.utils import Singleton
from .models.movie import Movie from .models.movie import Movie
from .models.serie import Serie from .models.serie import Serie
from .models.videos import Resource, Video, VideoCreated, VideoInfo from .models.videos import Resource, Video, VideoCreated, VideoInfo
@ -11,7 +13,7 @@ from .models.videos import Resource, Video, VideoCreated, VideoInfo
logger = getLogger(__name__) logger = getLogger(__name__)
class KyooClient: class KyooClient(metaclass=Singleton):
def __init__(self) -> None: def __init__(self) -> None:
api_key = os.environ.get("KYOO_APIKEY") api_key = os.environ.get("KYOO_APIKEY")
if not api_key: if not api_key:

View File

@ -20,8 +20,8 @@ logger = getLogger(__name__)
class Scanner: class Scanner:
def __init__( def __init__(
self, self,
client: Annotated[KyooClient, Depends], client: Annotated[KyooClient, Depends(KyooClient)],
requests: Annotated[RequestCreator, Depends], requests: Annotated[RequestCreator, Depends(RequestCreator)],
): ):
self._client = client self._client = client
self._requests = requests self._requests = requests

View File

@ -19,13 +19,13 @@ from ..models.season import Season, SeasonTranslation
from ..models.serie import SearchSerie, Serie, SerieStatus, SerieTranslation from ..models.serie import SearchSerie, Serie, SerieStatus, SerieTranslation
from ..models.staff import Character, Person, Role, Staff from ..models.staff import Character, Person, Role, Staff
from ..models.studio import Studio, StudioTranslation from ..models.studio import Studio, StudioTranslation
from ..utils import clean, to_slug from ..utils import Singleton, clean, to_slug
from .provider import Provider, ProviderError from .provider import Provider, ProviderError
logger = getLogger(__name__) logger = getLogger(__name__)
class TheMovieDatabase(Provider): class TheMovieDatabase(Provider, metaclass=Singleton):
THEMOVIEDB_API_ACCESS_TOKEN = "eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJjOWYzMjhhMDEwMTFiMjhmMjI0ODM3MTczOTVmYzNmYSIsIm5iZiI6MTU4MTYzMTExOS44NjgsInN1YiI6IjVlNDVjNjhmODNlZTY3MDAxMTFmMmU5NiIsInNjb3BlcyI6WyJhcGlfcmVhZCJdLCJ2ZXJzaW9uIjoxfQ.CeXrQwgB3roCAVs-Z2ayLRx99VIJbym7XSpcRjGzyLA" THEMOVIEDB_API_ACCESS_TOKEN = "eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJjOWYzMjhhMDEwMTFiMjhmMjI0ODM3MTczOTVmYzNmYSIsIm5iZiI6MTU4MTYzMTExOS44NjgsInN1YiI6IjVlNDVjNjhmODNlZTY3MDAxMTFmMmU5NiIsInNjb3BlcyI6WyJhcGlfcmVhZCJdLCJ2ZXJzaW9uIjoxfQ.CeXrQwgB3roCAVs-Z2ayLRx99VIJbym7XSpcRjGzyLA"
def __init__(self) -> None: def __init__(self) -> None:

View File

@ -6,7 +6,7 @@ from typing import Annotated, Literal
from asyncpg import Connection from asyncpg import Connection
from fastapi import Depends from fastapi import Depends
from pydantic import Field from pydantic import Field, TypeAdapter
from .client import KyooClient from .client import KyooClient
from .database import get_db from .database import get_db
@ -46,7 +46,7 @@ class RequestCreator:
do update set do update set
videos = videos || excluded.videos videos = videos || excluded.videos
""", """,
(x.model_dump() for x in requests), TypeAdapter(list[Request]).dump_python(requests),
) )
_ = await self._database.execute("notify scanner.requests") _ = await self._database.execute("notify scanner.requests")

View File

@ -12,10 +12,11 @@ router = APIRouter()
"/scan", "/scan",
status_code=204, status_code=204,
response_description="Scan started.", response_description="Scan started.",
response_model=None,
) )
async def trigger_scan( async def trigger_scan(
tasks: BackgroundTasks, tasks: BackgroundTasks,
# scanner: Annotated[Scanner, Depends], scanner: Annotated[Scanner, Depends(Scanner)],
_: Annotated[None, Security(validate_bearer, scopes=["scanner.trigger"])], _: Annotated[None, Security(validate_bearer, scopes=["scanner.trigger"])],
): ):
""" """

View File

@ -1,4 +1,5 @@
from typing import Annotated, Any, Callable from abc import ABC, ABCMeta
from typing import Annotated, Any, Callable, override
from langcodes import Language as BaseLanguage from langcodes import Language as BaseLanguage
from pydantic import AliasGenerator, BaseModel, ConfigDict, GetJsonSchemaHandler from pydantic import AliasGenerator, BaseModel, ConfigDict, GetJsonSchemaHandler
@ -15,6 +16,16 @@ def clean(val: str) -> str | None:
return val or None return val or None
class Singleton(ABCMeta, type):
_instances = {}
@override
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
class Model(BaseModel): class Model(BaseModel):
model_config = ConfigDict( model_config = ConfigDict(
use_enum_values=True, use_enum_values=True,