File size: 9,715 Bytes
e317359
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
#!/usr/bin/env python3
"""Initialize and publish a TS-Live community endpoint with fewer manual steps."""

from __future__ import annotations

import argparse
import json
import shutil
import subprocess
import sys
from datetime import datetime, timezone
from pathlib import Path
from typing import Callable, Sequence

import yaml

REPO_ROOT = Path(__file__).resolve().parents[1]
if str(REPO_ROOT) not in sys.path:
    sys.path.insert(0, str(REPO_ROOT))

from scripts.community_endpoint_protocol import validate_endpoint
from scripts.generate_community_model_metadata import (
    build_metadata,
    validate_submission_identity,
)


TEMPLATE_DIR = REPO_ROOT / "examples" / "community_endpoint"
TEMPLATE_FILES = (
    "app.py",
    "Dockerfile",
    "requirements.txt",
    "README.md",
    ".dockerignore",
    "compose.yaml",
)


def initialize_service(output_dir: Path, *, force: bool = False) -> list[Path]:
    """Copy the portable endpoint template without clobbering user work."""

    output_dir = output_dir.resolve()
    conflicts = [output_dir / name for name in TEMPLATE_FILES if (output_dir / name).exists()]
    if conflicts and not force:
        names = ", ".join(path.name for path in conflicts)
        raise RuntimeError(
            f"refusing to overwrite existing files in {output_dir}: {names}; "
            "pass --force only if this is intentional"
        )
    output_dir.mkdir(parents=True, exist_ok=True)
    copied = []
    for name in TEMPLATE_FILES:
        destination = output_dir / name
        shutil.copy2(TEMPLATE_DIR / name, destination)
        copied.append(destination)
    return copied


def _run_command(
    command: Sequence[str],
    *,
    runner: Callable[..., subprocess.CompletedProcess[str]] = subprocess.run,
) -> subprocess.CompletedProcess[str]:
    try:
        result = runner(
            list(command),
            check=False,
            capture_output=True,
            text=True,
        )
    except FileNotFoundError as exc:
        raise RuntimeError(
            f"{command[0]!r} was not found; install Tailscale and run "
            "`tailscale up` once before publishing"
        ) from exc
    if result.returncode != 0:
        details = "\n".join(
            part.strip() for part in (result.stdout, result.stderr) if part.strip()
        )
        suffix = f"\n{details}" if details else ""
        raise RuntimeError(f"command failed: {' '.join(command)}{suffix}")
    return result


def _tailscale_dns_name(
    tailscale_bin: str = "tailscale",
    *,
    runner: Callable[..., subprocess.CompletedProcess[str]] = subprocess.run,
) -> str:
    result = _run_command([tailscale_bin, "status", "--json"], runner=runner)
    try:
        payload = json.loads(result.stdout)
        dns_name = str(payload["Self"]["DNSName"]).strip().rstrip(".")
    except (KeyError, TypeError, ValueError, json.JSONDecodeError) as exc:
        raise RuntimeError(
            "could not read this device's MagicDNS name from `tailscale status --json`; "
            "confirm that Tailscale is connected and MagicDNS is enabled"
        ) from exc
    if not dns_name or "." not in dns_name:
        raise RuntimeError(f"Tailscale returned an invalid DNS name: {dns_name!r}")
    return dns_name


def start_tailscale_funnel(
    *,
    local_port: int,
    tailscale_bin: str = "tailscale",
    runner: Callable[..., subprocess.CompletedProcess[str]] = subprocess.run,
) -> str:
    """Persistently publish a loopback HTTP service and return its HTTPS URL."""

    if not 1 <= local_port <= 65535:
        raise ValueError("local port must be between 1 and 65535")
    dns_name = _tailscale_dns_name(tailscale_bin, runner=runner)
    target = f"http://127.0.0.1:{local_port}"
    _run_command(
        [tailscale_bin, "funnel", "--bg", "--https=443", target],
        runner=runner,
    )
    # A successful status call catches permission/configuration failures that
    # some client versions report only after accepting the Funnel command.
    _run_command(
        [tailscale_bin, "funnel", "status", "--json"],
        runner=runner,
    )
    return f"https://{dns_name}/forecast"


