fix(stalker): release abandoned edit fences

This commit is contained in:
4gray committed 2026-08-09 13:53:04 +02:00
1 parent 854eb2c2e9
commit a41a1d352a
8 files changed
+148 -7

No files matched your search

+2 -1
View File
@@ -5,4 +5,5 @@ area: stalker
Stalker setup now accepts a host or `/c` address, discovers the working API
endpoint and authentication mode, and rechecks connection details edited
later. Failed edits leave the saved playlist and active session unchanged.
later. Canceled or failed edits leave the saved playlist and active session
unchanged.
+1 -1
View File
@@ -1262,7 +1262,7 @@ engine` (restart required) or
- Portal mode (full vs. simple) follows OBSERVED behavior, never a URL substring. The single predicate is `isFullStalkerPortalPlaylist()` / `isFullStalkerPortalUrl()` in `@iptvnator/shared/interfaces` (`stalker-portal-mode.util.ts`): the persisted `Playlist.isFullStalkerPortal` flag is authoritative and the URL shape is a fallback for legacy rows only. Three diverging copies of this rule used to exist and shipped broken configurations (#850/#686/#755) — never re-implement it. A token-enforcing `portal.php` panel is a full portal; a `server/load.php` endpoint that answers without a token is a simple one.
- Import requires an explicit HTTP(S) scheme but accepts a bare host, `/c`, or a concrete `.php` address. It probes candidates in order (a pasted `.php` endpoint first, then `<base>/portal.php` → `<base>/server/load.php` → `<base>/stalker_portal/server/load.php`) and classifies each by behavior — a token-less `itv/get_genres` returning data proves a token-free panel; the plain-text auth failure proves a full portal, confirmed by a real handshake + `get_profile`. `StalkerPortalDiscoveryService` (`libs/portal/stalker/data-access`) persists and displays the proven endpoint and mode. An unreachable panel-style import remains allowed with a warning; a bare host falls back to `<base>/portal.php`, while canonical-shaped unreachable addresses still abort.
- The playlist-info Edit dialog loads the complete persisted Stalker row before enabling the form, because Electron's startup metadata projection omits payload-only serial/device/signature/mode fields; a summarized row must never render and then persist an empty portal identity. It preserves an unchanged connection byte-for-byte and skips discovery. Changing URL, MAC, credentials, serial, device IDs or signatures blocks duplicate saves, disables dialog closure for the validation window, and runs the existing discovery service through the app-provided `STALKER_PLAYLIST_CONNECTION_EDITOR` token, keeping Stalker data-access out of `playlist-shared-ui`. Before discovery it reserves the playlist ID; a second Edit cannot replace that owner. The reservation blocks every new authentication (including fingerprint-equivalent URL edits) and repair, drains existing work, and rechecks ownership after every asynchronous drain/rebase; failure releases it without changing the saved or runtime connection. Success uses one awaited write to atomically replace endpoint, mode, normalized identity and session metadata, then feeds its complete merged row into the state-only NgRx update and active `StalkerStore`/session/watchdog replacement before another same-route request can use the old connection. This preserves playback headers and other metadata absent from the form. Runtime session authority may rebase a changed fingerprint only when the persisted row proves that it owns the same playlist ID, so delete/restore and backup merge remain usable. The transient `PlaylistMetaUpdate.stalkerSessionPatch` preserves on absence, clears on `null`, and fully replaces from an object before storage; it is projected onto existing flat playlist fields and never changes the DB or backup shape.
- The playlist-info Edit dialog loads the complete persisted Stalker row before enabling the form, because Electron's startup metadata projection omits payload-only serial/device/signature/mode fields; a summarized row must never render and then persist an empty portal identity. It preserves an unchanged connection byte-for-byte and skips discovery. Changing URL, MAC, credentials, serial, device IDs or signatures blocks duplicate saves, disables dialog closure for the validation window, and runs the existing discovery service through the app-provided `STALKER_PLAYLIST_CONNECTION_EDITOR` token, keeping Stalker data-access out of `playlist-shared-ui`. Before discovery it reserves the playlist ID; a second Edit cannot replace that owner. The reservation blocks every new authentication (including fingerprint-equivalent URL edits) and repair, drains existing work, and rechecks ownership after every asynchronous drain/rebase; failure releases it without changing the saved or runtime connection. If navigation or another owner closes/destroys the dialog while discovery is in flight, the UI discards a later successful result through `discardResolvedConnection()` and releases both reservations without persisting it. Success uses one awaited write to atomically replace endpoint, mode, normalized identity and session metadata, then feeds its complete merged row into the state-only NgRx update and active `StalkerStore`/session/watchdog replacement before another same-route request can use the old connection. This preserves playback headers and other metadata absent from the form. Runtime session authority may rebase a changed fingerprint only when the persisted row proves that it owns the same playlist ID, so delete/restore and backup merge remain usable. The transient `PlaylistMetaUpdate.stalkerSessionPatch` preserves on absence, clears on `null`, and fully replaces from an object before storage; it is projected onto existing flat playlist fields and never changes the DB or backup shape.
- `executeStalkerRequest()` (`stores/utils/stalker-request.utils.ts`) is the choke point for catalog, content and playback requests: mode routing, the in-session repair override, and retry-once all live there. Four callers are deliberately outside it because they run below or before the thing it routes on — `StalkerAuthApi` (handshake/`get_profile`/`do_auth`, which the full-portal branch is built from; routing them back would recurse), `StalkerPortalDiscoveryService` (probes precede the mode they determine), `StalkerAccountInfoService.fetchViaProfile()`, and `StreamResolverService` for a collection item with no playlist row. They are exempt from the routing, not from the repair it hooks, but only `fetchViaProfile()` wires `StalkerPortalRepairService` itself: discovery is what repair _drives_, the row-less resolver branch has no playlist to repair, and the auth layer needs nothing — a terminal handshake failure propagates out of the full-portal branch into whichever `executeStalkerRequest()` call triggered the authentication, which is why terminal handshake failures are a repair trigger. Anything new that is not auth or discovery belongs on `executeStalkerRequest()`. Existing playlists are repaired LAZILY (`StalkerPortalRepairService`) — only after a request fails with a shape a wrong endpoint/mode produces, at most once per source configuration per playlist per session, persisted through the atomic `PlaylistsService.transformPlaylistMeta`. There is deliberately **no eager one-shot migration**: a portal that works is never re-probed.
- Explicit Edit advances the repair generation before installing its resolved session. A lazy repair that started earlier is discarded even if it had already verified its row, so it cannot restore an older endpoint, mode or token after Edit.
- Both transports build the wire format from the same shared builders in `@iptvnator/shared/interfaces` — `buildStalkerRequestUrl()`, `buildStalkerIdentityRequestContext()`, `encodeStalkerCmdValue()` — so the Electron and PWA legs cannot drift. The mock's `/stalker` mirror shares the identity builder only — it dispatches in-process, so there is no portal URL to build and it mirrors the `JsHttpRequest` default by hand. Never fork any of them.
@@ -126,6 +126,23 @@ describe('AppStalkerPlaylistConnectionEditorService', () => {
});
});
it('releases a successful discovery fence when the resolved edit is discarded', async () => {
discovery.discover.mockResolvedValue({
status: 'resolved',
portalUrl: 'https://portal.example.com/portal.php',
isFullStalkerPortal: false,
});
await service.resolveConnection(draft);
service.discardResolvedConnection(draft._id);
expect(stalkerSession.cancelEditDiscovery).toHaveBeenCalledWith(
expect.objectContaining({ playlistId: draft._id })
);
expect(portalRepair.releasePlaylistEdit).toHaveBeenCalledWith(
draft._id
);
});
it('replaces a full-portal session with the confirmed authorization result', async () => {
discovery.discover.mockResolvedValue({
status: 'resolved',
@@ -77,6 +77,13 @@ export class AppStalkerPlaylistConnectionEditorService implements StalkerPlaylis
}
}
discardResolvedConnection(playlistId: string): void {
const fence = this.editFences.get(playlistId);
if (fence) {
this.releaseEditFence(playlistId, fence);
}
}
async resolveConnection(
playlist: PlaylistMeta
): Promise<StalkerPlaylistConnectionResult> {
+8 -4
View File
@@ -204,7 +204,10 @@ then persist empty serial, device ID, signature, or mode values.
Changing any connection field disables the form while the same discovery
service validates the draft. Auth rejection or an unreachable portal leaves
the dialog open and writes nothing. Escape/backdrop closure is disabled for the
validation window. Before discovery starts, Edit reserves the playlist ID; an
validation window. If navigation or another owner starts closing/destroys the
dialog while discovery is in flight, the successful result is discarded before
persistence and both the session and repair reservations are released. Before
discovery starts, Edit reserves the playlist ID; an
overlapping Edit cannot replace that owner. The reservation blocks every new
authentication (including a URL edit with the same normalized fingerprint) and
repair, and drains any work already in flight. Ownership is rechecked after
@@ -231,9 +234,10 @@ schema or backup-version migration is required.
The shared playlist UI exposes only
`STALKER_PLAYLIST_CONNECTION_EDITOR` and its
`resolved | auth-rejected | unreachable` result contract. The web composition
layer implements the token with Stalker data-access; the UI library must not
import Stalker discovery directly.
`resolved | auth-rejected | unreachable` result contract, plus the narrow
`discardResolvedConnection()` cleanup hook for a closing dialog. The web
composition layer implements the token with Stalker data-access; the UI library
must not import Stalker discovery directly.
**Lazy repair (existing playlists).** The flag is frozen in the DB, so
records persisted by the old guess stay broken without repair — but a large
@@ -51,10 +51,14 @@ describe('PlaylistInfoComponent', () => {
dispatch: jest.Mock;
};
let dialogRef: {
beforeClosed: jest.Mock;
close: jest.Mock;
disableClose: boolean;
};
let dialogBeforeClosed: Subject<void>;
let stalkerConnectionEditor: {
applyResolvedConnection: jest.Mock;
discardResolvedConnection: jest.Mock;
resolveConnection: jest.Mock;
};
const originalElectron = window.electron;
@@ -105,12 +109,15 @@ describe('PlaylistInfoComponent', () => {
store = {
dispatch: jest.fn(),
};
dialogBeforeClosed = new Subject<void>();
dialogRef = {
beforeClosed: jest.fn(() => dialogBeforeClosed),
close: jest.fn(),
disableClose: false,
};
stalkerConnectionEditor = {
applyResolvedConnection: jest.fn().mockResolvedValue(undefined),
discardResolvedConnection: jest.fn(),
resolveConnection: jest.fn(
async (updatedPlaylist: PlaylistMeta) => ({
status: STALKER_PLAYLIST_CONNECTION_EDITOR_STATUS.RESOLVED,
@@ -825,6 +832,98 @@ describe('PlaylistInfoComponent', () => {
expect(dialogRef.close).toHaveBeenCalledTimes(1);
});
it('discards a resolved edit when the dialog closes before discovery finishes', async () => {
await createStalkerComponent();
const resolvedPlaylist = {
...component.playlistDetails.getRawValue(),
portalUrl: 'https://portal.example.com/server/load.php',
isFullStalkerPortal: true,
stalkerSessionPatch: {
stalkerToken: 'NEW_TOKEN',
stalkerSessionIdentity: 'new-fingerprint',
},
};
let finishDiscovery:
| ((value: {
status: 'resolved';
playlist: typeof resolvedPlaylist;
}) => void)
| undefined;
stalkerConnectionEditor.resolveConnection.mockReturnValueOnce(
new Promise((resolve) => {
finishDiscovery = resolve;
})
);
component.playlistDetails
.get('portalUrl')
?.setValue('https://new.example.com');
const saving = component.saveChanges(
component.playlistDetails.getRawValue() as PlaylistMeta
);
await Promise.resolve();
fixture.destroy();
finishDiscovery?.({
status: STALKER_PLAYLIST_CONNECTION_EDITOR_STATUS.RESOLVED,
playlist: resolvedPlaylist,
});
await saving;
expect(
stalkerConnectionEditor.discardResolvedConnection
).toHaveBeenCalledWith('playlist-1');
expect(
stalkerConnectionEditor.applyResolvedConnection
).not.toHaveBeenCalled();
expect(store.dispatch).not.toHaveBeenCalled();
});
it('discards a resolved edit while the dialog close animation is pending', async () => {
await createStalkerComponent();
const resolvedPlaylist = {
...component.playlistDetails.getRawValue(),
portalUrl: 'https://portal.example.com/server/load.php',
isFullStalkerPortal: true,
stalkerSessionPatch: {
stalkerToken: 'NEW_TOKEN',
stalkerSessionIdentity: 'new-fingerprint',
},
};
let finishDiscovery:
| ((value: {
status: 'resolved';
playlist: typeof resolvedPlaylist;
}) => void)
| undefined;
stalkerConnectionEditor.resolveConnection.mockReturnValueOnce(
new Promise((resolve) => {
finishDiscovery = resolve;
})
);
component.playlistDetails
.get('portalUrl')
?.setValue('https://new.example.com');
const saving = component.saveChanges(
component.playlistDetails.getRawValue() as PlaylistMeta
);
await Promise.resolve();
dialogBeforeClosed.next();
finishDiscovery?.({
status: STALKER_PLAYLIST_CONNECTION_EDITOR_STATUS.RESOLVED,
playlist: resolvedPlaylist,
});
await saving;
expect(
stalkerConnectionEditor.discardResolvedConnection
).toHaveBeenCalledWith('playlist-1');
expect(
stalkerConnectionEditor.applyResolvedConnection
).not.toHaveBeenCalled();
expect(store.dispatch).not.toHaveBeenCalled();
});
it('does not update UI state or report success when resolved persistence fails', async () => {
const consoleError = jest
.spyOn(console, 'error')
@@ -1,6 +1,6 @@
import { Clipboard, ClipboardModule } from '@angular/cdk/clipboard';
import { DatePipe } from '@angular/common';
import { Component, inject, signal } from '@angular/core';
import { Component, DestroyRef, inject, signal } from '@angular/core';
import {
FormControl,
ReactiveFormsModule,
@@ -184,6 +184,7 @@ export class PlaylistInfoComponent {
private runtime = inject(RuntimeCapabilitiesService);
private readonly epgBridge = inject(EpgRuntimeBridgeService);
private readonly settingsStore = inject(SettingsStore);
private readonly destroyRef = inject(DestroyRef);
private readonly stalkerConnectionEditor = inject(
STALKER_PLAYLIST_CONNECTION_EDITOR
);
@@ -194,6 +195,7 @@ export class PlaylistInfoComponent {
readonly isSaving = signal(false);
readonly isHydratingStalkerPlaylist = signal(false);
readonly stalkerPlaylistHydrationFailed = signal(false);
private dialogClosing = false;
private readonly stalkerPlaylistHydration: Promise<void>;
get isDesktop(): boolean {
@@ -296,6 +298,9 @@ export class PlaylistInfoComponent {
playlistDetails!: UntypedFormGroup;
constructor() {
this.dialogRef?.beforeClosed().subscribe(() => {
this.dialogClosing = true;
});
this.playlist = this.playlistData;
this.createForm();
if (this.playlist.portalUrl) {
@@ -418,6 +423,12 @@ export class PlaylistInfoComponent {
);
return;
}
if (this.dialogClosing || this.destroyRef.destroyed) {
this.stalkerConnectionEditor.discardResolvedConnection(
result.playlist._id
);
return;
}
normalizedPlaylist = result.playlist;
resolvedStalkerConnection = true;
} else {
@@ -40,6 +40,8 @@ export interface StalkerPlaylistConnectionEditor {
): Promise<StalkerPlaylistConnectionResult>;
/** Atomically persists a resolved edit, then synchronizes in-run state. */
applyResolvedConnection(playlist: PlaylistMetaUpdate): Promise<void>;
/** Releases a resolved edit that the dialog closed without applying. */
discardResolvedConnection(playlistId: string): void;
}
export const STALKER_PLAYLIST_CONNECTION_EDITOR =