fix(stalker): preserve concurrent edit state

This commit is contained in:
4gray committed 2026-08-09 18:15:37 +02:00
1 parent a998b0ebdd
commit e4bee6da40
5 files changed
+127 -47

No files matched your search

+1 -1
View File
@@ -1263,7 +1263,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. If bounded discovery returns while abandoned authentication remains on the wire, the refusal is shown immediately but Add and every form field stay disabled until its settlement promise resolves.
- 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. A persisted `portalUrl` keeps the row on the Stalker save path even if legacy Xtream fields remain. 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; ordinary failure releases it without changing the saved or runtime connection. If discovery returns after its bounded drain while an abandoned authentication is still on the wire, that result carries its settlement promise and both reservations remain installed until it resolves, so catalog, watchdog, repair, or retry authentication cannot race a late `get_profile`. Once Save starts, navigation or dialog destruction does not discard a later successful result: `get_profile` may already have pinned the submitted serial/device identity remotely and cannot be recalled. That late commit uses `transformPlaylistMeta()` inside the per-playlist write queue to merge only connection/session fields into the current row, so newer title/EPG/metadata edits win; its returned row feeds the state-only update while success UI is suppressed. 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 configuration authority covers the observed full/simple mode as well as the session fingerprint, and both authenticated and direct simple requests cross its guard before dispatch and after transport, so a same-endpoint mode change rejects stale snapshots and completed responses in either direction. A changed authority may rebase only when the persisted row proves that it owns the same playlist ID, keeping delete/restore and backup merge 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. A metadata-only Save omits connection/mode fields from its queued update, so the stored connection stays byte-identical even if the dialog hydrated before a concurrent discovery committed; it skips discovery. A persisted `portalUrl` keeps the row on the Stalker save path even if legacy Xtream fields remain. 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; ordinary failure releases it without changing the saved or runtime connection. If discovery returns after its bounded drain while an abandoned authentication is still on the wire, that result carries its settlement promise and both reservations remain installed until it resolves, so catalog, watchdog, repair, or retry authentication cannot race a late `get_profile`. Once Save starts, navigation or dialog destruction does not discard a later successful result: `get_profile` may already have pinned the submitted serial/device identity remotely and cannot be recalled. That late commit uses `transformPlaylistMeta()` inside the per-playlist write queue to merge only connection/session fields into the current row, so newer title/EPG/metadata edits win; its returned row feeds the state-only update together with discovery's transient session patch, so NgRx replaces or clears its session fields while success UI is suppressed. 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 configuration authority covers the observed full/simple mode as well as the session fingerprint, and both authenticated and direct simple requests cross its guard before dispatch and after transport, so a same-endpoint mode change rejects stale snapshots and completed responses in either direction. A changed authority may rebase only when the persisted row proves that it owns the same playlist ID, keeping delete/restore and backup merge 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`. Before an unrecorded repair calls discovery, it verifies that the persisted row still owns the failing source, so a late pre-Edit request cannot authenticate against the old portal after Edit commits and invalidate the newly saved token. Its in-session override is bound to source endpoint, mode, device identity, and credentials; an Edit or backup restore with the same playlist ID but different connection metadata retires the override and token only after the persisted row confirms ownership and only if no explicit Edit took ownership during that read, so a delayed stale request cannot remove valid runtime state or a token negotiated by the overlapping Edit. Each repair installs a session-level authentication fence synchronously, drains the existing token slot before probing, and keeps request routing ahead of effective-connection selection until repair finishes; an abandoned transport keeps both the repair and session fences until it actually settles. 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. Lazy repair captures that generation before any probe-history row read and rechecks it with the active Edit fence before reserving discovery. A repair that started earlier is therefore discarded even if it was restoring a `discarded` history record or had already verified its row, so it cannot probe alongside Edit or restore an older endpoint, mode or token afterwards.
- 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.
+6 -2
View File
@@ -196,7 +196,9 @@ discovery, since every candidate shares the host.
The playlist-info Edit dialog compares URL, MAC, username/password, serial,
device IDs and signatures as one connection identity. A metadata-only edit
does not run discovery and preserves the stored connection byte-for-byte.
does not run discovery; its queued write omits every connection/mode field so
the current stored connection stays byte-for-byte, including when the dialog
was hydrated before an older discovery result committed.
Before enabling a Stalker form, the dialog loads the complete persisted
playlist row by ID. Electron's startup metadata projection omits payload-only
identity fields, so editing that summary directly could otherwise display and
@@ -231,7 +233,9 @@ complete merged playlist row before NgRx receives its state-only update and
before the app adapter replaces the active `StalkerStore` snapshot and
session/watchdog state, so persistence failure cannot expose a partial runtime
edit and metadata absent from the form (such as playback `Referer`/`Origin`)
survives the replacement.
survives the replacement. The state-only update reattaches the transient
session patch from discovery, because the persisted flat row deliberately does
not contain that field; this lets NgRx replace or clear its session projection.
Runtime configuration authority combines the session fingerprint with the
observed full/simple mode. Both authenticated calls and direct simple-mode
requests cross that guard before dispatch and again after transport, so a
@@ -753,14 +753,25 @@ describe('PlaylistInfoComponent', () => {
PlaylistActions.updatePlaylistMeta({
playlist: expect.objectContaining({
title: 'Renamed',
portalUrl: 'https://portal.example.com/c',
macAddress: '00:1a:79:aa:bb:cc',
username: 'subscriber',
password: 'secret',
stalkerSerialNumber: 'SERIAL',
}) as PlaylistMeta,
})
);
const dispatchedPlaylist = store.dispatch.mock.calls[0][0]
.playlist as PlaylistMeta;
expect(dispatchedPlaylist).not.toHaveProperty('portalUrl');
expect(dispatchedPlaylist).not.toHaveProperty(
'isFullStalkerPortal'
);
expect(dispatchedPlaylist).not.toHaveProperty('macAddress');
expect(dispatchedPlaylist).not.toHaveProperty('username');
expect(dispatchedPlaylist).not.toHaveProperty('password');
expect(dispatchedPlaylist).not.toHaveProperty(
'stalkerSerialNumber'
);
expect(dispatchedPlaylist).not.toHaveProperty('stalkerDeviceId1');
expect(dispatchedPlaylist).not.toHaveProperty('stalkerDeviceId2');
expect(dispatchedPlaylist).not.toHaveProperty('stalkerSignature1');
expect(dispatchedPlaylist).not.toHaveProperty('stalkerSignature2');
});
it.each([
@@ -807,10 +818,17 @@ describe('PlaylistInfoComponent', () => {
stalkerTimeslot: 4,
},
};
const {
stalkerSessionPatch,
...persistedPlaylistWithoutSessionPatch
} = resolvedPlaylist;
stalkerConnectionEditor.resolveConnection.mockResolvedValue({
status: STALKER_PLAYLIST_CONNECTION_EDITOR_STATUS.RESOLVED,
playlist: resolvedPlaylist,
});
stalkerConnectionEditor.applyResolvedConnection.mockResolvedValueOnce(
persistedPlaylistWithoutSessionPatch
);
component.playlistDetails
.get('portalUrl')
?.setValue('https://portal.example.com/c');
@@ -822,7 +840,10 @@ describe('PlaylistInfoComponent', () => {
expect(store.dispatch).toHaveBeenCalledWith(
PlaylistActions.updatePlaylistMeta({
playlist: resolvedPlaylist,
playlist: {
...persistedPlaylistWithoutSessionPatch,
stalkerSessionPatch,
},
persist: false,
})
);
@@ -832,6 +853,44 @@ describe('PlaylistInfoComponent', () => {
expect(dialogRef.close).toHaveBeenCalledTimes(1);
});
it('retains a simple-portal session clear in the state-only update', async () => {
await createStalkerComponent();
const resolvedPlaylist = {
...component.playlistDetails.getRawValue(),
portalUrl: 'https://portal.example.com/server/load.php',
isFullStalkerPortal: false,
stalkerSessionPatch: null,
};
const persistedPlaylist = {
...resolvedPlaylist,
stalkerSessionPatch: undefined,
};
stalkerConnectionEditor.resolveConnection.mockResolvedValue({
status: STALKER_PLAYLIST_CONNECTION_EDITOR_STATUS.RESOLVED,
playlist: resolvedPlaylist,
});
stalkerConnectionEditor.applyResolvedConnection.mockResolvedValueOnce(
persistedPlaylist
);
component.playlistDetails
.get('portalUrl')
?.setValue('https://portal.example.com/server/load.php');
await component.saveChanges(
component.playlistDetails.getRawValue() as PlaylistMeta
);
expect(store.dispatch).toHaveBeenCalledWith(
PlaylistActions.updatePlaylistMeta({
playlist: {
...persistedPlaylist,
stalkerSessionPatch: null,
},
persist: false,
})
);
});
it('does not route a Stalker edit through stale Xtream metadata', async () => {
runtime.supportsXtreamSqliteDataSource = true;
await createStalkerComponent({
@@ -855,6 +914,27 @@ describe('PlaylistInfoComponent', () => {
).toHaveBeenCalledTimes(1);
});
it('does not normalize Stalker credentials through stale Xtream metadata', async () => {
await createStalkerComponent({
serverUrl: 'https://old-xtream.example.com',
username: ' subscriber ',
password: ' secret ',
});
component.playlistDetails.get('title')?.setValue('Renamed');
await component.saveChanges(
component.playlistDetails.getRawValue() as PlaylistMeta
);
expect(
stalkerConnectionEditor.resolveConnection
).not.toHaveBeenCalled();
const dispatchedPlaylist = store.dispatch.mock.calls[0][0]
.playlist as PlaylistMeta;
expect(dispatchedPlaylist).not.toHaveProperty('username');
expect(dispatchedPlaylist).not.toHaveProperty('password');
});
it('persists a resolved edit when the component is destroyed during discovery', async () => {
await createStalkerComponent();
const resolvedPlaylist = {
@@ -1098,13 +1178,9 @@ describe('PlaylistInfoComponent', () => {
component.playlistDetails.value as PlaylistMeta
);
expect(store.dispatch).toHaveBeenCalledWith(
PlaylistActions.updatePlaylistMeta({
playlist: expect.objectContaining({
macAddress: 'legacy-device-42',
}) as PlaylistMeta,
})
);
const dispatchedPlaylist = store.dispatch.mock.calls[0][0]
.playlist as PlaylistMeta;
expect(dispatchedPlaylist).not.toHaveProperty('macAddress');
});
it('leaves a non-canonical MAC alone when focus passes through it', async () => {
@@ -1127,13 +1203,9 @@ describe('PlaylistInfoComponent', () => {
component.playlistDetails.value as PlaylistMeta
);
expect(store.dispatch).toHaveBeenCalledWith(
PlaylistActions.updatePlaylistMeta({
playlist: expect.objectContaining({
macAddress: '00-1a-79-aa-bb-cc',
}) as PlaylistMeta,
})
);
const dispatchedPlaylist = store.dispatch.mock.calls[0][0]
.playlist as PlaylistMeta;
expect(dispatchedPlaylist).not.toHaveProperty('macAddress');
});
it('leaves an untouched non-canonical MAC alone on an unrelated save', async () => {
@@ -1153,11 +1225,13 @@ describe('PlaylistInfoComponent', () => {
expect(store.dispatch).toHaveBeenCalledWith(
PlaylistActions.updatePlaylistMeta({
playlist: expect.objectContaining({
macAddress: '00-1a-79-aa-bb-cc',
title: 'Renamed',
}) as PlaylistMeta,
})
);
const dispatchedPlaylist = store.dispatch.mock.calls[0][0]
.playlist as PlaylistMeta;
expect(dispatchedPlaylist).not.toHaveProperty('macAddress');
});
it('does not claim a simple portal has pinned its device IDs', async () => {
@@ -46,7 +46,7 @@ import {
} from '@iptvnator/shared/m3u-utils';
import {
hasStalkerConnectionChanged,
preserveStalkerConnection,
omitStalkerConnection,
STALKER_PORTAL_URL_PATTERN,
} from './stalker-playlist-edit.utils';
import {
@@ -397,6 +397,8 @@ export class PlaylistInfoComponent {
}
let resolvedStalkerConnection = false;
let resolvedStalkerSessionPatch:
PlaylistMetaUpdate['stalkerSessionPatch'] | undefined;
let preserveCurrentMetadata = false;
let normalizedPlaylist: PlaylistMetaUpdate =
this.normalizeStalkerPlaylistMeta(
@@ -425,14 +427,14 @@ export class PlaylistInfoComponent {
return;
}
normalizedPlaylist = result.playlist;
resolvedStalkerSessionPatch =
result.playlist.stalkerSessionPatch;
resolvedStalkerConnection = true;
preserveCurrentMetadata =
this.dialogClosing || this.destroyRef.destroyed;
} else {
normalizedPlaylist = preserveStalkerConnection(
this.playlist,
normalizedPlaylist
);
normalizedPlaylist =
omitStalkerConnection(normalizedPlaylist);
}
}
const isXtream =
@@ -454,6 +456,10 @@ export class PlaylistInfoComponent {
: await this.stalkerConnectionEditor.applyResolvedConnection(
normalizedPlaylist
);
normalizedPlaylist = {
...normalizedPlaylist,
stalkerSessionPatch: resolvedStalkerSessionPatch,
};
}
// Resolved Stalker edits cross an awaited, atomic persistence
@@ -570,7 +576,12 @@ export class PlaylistInfoComponent {
}
private normalizeXtreamPlaylistMeta(playlist: PlaylistMeta): PlaylistMeta {
if (!playlist.serverUrl || !playlist.username || !playlist.password) {
if (
this.playlist.portalUrl ||
!playlist.serverUrl ||
!playlist.username ||
!playlist.password
) {
return playlist;
}
@@ -32,23 +32,14 @@ export function hasStalkerConnectionChanged(
);
}
/** Keeps an unchanged connection byte-identical during metadata-only edits. */
export function preserveStalkerConnection(
current: Playlist,
update: PlaylistMeta
): PlaylistMeta {
return {
...update,
portalUrl: current.portalUrl,
macAddress: current.macAddress,
username: current.username,
password: current.password,
stalkerSerialNumber: current.stalkerSerialNumber,
stalkerDeviceId1: current.stalkerDeviceId1,
stalkerDeviceId2: current.stalkerDeviceId2,
stalkerSignature1: current.stalkerSignature1,
stalkerSignature2: current.stalkerSignature2,
};
/** Lets the queued persistence boundary preserve its current connection. */
export function omitStalkerConnection(update: PlaylistMeta): PlaylistMeta {
const metadata = { ...update };
for (const field of STALKER_CONNECTION_FIELDS) {
delete metadata[field];
}
delete metadata.isFullStalkerPortal;
return metadata;
}
function comparableConnectionValue(