Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions backend/app/share/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,15 @@ def share_registry_revoke(token: str) -> bool:
return _shares.pop(token, None) is not None


def share_registry_purge_expired() -> int:
"""Drop every expired share and return how many went."""
with _lock:
expired = [token for token, entry in _shares.items() if entry.is_expired]
for token in expired:
del _shares[token]
return len(expired)


def share_registry_count() -> int:
"""Live share count; the server stops once this reaches zero."""
with _lock:
Expand Down
39 changes: 37 additions & 2 deletions backend/app/utils/share.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,15 @@
from __future__ import annotations

import asyncio
from typing import List, Optional, TypedDict
from datetime import datetime, timezone
from typing import List, Optional, Set, TypedDict

from app.database.albums import db_count_album_images, db_get_album
from app.share.registry import (
ShareEntry,
share_registry_count,
share_registry_create,
share_registry_purge_expired,
share_registry_revoke,
)
from app.share.server import share_server_start, share_server_stop
Expand Down Expand Up @@ -50,6 +52,36 @@ class ShareDescription(TypedDict):
_orchestration_lock = asyncio.Lock()


# Strong references: the loop only keeps weak ones, so an unreferenced timer
# could be collected before it fires.
_expiry_timers: Set["asyncio.Task[None]"] = set()


async def share_util_sweep() -> None:
"""Drop expired shares and stop the listener if none are left."""
async with _orchestration_lock:
share_registry_purge_expired()
if share_registry_count() == 0:
await share_server_stop()


async def _sweep_at(expires_at: datetime) -> None:
# Expiry is otherwise noticed only when someone requests the token, so
# without this the listener outlives its last share.
# Looped because the sleep clock and the wall clock can disagree by a hair,
# and waking just early would leave the share unexpired and never revisited.
while (expires_at - datetime.now(timezone.utc)).total_seconds() > 0:
delay = (expires_at - datetime.now(timezone.utc)).total_seconds()
await asyncio.sleep(max(delay, 0.01))
await share_util_sweep()


def _schedule_sweep(expires_at: datetime) -> None:
timer = asyncio.create_task(_sweep_at(expires_at))
_expiry_timers.add(timer)
timer.add_done_callback(_expiry_timers.discard)


