Spaces:
Running

File size: 13,548 Bytes
6235836
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
"""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', 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")