mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-30 20:06:22 -05:00
Request sessions keep objects after commit; guard dict() serializers (#811)
A RequestSession no longer expires loaded objects at commit, so a handler serializes what it committed without a reload query. An AsyncSession cannot run that reload at all, so this is groundwork for moving request handling to async. Background sessions (get_db_session) keep SQLAlchemy's default: they change data outside the ORM (raw SQL, triggers) and rely on the reload. Collection, CollectionItem and Channel dict() now run inside the serializer guard. Fixes it found: - Channel.dict() no longer loads the deferred yt-dlp catalog (info_json), which the channel handler loaded only to discard. - get_channel eager-loads what Channel.dict() reads (populate_existing replaces a refresh query). - create_channel / get_or_create_download link through relationships, so a loaded Collection.downloads stays current. - Setting a Repo to Never removes the deleted Download from the loaded collection; the response reported the old frequency. - The downloader no longer calls channel.dict() to preload a Channel; its callers read it inside the session. Tests run each request with expiry off, as production does, and turn it back on for the background work that shares the test Session. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
1f8a887c11
commit
673c23188c
13 changed files with 82 additions and 31 deletions
|
|
@ -604,6 +604,8 @@ async def test_get_archive_loads_history_eagerly(test_session, archive_factory,
|
|||
test_session.commit()
|
||||
|
||||
async def get(archive):
|
||||
url = f'/api/archive/{archive.file_group_id}?skip_viewed=true'
|
||||
test_session.expire_all() # Each request starts from the same Session state.
|
||||
statements = []
|
||||
|
||||
def count(conn, cursor, statement, *_):
|
||||
|
|
@ -611,7 +613,7 @@ async def test_get_archive_loads_history_eagerly(test_session, archive_factory,
|
|||
|
||||
event.listen(Engine, 'before_cursor_execute', count)
|
||||
try:
|
||||
request, response = await async_client.get(f'/api/archive/{archive.file_group_id}?skip_viewed=true')
|
||||
request, response = await async_client.get(url)
|
||||
finally:
|
||||
event.remove(Engine, 'before_cursor_execute', count)
|
||||
assert response.status_code == HTTPStatus.OK, response.json
|
||||
|
|
|
|||
|
|
@ -738,6 +738,8 @@ def _set_repository_download(session: Session, repo: Repository, frequency: int,
|
|||
(`frequency` is NEVER) has none; with `clone`, it is cloned once if its clone is missing."""
|
||||
if not frequency:
|
||||
if download := repo.download:
|
||||
# A deleted object stays in loaded collections; remove it so the Repo reads as never updated.
|
||||
repo.collection.downloads.remove(download)
|
||||
session.delete(download)
|
||||
if clone and not (repo.directory / '.git').exists():
|
||||
request_repository_update(session, repo)
|
||||
|
|
|
|||
|
|
@ -37,7 +37,6 @@ async def get_channels(request: Request):
|
|||
def channel_get(request: Request, channel_id: int = None):
|
||||
session = request.ctx.session
|
||||
channel = lib.get_channel(session, channel_id=channel_id, return_dict=True)
|
||||
channel.pop('info_json')
|
||||
return json_response({'channel': channel})
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ from pathlib import Path
|
|||
from typing import List, Optional, Union
|
||||
|
||||
from sqlalchemy import or_, func, desc
|
||||
from sqlalchemy.orm import Query, Session, joinedload
|
||||
from sqlalchemy.orm import Query, Session
|
||||
|
||||
from wrolpi import flags
|
||||
from wrolpi.collections import Collection
|
||||
|
|
@ -71,9 +71,11 @@ def get_channel(session: Session, *, channel_id: int = None, source_id: str = No
|
|||
"""
|
||||
channel: COD = None # noqa
|
||||
# Try to find the channel by the most reliable methods first.
|
||||
# Always eagerly load Collection to ensure name/directory/tag_id are available
|
||||
# Load what `Channel.dict()` reads: the Collection (name/directory/tag) and its Downloads. Overwrite any
|
||||
# copy already in the Session so the Channel reflects the database.
|
||||
query = session.query(Channel).options(*Channel.json_options()).populate_existing()
|
||||
if channel_id:
|
||||
channel = session.query(Channel).options(joinedload(Channel.collection)).filter_by(id=channel_id).one_or_none()
|
||||
channel = query.filter_by(id=channel_id).one_or_none()
|
||||
if not channel and directory:
|
||||
directory = Path(directory)
|
||||
if not directory.is_absolute():
|
||||
|
|
@ -85,31 +87,27 @@ def get_channel(session: Session, *, channel_id: int = None, source_id: str = No
|
|||
media_dir = get_media_directory()
|
||||
current = directory
|
||||
while current != media_dir and current != current.parent:
|
||||
channel = session.query(Channel).options(joinedload(Channel.collection)).join(Collection).filter(
|
||||
Collection.directory == str(current)).one_or_none()
|
||||
channel = query.join(Collection).filter(Collection.directory == str(current)).one_or_none()
|
||||
if channel:
|
||||
break
|
||||
current = current.parent
|
||||
if not channel and source_id:
|
||||
channel = session.query(Channel).options(joinedload(Channel.collection)).filter_by(
|
||||
source_id=source_id).one_or_none()
|
||||
channel = query.filter_by(source_id=source_id).one_or_none()
|
||||
if not channel and url:
|
||||
channel = session.query(Channel).options(joinedload(Channel.collection)).filter_by(url=url).one_or_none()
|
||||
channel = query.filter_by(url=url).one_or_none()
|
||||
if not channel and url:
|
||||
# Try to extract YouTube channel ID from the URL and match by source_id.
|
||||
from modules.videos.common import get_youtube_channel_id
|
||||
yt_channel_id = get_youtube_channel_id(url)
|
||||
if yt_channel_id:
|
||||
channel = session.query(Channel).options(joinedload(Channel.collection)).filter_by(
|
||||
source_id=yt_channel_id).one_or_none()
|
||||
channel = query.filter_by(source_id=yt_channel_id).one_or_none()
|
||||
if not channel and name:
|
||||
channel = session.query(Channel).join(Collection).filter(Collection.name == name).one_or_none()
|
||||
channel = query.join(Collection).filter(Collection.name == name).one_or_none()
|
||||
|
||||
if not channel:
|
||||
raise UnknownChannel(f'No channel matches {channel_id=} {source_id=} {url=} {directory=}')
|
||||
|
||||
logger.debug(f'Found {channel=} using {channel_id=} {source_id=} {url=} {directory=}')
|
||||
session.refresh(channel)
|
||||
if return_dict:
|
||||
statistics = channel.get_statistics()
|
||||
channel = channel.dict()
|
||||
|
|
@ -179,12 +177,13 @@ def create_channel(session: Session, data: schema.ChannelPostRequest, return_dic
|
|||
name=data.name,
|
||||
kind='channel',
|
||||
directory=directory,
|
||||
downloads=[], # A new Collection has none; nothing to load.
|
||||
)
|
||||
session.add(collection)
|
||||
session.flush([collection])
|
||||
|
||||
# Create Channel linked to Collection
|
||||
channel = Channel(collection_id=collection.id)
|
||||
channel = Channel(collection=collection)
|
||||
session.add(channel)
|
||||
session.flush([channel])
|
||||
# Apply the changes now that we've OK'd them
|
||||
|
|
@ -199,7 +198,7 @@ def create_channel(session: Session, data: schema.ChannelPostRequest, return_dic
|
|||
|
||||
def delete_channel(session: Session, *, channel_id: int):
|
||||
check_channels_config_imported()
|
||||
channel = Channel.find_by_id(session, channel_id)
|
||||
channel = get_channel(session, channel_id=channel_id, return_dict=False)
|
||||
|
||||
channel_dict = channel.dict()
|
||||
channel.delete_with_videos()
|
||||
|
|
|
|||
|
|
@ -317,6 +317,8 @@ async def test_channel_by_id(test_session, async_client, simple_channel, simple_
|
|||
channel = response.json['channel']
|
||||
# needs_reorganization should be included for UI to display reorganization status
|
||||
assert 'needs_reorganization' in channel
|
||||
# The yt-dlp catalog is large and deferred; it is never loaded for a response.
|
||||
assert 'info_json' not in channel
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
|
|
|||
|
|
@ -115,14 +115,14 @@ async def test_channels_no_url(async_client, test_session, test_directory, test_
|
|||
directory=str(channel1_directory),
|
||||
)
|
||||
channel1.url = ''
|
||||
lib.create_channel(test_session, data=channel1)
|
||||
lib.create_channel(test_session, data=channel1, return_dict=False)
|
||||
|
||||
channel2 = schema.ChannelPostRequest(
|
||||
name='bar',
|
||||
directory=str(channel2_directory),
|
||||
url=''
|
||||
)
|
||||
lib.create_channel(test_session, data=channel2)
|
||||
lib.create_channel(test_session, data=channel2, return_dict=False)
|
||||
|
||||
channels = list(test_session.query(Channel))
|
||||
assert len(channels) == 2
|
||||
|
|
|
|||
|
|
@ -712,7 +712,6 @@ class ChannelDownloader(Downloader, ABC):
|
|||
with get_db_session(commit=True) as session:
|
||||
channel = get_or_create_channel(session, channel_source_id, channel_url, name, channel_tag_name,
|
||||
destination=prepared.destination)
|
||||
channel.dict() # get all attributes while we have the session.
|
||||
if channel and channel.id:
|
||||
channel_id = channel.id
|
||||
collection_id = channel.collection_id
|
||||
|
|
@ -1469,8 +1468,6 @@ def get_or_create_channel(session: Session, source_id: str = None, url: str = No
|
|||
"""
|
||||
try:
|
||||
channel = get_channel(session, source_id=source_id, url=url, name=name, return_dict=False)
|
||||
# Get all properties while we have the session.
|
||||
channel.dict()
|
||||
return channel
|
||||
except UnknownChannel:
|
||||
pass
|
||||
|
|
@ -1481,7 +1478,6 @@ def get_or_create_channel(session: Session, source_id: str = None, url: str = No
|
|||
if destination:
|
||||
try:
|
||||
channel = get_channel(session, directory=destination, return_dict=False)
|
||||
channel.dict()
|
||||
return channel
|
||||
except UnknownChannel:
|
||||
pass
|
||||
|
|
@ -1498,7 +1494,6 @@ def get_or_create_channel(session: Session, source_id: str = None, url: str = No
|
|||
# Reuse the Channel that already owns this directory instead of creating a conflicting one.
|
||||
try:
|
||||
channel = get_channel(session, directory=channel_directory, return_dict=False)
|
||||
channel.dict()
|
||||
return channel
|
||||
except UnknownChannel:
|
||||
pass
|
||||
|
|
@ -1519,9 +1514,6 @@ def get_or_create_channel(session: Session, source_id: str = None, url: str = No
|
|||
f'Cannot create channel {name!r}: conflicts with an existing channel') from e
|
||||
# Create the directory now that the channel is approved.
|
||||
channel_directory.mkdir(exist_ok=True)
|
||||
# Get all properties while we have the session.
|
||||
channel.dict()
|
||||
|
||||
return channel
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -632,6 +632,9 @@ class Channel(ModelHelper, Base):
|
|||
# Joined: a Channel's name, directory and Tag live on its Collection.
|
||||
collection = relationship('Collection', foreign_keys=[collection_id], lazy='joined')
|
||||
|
||||
# The yt-dlp catalog is large and no response reads it.
|
||||
dict_exclude = ('info_json',)
|
||||
|
||||
@property
|
||||
def downloads(self) -> list:
|
||||
"""Get recurring downloads from associated Collection. Once-downloads are excluded because they are not
|
||||
|
|
@ -966,6 +969,7 @@ class Channel(ModelHelper, Base):
|
|||
)
|
||||
return d
|
||||
|
||||
@serializer
|
||||
def dict(self, with_statistics: bool = False, with_downloads: bool = True) -> dict:
|
||||
d = super(Channel, self).dict()
|
||||
# Add Collection-delegated properties
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue