Spaces:
Running

clefourrier's picture
clefourrier HF Staff
Deploy msgboard 0.1.0
7ad3e85 verified
Raw History Blame Contribute Delete
13.6 kB
"""Deploy a board to a Hugging Face Space: `msgboard.space.deploy()`.
The Space runs `msgboard.space.app` from the files of the msgboard install that calls deploy(),
keeps its board in SQLite on its own disk and pushes snapshots to a private bucket through the
Hub API (DEPLOY_SPACES.md explains why it is not a bucket mount).
"""
import json
import logging
import re
from dataclasses import dataclass, field
from importlib import metadata
from pathlib import Path
from .. import auth
log = logging.getLogger("msgboard.space")
TAG = "msgboard" # deploy() puts it in the Space card, and reuses only Spaces that have it
SNAPSHOT_INTERVAL = "15" # MSGBOARD_SNAPSHOT_INTERVAL, in seconds
_HERE = Path(__file__).resolve().parent
_PACKAGE = _HERE.parent # the installed msgboard package, uploaded as-is
class DeployError(Exception):
"""deploy() refused, before changing anything on the Hub."""
@dataclass(frozen=True)
class Deployment:
"""What deploy() set up."""
space_id: str # "namespace/name"; a bare name gets the logged-in account
url: str # the board's base URL, https://<namespace>-<name>.hf.space
bucket_id: str # "namespace/name" of the private bucket that holds the snapshots
created: bool # True if this call created the Space, False if it reused one
private: bool # the Space's visibility; a reused Space keeps its own
commit: str # the Space repo commit that holds this deployment
# The admin token deploy() made when called without operator_token (None if the caller passed one).
# It's left out of repr() so printing or logging a Deployment never shows it.
operator_token: str | None = field(default=None, repr=False)
def _resolve_space_id(space_id: str, *, token: str | None = None) -> str:
"""Return `space_id` as "namespace/name". A bare name goes in the logged-in account, as in Trackio."""
return _Names(_hf_api(_hf_token(token))).full(space_id)
def deploy(space_id: str, *, token: str | None = None, operator_token: str | None = None,
bucket_id: str | None = None, private: bool | None = None, title: str | None = None) -> Deployment:
"""Create or update the board Space `space_id` and return a `Deployment`.
`space_id` is "namespace/name" or a bare name for the logged-in account. A missing Space is
created (Docker SDK, CPU Basic) with `private` as its visibility (None: the namespace's default).
An existing Space is reused, and keeps its visibility, only if its card has the `msgboard` tag
that deploy() puts there. Any other Space raises DeployError without being changed, including one
left by a first deploy() that failed before its upload: delete that one and deploy again.
A reused board keeps its bucket, the one its MSGBOARD_REPLICA names. A new board's is `bucket_id`,
else "<space_id>-bucket", or -2, -3 ... if that exists, so it never restores the snapshots a
deleted Space left behind. The bucket is always private, whatever `private` says: it holds every
message, token hash and invite. An existing public bucket is refused. So is anything that would
restart a board against an empty bucket: a `bucket_id` other than the board's, a MSGBOARD_REPLICA
that isn't the hf://buckets/<namespace>/<bucket> deploy() set, or a bucket that is missing
(deleted or not visible to this token). All checks run before the first write.
The Space gets the secrets MSGBOARD_OPERATOR_TOKEN (`operator_token`, from
`msgboard.auth.new_token()`; the app makes it the admin credential on every boot) and HF_TOKEN
(`token`, default: the logged-in token), and the variables MSGBOARD_REPLICA=hf://buckets/<bucket>
and MSGBOARD_SNAPSHOT_INTERVAL=15. That one HF token makes deploy()'s Hub calls and is what the
Space writes the bucket with, so it needs write access to both the Space and its bucket.
Without `operator_token`, deploy() makes one with new_token() and returns it as
`Deployment.operator_token` (None when you pass one). On a reused board that rotates the admin
token: the new one replaces the secret, and the old one stops working once the Space restarts.
So omit it only if you'll keep the returned one; a deploy() that raises returns no token, and the
next call makes another.
The Space's files become the installed msgboard package, LICENSE, requirements.txt, the Dockerfile
and the card, whose title is `title` (default: the Space's name); anything else in the Space repo
is deleted.
The Space then builds or restarts, which takes a few minutes: wait with `Client.wait_ready()`.
A reused Space keeps answering with its previous container for a while; wait_ready() with the
operator token waits until the board accepts that token. A restart or rebuild can still follow
after wait_ready() returns: if `operator_token` is the one the Space already has, the old healthy
container satisfies wait_ready() before the pending restart. Keep retrying through 503 after it.
"""
from huggingface_hub import CommitOperationAdd, CommitOperationDelete
from huggingface_hub.errors import RepositoryNotFoundError
generated = operator_token is None
if generated:
operator_token = auth.new_token()[1]
elif auth.parse_token(operator_token) is None:
raise DeployError("operator_token is not a board token; make one with msgboard.auth.new_token()")
token = _hf_token(token)
api = _hf_api(token)
names = _Names(api)
space_id = names.full(space_id)
bucket_id = names.full(bucket_id) if bucket_id else None
try:
info = api.space_info(space_id)
except RepositoryNotFoundError:
info = None
variables: dict[str, str] = {}
if info is not None:
if TAG not in (info.tags or []):
raise DeployError(f"{space_id} exists but is not a msgboard board (no {TAG!r} tag in its card), so it "
"was left alone; choose another Space ID")
# A restart boots a reused board from its bucket, so never let it come back against an empty one.
variables = {k: v.value for k, v in api.get_space_variables(space_id).items()}
replica = variables.get("MSGBOARD_REPLICA")
current = _bucket_of(replica)
if current is None:
raise DeployError(f"{space_id} has MSGBOARD_REPLICA={replica!r}, not hf://buckets/<namespace>/<bucket> "
"as deploy() sets it; set it back to the bucket that holds the board's snapshots")
if bucket_id and bucket_id != current:
raise DeployError(f"{space_id} keeps its board in bucket {current}, not {bucket_id}; "
"leave bucket_id out to keep using it")
bucket_id = current
bucket_id = bucket_id or _free_bucket_id(api, f"{space_id}-bucket")
bucket = _bucket_info(api, bucket_id)
if bucket is None and info is not None:
raise DeployError(f"{space_id} is a deployed board, and its bucket {bucket_id} was not found (deleted, "
"or not visible to this token); refusing to restart the board against an empty bucket")
if bucket is not None and not bucket.private:
raise DeployError(f"bucket {bucket_id} is public; a board's bucket must be private, because its "
"snapshots hold every message, token hash and invite")
dist = _distribution()
files = _space_files(space_id, dist, title)
secrets = {"MSGBOARD_OPERATOR_TOKEN": operator_token, "HF_TOKEN": token}
wanted = {"MSGBOARD_REPLICA": f"hf://buckets/{bucket_id}", "MSGBOARD_SNAPSHOT_INTERVAL": SNAPSHOT_INTERVAL}
created = info is None
if created: # secrets and variables come with the Space; nothing runs before the first commit
api.create_repo(space_id, repo_type="space", private=private, space_sdk="docker",
space_hardware="cpu-basic",
space_secrets=[{"key": k, "value": v} for k, v in secrets.items()],
space_variables=[{"key": k, "value": v} for k, v in wanted.items()])
if bucket is None:
api.create_bucket(bucket_id, private=True, exist_ok=True)
if not created: # each of these restarts the board
for key, value in secrets.items():
api.add_space_secret(space_id, key, value)
for key, value in wanted.items():
if variables.get(key) != value:
api.add_space_variable(space_id, key, value)
stale = set(api.list_repo_files(space_id, repo_type="space")) - set(files) - {".gitattributes"}
operations = [CommitOperationAdd(path, data) for path, data in files.items()]
operations += [CommitOperationDelete(path) for path in sorted(stale)]
commit = api.create_commit(space_id, repo_type="space", operations=operations,
commit_message=f"Deploy msgboard {dist.version}")
info = api.space_info(space_id)
return Deployment(space_id=space_id, url=(info.host or f"https://{info.subdomain}.hf.space").rstrip("/"),
bucket_id=bucket_id, created=created, private=bool(info.private), commit=commit.oid,
operator_token=operator_token if generated else None)
def _hf_token(token: str | None) -> str:
from huggingface_hub import get_token
token = token or get_token()
if not token:
raise DeployError("no Hugging Face token: log in with `hf auth login` or set HF_TOKEN")
return token
def _hf_api(token: str):
from huggingface_hub import HfApi
return HfApi(token=token)
class _Names:
"""Fills in the logged-in account for bare repo names, asking the Hub at most once."""
def __init__(self, api):
self.api = api
self._namespace = None
def full(self, repo_id: str) -> str:
from huggingface_hub.utils import validate_repo_id
if "/" not in repo_id:
self._namespace = self._namespace or self.api.whoami()["name"]
repo_id = f"{self._namespace}/{repo_id}"
validate_repo_id(repo_id)
return repo_id
def _bucket_of(replica: str | None) -> str | None:
"""The bucket ID in the MSGBOARD_REPLICA deploy() sets, `hf://buckets/<namespace>/<bucket>`."""
match = re.fullmatch(r"hf://buckets/([^/]+/[^/]+)", replica or "")
return match[1] if match else None
def _bucket_info(api, bucket_id: str):
from huggingface_hub.errors import BucketNotFoundError
try:
return api.bucket_info(bucket_id)
except BucketNotFoundError:
return None
def _free_bucket_id(api, preferred: str) -> str:
"""`preferred`, or the first of preferred-2, -3 ... that doesn't exist, as Trackio's resolve_auto_bucket_id."""
candidate, n = preferred, 1
while _bucket_info(api, candidate) is not None:
n += 1
candidate = f"{preferred}-{n}"
if candidate != preferred:
log.info("bucket %s already exists; using %s", preferred, candidate)
return candidate
def _distribution():
try:
return metadata.distribution("msgboard")
except metadata.PackageNotFoundError:
raise DeployError("msgboard is not installed; deploy() uploads the installed package "
"(pip install 'msgboard @ git+https://github.com/huggingface/msgboard', "
"or pip install -e . in a checkout)") from None
def _space_files(space_id: str, dist, title: str | None = None) -> dict[str, bytes]:
"""The Space repo's files by path: card, Dockerfile, requirements.txt, LICENSE and the package."""
# A JSON string is a quoted YAML string, so `true`, `null`, `2024`, ':' or '#' stay the title as written.
# ensure_ascii=False keeps an emoji whole (YAML reads JSON's surrogate pair as two lone halves). YAML
# reads U+0085/U+2028/U+2029 as line breaks and refuses DEL and C1 controls, so those stay escaped.
title = re.sub(r"[\x7f-\x9f\u2028\u2029]", lambda m: f"\\u{ord(m[0]):04x}",
json.dumps(title or space_id.split("/")[1], ensure_ascii=False))
card = (_HERE / "README.md").read_text().replace("title: msgboard\n", f"title: {title}\n", 1)
files = {"README.md": card.encode(), "Dockerfile": (_HERE / "Dockerfile").read_bytes(),
"requirements.txt": _requirements(dist).encode(), "LICENSE": _license(dist)}
# An allowlist, so stray files in an editable install's src/msgboard (a test board's token, say)
# never reach a public Space. Keep it in step with [tool.setuptools.package-data] in pyproject.toml.
for path in sorted(_PACKAGE.rglob("*")):
if (path.suffix in (".py", ".html") and "__pycache__" not in path.parts and path.is_file()
and path.resolve().is_relative_to(_PACKAGE)): # no symlinks out of the package
files["msgboard/" + path.relative_to(_PACKAGE).as_posix()] = path.read_bytes()
return files
def _requirements(dist) -> str:
"""Runtime requirements only; optional extras are left out."""
return "\n".join(req.strip() for req in dist.requires or [] if "extra" not in req.partition(";")[2]) + "\n"
def _license(dist) -> bytes:
"""LICENSE from the install's dist-info, in licenses/ as setuptools 77+ (PEP 639) puts it."""
for name in dist.metadata.get_all("License-File") or []:
text = dist.read_text(f"licenses/{name}")
if text:
return text.encode()
raise DeployError("the installed msgboard has no LICENSE in its metadata; reinstall it with setuptools>=77")