simplify(pr-ready step 3): collapse duplicated branches and dead code

- config: one _keys_by_label grouping serves both the unique-label map
  and the shared-label warning.
- claim_session: one abort-and-raise for either refused pick; the
  newest-save lookup is a single conditional expression.
- launch: pick refusal fields off one optional ImportRefusedError.
- imports: skip_state is always true for a foreign save archive; drop an
  unreachable KeyError and the unused str form of _read_member.
- webstation: ImportSpec.state_channel is a Literal.
- Stream.vue: the 400 refusal hint folds into the generic server branch;
  pickableStates drops a guard nativeStreamStates already has.
This commit is contained in:
Zach Clendenen committed 2026-09-25 19:20:30 -05:00
1 parent b6f2abb30f
commit 9ade9dfdb8
6 files changed
+47 -54

No files matched your search

+16 -19
View File
@@ -870,14 +870,13 @@ async def claim_session(
newest_state = max(own_states, key=lambda s: (s.created_at, s.id), default=None)
state_off_archive = newest_state is None or newest_state.id != resume_state.id
if not state_off_archive and picked_save is not None:
newest_save = None
if not save_foreign:
newest_save = await asyncio.to_thread(
saves.newest_restorable,
request.user.id,
rom.id,
container.emulator,
newest_save = (
None
if save_foreign
else await asyncio.to_thread(
saves.newest_restorable, request.user.id, rom.id, container.emulator
)
)
state_off_archive = newest_save is None or newest_save.id != picked_save.id
# The pre-win checks asked the pool's reference; the won container's own
@@ -887,19 +886,17 @@ async def claim_session(
spec = await asyncio.to_thread(
webstation.import_spec, container, container.emulator, container.platform
)
if resume_foreign:
import_slot = spec.resume_slot() if spec is not None else None
if import_slot is None:
await lifecycle.abort_claim(session_key, session)
raise HTTPException(
status_code=400, detail="This container cannot resume the picked state"
)
resume_slot = import_slot
if save_foreign and (spec is None or not spec.accepts("save")):
import_slot = spec.resume_slot() if spec is not None else None
refusal = None
if resume_foreign and import_slot is None:
refusal = "This container cannot resume the picked state"
elif save_foreign and (spec is None or not spec.accepts("save")):
refusal = "This container cannot restore the picked save"
if refusal is not None:
await lifecycle.abort_claim(session_key, session)
raise HTTPException(
status_code=400, detail="This container cannot restore the picked save"
)
raise HTTPException(status_code=400, detail=refusal)
if resume_foreign:
resume_slot = import_slot
resume_via_import = (
(resume_foreign or state_off_archive)
and spec is not None
+12 -9
View File
@@ -12,7 +12,6 @@ from __future__ import annotations
import hashlib
import json
import secrets
from collections import Counter
from collections.abc import Iterable, Sequence
from dataclasses import dataclass
from typing import Any
@@ -630,15 +629,22 @@ def _container_labels(resolved: Iterable[ResolvedContainer]) -> dict[str, str]:
return labels
def _keys_by_label(labels: dict[str, str]) -> list[list[str]]:
"""Container keys grouped by their case-folded label."""
groups: dict[str, list[str]] = {}
for key, label in labels.items():
groups.setdefault(label.casefold(), []).append(key)
return list(groups.values())
def _unique_labels(resolved: Sequence[ResolvedContainer]) -> dict[str, str]:
"""The labels that name exactly one container and are not another's key."""
labels = _container_labels(resolved)
counts = Counter(label.casefold() for label in labels.values())
keys = {container.key for container in resolved if container.key}
return {
key: label
for key, label in labels.items()
if counts[label.casefold()] == 1 and label not in keys
group[0]: labels[group[0]]
for group in _keys_by_label(labels)
if len(group) == 1 and labels[group[0]] not in keys
}
@@ -648,10 +654,7 @@ def _warn_about_shared_labels(
"""Name every label a URL cannot use because it names several containers,
once a day per config."""
labels = _container_labels(resolved)
by_label: dict[str, list[str]] = {}
for key, label in labels.items():
by_label.setdefault(label.casefold(), []).append(key)
shared = [keys for keys in by_label.values() if len(keys) > 1]
shared = [keys for keys in _keys_by_label(labels) if len(keys) > 1]
if not shared or not _first_to_warn(f"labels:{fingerprint}"):
return
for keys in shared:
+4 -5
View File
@@ -74,7 +74,7 @@ def _utf8_zipinfo(name: str, source: zipfile.ZipInfo | None) -> zipfile.ZipInfo:
return info
def _read_member(zf: zipfile.ZipFile, info: zipfile.ZipInfo | str) -> bytes:
def _read_member(zf: zipfile.ZipFile, info: zipfile.ZipInfo) -> bytes:
"""An entry's bytes, inflated a chunk at a time so a size the header
understates fails the CRC check before it can exhaust memory."""
out = bytearray()
@@ -94,7 +94,7 @@ def _manifest_files(zf: zipfile.ZipFile) -> dict[str, dict[str, Any]]:
return {}
try:
manifest = json.loads(_read_member(zf, info))
except (json.JSONDecodeError, KeyError, UnicodeDecodeError):
except (json.JSONDecodeError, UnicodeDecodeError):
return {}
files = manifest.get("files") if isinstance(manifest, dict) else None
return {
@@ -171,9 +171,8 @@ def _write_member(
staged[path] = (member.content, entry, None)
return
with inner:
# Another emulator's save archive also carries its exit state, which
# a save pick must not bring along.
_stage_zip(inner, staged, budget, skip_state=member.kind == "save", place=place)
# Another emulator's save archive also carries its exit state.
_stage_zip(inner, staged, budget, skip_state=True, place=place)
def build_import_archive(
+3 -7
View File
@@ -115,11 +115,7 @@ async def run_launch(
except Exception as exc:
log.exception("launch failed, platform=%s", platform)
await lifecycle.abort_claim(session_key, session, blank_card_id)
refusals = None
refusals_truncated = 0
if isinstance(exc, broker.ImportRefusedError):
refusals_truncated = exc.truncated
refusals = exc.refusals
refused = exc if isinstance(exc, broker.ImportRefusedError) else None
await push_to_user(
session.get("user_id"),
"streaming:launch-failed",
@@ -128,8 +124,8 @@ async def run_launch(
container=session_key,
claimed_at=session["claimed_at"],
detail=_failure_detail(exc),
refusals=refusals,
refusals_truncated=refusals_truncated,
refusals=refused.refusals if refused else None,
refusals_truncated=refused.truncated if refused else 0,
).model_dump(),
)
return
+2 -2
View File
@@ -42,7 +42,7 @@ class ImportSpec:
"""What one (emulator, platform) pair accepts through a declared import."""
kinds: frozenset[str]
state_channel: str
state_channel: Literal["archive", "push", "none"]
state_slot: int | None
def accepts(self, kind: str) -> bool:
@@ -67,7 +67,7 @@ class ImportSpec:
# Per container, so one broker's answer never speaks for another. A 404 or 422
# holds for the worker's life, an answer for one claim's checks, a failure not at all.
_IMPORT_SPEC_TTL = 30.0
_import_spec_cache: dict[tuple[str, str, str], tuple[float, "ImportSpec | None"]] = {}
_import_spec_cache: dict[tuple[str, str, str], tuple[float, ImportSpec | None]] = {}
def _parse_import_spec(body: dict[str, Any]) -> ImportSpec | None:
+10 -12
View File
@@ -362,12 +362,11 @@ const nativeStreamStates = computed<UserStateSchema[]>(() => {
// Every state regardless of which emulator wrote it where the broker declares
// it can import one, which routes a foreign pick through the import path.
const pickableStates = computed<UserStateSchema[]>(() => {
if (!rom.value) return [];
return container.value?.import_kinds.includes("state")
? (rom.value.all_user_states ?? [])
: nativeStreamStates.value;
});
const pickableStates = computed<UserStateSchema[]>(() =>
container.value?.import_kinds.includes("state")
? (rom.value?.all_user_states ?? [])
: nativeStreamStates.value,
);
// Every capture is kept, so a heavy save-stater ends up with a history the
// horizontal strip buries. Grid and list trade thumbnail size for how many
@@ -981,18 +980,17 @@ async function onPlay(cardImport?: MemoryCardImport): Promise<void> {
});
errorHint.value = t("play.error-hint-not-configured");
}
} else if (status === 400 && typeof detail === "string") {
// A refused save/state pick carries a reason worth more than the generic hint.
errorType.value = "server";
errorMessage.value = t("play.stream-error-generic");
errorHint.value = detail;
} else {
errorType.value = "server";
// The axios message ("Request failed with status code 502") is English
// and says nothing the hint does not, so the title stays translated and
// the status carries the detail.
errorMessage.value = t("play.stream-error-generic");
errorHint.value = hintForStatus(status);
// A refused save/state pick carries a reason worth more than the generic hint.
errorHint.value =
status === 400 && typeof detail === "string"
? detail
: hintForStatus(status);
}
}