greenaihack 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- greenaihack/__init__.py +6 -0
- greenaihack/cli.py +408 -0
- greenaihack/client.py +90 -0
- greenaihack/dryrun.py +56 -0
- greenaihack/local.py +197 -0
- greenaihack/project.py +331 -0
- greenaihack/submission.py +260 -0
- greenaihack/ui.py +179 -0
- greenaihack-0.0.1.dist-info/METADATA +45 -0
- greenaihack-0.0.1.dist-info/RECORD +12 -0
- greenaihack-0.0.1.dist-info/WHEEL +4 -0
- greenaihack-0.0.1.dist-info/entry_points.txt +3 -0
greenaihack/__init__.py
ADDED
greenaihack/cli.py
ADDED
|
@@ -0,0 +1,408 @@
|
|
|
1
|
+
"""Register a team or connect this machine to an existing Green AI Hack team."""
|
|
2
|
+
|
|
3
|
+
import configparser
|
|
4
|
+
import os
|
|
5
|
+
from typing import Annotated
|
|
6
|
+
|
|
7
|
+
import typer
|
|
8
|
+
from rich.markup import escape as markup
|
|
9
|
+
|
|
10
|
+
from . import __version__
|
|
11
|
+
from .client import Client, api_url
|
|
12
|
+
from .dryrun import DryRunClient
|
|
13
|
+
from .local import SetupError, identity, machine_directory, repository, save_credentials
|
|
14
|
+
from .project import (
|
|
15
|
+
commit,
|
|
16
|
+
configure,
|
|
17
|
+
load,
|
|
18
|
+
lock,
|
|
19
|
+
planned_files,
|
|
20
|
+
preflight,
|
|
21
|
+
push,
|
|
22
|
+
push_target,
|
|
23
|
+
setup_changes,
|
|
24
|
+
)
|
|
25
|
+
from .ui import (
|
|
26
|
+
choose,
|
|
27
|
+
confirm,
|
|
28
|
+
done,
|
|
29
|
+
dry_run_done,
|
|
30
|
+
dry_run_notice,
|
|
31
|
+
error,
|
|
32
|
+
info,
|
|
33
|
+
prompt,
|
|
34
|
+
require_terminal,
|
|
35
|
+
success,
|
|
36
|
+
warn,
|
|
37
|
+
welcome,
|
|
38
|
+
working,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
COMMIT_MESSAGE = "chore: set up Green AI Hack team"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def select_event(client):
|
|
45
|
+
with working("Looking for open events…"):
|
|
46
|
+
events = client.request("/events", None, method="GET")["events"]
|
|
47
|
+
if not events:
|
|
48
|
+
raise SetupError("No event is open for registration; contact the organizer")
|
|
49
|
+
if len(events) == 1:
|
|
50
|
+
success(f"Event: [bold]{markup(events[0]['id'])}[/]")
|
|
51
|
+
return events[0]["id"]
|
|
52
|
+
return events[choose([event["id"] for event in events], "Event")]["id"]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def new_password():
|
|
56
|
+
while True:
|
|
57
|
+
password = prompt(
|
|
58
|
+
"Team password (at least 12 characters)",
|
|
59
|
+
secret=True,
|
|
60
|
+
validate=lambda value: (
|
|
61
|
+
"Use at least 12 characters" if len(value) < 12 else None
|
|
62
|
+
),
|
|
63
|
+
)
|
|
64
|
+
if password == prompt("Confirm team password", secret=True):
|
|
65
|
+
return password
|
|
66
|
+
warn("Passwords do not match; try again")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def register_team(client, shared):
|
|
70
|
+
if shared:
|
|
71
|
+
# A retry must address the same infrastructure, even after local setup
|
|
72
|
+
# succeeded only partially.
|
|
73
|
+
event_id, name = shared["event_id"], shared["team_name"]
|
|
74
|
+
info(
|
|
75
|
+
f"Resuming registration of team [bold]{markup(name)}[/] for {markup(event_id)}."
|
|
76
|
+
)
|
|
77
|
+
else:
|
|
78
|
+
event_id, name = select_event(client), None
|
|
79
|
+
secret = prompt("Event secret", secret=True)
|
|
80
|
+
name = name or prompt(
|
|
81
|
+
"Team name",
|
|
82
|
+
validate=lambda value: "Use at most 80 characters" if len(value) > 80 else None,
|
|
83
|
+
)
|
|
84
|
+
password = new_password()
|
|
85
|
+
with working("Registering your team and preparing its infrastructure…"):
|
|
86
|
+
return client.request(
|
|
87
|
+
"/register",
|
|
88
|
+
{
|
|
89
|
+
"event_id": event_id,
|
|
90
|
+
"event_secret": secret,
|
|
91
|
+
"team_name": name,
|
|
92
|
+
"password": password,
|
|
93
|
+
},
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def sign_in(client, shared):
|
|
98
|
+
if shared:
|
|
99
|
+
event_id, team_id = shared["event_id"], shared["team_id"]
|
|
100
|
+
info(
|
|
101
|
+
f"This repository belongs to team [bold]{markup(shared['team_name'])}[/] "
|
|
102
|
+
f"({markup(event_id)})."
|
|
103
|
+
)
|
|
104
|
+
else:
|
|
105
|
+
event_id = select_event(client)
|
|
106
|
+
secret = prompt("Event secret", secret=True)
|
|
107
|
+
with working("Fetching teams…"):
|
|
108
|
+
teams = client.request(
|
|
109
|
+
"/teams/select", {"event_id": event_id, "event_secret": secret}
|
|
110
|
+
)["teams"]
|
|
111
|
+
if not teams:
|
|
112
|
+
raise SetupError("No teams are registered for this event yet")
|
|
113
|
+
labels = [f"{team['name']} ({team['state']})" for team in teams]
|
|
114
|
+
team_id = teams[choose(labels, "Team")]["id"]
|
|
115
|
+
password = prompt("Team password", secret=True)
|
|
116
|
+
with working("Signing in…"):
|
|
117
|
+
return client.request(
|
|
118
|
+
"/login", {"event_id": event_id, "team_id": team_id, "password": password}
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def publish(root, written):
|
|
123
|
+
"""Offer to commit the setup files and push them; return whether both happened."""
|
|
124
|
+
paths = setup_changes(root, written)
|
|
125
|
+
if not paths:
|
|
126
|
+
return True
|
|
127
|
+
target = push_target(root)
|
|
128
|
+
info("\nThese setup files are ready to share with your teammates:")
|
|
129
|
+
for path in paths:
|
|
130
|
+
info(f" [green]+[/] {markup(path)}")
|
|
131
|
+
where = "/".join(target) if target else None
|
|
132
|
+
if not confirm(
|
|
133
|
+
f"Commit them and push to {where}?" if where else "Commit them now?"
|
|
134
|
+
):
|
|
135
|
+
return False
|
|
136
|
+
if not commit(root, paths, COMMIT_MESSAGE):
|
|
137
|
+
warn("git commit failed; commit these files yourself, then push")
|
|
138
|
+
return False
|
|
139
|
+
success(f'Committed "{COMMIT_MESSAGE}"')
|
|
140
|
+
if not target:
|
|
141
|
+
warn("No collaboration remote found; add one and push so teammates can log in")
|
|
142
|
+
return False
|
|
143
|
+
try:
|
|
144
|
+
pushed = push(root, *target)
|
|
145
|
+
except KeyboardInterrupt:
|
|
146
|
+
pushed = False
|
|
147
|
+
if not pushed:
|
|
148
|
+
warn(f"Push did not complete; run git push {target[0]} {target[1]} when ready")
|
|
149
|
+
return False
|
|
150
|
+
success(f"Pushed to {markup(where)}")
|
|
151
|
+
return True
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def preview(root, register, team):
|
|
155
|
+
"""Report what connect() would change, without changing anything."""
|
|
156
|
+
steps = [
|
|
157
|
+
f"register team {team} and create its GitLab submission repository, "
|
|
158
|
+
"storage bucket and credentials"
|
|
159
|
+
if register
|
|
160
|
+
else f"sign in to team {team}",
|
|
161
|
+
"create an SSH key for this machine and register it with the API",
|
|
162
|
+
"save the credentials outside the repository",
|
|
163
|
+
"configure DVC and the greenaihack Git remote",
|
|
164
|
+
]
|
|
165
|
+
files = planned_files(root, register)
|
|
166
|
+
if files:
|
|
167
|
+
steps.append("create or update " + ", ".join(files))
|
|
168
|
+
if register:
|
|
169
|
+
target = push_target(root)
|
|
170
|
+
steps.append(
|
|
171
|
+
f"offer to commit these files and push them to {'/'.join(target)}"
|
|
172
|
+
if target
|
|
173
|
+
else "offer to commit these files (no collaboration remote found)"
|
|
174
|
+
)
|
|
175
|
+
info("\n[bold]Without --dry-run, this would:[/]")
|
|
176
|
+
for step in steps:
|
|
177
|
+
info(f" • {markup(step)}")
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def connect(command, api_override, dry_run=False):
|
|
181
|
+
register = command == "register"
|
|
182
|
+
root = repository()
|
|
183
|
+
preflight(root)
|
|
184
|
+
shared = load(root)
|
|
185
|
+
api = api_url(
|
|
186
|
+
api_override
|
|
187
|
+
or (shared or {}).get("api_url")
|
|
188
|
+
or os.getenv("GREENAIHACK_API_URL")
|
|
189
|
+
or "https://api.greenaihack.org"
|
|
190
|
+
)
|
|
191
|
+
if shared and api != shared["api_url"]:
|
|
192
|
+
raise SetupError("The API URL differs from the team's shared configuration")
|
|
193
|
+
client = DryRunClient(shared) if dry_run else Client(api)
|
|
194
|
+
# Fail before any network call rather than at the first prompt.
|
|
195
|
+
require_terminal()
|
|
196
|
+
welcome(command)
|
|
197
|
+
if dry_run:
|
|
198
|
+
dry_run_notice()
|
|
199
|
+
result = (register_team if register else sign_in)(client, shared)
|
|
200
|
+
team = result["team"]
|
|
201
|
+
if dry_run:
|
|
202
|
+
preview(root, register, team["name"])
|
|
203
|
+
dry_run_done(team["name"], team["event_id"])
|
|
204
|
+
return 0
|
|
205
|
+
name = f"[bold]{markup(team['name'])}[/]"
|
|
206
|
+
success(f"Team {name} is registered" if register else f"Signed in to team {name}")
|
|
207
|
+
with working("Setting up this machine…"):
|
|
208
|
+
directory = machine_directory(root, api, team["id"])
|
|
209
|
+
save_credentials(directory, api, result)
|
|
210
|
+
private_path, public_key = identity(directory)
|
|
211
|
+
client.request(
|
|
212
|
+
"/device-keys", {"public_key": public_key}, token=result["session_token"]
|
|
213
|
+
)
|
|
214
|
+
written = configure(root, api, result, directory, private_path, register)
|
|
215
|
+
success("Configured storage and the submission remote")
|
|
216
|
+
pushed = True
|
|
217
|
+
if register:
|
|
218
|
+
with working("Locking Python dependencies (uv lock)…"):
|
|
219
|
+
locked = lock(root)
|
|
220
|
+
if not locked:
|
|
221
|
+
warn("uv lock failed; run uv lock and commit uv.lock before submitting")
|
|
222
|
+
pushed = publish(root, written)
|
|
223
|
+
done(command, team["name"], team["event_id"], pushed)
|
|
224
|
+
return 0
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
app = typer.Typer(
|
|
228
|
+
help=__doc__,
|
|
229
|
+
no_args_is_help=True,
|
|
230
|
+
add_completion=False,
|
|
231
|
+
pretty_exceptions_enable=False,
|
|
232
|
+
context_settings={"help_option_names": ["-h", "--help"]},
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _show_version(value: bool):
|
|
237
|
+
if value:
|
|
238
|
+
typer.echo(__version__)
|
|
239
|
+
raise typer.Exit()
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
@app.callback()
|
|
243
|
+
def options(
|
|
244
|
+
version: Annotated[
|
|
245
|
+
bool,
|
|
246
|
+
typer.Option(
|
|
247
|
+
"--version",
|
|
248
|
+
callback=_show_version,
|
|
249
|
+
is_eager=True,
|
|
250
|
+
help="Show the CLI version and exit.",
|
|
251
|
+
),
|
|
252
|
+
] = False,
|
|
253
|
+
):
|
|
254
|
+
pass
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
ApiUrl = Annotated[
|
|
258
|
+
str | None,
|
|
259
|
+
typer.Option(
|
|
260
|
+
"--api-url",
|
|
261
|
+
help="API URL override; uses shared config, GREENAIHACK_API_URL, or https://api.greenaihack.org",
|
|
262
|
+
),
|
|
263
|
+
]
|
|
264
|
+
|
|
265
|
+
DryRun = Annotated[
|
|
266
|
+
bool,
|
|
267
|
+
typer.Option(
|
|
268
|
+
"--dry-run",
|
|
269
|
+
help="Try the command with sample data: nothing is sent to the API and nothing is changed.",
|
|
270
|
+
),
|
|
271
|
+
]
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
@app.command()
|
|
275
|
+
def register(api_url: ApiUrl = None, dry_run: DryRun = False):
|
|
276
|
+
"""Register a team and configure its repository."""
|
|
277
|
+
_connect("register", api_url, dry_run)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
@app.command()
|
|
281
|
+
def login(api_url: ApiUrl = None, dry_run: DryRun = False):
|
|
282
|
+
"""Connect this machine to an existing team."""
|
|
283
|
+
_connect("login", api_url, dry_run)
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
@app.command()
|
|
287
|
+
def submit(
|
|
288
|
+
no_model: Annotated[
|
|
289
|
+
bool,
|
|
290
|
+
typer.Option("--no-model", help="Submit without models, overriding defaults"),
|
|
291
|
+
] = False,
|
|
292
|
+
resume: Annotated[
|
|
293
|
+
str | None, typer.Option("--resume", help="Resume a saved submission ID")
|
|
294
|
+
] = None,
|
|
295
|
+
script: Annotated[
|
|
296
|
+
str | None,
|
|
297
|
+
typer.Option("--script", help="Evaluation script relative to the repository"),
|
|
298
|
+
] = None,
|
|
299
|
+
model: Annotated[
|
|
300
|
+
list[str] | None,
|
|
301
|
+
typer.Option(
|
|
302
|
+
"--model", help="Model file/directory; repeat for multiple models"
|
|
303
|
+
),
|
|
304
|
+
] = None,
|
|
305
|
+
name: Annotated[
|
|
306
|
+
str | None,
|
|
307
|
+
typer.Option(
|
|
308
|
+
"--name", help="Experiment name; generated automatically when omitted"
|
|
309
|
+
),
|
|
310
|
+
] = None,
|
|
311
|
+
):
|
|
312
|
+
"""Upload models and submit committed source for evaluation."""
|
|
313
|
+
from .submission import submit as send
|
|
314
|
+
|
|
315
|
+
if (no_model and model) or (resume and (script or model or name or no_model)):
|
|
316
|
+
typer.echo(
|
|
317
|
+
"Use --resume alone; --model and --no-model are mutually exclusive",
|
|
318
|
+
err=True,
|
|
319
|
+
)
|
|
320
|
+
raise typer.Exit(2)
|
|
321
|
+
_submission_call(lambda: send(script, [] if no_model else model, name, resume))
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
@app.command()
|
|
325
|
+
def status(
|
|
326
|
+
submission_id: str,
|
|
327
|
+
wait: Annotated[
|
|
328
|
+
bool, typer.Option("--wait", help="Poll until evaluation completes")
|
|
329
|
+
] = False,
|
|
330
|
+
):
|
|
331
|
+
"""Retrieve current evaluation status."""
|
|
332
|
+
from .submission import status as fetch
|
|
333
|
+
|
|
334
|
+
def poll():
|
|
335
|
+
import time
|
|
336
|
+
|
|
337
|
+
while True:
|
|
338
|
+
value = fetch(submission_id)
|
|
339
|
+
if not wait or value["state"] in {
|
|
340
|
+
"success",
|
|
341
|
+
"failed",
|
|
342
|
+
"canceled",
|
|
343
|
+
"skipped",
|
|
344
|
+
"trigger_uncertain",
|
|
345
|
+
}:
|
|
346
|
+
return value
|
|
347
|
+
typer.echo(f"Evaluation: {value['state']}")
|
|
348
|
+
time.sleep(5)
|
|
349
|
+
|
|
350
|
+
_submission_call(poll)
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
@app.command()
|
|
354
|
+
def logs(submission_id: str):
|
|
355
|
+
"""Retrieve completed evaluation logs."""
|
|
356
|
+
from .submission import status as fetch
|
|
357
|
+
|
|
358
|
+
_submission_call(lambda: fetch(submission_id, logs=True))
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
@app.command()
|
|
362
|
+
def results(submission_id: str):
|
|
363
|
+
"""Retrieve inference predictions (unscored)."""
|
|
364
|
+
from .submission import status as fetch
|
|
365
|
+
|
|
366
|
+
_submission_call(lambda: fetch(submission_id, results=True))
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def _submission_call(action):
|
|
370
|
+
import json
|
|
371
|
+
|
|
372
|
+
try:
|
|
373
|
+
typer.echo(json.dumps(action(), indent=2))
|
|
374
|
+
except KeyboardInterrupt:
|
|
375
|
+
typer.echo("Interrupted; reconnect with status SUBMISSION_ID", err=True)
|
|
376
|
+
raise typer.Exit(130) from None
|
|
377
|
+
except (SetupError, OSError, ValueError, KeyError, TypeError) as exc:
|
|
378
|
+
typer.echo(
|
|
379
|
+
str(exc)
|
|
380
|
+
if isinstance(exc, SetupError)
|
|
381
|
+
else "Submission failed; check local configuration",
|
|
382
|
+
err=True,
|
|
383
|
+
)
|
|
384
|
+
raise typer.Exit(2) from None
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def _connect(command: str, api_override: str | None, dry_run: bool = False):
|
|
388
|
+
try:
|
|
389
|
+
connect(command, api_override, dry_run)
|
|
390
|
+
except (
|
|
391
|
+
SetupError,
|
|
392
|
+
OSError,
|
|
393
|
+
ValueError,
|
|
394
|
+
configparser.Error,
|
|
395
|
+
EOFError,
|
|
396
|
+
KeyError,
|
|
397
|
+
TypeError,
|
|
398
|
+
) as exc:
|
|
399
|
+
message = (
|
|
400
|
+
str(exc)
|
|
401
|
+
if isinstance(exc, SetupError)
|
|
402
|
+
else "Local setup failed; check files and permissions, then retry"
|
|
403
|
+
)
|
|
404
|
+
error(message)
|
|
405
|
+
raise typer.Exit(code=2) from None
|
|
406
|
+
except KeyboardInterrupt:
|
|
407
|
+
warn("Interrupted. Retry the same command to resume setup.")
|
|
408
|
+
raise typer.Exit(code=130) from None
|
greenaihack/client.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Small HTTP client with explicit versioning and safe error messages."""
|
|
2
|
+
|
|
3
|
+
from urllib.parse import urlsplit
|
|
4
|
+
|
|
5
|
+
import httpx
|
|
6
|
+
|
|
7
|
+
from . import __version__
|
|
8
|
+
from .local import SetupError
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def api_url(value):
|
|
12
|
+
value = value.rstrip("/")
|
|
13
|
+
try:
|
|
14
|
+
parsed = urlsplit(value)
|
|
15
|
+
if (
|
|
16
|
+
parsed.username
|
|
17
|
+
or parsed.password
|
|
18
|
+
or parsed.query
|
|
19
|
+
or parsed.fragment
|
|
20
|
+
or not parsed.hostname
|
|
21
|
+
):
|
|
22
|
+
raise ValueError()
|
|
23
|
+
if parsed.scheme != "https" and not (
|
|
24
|
+
parsed.scheme == "http"
|
|
25
|
+
and parsed.hostname in {"localhost", "127.0.0.1", "::1"}
|
|
26
|
+
):
|
|
27
|
+
raise ValueError()
|
|
28
|
+
_ = parsed.port
|
|
29
|
+
except ValueError:
|
|
30
|
+
raise SetupError(
|
|
31
|
+
"Use an HTTPS API URL (HTTP is allowed only on localhost)"
|
|
32
|
+
) from None
|
|
33
|
+
return value
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Client:
|
|
37
|
+
def __init__(self, url):
|
|
38
|
+
self.url = api_url(url)
|
|
39
|
+
|
|
40
|
+
def request(self, path, payload, token=None, method="POST"):
|
|
41
|
+
headers = {"X-GreenAIHack-Version": __version__}
|
|
42
|
+
if token:
|
|
43
|
+
headers["Authorization"] = f"Bearer {token}"
|
|
44
|
+
try:
|
|
45
|
+
# Provisioning takes several bounded provider calls. No automatic
|
|
46
|
+
# POST retry: callers can safely repeat register after an interruption.
|
|
47
|
+
with httpx.Client(
|
|
48
|
+
timeout=httpx.Timeout(300, connect=10), follow_redirects=False
|
|
49
|
+
) as client:
|
|
50
|
+
response = client.request(
|
|
51
|
+
method, self.url + "/v1" + path, json=payload, headers=headers
|
|
52
|
+
)
|
|
53
|
+
except httpx.HTTPError:
|
|
54
|
+
raise SetupError(
|
|
55
|
+
"The API could not be reached; retry the same command to resume"
|
|
56
|
+
) from None
|
|
57
|
+
try:
|
|
58
|
+
result = response.json()
|
|
59
|
+
except ValueError:
|
|
60
|
+
raise SetupError("The API returned an invalid response") from None
|
|
61
|
+
if not response.is_success:
|
|
62
|
+
detail = result.get("detail", {})
|
|
63
|
+
code = (
|
|
64
|
+
detail.get("code", "request_failed")
|
|
65
|
+
if isinstance(detail, dict)
|
|
66
|
+
else "request_failed"
|
|
67
|
+
)
|
|
68
|
+
safe = {
|
|
69
|
+
"evaluation_provider_unavailable": "Evaluation service unavailable; use submit --resume ID or status ID to reconcile without duplicating the run",
|
|
70
|
+
"submission_conflict": "This submission ID already refers to different content",
|
|
71
|
+
"submission_not_found": "Submission not found for this team",
|
|
72
|
+
"evaluation_not_finished": "Evaluation is still running; use status ID --wait first",
|
|
73
|
+
"evaluation_not_successful": "Results require a successful evaluation; check status and logs",
|
|
74
|
+
"evaluation_results_unavailable": "Prediction artifact is unavailable or expired",
|
|
75
|
+
"invalid_session": "Session expired or revoked; log in again",
|
|
76
|
+
"invalid_event_credentials": "Event identifier or secret is incorrect, or registration is closed",
|
|
77
|
+
"invalid_team_credentials": "Team or password is incorrect",
|
|
78
|
+
"team_name_unavailable": "This team name is already registered with another password",
|
|
79
|
+
"provisioning_failed": "Team provisioning is incomplete; retry register with the same team and password",
|
|
80
|
+
"provisioning_in_progress": "Team provisioning is in progress; retry in ten minutes",
|
|
81
|
+
"team_not_ready": "The captain must finish registration before teammates can log in",
|
|
82
|
+
"authentication_rate_limited": "Too many authentication attempts; retry in ten minutes",
|
|
83
|
+
"client_upgrade_required": "Upgrade with uvx greenaihack@latest and retry",
|
|
84
|
+
"device_key_registration_failed": "SSH key registration failed; retry the same command",
|
|
85
|
+
"storage_credentials_expired": "Team storage credentials expired; contact the organizer",
|
|
86
|
+
}
|
|
87
|
+
raise SetupError(
|
|
88
|
+
safe.get(code, f"API request failed (HTTP {response.status_code})")
|
|
89
|
+
)
|
|
90
|
+
return result
|
greenaihack/dryrun.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""Offline stand-in for the API client, used by --dry-run.
|
|
2
|
+
|
|
3
|
+
It answers the requests register and login make before machine setup with
|
|
4
|
+
sample team data shaped like the real API responses.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import re
|
|
8
|
+
import unicodedata
|
|
9
|
+
from uuid import uuid4
|
|
10
|
+
|
|
11
|
+
SAMPLE_EVENTS = ["demo-event", "demo-event-2"]
|
|
12
|
+
SAMPLE_TEAMS = ["Sample team", "Another sample team"]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class DryRunClient:
|
|
16
|
+
def __init__(self, shared=None):
|
|
17
|
+
own = (
|
|
18
|
+
{"id": shared["team_id"], "name": shared["team_name"]}
|
|
19
|
+
if shared
|
|
20
|
+
else {"id": str(uuid4()), "name": SAMPLE_TEAMS[0]}
|
|
21
|
+
)
|
|
22
|
+
others = [{"id": str(uuid4()), "name": name} for name in SAMPLE_TEAMS[1:]]
|
|
23
|
+
self.teams = [own, *others]
|
|
24
|
+
self.event_id = (shared or {}).get("event_id", SAMPLE_EVENTS[0])
|
|
25
|
+
|
|
26
|
+
def request(self, path, payload, token=None, method="POST"):
|
|
27
|
+
if path == "/events":
|
|
28
|
+
return {"events": [{"id": event} for event in SAMPLE_EVENTS]}
|
|
29
|
+
if path == "/teams/select":
|
|
30
|
+
return {"teams": [self._team(team) for team in self.teams]}
|
|
31
|
+
if path == "/register":
|
|
32
|
+
self.event_id = payload["event_id"]
|
|
33
|
+
return {
|
|
34
|
+
"team": self._team({"id": str(uuid4()), "name": payload["team_name"]})
|
|
35
|
+
}
|
|
36
|
+
if path == "/login":
|
|
37
|
+
self.event_id = payload["event_id"]
|
|
38
|
+
team = next(t for t in self.teams if t["id"] == payload["team_id"])
|
|
39
|
+
return {"team": self._team(team)}
|
|
40
|
+
# A dry run stops after signing in, before any machine setup request.
|
|
41
|
+
raise AssertionError(f"Unexpected dry-run request: {method} {path}")
|
|
42
|
+
|
|
43
|
+
def _team(self, team):
|
|
44
|
+
# Mirrors the API's slugify; dry runs never name real resources.
|
|
45
|
+
ascii_name = (
|
|
46
|
+
unicodedata.normalize("NFKD", team["name"])
|
|
47
|
+
.encode("ascii", "ignore")
|
|
48
|
+
.decode("ascii")
|
|
49
|
+
)
|
|
50
|
+
slug = re.sub(r"[^a-z0-9]+", "-", ascii_name.lower()).strip("-")[:26]
|
|
51
|
+
return {
|
|
52
|
+
**team,
|
|
53
|
+
"slug": slug.rstrip("-") or "team",
|
|
54
|
+
"event_id": self.event_id,
|
|
55
|
+
"state": "ready",
|
|
56
|
+
}
|