async def share_util_create(
album_id: str,
expires_in_minutes: Optional[int] = None,
Expand All @@ -58,9 +90,12 @@ async def share_util_create(
"""Issue a token for an album and make sure the listener is up."""
async with _orchestration_lock:
await share_server_start()
return share_registry_create(
entry = share_registry_create(
album_id, expires_in_minutes=expires_in_minutes, password=password
)
if entry.expires_at is not None:
_schedule_sweep(entry.expires_at)
return entry


async def share_util_revoke(token: str) -> bool:
Expand Down
66 changes: 64 additions & 2 deletions backend/tests/test_share_server.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,25 @@
import asyncio
import socket
from datetime import datetime, timedelta, timezone
from typing import Iterator, List, Optional, Tuple

import pytest

from app.share import server as share_server
from app.share.registry import share_registry_clear, share_registry_create
import app.utils.share as share_utils
from app.share.registry import (
share_registry_clear,
share_registry_count,
share_registry_create,
)
from app.share.registry import ShareEntry
from app.share.server import (
share_server_is_running,
share_server_port,
share_server_start,
share_server_stop,
)
from app.utils.share import share_util_revoke
from app.utils.share import share_util_create, share_util_revoke, share_util_sweep

# Every assertion about listener state is made inside the coroutine, because
# asyncio.run cancels the serve task and clears the state on its way out.
Expand Down Expand Up @@ -137,3 +144,58 @@ async def scenario() -> bool:

def test_revoking_an_unknown_token_reports_false(self) -> None:
assert asyncio.run(share_util_revoke("nope")) is False


class TestExpiryOrchestration:
def test_sweeping_after_the_last_share_expires_stops_the_listener(self) -> None:
async def scenario() -> Tuple[bool, int]:
await share_server_start()
entry = share_registry_create("album-1", expires_in_minutes=1)
entry.expires_at = datetime.now(timezone.utc) - timedelta(seconds=1)
await share_util_sweep()
return share_server_is_running(), share_registry_count()

running, remaining = asyncio.run(scenario())
assert running is False
assert remaining == 0

def test_sweeping_keeps_the_listener_while_a_share_is_live(self) -> None:
async def scenario() -> bool:
await share_server_start()
expired = share_registry_create("album-1", expires_in_minutes=1)
expired.expires_at = datetime.now(timezone.utc) - timedelta(seconds=1)
share_registry_create("album-2")
await share_util_sweep()
return share_server_is_running()

assert asyncio.run(scenario()) is True

def test_an_expiring_share_stops_the_listener_without_any_request(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
real_create = share_utils.share_registry_create

# Only the deadline is shortened; scheduling is left to share_util_create.
def short_lived(
album_id: str,
expires_in_minutes: Optional[int] = None,
password: Optional[str] = None,
) -> ShareEntry:
entry = real_create(
album_id, expires_in_minutes=expires_in_minutes, password=password
)
entry.expires_at = datetime.now(timezone.utc) + timedelta(seconds=0.1)
return entry

monkeypatch.setattr(share_utils, "share_registry_create", short_lived)

async def scenario() -> bool:
await share_util_create("album-1", expires_in_minutes=1)
# Poll for the outcome rather than guessing how long shutdown takes.
for _ in range(100):
if not share_server_is_running():
return False
await asyncio.sleep(0.05)
return True

assert asyncio.run(scenario()) is False
29 changes: 27 additions & 2 deletions frontend/src/components/Albums/ShareAlbumDialog.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { useDispatch } from 'react-redux';
import { QRCodeSVG } from 'qrcode.react';
import { openUrl } from '@tauri-apps/plugin-opener';
Expand Down Expand Up @@ -27,7 +28,7 @@ import { Switch } from '@/components/ui/switch';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { Separator } from '@/components/ui/separator';
import { usePictoMutation, type BackendRes } from '@/hooks/useQueryExtension';
import { createShare, revokeShare } from '@/api/api-functions';
import { createShare, getShares, revokeShare } from '@/api/api-functions';
import { useMutationFeedback } from '@/hooks/useMutationFeedback';
import { showInfoDialog } from '@/features/infoDialogSlice';
import { cn } from '@/lib/utils';
Expand Down Expand Up @@ -63,6 +64,9 @@ const DOCS_URL =
'https://aossie-org.github.io/PictoPy/overview/sharing-albums/';
const DOCS_INTERNET_URL = `${DOCS_URL}#internet-mode`;

const isAlreadyGone = (error: unknown): boolean =>
axios.isAxiosError(error) && error.response?.status === 404;

const formatExpiry = (expiresAt: string | null): string =>
expiresAt ? new Date(expiresAt).toLocaleString() : 'Until you stop it';

Expand Down Expand Up @@ -165,7 +169,25 @@ export const ShareAlbumDialog: React.FC<ShareAlbumDialogProps> = ({
// serving the album. Wrapped rather than passed straight through because
// react-query hands the mutation function a context as a second argument.
mutationFn: async (tokens: string[]): Promise<BackendRes<null>> => {
await Promise.all(tokens.map((token) => revokeShare(token)));
// A share that expired meanwhile is already gone, which is the outcome
// wanted, so a 404 is not a failure. Letting it reject would skip the
// tunnel close below and leave the album reachable.
const results = await Promise.allSettled(
tokens.map((token) => revokeShare(token)),
);
const failure = results.find(
(result): result is PromiseRejectedResult =>
result.status === 'rejected' && !isAlreadyGone(result.reason),
Comment thread
rohan-pandeyy marked this conversation as resolved.
Resolved
);
if (failure) {
throw failure.reason;
}
// The tunnel serves every album, and this dialog only knows about one.
// Ask the backend what is still live before taking it down.
const remaining = await getShares();
if ((remaining.data?.length ?? 0) > 0) {
return { success: true };
}
// Closed through the hook, which asks whether one is running rather than
// reading state this dialog may not have received yet. A failure here
// rejects the mutation, so nothing claims the cleanup finished.
Expand Down Expand Up @@ -211,6 +233,9 @@ export const ShareAlbumDialog: React.FC<ShareAlbumDialogProps> = ({
setCreatedShare(null);
setSelectedUrl('');
setCopied(false);
// Shares can expire while nothing is looking, so the list handed in may
// still hold one that is gone.
onChanged();
// A share made earlier is still served by whatever tunnel is up, so ask
// rather than assume it was a local one. The mode follows the answer:
// showing an internet link while the help button explains local sharing
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import userEvent from '@testing-library/user-event';
import { act, render, screen, waitFor } from '@/test-utils';
import { createShare, revokeShare } from '@/api/api-functions';
import { createShare, getShares, revokeShare } from '@/api/api-functions';
import { openUrl } from '@tauri-apps/plugin-opener';
import { startTunnel, stopTunnel, tunnelStatus } from '@/utils/tunnel';
import { Album } from '@/types/Album';
Expand All @@ -10,6 +10,7 @@ import { ShareAlbumDialog } from '../ShareAlbumDialog';
jest.mock('@/api/api-functions', () => ({
createShare: jest.fn(),
revokeShare: jest.fn(),
getShares: jest.fn(),
}));

jest.mock('@tauri-apps/plugin-opener', () => ({
Expand All @@ -24,6 +25,7 @@ jest.mock('@/utils/tunnel', () => ({

const mockCreateShare = createShare as jest.Mock;
const mockRevokeShare = revokeShare as jest.Mock;
const mockGetShares = getShares as jest.Mock;
const mockStartTunnel = startTunnel as jest.Mock;
const mockStopTunnel = stopTunnel as jest.Mock;
const mockTunnelStatus = tunnelStatus as jest.Mock;
Expand Down Expand Up @@ -80,6 +82,7 @@ describe('ShareAlbumDialog', () => {
jest.clearAllMocks();
mockCreateShare.mockResolvedValue({ success: true, data: share });
mockRevokeShare.mockResolvedValue({ success: true });
mockGetShares.mockResolvedValue({ success: true, data: [] });
mockStartTunnel.mockResolvedValue('https://abc123.lhr.life');
mockStopTunnel.mockResolvedValue(undefined);
mockTunnelStatus.mockResolvedValue(null);
Expand Down Expand Up @@ -399,6 +402,74 @@ describe('ShareAlbumDialog', () => {
await waitFor(() => expect(onChanged).toHaveBeenCalled());
});

it('refreshes the share list when opened, in case one expired meanwhile', () => {
const onChanged = jest.fn();
renderDialog([share], onChanged);

expect(onChanged).toHaveBeenCalled();
});

// An expired share is already gone from the backend, so revoking it 404s.
// That must not stop the tunnel from closing or the dialog from reporting
// failure.
it('treats a share that already expired as stopped and still closes the tunnel', async () => {
const user = userEvent.setup();
mockTunnelStatus.mockResolvedValue('https://abc123.lhr.life');
mockRevokeShare.mockRejectedValue(
Object.assign(new Error('Not Found'), {
isAxiosError: true,
response: { status: 404 },
}),
);
renderDialog([share]);

await user.click(screen.getByRole('button', { name: /stop sharing/i }));

await waitFor(() => expect(mockStopTunnel).toHaveBeenCalled());
});

it('still reports a revoke that failed for another reason', async () => {
const user = userEvent.setup();
// 409 because the mutation retries any other failure, and those retries
// would leak into the next test's call counts.
mockRevokeShare.mockRejectedValue(
Object.assign(new Error('boom'), {
isAxiosError: true,
response: { status: 409 },
}),
);
const { store } = renderDialog([share]);

await user.click(screen.getByRole('button', { name: /stop sharing/i }));

await waitFor(() => expect(mockRevokeShare).toHaveBeenCalled());
await waitFor(() =>
expect(store.getState().infoDialog).toMatchObject({
isOpen: true,
title: 'Error',
variant: 'error',
}),
);
expect(mockStopTunnel).not.toHaveBeenCalled();
});

// One tunnel serves every album, so another album's live share keeps it up.
it('leaves the tunnel open while another album is still shared', async () => {
const user = userEvent.setup();
mockTunnelStatus.mockResolvedValue('https://abc123.lhr.life');
mockGetShares.mockResolvedValue({
success: true,
data: [{ ...share, token: 'other', album_id: 'album-2' }],
});
renderDialog([share]);

await user.click(screen.getByRole('button', { name: /stop sharing/i }));

await waitFor(() => expect(mockRevokeShare).toHaveBeenCalledWith('tok-1'));
await waitFor(() => expect(mockGetShares).toHaveBeenCalled());
expect(mockStopTunnel).not.toHaveBeenCalled();
});

// Creating a share leaves earlier ones valid, so stopping has to take down
// every token or the album stays reachable after the UI says it stopped.
it('stops every share the album has, not just the newest', async () => {
Expand Down
26 changes: 26 additions & 0 deletions frontend/src/pages/Album/Album.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import { selectAlbums } from '@/features/albumSelectors';
import { showInfoDialog } from '@/features/infoDialogSlice';
import { useMutationFeedback } from '@/hooks/useMutationFeedback';
import { usePersistedSort } from '@/hooks/usePersistedSort';
import { stopTunnel } from '@/utils/tunnel';
import { MEDIA_GRID_CLASS } from '@/constants/layout';
import { cn } from '@/lib/utils';
import { Album } from '@/types/Album';
Expand All @@ -37,6 +38,8 @@ import {
type SortOption,
} from '@/components/GallerySortDropdown';

const SHARES_POLL_MS = 30_000;

type AlbumSortValue = 'name' | 'photoCount' | 'dateCreated' | 'recentlyUpdated';

const ALBUM_SORT_OPTIONS: SortOption<AlbumSortValue>[] = [
Expand Down Expand Up @@ -112,8 +115,31 @@ function Albums() {
>({
queryKey: ['shares'],
queryFn: () => getShares(),
// Expiry happens in the backend with no event, so poll while something is
// shared to notice the last one lapsing. Idle once nothing is.
refetchInterval: (query) =>
(query.state.data?.data?.length ?? 0) > 0 ? SHARES_POLL_MS : false,
});

// One tunnel serves every share, and the dialog only closes it on "Stop
// sharing". When the last share lapses on its own nothing else would, so
// the album would stay reachable from the internet.
useEffect(() => {
if (shares && shares.length === 0) {
// Nothing running resolves quietly; a rejection means the ssh process
// may still be up, and its message carries the PID to kill by hand.
stopTunnel().catch((cause) =>
dispatch(
showInfoDialog({
title: 'Could not close the internet connection',
message: String(cause),
variant: 'error',
}),
),
);
}
}, [shares, dispatch]);

// Every share an album has, not just its newest: an album can be shared more
// than once, and each token serves it until it is revoked.
const sharesByAlbum = new Map<string, Share[]>();
Expand Down
Loading