def publish_submission(
    *,
    model_id: str,
    display_name: str,
    code_url: str,
    output_dir: Path,
    local_port: int = 7860,
    endpoint_url: str | None = None,
    tailscale_bin: str = "tailscale",
    wait_seconds: float = 600.0,
    timeout: float = 90.0,
    validator: Callable[..., dict[str, object]] = validate_endpoint,
    funnel_starter: Callable[..., str] = start_tailscale_funnel,
) -> dict[str, object]:
    """Validate local/public routes and write a complete submission bundle."""

    if not 1 <= local_port <= 65535:
        raise ValueError("local port must be between 1 and 65535")
    validate_submission_identity(
        model_id=model_id,
        display_name=display_name,
        code_url=code_url,
    )
    if endpoint_url is not None:
        # Fail fast on an invalid supplied route before making any requests.
        build_metadata(
            model_id=model_id,
            display_name=display_name,
            code_url=code_url,
            endpoint_url=endpoint_url,
        )
    local_url = f"http://127.0.0.1:{local_port}/forecast"
    local_receipt = validator(
        endpoint_url=local_url,
        model_id=model_id,
        timeout=timeout,
        require_https=False,
    )

    provider = "existing_https"
    if endpoint_url is None:
        endpoint_url = funnel_starter(
            local_port=local_port,
            tailscale_bin=tailscale_bin,
        )
        provider = "tailscale_funnel"

    # The endpoint was unknown during the preflight when Funnel was selected,
    # so validate the complete metadata before the public readiness wait.
    metadata = build_metadata(
        model_id=model_id,
        display_name=display_name,
        code_url=code_url,
        endpoint_url=endpoint_url,
    )
    public_receipt = validator(
        endpoint_url=endpoint_url,
        model_id=model_id,
        timeout=timeout,
        wait_seconds=wait_seconds,
        require_https=True,
    )

    receipt = {
        "status": "ok",
        "generated_at_utc": datetime.now(timezone.utc).isoformat(),
        "provider": provider,
        "endpoint_url": endpoint_url,
        "local_validation": local_receipt,
        "public_validation": public_receipt,
    }
    output_dir = output_dir.resolve()
    output_dir.mkdir(parents=True, exist_ok=True)
    metadata_path = output_dir / "community_model.yaml"
    receipt_path = output_dir / "validator_receipt.json"
    metadata_path.write_text(
        yaml.safe_dump(metadata, sort_keys=False, allow_unicode=True),
        encoding="utf-8",
    )
    receipt_path.write_text(
        json.dumps(receipt, indent=2, ensure_ascii=False) + "\n",
        encoding="utf-8",
    )
    return {
        "status": "ok",
        "endpoint_url": endpoint_url,
        "metadata_path": str(metadata_path),
        "receipt_path": str(receipt_path),
    }


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    subparsers = parser.add_subparsers(dest="command", required=True)

    init_parser = subparsers.add_parser(
        "init", help="copy the endpoint template into an editable service directory"
    )
    init_parser.add_argument("--output-dir", type=Path, default=Path("forecast-service"))
    init_parser.add_argument("--force", action="store_true")

    publish_parser = subparsers.add_parser(
        "publish",
        help="validate locally, publish through Funnel, and generate submission files",
    )
    publish_parser.add_argument("--model-id", required=True)
    publish_parser.add_argument("--display-name", required=True)
    publish_parser.add_argument("--code-url", required=True)
    publish_parser.add_argument("--local-port", type=int, default=7860)
    publish_parser.add_argument(
        "--endpoint-url",
        help="use an existing public HTTPS /forecast URL instead of Tailscale Funnel",
    )
    publish_parser.add_argument("--tailscale-bin", default="tailscale")
    publish_parser.add_argument("--wait-seconds", type=float, default=600.0)
    publish_parser.add_argument("--timeout", type=float, default=90.0)
    publish_parser.add_argument(
        "--output-dir", type=Path, default=Path("community-submission")
    )
    return parser.parse_args()


def main() -> int:
    args = parse_args()
    if args.command == "init":
        copied = initialize_service(args.output_dir, force=args.force)
        print(
            json.dumps(
                {
                    "status": "ok",
                    "service_dir": str(args.output_dir.resolve()),
                    "copied": [str(path) for path in copied],
                    "next": (
                        "Replace forecast_one, then run: docker compose -f "
                        f'"{args.output_dir.resolve() / "compose.yaml"}" '
                        "up -d --build"
                    ),
                },
                indent=2,
            )
        )
        return 0

    result = publish_submission(
        model_id=args.model_id,
        display_name=args.display_name,
        code_url=args.code_url,
        output_dir=args.output_dir,
        local_port=args.local_port,
        endpoint_url=args.endpoint_url,
        tailscale_bin=args.tailscale_bin,
        wait_seconds=args.wait_seconds,
        timeout=args.timeout,
    )
    print(json.dumps(result, indent=2))
    return 0


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except (RuntimeError, ValueError) as exc:
        raise SystemExit(f"community model setup failed: {exc}") from exc