Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
49 changes: 48 additions & 1 deletion cli/sidecart.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@
5 server returned 400 / 422 / other 4xx
6 server returned 503 (busy or SD unmounted)
7 server returned 5xx other than 503
8 network / DNS error (couldn't reach the host)
8 network error: couldn't reach the host, or it dropped the
connection (a reboot, a panic or a SELECT press all look like this)

Examples:
python3 cli/sidecart.py ping
Expand All @@ -57,6 +58,7 @@
import http.client
import json
import os
import socket
import sys
import urllib.error
import urllib.parse
Expand All @@ -67,6 +69,30 @@
USER_AGENT = "sidecart-cli/0.1"
REQUEST_TIMEOUT_S = 10

# The device dropping a connection is a normal thing to survive -- it reboots
# on a watchdog, a panic or a SELECT press, and the HTTP server closes idle
# connections on purpose. urllib only wraps some of that in URLError; the rest
# escapes as a bare OSError and used to reach the user as a traceback
# (EPIC-15 STORY-03). IncompleteRead is in here because a chunked body cut
# short raises it rather than an OSError.
CONNECTION_DROPPED = (
ConnectionResetError,
ConnectionAbortedError,
BrokenPipeError,
http.client.RemoteDisconnected,
http.client.IncompleteRead,
socket.timeout,
TimeoutError,
)


def _dropped(operation: str, exc: BaseException) -> int:
"""Report a dropped connection as one line and the network exit code."""
detail = str(exc) or exc.__class__.__name__
print(f"error: {operation}: connection dropped by the device ({detail})",
file=sys.stderr)
return EXIT_NETWORK

# Granular exit-code map (see docs/epics/02-http-api.md "CLI / Exit code
# map"). Lets shell scripts branch on category.
EXIT_OK = 0
Expand Down Expand Up @@ -143,6 +169,12 @@ def request_json(method: str, url: str, *, body: bytes | None = None,
with urllib.request.urlopen(req, timeout=timeout) as resp:
raw = resp.read()
status = resp.status
except CONNECTION_DROPPED as exc:
# Re-raised as URLError so the callers' existing handling applies;
# the reason carries what actually happened.
detail = str(exc) or exc.__class__.__name__
raise urllib.error.URLError(
f"connection dropped by the device ({detail})") from exc
except urllib.error.HTTPError as exc:
# Server returned >= 400 — read its body so we can render the
# error envelope, then close the response handle to silence
Expand Down Expand Up @@ -408,6 +440,8 @@ def cmd_get(args: argparse.Namespace) -> int:
req = urllib.request.Request(url, headers=headers, method="GET")
try:
resp = urllib.request.urlopen(req, timeout=REQUEST_TIMEOUT_S)
except CONNECTION_DROPPED as exc:
return _dropped(f"downloading {url}", exc)
except urllib.error.HTTPError as exc:
try:
raw = exc.read() if exc.fp is not None else b""
Expand Down Expand Up @@ -464,6 +498,13 @@ def cmd_get(args: argparse.Namespace) -> int:
# Newline after the progress line.
sys.stderr.write("\n")
sys.stderr.flush()
except CONNECTION_DROPPED as exc:
# Mid-transfer: the partial file is left in place so --resume can pick
# it up, which is the whole reason that option exists.
if not args.quiet:
sys.stderr.write("\n")
sys.stderr.flush()
return _dropped(f"downloading {url}", exc)
finally:
resp.close()

Expand Down Expand Up @@ -843,6 +884,8 @@ def cmd_debug_tail(args: argparse.Namespace) -> int:
try:
# No timeout — we deliberately want to block forever.
resp = urllib.request.urlopen(req, timeout=None)
except CONNECTION_DROPPED as exc:
return _dropped(f"tailing {url}", exc)
except urllib.error.HTTPError as exc:
# Non-200 from the server — render the error envelope if any.
try:
Expand Down Expand Up @@ -875,6 +918,10 @@ def cmd_debug_tail(args: argparse.Namespace) -> int:
out.flush()
except KeyboardInterrupt:
return EXIT_OK
except CONNECTION_DROPPED as exc:
# A tail is long-lived by design, so the device rebooting under it is
# the expected way for this to end, not an anomaly.
return _dropped(f"tailing {url}", exc)
finally:
resp.close()
return EXIT_OK
Expand Down
95 changes: 95 additions & 0 deletions cli/test_sidecart.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
import io
import json
import os
import socket
import struct
import sys
import tempfile
import threading
Expand Down Expand Up @@ -1714,3 +1716,96 @@ def test_known_codes(self) -> None:

if __name__ == "__main__":
unittest.main()


class _ResettingServer:
"""A server that accepts a connection and then drops it mid-response.

Covers what the device does when it reboots under a command: a watchdog,
a panic or a SELECT press all cut the socket without a reply, and urllib
surfaces that as ConnectionResetError or RemoteDisconnected rather than
URLError (EPIC-15 STORY-03).
"""

def __init__(self, mode: str = "immediate") -> None:
self.mode = mode
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind(("127.0.0.1", 0))
self.sock.listen(4)
self.port = self.sock.getsockname()[1]
self.host = f"127.0.0.1:{self.port}"
self.thread = threading.Thread(target=self._serve, daemon=True)
self.running = True
self.thread.start()

def _serve(self) -> None:
while self.running:
try:
conn, _addr = self.sock.accept()
except OSError:
return
try:
conn.recv(65536)
if self.mode == "partial":
# Headers promising a body, then the socket dies: this is
# what a reboot mid-download looks like.
conn.sendall(
b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n"
b"Content-Length: 1000\r\n\r\n" + b"x" * 10)
# Reset rather than a clean close, so the client sees ECONNRESET.
conn.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER,
struct.pack("ii", 1, 0))
except OSError:
pass
finally:
with contextlib.suppress(OSError):
conn.close()

def close(self) -> None:
self.running = False
with contextlib.suppress(OSError):
self.sock.close()
self.thread.join(timeout=2)


class DroppedConnectionTests(unittest.TestCase):
"""A device that drops the connection must never print a traceback."""

def _assert_clean_network_error(self, code: int, out: str, err: str) -> None:
self.assertEqual(code, sidecart.EXIT_NETWORK)
self.assertNotIn("Traceback", err)
self.assertNotIn("Traceback", out)
# Exactly one line, and it is an error line.
lines = [ln for ln in err.strip().splitlines() if ln.strip()]
self.assertEqual(len(lines), 1, f"expected one line, got: {lines!r}")
self.assertTrue(lines[0].startswith("error:"), lines[0])

def test_reset_before_reply(self) -> None:
server = _ResettingServer("immediate")
self.addCleanup(server.close)
code, out, err = _run_cli(["--host", server.host, "ping"])
self._assert_clean_network_error(code, out, err)

def test_reset_on_json_command(self) -> None:
server = _ResettingServer("immediate")
self.addCleanup(server.close)
code, out, err = _run_cli(
["--host", server.host, "gemdrive", "ls", "/"])
self._assert_clean_network_error(code, out, err)

def test_reset_mid_download(self) -> None:
server = _ResettingServer("partial")
self.addCleanup(server.close)
with tempfile.TemporaryDirectory() as tmp:
dest = os.path.join(tmp, "out.bin")
code, out, err = _run_cli(
["--host", server.host, "-q", "gemdrive", "get", "/A.BIN",
dest])
self._assert_clean_network_error(code, out, err)

def test_reset_on_health(self) -> None:
server = _ResettingServer("immediate")
self.addCleanup(server.close)
code, out, err = _run_cli(["--host", server.host, "health"])
self._assert_clean_network_error(code, out, err)
13 changes: 10 additions & 3 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ python3 cli/sidecart.py gemdrive rm SWITCHER.TOS
| `416 Range Not Satisfiable` | Range outside file bounds. Carries `Content-Range: bytes */<size>`. |
| `422 Unprocessable Entity` | Malformed JSON body, missing required field, listing-on-file, rename-into-own-descendant. |
| `500 Internal Server Error` | FatFs disk error. |
| `503 Service Unavailable` | Body-stream lock held, SD not mounted, Runner busy with another command, or `insufficient_memory`: FatFs could not allocate its working buffer, so the operation can be retried when memory frees up. Always carries `Retry-After: 1`. |
| `503 Service Unavailable` | Body-stream lock held (`busy`), no usable SD card (`no_sd_card`), Runner busy with another command (`busy`), or `insufficient_memory`: FatFs could not allocate its working buffer, so the operation can be retried when memory frees up. Always carries `Retry-After: 1`. |
| `504 Gateway Timeout` | Synchronous Runner endpoint exceeded its server-side spin-wait deadline (`gateway_timeout`). Per-endpoint deadlines: `runner load` 10 s; `runner unload` 5 s; `runner meminfo`, `runner adv/meminfo`, and each `runner adv/load` chunk 1 s. |

## Error code vocabulary
Expand All @@ -99,11 +99,18 @@ Clients can switch on `code` reliably. All defined symbols:
`bad_request`, `bad_path`, `bad_query`, `name_too_long`, `not_found`,
`is_directory`, `is_file`, `conflict`, `length_required`,
`payload_too_large`, `range_invalid`, `bad_json`, `unprocessable`,
`unsupported_media`, `method_not_allowed`, `busy`, `disk_error`,
`unsupported_media`, `method_not_allowed`, `busy`, `no_sd_card`, `disk_error`,
`insufficient_memory`, `internal_error`, `runner_inactive`, `gateway_timeout`, `no_snapshot`,
`wrong_hook`, `ram_overflow`, `pexec_failed`, `mfree_failed`,
`program_already_loaded`, `no_program_loaded`.

`no_sd_card` — there is no usable SD card mounted. **Every** endpoint that
needs the card answers this the same way: `volume`, listings, downloads,
uploads, folder operations, `runner load` and `runner run`. It is not a fault
to recover from by hand: the firmware retries the mount every two seconds, so
inserting a working card clears it within a few seconds with no reset, and the
setup menu shows `SD: NO CARD` meanwhile and refuses `[G]` and `[U]`.

Runner-specific codes (see *Runner mode* below):
- `runner_inactive` — the user didn't pick `[U]` at boot.
- `busy` — another foreground Runner command is in flight. Every
Expand Down Expand Up @@ -235,7 +242,7 @@ python3 cli/sidecart.py health
`UNKNOWN` (the SD card mounted but FatFs reported a filesystem
type the firmware doesn't have a string for).

**Errors:** `503 busy` if the SD card is not mounted.
**Errors:** `503 no_sd_card` if no usable SD card is mounted.

**`curl`**:
```sh
Expand Down
61 changes: 60 additions & 1 deletion rp/src/emul.c
Original file line number Diff line number Diff line change
Expand Up @@ -632,6 +632,13 @@ static void drawSetupInfoLine(const char *message) {
// Set when [G] or [U] was refused because no HELLO arrived since the RP
// booted (see emul_canLaunch). Cleared when HELLO lands.
static bool launchNeedsStReset = false;
// Set when [G] or [U] was refused because no usable SD card is mounted
// (EPIC-15 STORY-02). Cleared as soon as a card appears; the retry loop in
// sdcard_pollRemount is what makes that happen without a reset.
static bool launchNeedsSdCard = false;
// Tracks the card state the menu was last drawn with, so the line is redrawn
// when it changes rather than on every pass.
static bool lastDrawnSdMounted = false;
// True while the countdown itself is launching, so a refusal can restart the
// countdown once HELLO lands instead of leaving it stopped.
static bool countdownLaunching = false;
Expand All @@ -646,6 +653,8 @@ static void drawHaltedInfoLine(void) {
drawSetupInfoLine(
settingsSaveFailed
? "Saving the settings failed: the change was not stored."
: launchNeedsSdCard
? "Insert a working microSD card: GEMDRIVE needs one."
: launchNeedsStReset
? "Reset the Atari ST first: no HELLO since RP boot."
: "Countdown stopped. Press [G], [U] or [X] to continue.");
Expand Down Expand Up @@ -803,6 +812,14 @@ static uint32_t emul_devhooksApp(uint16_t commandId, const uint16_t *payload,
DPRINTF("devhooks: slow connect returned %d\n", (int)rc);
return 1;
}
case DEVHOOKS_APP_GEMDRIVE_STALL: {
uint16_t chunks = (payloadSize >= 2u) ? payload[0] : 1u;
uint16_t ds = (payloadSize >= 4u) ? payload[1] : 0u;
gemdrive_setWriteStall(chunks, ds);
DPRINTF("devhooks: stalling the next %u write chunk(s) by %u ds\n",
(unsigned)chunks, (unsigned)ds);
return 1;
}
case DEVHOOKS_APP_COUNTDOWN_STOP:
haltCountdown = true;
return 1;
Expand Down Expand Up @@ -1312,7 +1329,13 @@ static void menu(void) {

// Folder + drive read straight from aconfig, like source/md-drives.
vt52Cursor(2, 0);
term_printString("GEMDRIVE\n");
// The card's state goes on the header line, not a row of its own: the
// section dividers are at fixed pixel rows and the status icons are
// right-aligned per header row, so an extra line shifts every section below
// into them (EPIC-15 STORY-02). Kept short to clear the drive icon on the
// right.
term_printString(sdcard_isMounted() ? "GEMDRIVE SD: mounted\n"
: "GEMDRIVE SD: NO CARD\n");

SettingsConfigEntry *gemDriveFolder =
settings_find_entry(aconfig_getContext(), ACONFIG_PARAM_GEMDRIVE_FOLDER);
Expand Down Expand Up @@ -1514,6 +1537,17 @@ static void showCounter(int cdown) {
// run's shared variables survived in uncleared RAM.
static bool emul_canLaunch(void) {
haltCountdown = true;
// Without a card there is nothing to emulate a drive from, and both modes
// would come up broken. Refuse and say so; sdcard_pollRemount keeps trying,
// so inserting one clears this within a couple of seconds (EPIC-15 STORY-02).
if (!sdcard_isMounted()) {
DPRINTF("Launch refused: no SD card mounted\n");
launchNeedsSdCard = true;
restartCountdownOnHello = countdownLaunching;
menu();
display_refresh();
return false;
}
if (gemdrive_getPhystop(NULL, NULL)) return true;
DPRINTF("Launch refused: no HELLO from the ST since the RP booted\n");
launchNeedsStReset = true;
Expand Down Expand Up @@ -2186,6 +2220,31 @@ void emul_start() {
// press (≥ SELECT_LONG_RESET ms) fires reset_deviceAndEraseFlash.
select_checkPushReset();

// Bring a reinserted SD card back without a reset (EPIC-15 STORY-01).
// Cheap while the card is mounted.
sdcard_pollRemount();

// Follow the card's state on the menu, and lift the launch block as soon
// as a usable card appears (EPIC-15 STORY-02).
bool sdMountedNow = sdcard_isMounted();
if (sdMountedNow != lastDrawnSdMounted) {
lastDrawnSdMounted = sdMountedNow;
if (sdMountedNow && launchNeedsSdCard) {
launchNeedsSdCard = false;
if (restartCountdownOnHello) {
restartCountdownOnHello = false;
(void)term_consumeAnyKeyPressed();
countdown = BOOT_COUNTDOWN_SECONDS;
lastCountdownTick = get_absolute_time();
haltCountdown = false;
}
}
if (menuScreenActive) {
menu();
display_refresh();
}
}

// Heap sampling, the debug summary and debug test hooks.
health_tick();
devhooks_poll();
Expand Down
Loading
Loading