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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
3 changes: 2 additions & 1 deletion src/arcade/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
30 changes: 30 additions & 0 deletions src/arcade/hosting/__init__.py
Original file line number Diff line number Diff line change
@@ -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"]
25 changes: 25 additions & 0 deletions src/arcade/hosting/adapters/__init__.py
Original file line number Diff line number Diff line change
@@ -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"]
9 changes: 9 additions & 0 deletions src/arcade/hosting/adapters/null_reporter.py
Original file line number Diff line number Diff line change
@@ -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
52 changes: 52 additions & 0 deletions src/arcade/hosting/adapters/reloading_yaml_catalog.py
Original file line number Diff line number Diff line change
@@ -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
184 changes: 184 additions & 0 deletions src/arcade/hosting/core.py
Original file line number Diff line number Diff line change
@@ -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 <token> 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)
Loading
Loading