From 6a5cf648a9a12bb092da880a1f0d6ba9f6e2af9c Mon Sep 17 00:00:00 2001 From: Daniel McCoy Stephenson Date: Sat, 21 Nov 2026 00:44:17 -0700 Subject: [PATCH] refactor: move the hosting core behind ports and adapters The server's hosting policy (which game a host names, the /api/games description, upload and rollback, play counting) was moved out of server.py into src/arcade/hosting/: a core with no I/O, five ports (GameCatalog, VersionStore, PlayCounter, EventReporter, ReleaseNotes), the games.yaml catalog and a null reporter as adapters, and a service that wires the production ones. server.py stays the HTTP adapter. No behaviour was changed: 32 characterization tests pinned the old responses first, and 2,352 generated requests gave identical status, body, headers, stored state, trace events and log lines on the old and new code. Contract, core-on-fakes and architecture tests were added. drafted by Claude on behalf of Daniel Stephenson Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LYNeuk6eJu4dojpaZi8x82 --- CHANGELOG.md | 5 + README.md | 21 ++ src/arcade/__main__.py | 3 +- src/arcade/hosting/__init__.py | 30 +++ src/arcade/hosting/adapters/__init__.py | 25 ++ src/arcade/hosting/adapters/null_reporter.py | 9 + .../adapters/reloading_yaml_catalog.py | 52 ++++ src/arcade/hosting/core.py | 184 +++++++++++++ src/arcade/hosting/model.py | 50 ++++ src/arcade/hosting/ports/__init__.py | 19 ++ src/arcade/hosting/ports/event_reporter.py | 15 ++ src/arcade/hosting/ports/game_catalog.py | 21 ++ src/arcade/hosting/ports/play_counter.py | 23 ++ src/arcade/hosting/ports/release_notes.py | 16 ++ src/arcade/hosting/ports/version_store.py | 45 ++++ src/arcade/hosting/service.py | 33 +++ src/arcade/server.py | 242 ++++-------------- tests/hosting_fakes.py | 91 +++++++ tests/test_hosting_architecture.py | 65 +++++ tests/test_hosting_characterization.py | 217 ++++++++++++++++ tests/test_hosting_contracts.py | 143 +++++++++++ tests/test_hosting_core.py | 230 +++++++++++++++++ 22 files changed, 1343 insertions(+), 196 deletions(-) create mode 100644 src/arcade/hosting/__init__.py create mode 100644 src/arcade/hosting/adapters/__init__.py create mode 100644 src/arcade/hosting/adapters/null_reporter.py create mode 100644 src/arcade/hosting/adapters/reloading_yaml_catalog.py create mode 100644 src/arcade/hosting/core.py create mode 100644 src/arcade/hosting/model.py create mode 100644 src/arcade/hosting/ports/__init__.py create mode 100644 src/arcade/hosting/ports/event_reporter.py create mode 100644 src/arcade/hosting/ports/game_catalog.py create mode 100644 src/arcade/hosting/ports/play_counter.py create mode 100644 src/arcade/hosting/ports/release_notes.py create mode 100644 src/arcade/hosting/ports/version_store.py create mode 100644 src/arcade/hosting/service.py create mode 100644 tests/hosting_fakes.py create mode 100644 tests/test_hosting_architecture.py create mode 100644 tests/test_hosting_characterization.py create mode 100644 tests/test_hosting_contracts.py create mode 100644 tests/test_hosting_core.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 025004d..cf8d9f8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -103,6 +103,11 @@ All notable changes to this project are documented in this file. The format is b ### Changed +- Internal: the server's hosting policy (which game a host names, `/api/games` descriptions, upload and + rollback, play counting) moved out of `server.py` into `src/arcade/hosting/`, a pure core behind small + ports (`GameCatalog`, `VersionStore`, `PlayCounter`, `EventReporter`, `ReleaseNotes`) with the + production adapters wired in `hosting/service.py`. No behaviour changed: every response, status, error + text and log line is the same (checked old against new over 2,352 generated requests). - A play is counted at most once per visitor per game per UTC day: reloads, second tabs and later visits the same day no longer add to `plays`, `.plays-daily` or the `page-served` trace event. Whether a visitor has played a game today is a keyed hash in memory (HMAC-SHA256 of the client address, the diff --git a/README.md b/README.md index 3d085bc..26cf8e6 100644 --- a/README.md +++ b/README.md @@ -556,6 +556,27 @@ arcade keeps no access log (`log_message` is a no-op) and stores no IP address o python3 -m pytest # Python 3.8+, standard library only (pytest to run the tests) ``` +The server is laid out as ports and adapters. `src/arcade/server.py` is the HTTP adapter: it parses +requests, streams files and maps outcomes to responses. The hosting policy behind it lives in +`src/arcade/hosting/`: + +``` +server.py (HTTP) -> hosting/service.py (wiring) -> hosting/core.py (policy, no I/O) + -> hosting/ports/* <- adapters +``` + +| Port | Production adapter | Test double (`tests/hosting_fakes.py`) | +|---|---|---| +| `GameCatalog` | `hosting/adapters/reloading_yaml_catalog.py` (games.yaml, reloaded on change) | `FakeCatalog` | +| `VersionStore`, `PlayCounter` | `store.Store` (the data directory) | `FakeStore` | +| `EventReporter` | `trace_client.TraceClient`, or `hosting/adapters/null_reporter.py` with no key | `Recorder` | +| `ReleaseNotes` | `remote.Remote` (GitHub releases, cached) | `FakeNotes` | + +A new backend for a port is one new file in `hosting/adapters/`, one entry in that port's registry in +`hosting/adapters/__init__.py`, and its fixture added to the port's contract test in +`tests/test_hosting_contracts.py`. `tests/test_hosting_architecture.py` fails if `model`, `core` or a port +imports an adapter, the service or the server. + Play a real game locally. `*.localhost` resolves to loopback and counts as a secure context, so the page is cross-origin isolated over plain HTTP: diff --git a/src/arcade/__main__.py b/src/arcade/__main__.py index 2e1e309..5c88083 100644 --- a/src/arcade/__main__.py +++ b/src/arcade/__main__.py @@ -13,7 +13,8 @@ import sys from arcade import __version__, registry, routers -from arcade.server import Arcade, Config, hashToken, log, makeServer +from arcade.hosting import hashToken +from arcade.server import Arcade, Config, log, makeServer DEFAULT_DOMAIN = "play.danielstephenson.dev" REGISTRY_HELP = "the games.yaml to read" diff --git a/src/arcade/hosting/__init__.py b/src/arcade/hosting/__init__.py new file mode 100644 index 0000000..a5fcc8c --- /dev/null +++ b/src/arcade/hosting/__init__.py @@ -0,0 +1,30 @@ +# @author Daniel McCoy Stephenson +"""The hosting core: games, versions, deploys and plays, behind ports. + + callers (arcade.server's HTTP handler, arcade.__main__) + -> service.Service composition root: production adapters + -> core.Hosting pure policy, no I/O + -> ports/* one interface per file + <- adapters/* + existing modules that implement them + + Port Production adapter Test double + GameCatalog adapters.ReloadingYamlCatalog FakeCatalog + VersionStore arcade.store.Store FakeStore + PlayCounter arcade.store.Store FakeStore + EventReporter arcade.trace_client.TraceClient, Recorder + adapters.NullReporter (trace off) + ReleaseNotes arcade.remote.Remote FakeNotes + +Dependencies point inward: model, core and ports never import adapters or +service (tests/test_hosting_architecture.py enforces it). + +To add a new backend for a port: one new file in adapters/ implementing it, +one entry in that port's registry in adapters/__init__.py, and a run of the +port's contract test in tests/test_hosting_contracts.py against it. +""" + +from arcade.hosting.core import Hosting, addedOf, hashToken +from arcade.hosting.model import Denied, Deployed, Rejected +from arcade.hosting.service import Service + +__all__ = ["Denied", "Deployed", "Hosting", "Rejected", "Service", "addedOf", "hashToken"] diff --git a/src/arcade/hosting/adapters/__init__.py b/src/arcade/hosting/adapters/__init__.py new file mode 100644 index 0000000..e706433 --- /dev/null +++ b/src/arcade/hosting/adapters/__init__.py @@ -0,0 +1,25 @@ +# @author Daniel McCoy Stephenson +"""The hosting core's adapters, one implementation per file, and the +registries that name them. + +Three production adapters are existing modules that already have exactly the +port's shape, so they are registered here rather than wrapped: + + arcade.store.Store VersionStore and PlayCounter (the data directory) + arcade.remote.Remote ReleaseNotes (GitHub releases, cached on disk) + arcade.trace_client.TraceClient EventReporter (vendored byte-for-byte from + trace-client-python, so never edited here) +""" + +from arcade.hosting.adapters.null_reporter import NullReporter +from arcade.hosting.adapters.reloading_yaml_catalog import ReloadingYamlCatalog +from arcade.remote import Remote +from arcade.store import Store + +CATALOGS = {"yaml": ReloadingYamlCatalog} +STORES = {"filesystem": Store} +RELEASE_NOTES = {"github": Remote} +# TraceClient is imported where it is built (arcade.__main__), only when a key is set. +REPORTERS = {"none": NullReporter} + +__all__ = ["CATALOGS", "NullReporter", "RELEASE_NOTES", "REPORTERS", "ReloadingYamlCatalog", "STORES"] diff --git a/src/arcade/hosting/adapters/null_reporter.py b/src/arcade/hosting/adapters/null_reporter.py new file mode 100644 index 0000000..1a183f1 --- /dev/null +++ b/src/arcade/hosting/adapters/null_reporter.py @@ -0,0 +1,9 @@ +# @author Daniel McCoy Stephenson +"""NullReporter: the EventReporter when trace is off (no ARCADE_TRACE_KEY).""" + + +class NullReporter(object): + """Drops every event.""" + + def report(self, name, tags=None): + pass diff --git a/src/arcade/hosting/adapters/reloading_yaml_catalog.py b/src/arcade/hosting/adapters/reloading_yaml_catalog.py new file mode 100644 index 0000000..2adff86 --- /dev/null +++ b/src/arcade/hosting/adapters/reloading_yaml_catalog.py @@ -0,0 +1,52 @@ +# @author Daniel McCoy Stephenson +"""ReloadingYamlCatalog: the GameCatalog read from games.yaml.""" + +import os +import threading + +from arcade import registry as registryModule + + +class ReloadingYamlCatalog(object): + """The registry, reloaded when its file changes. A file that no longer + parses is logged and the last good registry stays in force.""" + + def __init__(self, path, domain, log): + self.path = path + self.domain = domain + self._log = log + self._lock = threading.Lock() + self._mtime = None + self._registry = registryModule.Registry([]) + self.refresh(initial=True) + + def refresh(self, initial=False): + try: + mtime = os.stat(self.path).st_mtime_ns + except OSError as e: + if initial: + raise + self._log("registry unreadable, keeping the last good one: %s" % e) + return + with self._lock: + if mtime == self._mtime: + return + try: + loaded = registryModule.load(self.path, domain=self.domain) + except (registryModule.RegistryError, OSError) as e: + if initial: + raise + self._log("registry invalid, keeping the last good one: %s" % e) + self._mtime = mtime + return + self._registry = loaded + self._mtime = mtime + self._log("registry loaded: %d game(s): %s" % (len(loaded), ", ".join(g.slug for g in loaded))) + + @property + def registry(self): + self.refresh() + return self._registry + + def games(self): + return self.registry diff --git a/src/arcade/hosting/core.py b/src/arcade/hosting/core.py new file mode 100644 index 0000000..70f9317 --- /dev/null +++ b/src/arcade/hosting/core.py @@ -0,0 +1,184 @@ +# @author Daniel McCoy Stephenson +"""The hosting core: which game a host names, what the API says about a +game, who may deploy it, and what counts as a play. Pure policy over the +ports in arcade.hosting.ports; it does no I/O of its own.""" + +import datetime +import hashlib +import hmac +import re + +from arcade import bundle +from arcade.hosting.model import Denied, Deployed, Rejected +from arcade.hosting.ports.version_store import VERSION_PATTERN, NoSuchVersion, VersionExists + +# User agents that are not a person opening a game: crawlers, link-preview +# fetchers and scripts. Their page loads are not counted as plays. +# `arcade-watch` is the nightly health check's own marker: it appends it to +# every browser profile's User-Agent (its iPhone profile is otherwise a plain +# Safari string), so its loads never count. +_NOT_A_PERSON = re.compile( + r"bot|crawl|spider|slurp|preview|facebookexternalhit|embedly|curl|wget|python|" + r"go-http-client|java/|okhttp|headless|lighthouse|monitor|uptime|arcade-watch", + re.I, +) + + +def hashToken(token): + return hashlib.sha256(token.encode("utf-8")).hexdigest() + + +def addedOf(game, store): + """When the game joined the arcade, as an ISO 8601 UTC time ("...Z"), or + None: the registry's `added:` (a day, as its midnight UTC, or a time) if + given, else its first upload.""" + if isinstance(game.added, datetime.datetime): + return game.added.astimezone(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + if game.added is not None: + return game.added.isoformat() + "T00:00:00Z" + stamp = store.added(game.slug) + if stamp is None: + return None + moment = datetime.datetime.fromtimestamp(stamp / 1e9, datetime.timezone.utc) + return moment.strftime("%Y-%m-%dT%H:%M:%SZ") + + +class Hosting(object): + """The policy one arcade process applies to every request. + + catalog GameCatalog the registered games + versions VersionStore each game's versions and current one + counter PlayCounter each game's plays + reporter EventReporter trace + notes ReleaseNotes "what's new" per current version + visits arcade.visits.Visits (in memory: who has played today) + log a callable taking one line for the server's log + """ + + def __init__(self, domain, catalog, versions, counter, reporter, notes, visits, maxUploadBytes, log): + self.domain = domain + self.catalog = catalog + self.versions = versions + self.counter = counter + self.reporter = reporter + self.notes = notes + self.visits = visits + self.maxUploadBytes = maxUploadBytes + self._log = log + + def games(self): + return self.catalog.games() + + # --- reading ------------------------------------------------------------ + + def gameForHost(self, host): + """The Game a request's Host header names, or None.""" + registry = self.catalog.games() + suffix = "." + self.domain + if host.endswith(suffix): + label = host[: -len(suffix)] + if "." not in label: + return registry.get(label) + return None + return registry.forAlias(host) + + def notesFor(self, game): + """"What's new" for the game's current version, or None (arcade.remote).""" + return self.notes.notes(game.slug, game.repo, self.versions.current(game.slug)) + + def describe(self, game): + return { + "slug": game.slug, + "title": game.title, + "repo": game.repo, + "url": "https://%s.%s/" % (game.slug, self.domain), + "aliases": list(game.aliases), + "kind": game.kind, + "isolation": game.isolation, + "current": self.versions.current(game.slug), + "versions": self.versions.versions(game.slug), + "plays": self.counter.plays(game.slug), + "added": addedOf(game, self.versions), + "tags": list(game.tags), + "org": game.org, + "engine": game.engine, + # "What's new" in the current version: the GitHub release's + # notes, once arcade has looked them up (arcade.remote). + "notes": self.notesFor(game), + } + + # --- plays -------------------------------------------------------------- + + def played(self, slug, userAgent, client=None): + """A person loaded the game's page: count it, and report it to trace, + once per visitor (`client`, the address, with `userAgent`) per game + per UTC day (arcade.visits). Reloads and later visits that day are + not plays.""" + if not userAgent or _NOT_A_PERSON.search(userAgent): + return + if not self.visits.first(slug, client or "", userAgent): + return + try: + self.counter.addPlay(slug) + except OSError as e: + self._log("could not count a play of %s: %s" % (slug, e)) + self.reporter.report("page-served", tags={"slug": slug}) + + # --- deploying ---------------------------------------------------------- + + def authorise(self, slug, authorization): + """The Game if the Authorization header's bearer token is right for + it; otherwise Denied.""" + game = self.catalog.games().get(slug) + header = authorization or "" + if not header.startswith("Bearer ") or not header[7:].strip(): + return Denied(401, "an Authorization: Bearer header is required") + presented = hashToken(header[7:].strip()) + expected = game.tokenSha256 if game else "0" * 64 + if game is None or not hmac.compare_digest(presented, expected): + # Unknown slug and wrong token look the same from outside. + return Denied(403, "this token cannot deploy that game") + return game + + @staticmethod + def checkVersion(version): + """Rejected if `version` cannot name a version; otherwise None.""" + if not VERSION_PATTERN.match(version): + return Rejected(400, "bad version %r" % version) + return None + + def deploy(self, game, version, data, activate, length): + """Unpack an uploaded bundle (`data`, the request body, which declared + `length` bytes) and store it as `version`: Deployed(201) or Rejected.""" + slug = game.slug + static = game.kind == "static" + try: + if static: + files = bundle.unpackStatic(data, version, self.maxUploadBytes) + else: + files = bundle.unpack(data, version, self.maxUploadBytes) + except bundle.BundleTooLarge as e: + return Rejected(413, str(e)) + except bundle.BundleError as e: + return Rejected(400, str(e)) + try: + self.versions.add(slug, version, files, activate=activate, static=static) + except VersionExists: + return Rejected(409, "version %s already exists; versions are immutable" % version) + except (ValueError, OSError) as e: + # Validation should have caught it; if not, still answer. + self._log("%s %s upload could not be stored: %s" % (slug, version, e)) + return Rejected(400, "the bundle could not be stored: %s" % e) + self._log( + "%s %s uploaded (%d bytes)%s" % (slug, version, length, " and made current" if activate else "") + ) + return Deployed(201, game=game) + + def rollback(self, game, version): + """Make a stored version current: Deployed(200) or Rejected(404).""" + try: + self.versions.setCurrent(game.slug, version) + except NoSuchVersion: + return Rejected(404, "version %r is not on disk" % version) + self._log("%s current set to %s" % (game.slug, version)) + return Deployed(200, game=game) diff --git a/src/arcade/hosting/model.py b/src/arcade/hosting/model.py new file mode 100644 index 0000000..7718900 --- /dev/null +++ b/src/arcade/hosting/model.py @@ -0,0 +1,50 @@ +# @author Daniel McCoy Stephenson +"""The hosting core's outcome values. + +A game is an arcade.registry.Game and the registered set an +arcade.registry.Registry: those existing types are the domain model and are +not copied here. What the core adds is how an API call ended, as a value the +HTTP handler turns into a response; exceptions are kept for bugs. +""" + + +class Outcome(object): + """How an API call ended: the HTTP status it maps to, and either an error + message or the game it acted on.""" + + __slots__ = ("status", "error", "game") + + def __init__(self, status, error=None, game=None): + self.status = status + self.error = error + self.game = game + + def __eq__(self, other): + return type(self) is type(other) and (self.status, self.error, self.game) == ( + other.status, + other.error, + other.game, + ) + + def __repr__(self): + return "%s(%r, %r, %r)" % (type(self).__name__, self.status, self.error, self.game) + + +class Denied(Outcome): + """The bearer token may not act on the game (401: none given; 403: wrong + token, or no such game - the two look the same from outside).""" + + __slots__ = () + + +class Rejected(Outcome): + """The request was understood and refused (bad version, bad bundle, a + version that exists or is missing).""" + + __slots__ = () + + +class Deployed(Outcome): + """The game's versions changed (201: uploaded; 200: current moved).""" + + __slots__ = () diff --git a/src/arcade/hosting/ports/__init__.py b/src/arcade/hosting/ports/__init__.py new file mode 100644 index 0000000..2c6614e --- /dev/null +++ b/src/arcade/hosting/ports/__init__.py @@ -0,0 +1,19 @@ +# @author Daniel McCoy Stephenson +"""The hosting core's ports: one interface per file (see arcade.hosting).""" + +from arcade.hosting.ports.event_reporter import EventReporter +from arcade.hosting.ports.game_catalog import GameCatalog +from arcade.hosting.ports.play_counter import PlayCounter +from arcade.hosting.ports.release_notes import ReleaseNotes +from arcade.hosting.ports.version_store import NoSuchVersion, VERSION_PATTERN, VersionExists, VersionStore + +__all__ = [ + "EventReporter", + "GameCatalog", + "NoSuchVersion", + "PlayCounter", + "ReleaseNotes", + "VERSION_PATTERN", + "VersionExists", + "VersionStore", +] diff --git a/src/arcade/hosting/ports/event_reporter.py b/src/arcade/hosting/ports/event_reporter.py new file mode 100644 index 0000000..7b2154a --- /dev/null +++ b/src/arcade/hosting/ports/event_reporter.py @@ -0,0 +1,15 @@ +# @author Daniel McCoy Stephenson +"""EventReporter: tell trace that something happened.""" + +from typing import Protocol, runtime_checkable + + +@runtime_checkable +class EventReporter(Protocol): + """report(name, tags) records one event (e.g. "page-served", with + {"slug": ...}). It never raises and never blocks a request: a reporter + that sends over the network queues and sends on its own thread. + Thread-safe.""" + + def report(self, name, tags=None): + ... diff --git a/src/arcade/hosting/ports/game_catalog.py b/src/arcade/hosting/ports/game_catalog.py new file mode 100644 index 0000000..79e8ef9 --- /dev/null +++ b/src/arcade/hosting/ports/game_catalog.py @@ -0,0 +1,21 @@ +# @author Daniel McCoy Stephenson +"""GameCatalog: which games are registered right now?""" + +from typing import Protocol, runtime_checkable + + +@runtime_checkable +class GameCatalog(Protocol): + """The registered games. + + games() returns an arcade.registry.Registry (the existing in-repo type is + the contract: get(slug), forAlias(host), iteration in slug order, len). + It never raises once the catalog has been built: a source that later goes + missing or stops parsing keeps answering with the last good registry. + Building one may raise (a missing or invalid registry at start-up). + It may read a file, so it can block briefly; it is called from many + request threads at once and must be thread-safe. + """ + + def games(self): + ... diff --git a/src/arcade/hosting/ports/play_counter.py b/src/arcade/hosting/ports/play_counter.py new file mode 100644 index 0000000..73ec2bb --- /dev/null +++ b/src/arcade/hosting/ports/play_counter.py @@ -0,0 +1,23 @@ +# @author Daniel McCoy Stephenson +"""PlayCounter: how many times has a game been played?""" + +from typing import Protocol, runtime_checkable + + +@runtime_checkable +class PlayCounter(Protocol): + """A game's play count. + + plays(slug) -> the total count, 0 for a game never played + addPlay(slug) counts one play today. OSError if it cannot be recorded; + the caller logs that and carries on (a lost play is not an + error the player should see). + + Both may touch disk and block; both must be thread-safe. + """ + + def plays(self, slug): + ... + + def addPlay(self, slug): + ... diff --git a/src/arcade/hosting/ports/release_notes.py b/src/arcade/hosting/ports/release_notes.py new file mode 100644 index 0000000..c502385 --- /dev/null +++ b/src/arcade/hosting/ports/release_notes.py @@ -0,0 +1,16 @@ +# @author Daniel McCoy Stephenson +"""ReleaseNotes: what's new in a game's current version?""" + +from typing import Protocol, runtime_checkable + + +@runtime_checkable +class ReleaseNotes(Protocol): + """notes(slug, repo, current) -> {"version", "text", "url"} for the + release `current` names, or None when there is none yet (not released, + not looked up yet, or empty). It never raises and never waits on the + network: a lookup it does not have yet is queued and answered later. + Thread-safe.""" + + def notes(self, slug, repo, current): + ... diff --git a/src/arcade/hosting/ports/version_store.py b/src/arcade/hosting/ports/version_store.py new file mode 100644 index 0000000..bceaefa --- /dev/null +++ b/src/arcade/hosting/ports/version_store.py @@ -0,0 +1,45 @@ +# @author Daniel McCoy Stephenson +"""VersionStore: which versions of a game exist, and which is current?""" + +from typing import Protocol, runtime_checkable + +# The store's own version rule and outcomes are the contract; they live in +# arcade.store (shared with its tests and arcade.bundle) and are named here. +from arcade.store import VERSION_PATTERN, NoSuchVersion, VersionExists + +__all__ = ["NoSuchVersion", "VERSION_PATTERN", "VersionExists", "VersionStore"] + + +@runtime_checkable +class VersionStore(Protocol): + """A game's uploaded versions. + + current(slug) -> the current version's name, or None + versions(slug) -> every stored version's name, oldest upload first + added(slug) -> time.time_ns() of the slug's first upload, or None + add(slug, version, files, activate=True, static=False) + stores `files` ({name: bytes}) as an immutable version, + making it current when `activate`. Raises VersionExists if + the version is already stored; ValueError or OSError if + the files cannot be stored. + setCurrent(slug, version) + makes a stored version current; NoSuchVersion if it is not. + + All may touch disk and block; all are called from request threads at + once and must be thread-safe. + """ + + def current(self, slug): + ... + + def versions(self, slug): + ... + + def added(self, slug): + ... + + def add(self, slug, version, files, activate=True, static=False): + ... + + def setCurrent(self, slug, version): + ... diff --git a/src/arcade/hosting/service.py b/src/arcade/hosting/service.py new file mode 100644 index 0000000..5c7b7c5 --- /dev/null +++ b/src/arcade/hosting/service.py @@ -0,0 +1,33 @@ +# @author Daniel McCoy Stephenson +"""The composition root: a Hosting core wired to the production adapters.""" + +from arcade.hosting.adapters.null_reporter import NullReporter +from arcade.hosting.adapters.reloading_yaml_catalog import ReloadingYamlCatalog +from arcade.hosting.core import Hosting +from arcade.store import Store + + +class Service(object): + """Builds the core from a server Config. + + The catalog is built first: a missing or invalid games.yaml raises before + anything is written to the data directory. `reporter` is the caller's + choice (None: trace is off). `notes` and `visits` are shared with the rest + of the server (the hall, and arcade.server.Arcade), so the caller builds + them and passes them in. `log` takes one line for the server's log. + """ + + def __init__(self, config, notes, visits, log, reporter=None): + self.catalog = ReloadingYamlCatalog(config.registryPath, config.domain, log) + self.store = Store(config.dataDirectory, keep=config.keep) + self.core = Hosting( + domain=config.domain, + catalog=self.catalog, + versions=self.store, + counter=self.store, + reporter=reporter if reporter is not None else NullReporter(), + notes=notes, + visits=visits, + maxUploadBytes=config.maxUploadBytes, + log=log, + ) diff --git a/src/arcade/server.py b/src/arcade/server.py index 027e90d..a8fb649 100644 --- a/src/arcade/server.py +++ b/src/arcade/server.py @@ -39,7 +39,6 @@ import datetime import hashlib -import hmac import http.server import json import os @@ -48,11 +47,9 @@ import shutil import sys import tempfile -import threading from urllib.parse import parse_qs, unquote, urlparse -from arcade import __version__, activity, bundle, filters, hall, landing, precompress, registry as registryModule, remote, routers, visits, walks -from arcade.store import VERSION_PATTERN, NoSuchVersion, Store, VersionExists +from arcade import __version__, activity, bundle, filters, hall, hosting, landing, precompress, remote, routers, visits, walks INDEX_PATHS = ("/", "/play", "/play/", "/index.html") WEB_FILES = {"/web/game.zip": "game.zip", "/web/version.txt": "version.txt"} @@ -69,16 +66,6 @@ ) LANDING_MODES = ("page", "redirect") DEFAULT_MAX_UPLOAD_BYTES = 64 * 1024 * 1024 -# User agents that are not a person opening a game: crawlers, link-preview -# fetchers and scripts. Their page loads are not counted as plays. -# `arcade-watch` is the nightly health check's own marker: it appends it to -# every browser profile's User-Agent (its iPhone profile is otherwise a plain -# Safari string), so its loads never count. -_NOT_A_PERSON = re.compile( - r"bot|crawl|spider|slurp|preview|facebookexternalhit|embedly|curl|wget|python|" - r"go-http-client|java/|okhttp|headless|lighthouse|monitor|uptime|arcade-watch", - re.I, -) _FETCHED = re.compile(r"^fetched/([a-z0-9][a-z0-9-]{0,62})\.jpg$") _API_GAME = re.compile(r"^/api/games/([a-z0-9-]+)$") _API_VERSION = re.compile(r"^/api/games/([a-z0-9-]+)/versions/([^/]+)$") @@ -190,74 +177,27 @@ def fromEnvironment(cls, environ=None): ) -class RegistryHolder(object): - """The registry, reloaded when its file changes. A file that no longer - parses is logged and the last good registry stays in force.""" - - def __init__(self, path, domain): - self.path = path - self.domain = domain - self._lock = threading.Lock() - self._mtime = None - self._registry = registryModule.Registry([]) - self.refresh(initial=True) - - def refresh(self, initial=False): - try: - mtime = os.stat(self.path).st_mtime_ns - except OSError as e: - if initial: - raise - log("registry unreadable, keeping the last good one: %s" % e) - return - with self._lock: - if mtime == self._mtime: - return - try: - loaded = registryModule.load(self.path, domain=self.domain) - except (registryModule.RegistryError, OSError) as e: - if initial: - raise - log("registry invalid, keeping the last good one: %s" % e) - self._mtime = mtime - return - self._registry = loaded - self._mtime = mtime - log("registry loaded: %d game(s): %s" % (len(loaded), ", ".join(g.slug for g in loaded))) - - @property - def registry(self): - self.refresh() - return self._registry - - -def addedOf(game, store): - """When the game joined the arcade, as an ISO 8601 UTC time ("...Z"), or - None: the registry's `added:` (a day, as its midnight UTC, or a time) if - given, else its first upload.""" - if isinstance(game.added, datetime.datetime): - return game.added.astimezone(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") - if game.added is not None: - return game.added.isoformat() + "T00:00:00Z" - stamp = store.added(game.slug) - if stamp is None: - return None - moment = datetime.datetime.fromtimestamp(stamp / 1e9, datetime.timezone.utc) - return moment.strftime("%Y-%m-%dT%H:%M:%SZ") - - -def hashToken(token): - return hashlib.sha256(token.encode("utf-8")).hexdigest() - - class Arcade(object): - """The state one server process shares across requests.""" + """The state one server process shares across requests: the hosting core + (arcade.hosting) and what the hall and the file server keep beside it.""" def __init__(self, config, reporter=None): self.config = config - self.registry = RegistryHolder(config.registryPath, config.domain) - self.store = Store(config.dataDirectory, keep=config.keep) + # The caller's choice: None when trace is off (arcade.__main__). self.reporter = reporter + # Which visitors have already played each game today: keyed hashes in + # memory only, forgotten at midnight UTC (arcade.visits). + self.visits = visits.Visits() + # Trailer stills and release notes, fetched in the background and + # kept beside the games (a dot name, so never a slug). + self.remote = remote.Remote(os.path.join(config.dataDirectory, ".remote"), enabled=config.remoteFetch) + # Builds the registry first (a bad games.yaml raises here), then the store. + service = hosting.Service(config, notes=self.remote, visits=self.visits, log=log, reporter=reporter) + self.hosting = service.core + # The games.yaml adapter itself: tests call refresh() on it after + # rewriting the file. + self.registry = service.catalog + self.store = service.store # Versions stored before arcade wrote .gz siblings get theirs the # first time each file is asked for, one file at a time. self.backfill = precompress.Backfill() @@ -267,12 +207,6 @@ def __init__(self, config, reporter=None): self.walks = walks.Walks(os.path.join(config.dataDirectory, ".hall-walks")) self.layouts = walks.Layouts() self.walkLimit = walks.RateLimit() - # Which visitors have already played each game today: keyed hashes in - # memory only, forgotten at midnight UTC (arcade.visits). - self.visits = visits.Visits() - # Trailer stills and release notes, fetched in the background and - # kept beside the games (a dot name, so never a slug). - self.remote = remote.Remote(os.path.join(config.dataDirectory, ".remote"), enabled=config.remoteFetch) def fetchedPoster(self, slug, urls): """The hall URL of a cabinet's fetched trailer still, or None (arcade.remote).""" @@ -285,40 +219,6 @@ def fetchedPoster(self, slug, urls): return None return "fetched/%s.jpg?v=%x" % (slug, stamp) - def notesFor(self, game): - """"What's new" for the game's current version, or None (arcade.remote).""" - return self.remote.notes(game.slug, game.repo, self.store.current(game.slug)) - - def gameForHost(self, host): - """The Game a request's Host header names, or None.""" - registry = self.registry.registry - suffix = "." + self.config.domain - if host.endswith(suffix): - label = host[: -len(suffix)] - if "." not in label: - return registry.get(label) - return None - return registry.forAlias(host) - - def report(self, name, slug): - if self.reporter is not None: - self.reporter.report(name, tags={"slug": slug}) - - def played(self, slug, userAgent, client=None): - """A person loaded the game's page: count it, and report it to trace, - once per visitor (`client`, the address, with `userAgent`) per game - per UTC day (arcade.visits). Reloads and later visits that day are - not plays.""" - if not userAgent or _NOT_A_PERSON.search(userAgent): - return - if not self.visits.first(slug, client or "", userAgent): - return - try: - self.store.addPlay(slug) - except OSError as e: - log("could not count a play of %s: %s" % (slug, e)) - self.report("page-served", slug) - def makeHandler(arcade): config = arcade.config @@ -406,7 +306,7 @@ def _dispatch(self, read): if host == config.internalHost: if read and path == "/traefik/dynamic.json": document = routers.providerDocument( - arcade.registry.registry, + arcade.hosting.games(), config.domain, service=config.traefikService, middlewares=config.traefikMiddlewares, @@ -418,7 +318,7 @@ def _dispatch(self, read): if host == config.domain: self._api(path, read) return - game = arcade.gameForHost(host) + game = arcade.hosting.gameForHost(host) if game is None: self._text(404, "No game is served at this address.") return @@ -442,7 +342,7 @@ def _game(self, game, path): if path in INDEX_PATHS: self._file(game.slug, version, "index.html", "text/html; charset=utf-8") if self.command == "GET": - arcade.played(game.slug, self.headers.get("User-Agent"), self._client()) + arcade.hosting.played(game.slug, self.headers.get("User-Agent"), self._client()) return if path in WEB_FILES: name = WEB_FILES[path] @@ -477,7 +377,7 @@ def _static(self, game, version, path): if not self._stream(stored, contentType, '"%s-%s"' % (version, tag)): return if relative == "index.html" and self.command == "GET": - arcade.played(game.slug, self.headers.get("User-Agent"), self._client()) + arcade.hosting.played(game.slug, self.headers.get("User-Agent"), self._client()) def _file(self, slug, version, name, contentType): self._stream(arcade.store.filePath(slug, version, name), contentType, '"%s-%s"' % (version, name)) @@ -609,7 +509,7 @@ def _api(self, path, read): if read and path == "/api/games": # ?tag=, ?org=, ?engine=, ?q= narrow the list and ?sort= orders it, as on the landing page. chosen = filters.Filter.parse(urlparse(self.path).query) - described = [self._describe(game) for game in arcade.registry.registry] + described = [self._describe(game) for game in arcade.hosting.games()] if chosen.active: described = [game for game in described if chosen.matches(game)] if chosen.sort != "name": @@ -619,7 +519,7 @@ def _api(self, path, read): if read and path == "/api/activity": # The hall's ghosts: a 0..4 level per game, never a count (RFC 0030 ยง2.2). doc = activity.document( - [game.slug for game in arcade.registry.registry], + [game.slug for game in arcade.hosting.games()], lambda slug: arcade.store.recentPlays(slug, activity.WINDOW_DAYS), ) body = (json.dumps(doc, indent=2, sort_keys=True) + "\n").encode("utf-8") @@ -638,7 +538,7 @@ def _api(self, path, read): return match = _API_GAME.match(path) if match and read: - game = arcade.registry.registry.get(match.group(1)) + game = arcade.hosting.games().get(match.group(1)) if game is None: self._json(404, {"error": "no such game"}) return @@ -675,7 +575,7 @@ def _hall(self, path): self.isolate = params.get("isolated", [""])[0] == "1" # A link to one cabinet (?at=) unfurls with that game's # title and card; anything else with the hall's. - game = arcade.registry.registry.get(params.get("at", [""])[0]) + game = arcade.hosting.games().get(params.get("at", [""])[0]) body = hall.page(config.domain, game.slug, game.title) if game else hall.page(config.domain) tag = '"hall-page-%s-%s"' % ( hashlib.sha256(body).hexdigest()[:16], @@ -694,7 +594,7 @@ def _hall(self, path): self._send(200, body, "text/html; charset=utf-8", headers=headers) return if name == "layout.json": - registry = arcade.registry.registry + registry = arcade.hosting.games() games = [self._describe(game) for game in registry] # ?season=halloween (or none) shows a season's decor on any date, for testing. season = parse_qs(query).get("season", [None])[0] @@ -739,7 +639,7 @@ def _client(self): return forwarded[-1] if forwarded else self.client_address[0] def _currentLayout(self): - games = [self._describe(game) for game in arcade.registry.registry] + games = [self._describe(game) for game in arcade.hosting.games()] return hall.served_layout(games, config.hallEmbed, fetched=arcade.fetchedPoster) def _leaveWalk(self): @@ -791,16 +691,16 @@ def _landing(self, theme=None): self._send(302, b"", headers=(("Location", config.landingUrl),)) return body = landing.render( - arcade.registry.registry, + arcade.hosting.games(), config.domain, config.landingUrl, deployed=lambda slug: arcade.store.current(slug) is not None, plays=arcade.store.plays, - added=lambda game: addedOf(game, arcade.store), + added=lambda game: hosting.addedOf(game, arcade.store), query=urlparse(self.path).query, theme=theme, weekly=lambda slug: arcade.store.recentPlays(slug, activity.WINDOW_DAYS), - notes=arcade.notesFor, + notes=arcade.hosting.notesFor, ) self._send( 200, @@ -821,7 +721,7 @@ def _random(self): "Random game" without script. Back to the list if none is live.""" chosen = filters.Filter.parse(urlparse(self.path).query) pool = [] - for game in arcade.registry.registry: + for game in arcade.hosting.games(): if arcade.store.current(game.slug) is None: continue if chosen.active and not chosen.matches(self._describe(game)): @@ -837,7 +737,7 @@ def _bundle(self, slug): """The live version's files as one uncompressed tar, so a game can be kept and played offline: what was uploaded, less arcade's own bookkeeping and the gzip siblings it wrote. Public, like the game itself; not a play.""" - game = arcade.registry.registry.get(slug) + game = arcade.hosting.games().get(slug) version = arcade.store.current(slug) if game else None if version is None: self._json(404, {"error": "no such game" if game is None else "not deployed yet"}) @@ -858,41 +758,15 @@ def _bundle(self, slug): shutil.copyfileobj(spool, self.wfile) def _describe(self, game): - return { - "slug": game.slug, - "title": game.title, - "repo": game.repo, - "url": "https://%s.%s/" % (game.slug, config.domain), - "aliases": list(game.aliases), - "kind": game.kind, - "isolation": game.isolation, - "current": arcade.store.current(game.slug), - "versions": arcade.store.versions(game.slug), - "plays": arcade.store.plays(game.slug), - "added": addedOf(game, arcade.store), - "tags": list(game.tags), - "org": game.org, - "engine": game.engine, - # "What's new" in the current version: the GitHub release's - # notes, once arcade has looked them up (arcade.remote). - "notes": arcade.notesFor(game), - } + return arcade.hosting.describe(game) def _authorise(self, slug): """The Game if the bearer token is right for it; otherwise None, with the error already sent.""" - game = arcade.registry.registry.get(slug) - header = self.headers.get("Authorization") or "" - if not header.startswith("Bearer ") or not header[7:].strip(): - self._drain() - self._json(401, {"error": "an Authorization: Bearer header is required"}) - return None - presented = hashToken(header[7:].strip()) - expected = game.tokenSha256 if game else "0" * 64 - if game is None or not hmac.compare_digest(presented, expected): + game = arcade.hosting.authorise(slug, self.headers.get("Authorization")) + if isinstance(game, hosting.Denied): self._drain() - # Unknown slug and wrong token look the same from outside. - self._json(403, {"error": "this token cannot deploy that game"}) + self._json(game.status, {"error": game.error}) return None return game @@ -925,9 +799,10 @@ def _upload(self, slug, version): game = self._authorise(slug) if game is None: return - if not VERSION_PATTERN.match(version): + rejected = arcade.hosting.checkVersion(version) + if rejected is not None: self._drain() - self._json(400, {"error": "bad version %r" % version}) + self._json(rejected.status, {"error": rejected.error}) return length = self._contentLength() if length is None: @@ -939,31 +814,8 @@ def _upload(self, slug, version): self._json(413, {"error": "uploads are capped at %d bytes" % config.maxUploadBytes}) return data = self.rfile.read(length) - static = game.kind == "static" - try: - if static: - files = bundle.unpackStatic(data, version, config.maxUploadBytes) - else: - files = bundle.unpack(data, version, config.maxUploadBytes) - except bundle.BundleTooLarge as e: - self._json(413, {"error": str(e)}) - return - except bundle.BundleError as e: - self._json(400, {"error": str(e)}) - return activate = parse_qs(urlparse(self.path).query).get("activate", ["true"])[0] != "false" - try: - arcade.store.add(slug, version, files, activate=activate, static=static) - except VersionExists: - self._json(409, {"error": "version %s already exists; versions are immutable" % version}) - return - except (ValueError, OSError) as e: - # Validation should have caught it; if not, still answer. - log("%s %s upload could not be stored: %s" % (slug, version, e)) - self._json(400, {"error": "the bundle could not be stored: %s" % e}) - return - log("%s %s uploaded (%d bytes)%s" % (slug, version, length, " and made current" if activate else "")) - self._json(201, self._describe(game)) + self._answer(arcade.hosting.deploy(game, version, data, activate, length)) def _rollback(self, slug): game = self._authorise(slug) @@ -982,13 +834,13 @@ def _rollback(self, slug): except (ValueError, KeyError, TypeError, RecursionError): self._json(400, {"error": 'expected a JSON body {"version": ""}'}) return - try: - arcade.store.setCurrent(slug, version) - except NoSuchVersion: - self._json(404, {"error": "version %r is not on disk" % version}) - return - log("%s current set to %s" % (slug, version)) - self._json(200, self._describe(game)) + self._answer(arcade.hosting.rollback(game, version)) + + def _answer(self, outcome): + if isinstance(outcome, hosting.Deployed): + self._json(outcome.status, self._describe(outcome.game)) + else: + self._json(outcome.status, {"error": outcome.error}) return Handler diff --git a/tests/hosting_fakes.py b/tests/hosting_fakes.py new file mode 100644 index 0000000..7f15f51 --- /dev/null +++ b/tests/hosting_fakes.py @@ -0,0 +1,91 @@ +"""Test doubles for the hosting core's ports (arcade.hosting.ports). Each one +passes the same contract test as its production adapter +(test_hosting_contracts.py).""" + +from arcade import registry +from arcade.hosting.ports import NoSuchVersion, VersionExists + + +class FakeCatalog(object): + def __init__(self, text="games: []\n", domain=None): + self._registry = registry.loads(text, domain=domain) + + def games(self): + return self._registry + + +class FakeStore(object): + """VersionStore and PlayCounter in memory.""" + + def __init__(self, now=1_700_000_000_000_000_000): + self.now = now + self.stored = {} # slug -> {version: files}, in upload order + self.currents = {} + self.firsts = {} + self.counts = {} + self.failPlays = False + + def current(self, slug): + return self.currents.get(slug) + + def versions(self, slug): + return list(self.stored.get(slug, {})) + + def added(self, slug): + return self.firsts.get(slug) + + def add(self, slug, version, files, activate=True, static=False): + versions = self.stored.setdefault(slug, {}) + if version in versions: + raise VersionExists(version) + versions[version] = dict(files) + self.firsts.setdefault(slug, self.now) + if activate: + self.currents[slug] = version + + def setCurrent(self, slug, version): + if version not in self.stored.get(slug, {}): + raise NoSuchVersion(version) + self.currents[slug] = version + + def plays(self, slug): + return self.counts.get(slug, 0) + + def addPlay(self, slug): + if self.failPlays: + raise OSError("disk full") + self.counts[slug] = self.counts.get(slug, 0) + 1 + + +class Recorder(object): + """EventReporter that keeps what it was told.""" + + def __init__(self): + self.events = [] + + def report(self, name, tags=None): + self.events.append((name, tags)) + + +class FakeNotes(object): + """ReleaseNotes from a dict: (slug, current) -> notes.""" + + def __init__(self, known=None): + self.known = dict(known or {}) + + def notes(self, slug, repo, current): + return self.known.get((slug, current)) + + +class FakeVisits(object): + """Every visit is the visitor's first today, unless `seen` says not.""" + + def __init__(self): + self.seen = set() + + def first(self, slug, client, userAgent): + key = (slug, client, userAgent) + if key in self.seen: + return False + self.seen.add(key) + return True diff --git a/tests/test_hosting_architecture.py b/tests/test_hosting_architecture.py new file mode 100644 index 0000000..c0b56c0 --- /dev/null +++ b/tests/test_hosting_architecture.py @@ -0,0 +1,65 @@ +"""Architecture tests for arcade.hosting: dependencies point inward, and each +port or adapter file holds exactly one class.""" + +import ast +import pathlib + +import pytest + +HOSTING = pathlib.Path(__file__).resolve().parent.parent / "src" / "arcade" / "hosting" +INNER = [HOSTING / "model.py", HOSTING / "core.py"] + sorted((HOSTING / "ports").glob("*.py")) +# Inner layers may not reach the outer layers, nor the modules that do I/O +# for them (those are adapters, wired in by the service). +FORBIDDEN = ( + "arcade.hosting.adapters", + "arcade.hosting.service", + "arcade.server", + "arcade.__main__", + "arcade.remote", + "arcade.trace_client", +) + + +def imports(source): + found = [] + for node in ast.walk(ast.parse(source)): + if isinstance(node, ast.Import): + found += [alias.name for alias in node.names] + elif isinstance(node, ast.ImportFrom) and node.module: + found.append(node.module) + found += ["%s.%s" % (node.module, alias.name) for alias in node.names] + return found + + +def violations(source): + return sorted({name for name in imports(source) if name.startswith(FORBIDDEN)}) + + +def classes(source): + return [node.name for node in ast.parse(source).body if isinstance(node, ast.ClassDef)] + + +@pytest.mark.parametrize("path", INNER, ids=lambda p: p.relative_to(HOSTING).as_posix()) +def test_inner_layers_never_import_outer_ones(path): + assert violations(path.read_text()) == [] + + +@pytest.mark.parametrize( + "path", + [p for p in sorted((HOSTING / "ports").glob("*.py")) + sorted((HOSTING / "adapters").glob("*.py")) + if p.name != "__init__.py"], + ids=lambda p: p.relative_to(HOSTING).as_posix(), +) +def test_one_class_per_port_or_adapter_file(path): + assert len(classes(path.read_text())) == 1 + + +def test_the_checks_can_fail(): + # A checker that cannot see a violation passes it. + assert violations("from arcade.hosting.adapters import NullReporter\nimport arcade.server\n") == [ + "arcade.hosting.adapters", + "arcade.hosting.adapters.NullReporter", + "arcade.server", + ] + assert violations("from arcade.hosting import adapters\n") == ["arcade.hosting.adapters"] + assert len(classes("class A(object):\n pass\n\n\nclass B(object):\n pass\n")) == 2 diff --git a/tests/test_hosting_characterization.py b/tests/test_hosting_characterization.py new file mode 100644 index 0000000..8f90d71 --- /dev/null +++ b/tests/test_hosting_characterization.py @@ -0,0 +1,217 @@ +"""Characterization tests for the hosting core (written against the code +before the ports-and-adapters refactor, and kept green through it). + +They pin the API's exact status codes and error texts, the fields `describe` +returns, which page loads count as plays, and which hosts name which game. +""" + +import json +import socket + +import pytest + +from helpers import OTHER_TOKEN, TOKEN, bundleFiles, tarBundle +from test_server import API, DOMAIN, arcade, plays, request, upload, waitFor # noqa: F401 (fixture) + + +def body(data): + return json.loads(data) + + +def rollback(arcade, slug, payload, token=TOKEN): + headers = {"Content-Type": "application/json"} + if token is not None: + headers["Authorization"] = "Bearer " + token + data = payload if isinstance(payload, bytes) else json.dumps(payload).encode() + return request(arcade, "POST", API, "/api/games/%s/current" % slug, data, headers) + + +# --- authorise ------------------------------------------------------------ + + +@pytest.mark.parametrize("token", [None, "", " "]) +def test_upload_without_a_bearer_token_is_401(arcade, token): + headers = {} if token is None else {"Authorization": "Bearer " + token} + response, data = request(arcade, "PUT", API, "/api/games/tidewater/versions/1.0.0", b"x", headers) + assert response.status == 401 + assert body(data) == {"error": "an Authorization: Bearer header is required"} + + +def test_upload_with_another_games_token_is_403(arcade): + response, data = upload(arcade, slug="tidewater", token=OTHER_TOKEN) + assert response.status == 403 + assert body(data) == {"error": "this token cannot deploy that game"} + + +def test_upload_to_an_unknown_slug_is_403(arcade): + response, data = upload(arcade, slug="nosuch") + assert response.status == 403 + assert body(data) == {"error": "this token cannot deploy that game"} + + +# --- upload --------------------------------------------------------------- + + +def test_upload_with_a_bad_version_is_400(arcade): + response, data = upload(arcade, version="current") + assert response.status == 400 + assert body(data) == {"error": "bad version 'current'"} + + +def test_upload_of_a_broken_bundle_is_400_with_the_bundle_error(arcade): + response, data = upload(arcade, body=b"this is not an archive") + assert response.status == 400 + assert set(body(data)) == {"error"} + assert body(data)["error"] + + +def test_upload_twice_is_409(arcade): + assert upload(arcade)[0].status == 201 + response, data = upload(arcade) + assert response.status == 409 + assert body(data) == {"error": "version 1.0.0 already exists; versions are immutable"} + + +def test_upload_over_the_cap_is_413_with_its_message(arcade): + # Only the headers are sent; the server refuses from the declared length + # and closes the connection, so read until it does. + sock = socket.create_connection(("127.0.0.1", arcade.port), timeout=10) + sock.sendall( + b"PUT /api/games/tidewater/versions/1 HTTP/1.1\r\nHost: %s\r\n" + b"Authorization: Bearer %s\r\nContent-Length: %d\r\n\r\n" + % (API.encode(), TOKEN.encode(), arcade.config.maxUploadBytes + 1) + ) + reply = b"" + while True: + chunk = sock.recv(4096) + if not chunk: + break + reply += chunk + sock.close() + assert reply.startswith(b"HTTP/1.1 413") + assert body(reply.split(b"\r\n\r\n", 1)[1]) == { + "error": "uploads are capped at %d bytes" % arcade.config.maxUploadBytes + } + + +def test_upload_answers_201_with_the_full_description(arcade): + response, data = upload(arcade) + assert response.status == 201 + assert body(data) == { + "slug": "tidewater", + "title": "Tidewater", + "repo": "Stephenson-Software/Tidewater", + "url": "https://tidewater.%s/" % DOMAIN, + "aliases": ["tidewater.example.org"], + "kind": "tak", + "isolation": True, + "current": "1.0.0", + "versions": ["1.0.0"], + "plays": 0, + "added": body(data)["added"], + "tags": [], + "org": body(data)["org"], + "engine": body(data)["engine"], + "notes": None, + } + assert body(data)["added"].endswith("Z") + + +def test_upload_with_activate_false_keeps_nothing_current(arcade): + response, data = upload(arcade, query="?activate=false") + assert response.status == 201 + assert body(data)["current"] is None + assert body(data)["versions"] == ["1.0.0"] + + +def test_the_registry_added_day_wins_over_the_first_upload(arcade): + upload(arcade, slug="overwinter", token=OTHER_TOKEN) + data = request(arcade, "GET", API, "/api/games/overwinter")[1] + assert body(data)["added"] == "2026-10-01T00:00:00Z" + + +# --- rollback ------------------------------------------------------------- + + +def test_rollback_to_a_missing_version_is_404(arcade): + upload(arcade) + response, data = rollback(arcade, "tidewater", {"version": "9.9.9"}) + assert response.status == 404 + assert body(data) == {"error": "version '9.9.9' is not on disk"} + + +def test_rollback_with_a_large_body_is_413(arcade): + response, data = rollback(arcade, "tidewater", b" " * 4097) + assert response.status == 413 + assert body(data) == {"error": "body too large"} + + +@pytest.mark.parametrize("payload", [b"[]", b"{}", b'{"version": 3}', b"not json"]) +def test_rollback_with_a_bad_body_is_400(arcade, payload): + response, data = rollback(arcade, "tidewater", payload) + assert response.status == 400 + assert body(data) == {"error": 'expected a JSON body {"version": ""}'} + + +def test_rollback_moves_current_and_answers_the_description(arcade): + upload(arcade, version="1.0.0") + upload(arcade, version="1.1.0") + response, data = rollback(arcade, "tidewater", {"version": "1.0.0"}) + assert response.status == 200 + assert body(data)["current"] == "1.0.0" + assert body(data)["versions"] == ["1.0.0", "1.1.0"] + + +# --- hosts ---------------------------------------------------------------- + + +@pytest.mark.parametrize( + "host", + ["nosuch." + DOMAIN, "a.tidewater." + DOMAIN, "elsewhere.example.org", "tidewater.example.org.evil"], +) +def test_hosts_that_name_no_game_are_404(arcade, host): + response, data = request(arcade, "GET", host, "/") + assert (response.status, data) == (404, b"No game is served at this address.\n") + + +def test_an_alias_serves_its_game(arcade): + upload(arcade) + response, data = request(arcade, "GET", "tidewater.example.org", "/") + assert response.status == 200 + assert b"v1.0.0" in data + + +def test_an_undeployed_game_says_so(arcade): + response, data = request(arcade, "GET", "tidewater." + DOMAIN, "/") + assert (response.status, data) == (404, b"Tidewater has not been deployed yet.\n") + + +def test_writes_to_a_game_host_are_405(arcade): + response, data = request(arcade, "PUT", "tidewater." + DOMAIN, "/", b"") + assert response.status == 405 + assert data == ("Games are read-only; uploads go to https://%s/api/\n" % DOMAIN).encode() + + +# --- plays ---------------------------------------------------------------- + + +@pytest.mark.parametrize("agent", ["", "Googlebot/2.1", "curl/8.0", "Mozilla/5.0 arcade-watch"]) +def test_scripts_and_crawlers_are_not_plays(arcade, agent): + upload(arcade) + request(arcade, "GET", "tidewater." + DOMAIN, "/", headers={"User-Agent": agent}) + assert plays(arcade, 0) == 0 + assert arcade.reporter.events == [] + + +def test_one_visitor_counts_once_a_day(arcade): + upload(arcade) + for _ in range(3): + request(arcade, "GET", "tidewater." + DOMAIN, "/") + assert plays(arcade, 1) == 1 + assert waitFor(lambda: arcade.reporter.events) == [("page-served", {"slug": "tidewater"})] + + +def test_a_head_request_is_not_a_play(arcade): + upload(arcade) + request(arcade, "HEAD", "tidewater." + DOMAIN, "/") + assert plays(arcade, 0) == 0 diff --git a/tests/test_hosting_contracts.py b/tests/test_hosting_contracts.py new file mode 100644 index 0000000..7da9c88 --- /dev/null +++ b/tests/test_hosting_contracts.py @@ -0,0 +1,143 @@ +"""Contract tests: each port's fake and its production adapter pass the same +tests, so a fake cannot drift from the real thing.""" + +import os + +import pytest + +from arcade.hosting import ports +from arcade.hosting.adapters import NullReporter, ReloadingYamlCatalog +from arcade.remote import Remote +from arcade.store import Store +from helpers import bundleFiles, game, registryText +from hosting_fakes import FakeCatalog, FakeNotes, FakeStore, Recorder + +DOMAIN = "play.example.com" +TEXT = registryText([game("tidewater", aliases=["tidewater.example.org"]), game("rps", kind="static")]) + + +# --- GameCatalog ------------------------------------------------------------ + + +@pytest.fixture(params=["fake", "yaml"]) +def catalog(request, tmp_path): + if request.param == "fake": + return FakeCatalog(TEXT, domain=DOMAIN) + path = tmp_path / "games.yaml" + path.write_text(TEXT) + return ReloadingYamlCatalog(str(path), DOMAIN, log=lambda line: None) + + +def test_a_catalog_is_a_game_catalog(catalog): + assert isinstance(catalog, ports.GameCatalog) + + +def test_a_catalog_answers_slugs_and_aliases(catalog): + games = catalog.games() + assert [g.slug for g in games] == ["rps", "tidewater"] + assert len(games) == 2 + assert games.get("tidewater").slug == "tidewater" + assert games.get("nosuch") is None + assert games.forAlias("tidewater.example.org").slug == "tidewater" + assert games.forAlias("elsewhere.example.org") is None + + +def test_the_yaml_catalog_keeps_the_last_good_registry(tmp_path): + path = tmp_path / "games.yaml" + path.write_text(TEXT) + lines = [] + catalog = ReloadingYamlCatalog(str(path), DOMAIN, log=lines.append) + path.write_text("games:\n - slug: x\n") + os.utime(str(path), ns=(10**18, 10**18)) + assert [g.slug for g in catalog.games()] == ["rps", "tidewater"] + assert lines[-1].startswith("registry invalid, keeping the last good one: ") + path.unlink() + assert len(catalog.games()) == 2 + assert lines[-1].startswith("registry unreadable, keeping the last good one: ") + + +def test_the_yaml_catalog_refuses_a_missing_file_at_start(tmp_path): + with pytest.raises(OSError): + ReloadingYamlCatalog(str(tmp_path / "missing.yaml"), DOMAIN, log=lambda line: None) + + +# --- VersionStore and PlayCounter ------------------------------------------- + + +@pytest.fixture(params=["fake", "filesystem"]) +def store(request, tmp_path): + if request.param == "fake": + return FakeStore() + return Store(str(tmp_path / "data"), keep=3) + + +def test_a_store_is_a_version_store_and_a_play_counter(store): + assert isinstance(store, ports.VersionStore) + assert isinstance(store, ports.PlayCounter) + + +def test_an_empty_store(store): + assert store.current("tidewater") is None + assert store.versions("tidewater") == [] + assert store.added("tidewater") is None + assert store.plays("tidewater") == 0 + + +def test_add_makes_a_version_current_unless_told_not_to(store): + store.add("tidewater", "1.0.0", bundleFiles("1.0.0")) + assert store.current("tidewater") == "1.0.0" + store.add("tidewater", "1.1.0", bundleFiles("1.1.0"), activate=False) + assert store.current("tidewater") == "1.0.0" + assert store.versions("tidewater") == ["1.0.0", "1.1.0"] + assert isinstance(store.added("tidewater"), int) + + +def test_versions_are_immutable(store): + store.add("tidewater", "1.0.0", bundleFiles("1.0.0")) + with pytest.raises(ports.VersionExists): + store.add("tidewater", "1.0.0", bundleFiles("1.0.0")) + + +def test_set_current_needs_a_stored_version(store): + store.add("tidewater", "1.0.0", bundleFiles("1.0.0")) + store.add("tidewater", "1.1.0", bundleFiles("1.1.0")) + store.setCurrent("tidewater", "1.0.0") + assert store.current("tidewater") == "1.0.0" + with pytest.raises(ports.NoSuchVersion): + store.setCurrent("tidewater", "9.9.9") + + +def test_plays_count_up(store): + store.addPlay("tidewater") + store.addPlay("tidewater") + assert store.plays("tidewater") == 2 + assert store.plays("rps") == 0 + + +# --- EventReporter ---------------------------------------------------------- + + +@pytest.mark.parametrize("reporter", [NullReporter(), Recorder()], ids=["null", "recorder"]) +def test_a_reporter_takes_events_without_raising(reporter): + assert isinstance(reporter, ports.EventReporter) + reporter.report("page-served", tags={"slug": "tidewater"}) + reporter.report("startup") + + +# --- ReleaseNotes ----------------------------------------------------------- + + +@pytest.fixture(params=["fake", "remote"]) +def notes(request, tmp_path): + if request.param == "fake": + return FakeNotes() + return Remote(str(tmp_path / ".remote"), enabled=False, start=False) + + +def test_notes_are_release_notes(notes): + assert isinstance(notes, ports.ReleaseNotes) + + +@pytest.mark.parametrize("current", [None, "1.0.0", "1.0.0-dev.3"]) +def test_nothing_looked_up_yet_is_none(notes, current): + assert notes.notes("tidewater", "Stephenson-Software/Tidewater", current) is None diff --git a/tests/test_hosting_core.py b/tests/test_hosting_core.py new file mode 100644 index 0000000..ff39e4e --- /dev/null +++ b/tests/test_hosting_core.py @@ -0,0 +1,230 @@ +"""The hosting core on fakes alone: no HTTP server, no disk, no network.""" + +import datetime + +import pytest + +from arcade.hosting import Denied, Deployed, Hosting, Rejected, addedOf, hashToken +from helpers import OTHER_TOKEN, TOKEN, bundleFiles, game, registryText, tarBundle +from hosting_fakes import FakeCatalog, FakeNotes, FakeStore, FakeVisits, Recorder + +DOMAIN = "play.example.com" +NOTES = {"version": "1.0.0", "text": "New boats.", "url": "https://example.com/r"} + + +@pytest.fixture +def parts(): + text = registryText( + [ + game("tidewater", aliases=["tidewater.example.org"]), + game("overwinter", added="2026-10-01"), + game("rps", kind="static"), + ] + ) + store = FakeStore() + lines = [] + core = Hosting( + domain=DOMAIN, + catalog=FakeCatalog(text, domain=DOMAIN), + versions=store, + counter=store, + reporter=Recorder(), + notes=FakeNotes({("tidewater", "1.0.0"): NOTES}), + visits=FakeVisits(), + maxUploadBytes=1024 * 1024, + log=lines.append, + ) + return core, store, lines + + +def tidewater(core): + return core.games().get("tidewater") + + +# --- hosts ------------------------------------------------------------------ + + +@pytest.mark.parametrize( + "host, slug", + [ + ("tidewater." + DOMAIN, "tidewater"), + ("tidewater.example.org", "tidewater"), + ("nosuch." + DOMAIN, None), + ("a.tidewater." + DOMAIN, None), + (DOMAIN, None), + ("elsewhere.example.org", None), + ], +) +def test_game_for_host(parts, host, slug): + core = parts[0] + found = core.gameForHost(host) + assert (found.slug if found else None) == slug + + +# --- authorise -------------------------------------------------------------- + + +@pytest.mark.parametrize("header", [None, "", "Bearer ", "Bearer ", "Basic abc", "bearer " + TOKEN]) +def test_no_bearer_token_is_401(parts, header): + assert parts[0].authorise("tidewater", header) == Denied( + 401, "an Authorization: Bearer header is required" + ) + + +@pytest.mark.parametrize("slug, token", [("tidewater", OTHER_TOKEN), ("nosuch", TOKEN)]) +def test_wrong_token_and_unknown_slug_look_the_same(parts, slug, token): + assert parts[0].authorise(slug, "Bearer " + token) == Denied(403, "this token cannot deploy that game") + + +def test_the_right_token_returns_the_game(parts): + core = parts[0] + assert core.authorise("tidewater", "Bearer %s " % TOKEN) is tidewater(core) + + +# --- deploy and rollback ---------------------------------------------------- + + +@pytest.mark.parametrize("version, ok", [("1.0.0", True), ("v2-rc.1+b", True), ("current", False), ("plays", False), ("-1", False), ("a/b", False), ("x" * 65, False)]) +def test_check_version(version, ok): + rejected = Hosting.checkVersion(version) + assert rejected is None if ok else rejected == Rejected(400, "bad version %r" % version) + + +def test_deploy_stores_and_logs(parts): + core, store, lines = parts + data = tarBundle(bundleFiles("1.0.0")) + assert core.deploy(tidewater(core), "1.0.0", data, True, len(data)) == Deployed(201, game=tidewater(core)) + assert store.current("tidewater") == "1.0.0" + assert lines == ["tidewater 1.0.0 uploaded (%d bytes) and made current" % len(data)] + + +def test_deploy_without_activating(parts): + core, store, lines = parts + data = tarBundle(bundleFiles("1.0.0")) + core.deploy(tidewater(core), "1.0.0", data, False, 7) + assert store.current("tidewater") is None + assert lines == ["tidewater 1.0.0 uploaded (7 bytes)"] + + +def test_deploy_twice_is_409(parts): + core = parts[0] + data = tarBundle(bundleFiles("1.0.0")) + core.deploy(tidewater(core), "1.0.0", data, True, len(data)) + assert core.deploy(tidewater(core), "1.0.0", data, True, len(data)) == Rejected( + 409, "version 1.0.0 already exists; versions are immutable" + ) + + +def test_a_bad_bundle_is_400_and_stores_nothing(parts): + core, store, lines = parts + outcome = core.deploy(tidewater(core), "1.0.0", b"not an archive", True, 14) + assert isinstance(outcome, Rejected) and outcome.status == 400 and outcome.error + assert store.versions("tidewater") == [] and lines == [] + + +def test_a_store_failure_is_400_and_logged(parts): + core, store, lines = parts + + def broken(*args, **kwargs): + raise OSError("disk full") + + store.add = broken + data = tarBundle(bundleFiles("1.0.0")) + assert core.deploy(tidewater(core), "1.0.0", data, True, len(data)) == Rejected( + 400, "the bundle could not be stored: disk full" + ) + assert lines == ["tidewater 1.0.0 upload could not be stored: disk full"] + + +def test_rollback(parts): + core, store, lines = parts + store.add("tidewater", "1.0.0", {}) + store.add("tidewater", "1.1.0", {}) + assert core.rollback(tidewater(core), "1.0.0") == Deployed(200, game=tidewater(core)) + assert store.current("tidewater") == "1.0.0" + assert lines == ["tidewater current set to 1.0.0"] + assert core.rollback(tidewater(core), "9.9.9") == Rejected(404, "version '9.9.9' is not on disk") + + +# --- describe --------------------------------------------------------------- + + +def test_describe(parts): + core, store = parts[:2] + store.add("tidewater", "1.0.0", {}) + store.addPlay("tidewater") + described = core.describe(tidewater(core)) + assert described["url"] == "https://tidewater.%s/" % DOMAIN + assert (described["current"], described["versions"], described["plays"]) == ("1.0.0", ["1.0.0"], 1) + assert described["added"] == "2023-11-14T22:13:20Z" + assert described["notes"] == NOTES + assert described["aliases"] == ["tidewater.example.org"] + + +def test_added_prefers_the_registry(parts): + core, store = parts[:2] + store.add("overwinter", "1.0.0", {}) + assert addedOf(core.games().get("overwinter"), store) == "2026-10-01T00:00:00Z" + assert addedOf(core.games().get("rps"), store) is None + + +def test_added_with_a_time(): + class Timed(object): + slug = "x" + added = datetime.datetime(2026, 10, 1, 12, 0, tzinfo=datetime.timezone(datetime.timedelta(hours=-6))) + + assert addedOf(Timed(), FakeStore()) == "2026-10-01T18:00:00Z" + + +# --- plays ------------------------------------------------------------------ + + +@pytest.mark.parametrize("agent", [None, "", "Googlebot", "curl/8", "python-requests", "HeadlessChrome", "x arcade-watch"]) +def test_scripts_are_not_plays(parts, agent): + core, store = parts[:2] + core.played("tidewater", agent, "1.2.3.4") + assert store.plays("tidewater") == 0 and core.reporter.events == [] + + +def test_a_person_plays_once_a_day(parts): + core, store = parts[:2] + for _ in range(2): + core.played("tidewater", "Mozilla/5.0", "1.2.3.4") + assert store.plays("tidewater") == 1 + assert core.reporter.events == [("page-served", {"slug": "tidewater"})] + + +def test_a_play_that_cannot_be_counted_is_logged_and_still_reported(parts): + core, store, lines = parts + store.failPlays = True + core.played("tidewater", "Mozilla/5.0", None) + assert lines == ["could not count a play of tidewater: disk full"] + assert core.reporter.events == [("page-served", {"slug": "tidewater"})] + + +def test_hash_token(): + assert hashToken("abc") == "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + + +def test_a_bundle_too_large_unpacked_is_413(parts): + core, store, lines = parts + core.maxUploadBytes = 64 * 1024 + files = bundleFiles("1.0.0") + files["index.html"] = b"0" * (core.maxUploadBytes + 1) # compresses far below the cap + data = tarBundle(files, compression="gz") + assert len(data) < core.maxUploadBytes + outcome = core.deploy(tidewater(core), "1.0.0", data, True, len(data)) + assert isinstance(outcome, Rejected) and outcome.status == 413 and outcome.error + assert store.versions("tidewater") == [] and lines == [] + + +def test_a_static_game_takes_a_static_bundle(parts): + core, store = parts[:2] + added = [] + real = store.add + store.add = lambda *args, **kwargs: (added.append(kwargs["static"]), real(*args, **kwargs)) + rps = core.games().get("rps") + data = tarBundle({"index.html": b"", "version.txt": b"1.0.0\n"}) + assert core.deploy(rps, "1.0.0", data, True, len(data)) == Deployed(201, game=rps) + assert added == [True] + assert core.deploy(tidewater(core), "1.0.0", data, True, len(data)).status == 400