opensees-cli 0.2.4__tar.gz → 0.2.6__tar.gz

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.
Files changed (29) hide show
  1. {opensees_cli-0.2.4 → opensees_cli-0.2.6}/PKG-INFO +1 -1
  2. {opensees_cli-0.2.4 → opensees_cli-0.2.6}/pyproject.toml +1 -1
  3. {opensees_cli-0.2.4 → opensees_cli-0.2.6}/src/opensees_cli/__init__.py +1 -1
  4. {opensees_cli-0.2.4 → opensees_cli-0.2.6}/src/opensees_cli/auth.py +2 -0
  5. {opensees_cli-0.2.4 → opensees_cli-0.2.6}/src/opensees_cli/main.py +0 -18
  6. {opensees_cli-0.2.4 → opensees_cli-0.2.6}/src/opensees_cli.egg-info/PKG-INFO +1 -1
  7. {opensees_cli-0.2.4 → opensees_cli-0.2.6}/src/opensees_cli.egg-info/SOURCES.txt +0 -2
  8. {opensees_cli-0.2.4 → opensees_cli-0.2.6}/tests/test_auth_commands.py +9 -5
  9. {opensees_cli-0.2.4 → opensees_cli-0.2.6}/tests/test_main_commands.py +2 -2
  10. opensees_cli-0.2.4/src/opensees_cli/admin.py +0 -587
  11. opensees_cli-0.2.4/tests/test_admin_commands.py +0 -296
  12. {opensees_cli-0.2.4 → opensees_cli-0.2.6}/README.md +0 -0
  13. {opensees_cli-0.2.4 → opensees_cli-0.2.6}/setup.cfg +0 -0
  14. {opensees_cli-0.2.4 → opensees_cli-0.2.6}/src/opensees_cli/__main__.py +0 -0
  15. {opensees_cli-0.2.4 → opensees_cli-0.2.6}/src/opensees_cli/api.py +0 -0
  16. {opensees_cli-0.2.4 → opensees_cli-0.2.6}/src/opensees_cli/config.py +0 -0
  17. {opensees_cli-0.2.4 → opensees_cli-0.2.6}/src/opensees_cli/files.py +0 -0
  18. {opensees_cli-0.2.4 → opensees_cli-0.2.6}/src/opensees_cli/path_setup.py +0 -0
  19. {opensees_cli-0.2.4 → opensees_cli-0.2.6}/src/opensees_cli/run.py +0 -0
  20. {opensees_cli-0.2.4 → opensees_cli-0.2.6}/src/opensees_cli/version.py +0 -0
  21. {opensees_cli-0.2.4 → opensees_cli-0.2.6}/src/opensees_cli.egg-info/dependency_links.txt +0 -0
  22. {opensees_cli-0.2.4 → opensees_cli-0.2.6}/src/opensees_cli.egg-info/entry_points.txt +0 -0
  23. {opensees_cli-0.2.4 → opensees_cli-0.2.6}/src/opensees_cli.egg-info/requires.txt +0 -0
  24. {opensees_cli-0.2.4 → opensees_cli-0.2.6}/src/opensees_cli.egg-info/top_level.txt +0 -0
  25. {opensees_cli-0.2.4 → opensees_cli-0.2.6}/tests/test_api.py +0 -0
  26. {opensees_cli-0.2.4 → opensees_cli-0.2.6}/tests/test_config.py +0 -0
  27. {opensees_cli-0.2.4 → opensees_cli-0.2.6}/tests/test_files_commands.py +0 -0
  28. {opensees_cli-0.2.4 → opensees_cli-0.2.6}/tests/test_run_commands.py +0 -0
  29. {opensees_cli-0.2.4 → opensees_cli-0.2.6}/tests/test_version_commands.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: opensees_cli
3
- Version: 0.2.4
3
+ Version: 0.2.6
4
4
  Summary: Run OpenSees simulations in the cloud from the command line.
5
5
  Author: Minjie Zhu
6
6
  License: Proprietary
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "opensees_cli"
7
- version = "0.2.4"
7
+ version = "0.2.6"
8
8
  description = "Run OpenSees simulations in the cloud from the command line."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
@@ -1,3 +1,3 @@
1
1
  """OpenSees CLI — run structural simulations in the cloud."""
2
2
 
3
- __version__ = "0.2.4"
3
+ __version__ = "0.2.6"
@@ -527,6 +527,8 @@ def login(email: Optional[str] = typer.Option(None, "--email", "-e")):
527
527
  )
528
528
  api.invalidate_session_cache()
529
529
  console.print(f"[green]Logged in as [bold]{email}[/bold][/green]")
530
+ if r.get("cli_upgrade"):
531
+ console.print(f"[yellow]{r['cli_upgrade']}[/yellow]")
530
532
  maybe_print_cli_upgrade()
531
533
  except api.ApiError as e:
532
534
  console.print(f"[red]{e.message}[/red]")
@@ -12,7 +12,6 @@ from opensees_cli.auth import (
12
12
  print_me,
13
13
  print_quota,
14
14
  )
15
- from opensees_cli.admin import app as admin_app
16
15
  from opensees_cli.run import app as run_app
17
16
  from opensees_cli.files import app as files_app
18
17
  from opensees_cli.version import app as version_app
@@ -78,12 +77,6 @@ app.add_typer(auth_app, name="auth")
78
77
  app.add_typer(run_app, name="run")
79
78
  app.add_typer(files_app, name="files")
80
79
  app.add_typer(version_app, name="version")
81
- # Admin typer: hidden from help unless logged-in admin; non-admins get "no such command" in admin callback.
82
- app.add_typer(
83
- admin_app,
84
- name="admin",
85
- hidden=not (api.has_stored_credentials() and config.is_admin()),
86
- )
87
80
 
88
81
 
89
82
  def _add_help_command(typer_app: typer.Typer) -> None:
@@ -102,7 +95,6 @@ _add_help_command(auth_app)
102
95
  _add_help_command(run_app)
103
96
  _add_help_command(files_app)
104
97
  _add_help_command(version_app)
105
- _add_help_command(admin_app)
106
98
 
107
99
 
108
100
  def _print_help() -> None:
@@ -137,16 +129,6 @@ def _print_help() -> None:
137
129
  console.print("[bold]ops auth[/bold]\n")
138
130
  console.print(" [bold]change-password[/bold] Change your password")
139
131
  console.print(" [bold]logout[/bold] Log out")
140
- if config.is_admin():
141
- console.print()
142
- console.print("[bold]ops admin[/bold]\n")
143
- console.print(" [bold]list-users[/bold] List all users")
144
- console.print(" [bold]user-info[/bold] Account details; run / files inspect that user")
145
- console.print(" [bold]set-quota[/bold] Update a user's quota")
146
- console.print(" [bold]enable-user[/bold] Re-enable a user")
147
- console.print(" [bold]disable-user[/bold] Disable a user")
148
- console.print(" [bold]delete-user[/bold] Delete a user")
149
- console.print(" [bold]workers[/bold] Live Lambda + Fargate workers (--json / -j)")
150
132
  else:
151
133
  console.print(" Not logged in.\n")
152
134
  console.print("[bold]Get started:[/bold]\n")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: opensees_cli
3
- Version: 0.2.4
3
+ Version: 0.2.6
4
4
  Summary: Run OpenSees simulations in the cloud from the command line.
5
5
  Author: Minjie Zhu
6
6
  License: Proprietary
@@ -2,7 +2,6 @@ README.md
2
2
  pyproject.toml
3
3
  src/opensees_cli/__init__.py
4
4
  src/opensees_cli/__main__.py
5
- src/opensees_cli/admin.py
6
5
  src/opensees_cli/api.py
7
6
  src/opensees_cli/auth.py
8
7
  src/opensees_cli/config.py
@@ -17,7 +16,6 @@ src/opensees_cli.egg-info/dependency_links.txt
17
16
  src/opensees_cli.egg-info/entry_points.txt
18
17
  src/opensees_cli.egg-info/requires.txt
19
18
  src/opensees_cli.egg-info/top_level.txt
20
- tests/test_admin_commands.py
21
19
  tests/test_api.py
22
20
  tests/test_auth_commands.py
23
21
  tests/test_config.py
@@ -94,14 +94,18 @@ class TestLogin:
94
94
  assert result.exit_code == 0
95
95
  assert "Logged in" in result.output
96
96
 
97
- def test_login_stale_cli(self, cli_runner, patch_httpx, mock_router):
98
- mock_router.add("POST", "/prod/auth/login", status=400, json={
99
- "error": "This CLI (0.2.3) is out of date. Upgrade with: pip install -U opensees_cli",
100
- "code": "auth_error",
97
+ def test_login_stale_cli_warns(self, cli_runner, patch_httpx, mock_router):
98
+ mock_router.add("POST", "/prod/auth/login", json={
99
+ "access_token": "at",
100
+ "refresh_token": "rt",
101
+ "id_token": "id",
102
+ "is_admin": False,
103
+ "cli_upgrade": "This CLI (0.2.3) is out of date. Upgrade with: pip install -U opensees_cli",
101
104
  })
102
105
  with patch("opensees_cli.auth._ask_password", return_value="Pass1!"):
103
106
  result = cli_runner.invoke(app, ["auth", "login", "-e", "u@t.com"])
104
- assert result.exit_code == 1
107
+ assert result.exit_code == 0
108
+ assert "Logged in" in result.output
105
109
  assert "pip install -U opensees_cli" in result.output
106
110
 
107
111
 
@@ -108,8 +108,8 @@ class TestOpsHelpLoggedIn:
108
108
  assert "ops quota" not in result.output
109
109
 
110
110
 
111
- class TestNonAdminAdminHidden:
112
- """Non-admins must not see admin in Typer help or invoke admin (unknown command)."""
111
+ class TestAdminCommandRemoved:
112
+ """Admin operations live in web/admin. The CLI has no admin command."""
113
113
 
114
114
  def test_ops_help_hides_admin_after_reload(self, cli_runner, logged_in_creds):
115
115
  import opensees_cli.main as main_mod
@@ -1,587 +0,0 @@
1
- """Admin CLI commands."""
2
-
3
- import json
4
- import re
5
- from pathlib import Path
6
- from typing import Any, List, Optional
7
-
8
- import click
9
- import typer
10
- from rich.console import Console
11
- from rich.table import Table
12
- from typer.core import TyperGroup
13
-
14
- from opensees_cli import __version__, api, config
15
- from opensees_cli.auth import _to_local, print_quota
16
- from opensees_cli.files import download as files_download
17
- from opensees_cli.files import list_files as files_list
18
- from opensees_cli.run import _BareDefaultCommand
19
- from opensees_cli.run import data as run_data
20
- from opensees_cli.run import list_analyses as run_list
21
- from opensees_cli.run import output as run_output
22
- from opensees_cli.run import stats as run_stats
23
- from opensees_cli.run import status as run_status
24
-
25
- _RUNTIME_TOKEN_RE = re.compile(r"^((\d+(?:\.\d+)?)(h|m|s))+$")
26
-
27
-
28
- def _cli_cell(raw: Optional[str], current: str) -> str:
29
- v = (raw or "").strip()
30
- if not v:
31
- return "-"
32
- if config.is_older_version(v, current):
33
- return f"[yellow]{v}[/yellow]"
34
- return v
35
-
36
-
37
- def _parse_runtime_quota(raw: str) -> int:
38
- """Parse -r: plain digits = seconds; or duration tokens like 2h, 10m, 1h30m, 90s."""
39
- s = raw.strip().lower().replace(" ", "")
40
- if not s:
41
- raise ValueError("value is empty")
42
- if re.fullmatch(r"\d+", s):
43
- return int(s)
44
- if not _RUNTIME_TOKEN_RE.fullmatch(s):
45
- raise ValueError(
46
- "expected digits (seconds) or duration like 2h, 10m, 1h30m, 90s"
47
- )
48
- total = 0.0
49
- for m in re.finditer(r"(\d+(?:\.\d+)?)(h|m|s)", s):
50
- val = float(m.group(1))
51
- u = m.group(2)
52
- if u == "h":
53
- total += val * 3600
54
- elif u == "m":
55
- total += val * 60
56
- else:
57
- total += val
58
- return int(round(total))
59
-
60
-
61
- def _parse_storage_quota(raw: str) -> int:
62
- """Parse -s: plain digits = bytes; or 500kb, 10mb, 2gb (base 1024)."""
63
- s = raw.strip().lower().replace(" ", "")
64
- if not s:
65
- raise ValueError("value is empty")
66
- if re.fullmatch(r"\d+", s):
67
- return int(s)
68
- m = re.fullmatch(r"(\d+(?:\.\d+)?)(kb|mb|gb)", s)
69
- if not m:
70
- raise ValueError("expected digits (bytes) or size like 500kb, 10mb, 2gb")
71
- val = float(m.group(1))
72
- unit = m.group(2)
73
- mult = {"kb": 1024, "mb": 1024**2, "gb": 1024**3}
74
- return int(round(val * mult[unit]))
75
-
76
-
77
- console = Console()
78
-
79
-
80
- def _require_admin_or_no_such_command(ctx: click.Context) -> None:
81
- """Logged-in non-admins must not see admin help or reach admin subcommands."""
82
- api.require_login()
83
- if not config.is_admin():
84
- click.echo("Error: No such command 'admin'.", err=True)
85
- ctx.exit(2)
86
-
87
-
88
- class _AdminTyperGroup(TyperGroup):
89
- """Runs before --help formatting so ``ops admin --help`` is hidden from non-admins."""
90
-
91
- def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
92
- _require_admin_or_no_such_command(ctx)
93
- super().format_help(ctx, formatter)
94
-
95
- def invoke(self, ctx: click.Context) -> Any:
96
- _require_admin_or_no_such_command(ctx)
97
- return super().invoke(ctx)
98
-
99
-
100
- app = typer.Typer(
101
- help="Admin operations (requires admin privileges).",
102
- cls=_AdminTyperGroup,
103
- )
104
-
105
-
106
- @app.callback(invoke_without_command=True)
107
- def _admin_callback(ctx: typer.Context) -> None:
108
- if ctx.invoked_subcommand is None:
109
- typer.echo(ctx.get_help())
110
- raise typer.Exit(0)
111
-
112
-
113
- @app.command("list-users")
114
- def list_users():
115
- """List all registered users."""
116
- try:
117
- r = api.get("/admin/users")
118
- except api.ApiError as e:
119
- console.print(f"[red]{e.message}[/red]")
120
- raise typer.Exit(1)
121
-
122
- users = r.get("users", [])
123
- if not users:
124
- console.print("[dim]No users found.[/dim]")
125
- return
126
-
127
- current_cli = __version__
128
- table = Table(title=f"Users ({len(users)}) · current CLI {current_cli}")
129
- # Always show the full email (never ellipsize / crop).
130
- table.add_column("Email", style="cyan", overflow="ignore", no_wrap=True)
131
- table.add_column("Status")
132
- table.add_column("Enabled")
133
- table.add_column("Admin")
134
- table.add_column("Last Login")
135
- table.add_column("Last Activity")
136
- table.add_column("CLI", overflow="ignore", no_wrap=True)
137
- table.add_column("Pinned", overflow="ignore", no_wrap=True)
138
-
139
- for u in users:
140
- enabled = "[green]yes[/green]" if u.get("enabled") else "[red]no[/red]"
141
- admin = "[yellow]yes[/yellow]" if u.get("is_admin") else "no"
142
- table.add_row(
143
- u.get("email", ""),
144
- u.get("status", ""),
145
- enabled,
146
- admin,
147
- u.get("last_login_at", "") or "-",
148
- u.get("last_activity_at", "") or "-",
149
- _cli_cell(u.get("last_cli_version"), current_cli),
150
- u.get("openseespy_version", "") or "-",
151
- )
152
- console.print(table)
153
-
154
-
155
- @app.command("disable-user")
156
- def disable_user(email: Optional[str] = typer.Option(None, "--email", "-e")):
157
- """Disable a user account (prevents login)."""
158
- if not email:
159
- email = typer.prompt("Email to disable")
160
- try:
161
- r = api.post("/admin/disable-user", {"email": email})
162
- console.print(f"[green]{r.get('message', 'User disabled.')}[/green]")
163
- except api.ApiError as e:
164
- console.print(f"[red]{e.message}[/red]")
165
- raise typer.Exit(1)
166
-
167
-
168
- @app.command("enable-user")
169
- def enable_user(email: Optional[str] = typer.Option(None, "--email", "-e")):
170
- """Re-enable a disabled user account."""
171
- if not email:
172
- email = typer.prompt("Email to enable")
173
- try:
174
- r = api.post("/admin/enable-user", {"email": email})
175
- console.print(f"[green]{r.get('message', 'User enabled.')}[/green]")
176
- except api.ApiError as e:
177
- console.print(f"[red]{e.message}[/red]")
178
- raise typer.Exit(1)
179
-
180
-
181
- @app.command("delete-user")
182
- def delete_user(email: Optional[str] = typer.Option(None, "--email", "-e")):
183
- """Permanently delete a user account."""
184
- if not email:
185
- email = typer.prompt("Email to delete")
186
-
187
- confirmed = typer.confirm(f"Permanently delete {email}? This cannot be undone")
188
- if not confirmed:
189
- console.print("[dim]Cancelled.[/dim]")
190
- raise typer.Exit(0)
191
-
192
- try:
193
- r = api.post("/admin/delete-user", {"email": email})
194
- console.print(f"[green]{r.get('message', 'User deleted.')}[/green]")
195
- except api.ApiError as e:
196
- console.print(f"[red]{e.message}[/red]")
197
- raise typer.Exit(1)
198
-
199
-
200
- def _print_user_info(email: str) -> None:
201
- try:
202
- r = api.post("/admin/user-info", {"email": email})
203
- except api.ApiError as e:
204
- console.print(f"[red]{e.message}[/red]")
205
- raise typer.Exit(1)
206
-
207
- console.print(f" Email: [bold]{r.get('email', '')}[/bold]")
208
- console.print(f" Admin: {'[yellow]yes[/yellow]' if r.get('is_admin') else 'no'}")
209
- console.print(f" Enabled: {'[green]yes[/green]' if r.get('is_enabled') else '[red]no[/red]'}")
210
- if r.get("signup_at"):
211
- console.print(f" Signed up: {_to_local(r['signup_at'])}")
212
- if r.get("last_login_at"):
213
- console.print(f" Last login: {_to_local(r['last_login_at'])}")
214
- if r.get("last_activity_at"):
215
- console.print(f" Last active: {_to_local(r['last_activity_at'])}")
216
- pin = r.get("openseespy_version") or ""
217
- if pin:
218
- console.print(f" OpenSeesPy: {pin} (pinned)")
219
- else:
220
- console.print(" OpenSeesPy: [dim]-[/dim] (not pinned)")
221
- cli_ver = (r.get("last_cli_version") or "").strip()
222
- if cli_ver:
223
- if config.is_older_version(cli_ver, __version__):
224
- console.print(f" CLI: [yellow]{cli_ver}[/yellow] (behind {__version__})")
225
- else:
226
- console.print(f" CLI: {cli_ver}")
227
- else:
228
- console.print(" CLI: [dim]-[/dim]")
229
- if r.get("last_ip"):
230
- console.print(f" Last IP: {r['last_ip']}")
231
-
232
- q = r.get("quota")
233
- if q:
234
- console.print()
235
- print_quota(q)
236
-
237
-
238
- @app.command("set-quota")
239
- def set_quota(
240
- email: Optional[str] = typer.Option(None, "--email", "-e"),
241
- concurrent: Optional[int] = typer.Option(None, "--concurrent", "-c", help="Max concurrent tasks"),
242
- tasks: Optional[int] = typer.Option(None, "--tasks", help="Max tasks per analysis"),
243
- runtime: Optional[str] = typer.Option(None, "--runtime", "-r", help="Max monthly runtime: seconds (300) or duration (2h, 10m, 1h30m)"),
244
- storage: Optional[str] = typer.Option(None, "--storage", "-s", help="Max monthly storage: bytes (1048576) or size (500kb, 10mb, 2gb)"),
245
- max_timeout: Optional[str] = typer.Option(None, "--max-timeout", "-t", help="Max timeout per task: seconds (120) or duration (2h, 10m, 1h30m)"),
246
- max_storage_per_task: Optional[str] = typer.Option(None, "--max-storage-per-task", help="Max storage per task: bytes or size (50mb, 200mb, 1gb)"),
247
- ):
248
- """Update a user's quota limits."""
249
- if not email:
250
- email = typer.prompt("Email")
251
- if concurrent is None and tasks is None and runtime is None and storage is None and max_timeout is None and max_storage_per_task is None:
252
- console.print("Provide at least one of --concurrent, --tasks, --runtime, --storage, --max-timeout, or --max-storage-per-task.")
253
- raise typer.Exit(0)
254
-
255
- runtime_secs: Optional[int] = None
256
- if runtime is not None:
257
- try:
258
- runtime_secs = _parse_runtime_quota(runtime)
259
- except ValueError as exc:
260
- console.print(f"[red]Invalid --runtime value '{runtime}': {exc}[/red]")
261
- raise typer.Exit(1)
262
-
263
- storage_bytes: Optional[int] = None
264
- if storage is not None:
265
- try:
266
- storage_bytes = _parse_storage_quota(storage)
267
- except ValueError as exc:
268
- console.print(f"[red]Invalid --storage value '{storage}': {exc}[/red]")
269
- raise typer.Exit(1)
270
-
271
- max_timeout_secs: Optional[int] = None
272
- if max_timeout is not None:
273
- try:
274
- max_timeout_secs = _parse_runtime_quota(max_timeout)
275
- except ValueError as exc:
276
- console.print(f"[red]Invalid --max-timeout value '{max_timeout}': {exc}[/red]")
277
- raise typer.Exit(1)
278
-
279
- max_storage_per_task_bytes: Optional[int] = None
280
- if max_storage_per_task is not None:
281
- try:
282
- max_storage_per_task_bytes = _parse_storage_quota(max_storage_per_task)
283
- except ValueError as exc:
284
- console.print(f"[red]Invalid --max-storage-per-task value '{max_storage_per_task}': {exc}[/red]")
285
- raise typer.Exit(1)
286
-
287
- body: dict = {"email": email}
288
- if concurrent is not None:
289
- body["max_concurrent_runs"] = concurrent
290
- if tasks is not None:
291
- body["max_tasks_per_analysis"] = tasks
292
- if runtime_secs is not None:
293
- body["max_monthly_runtime"] = runtime_secs
294
- if storage_bytes is not None:
295
- body["max_monthly_storage"] = storage_bytes
296
- if max_timeout_secs is not None:
297
- body["max_task_timeout"] = max_timeout_secs
298
- if max_storage_per_task_bytes is not None:
299
- body["max_storage_per_task"] = max_storage_per_task_bytes
300
-
301
- try:
302
- r = api.post("/admin/set-quota", body)
303
- console.print(f"[green]{r.get('message', 'Quota updated.')}[/green]")
304
- except api.ApiError as e:
305
- console.print(f"[red]{e.message}[/red]")
306
- raise typer.Exit(1)
307
-
308
-
309
- @app.command("workers")
310
- def workers(
311
- as_json: bool = typer.Option(False, "--json", "-j", help="Output as JSON"),
312
- ):
313
- """Show live Lambda + Fargate worker activity (low-level).
314
-
315
- \b
316
- Lambda: reports the configured simulation function plus the CloudWatch
317
- ConcurrentExecutions max over the last 5 minutes (AWS does not
318
- expose individual in-flight invocations).
319
- Fargate: lists every running ECS task in the configured cluster.
320
- """
321
- try:
322
- r = api.get("/admin/workers")
323
- except api.ApiError as e:
324
- console.print(f"[red]{e.message}[/red]")
325
- raise typer.Exit(1)
326
-
327
- if as_json:
328
- typer.echo(json.dumps(r, indent=2, ensure_ascii=False))
329
- return
330
-
331
- lam = r.get("lambda") or {}
332
- fg = r.get("fargate") or {}
333
-
334
- console.print("[bold]Lambda[/bold]")
335
- if not lam.get("configured"):
336
- console.print(f" [dim]not configured: {lam.get('reason', 'unknown')}[/dim]")
337
- else:
338
- console.print(f" Function: {lam.get('function_name', '-')}")
339
- console.print(f" State: {lam.get('state', '-')}")
340
- console.print(f" Timeout: {lam.get('timeout', '-')}s")
341
- console.print(f" Memory: {lam.get('memory_size', '-')} MB")
342
- win = lam.get("metric_window_seconds", 0)
343
- ce = lam.get("concurrent_executions_max")
344
- inv = lam.get("invocations_sum")
345
- console.print(
346
- f" Concurrent (last {win}s): "
347
- f"max={ce if ce is not None else '-'} · invocations={inv if inv is not None else '-'}"
348
- )
349
- if lam.get("metric_error"):
350
- console.print(f" [red]Metric error: {lam['metric_error']}[/red]")
351
- if lam.get("configuration_error"):
352
- console.print(f" [red]Config error: {lam['configuration_error']}[/red]")
353
-
354
- console.print()
355
- console.print("[bold]Fargate[/bold]")
356
- if not fg.get("configured"):
357
- console.print(f" [dim]not configured: {fg.get('reason', 'unknown')}[/dim]")
358
- return
359
- console.print(f" Cluster: {fg.get('cluster', '-')}")
360
- console.print(f" Running tasks: {fg.get('running_count', 0)}")
361
- if fg.get("error"):
362
- console.print(f" [red]Error: {fg['error']}[/red]")
363
- return
364
-
365
- tasks = fg.get("tasks") or []
366
- if not tasks:
367
- return
368
-
369
- table = Table(show_header=True)
370
- table.add_column("Task ID", style="dim", max_width=12)
371
- table.add_column("Status")
372
- table.add_column("Container")
373
- table.add_column("CPU", justify="right")
374
- table.add_column("Memory", justify="right")
375
- table.add_column("Started")
376
- for t in tasks:
377
- table.add_row(
378
- (t.get("task_id") or "")[:12],
379
- t.get("last_status", "-") or "-",
380
- t.get("container_status", "-") or "-",
381
- t.get("cpu", "-") or "-",
382
- t.get("memory", "-") or "-",
383
- _to_local(t["started_at"]) if t.get("started_at") else "-",
384
- )
385
- console.print(table)
386
-
387
-
388
- # ---------------------------------------------------------------------------
389
- # user-info: account details, plus read-only run / files inspect
390
- # ---------------------------------------------------------------------------
391
-
392
- user_info_grp = typer.Typer(help="Show a user's account details; run / files inspect that user.")
393
- run_grp = typer.Typer(help="Inspect the user's analyses (read-only).")
394
- files_grp = typer.Typer(help="Inspect the user's files (read-only).")
395
-
396
-
397
- def _email_from_ctx(ctx: typer.Context) -> Optional[str]:
398
- cur: Optional[click.Context] = ctx
399
- while cur is not None:
400
- obj = cur.obj
401
- if isinstance(obj, dict) and obj.get("email"):
402
- return str(obj["email"])
403
- cur = cur.parent
404
- return None
405
-
406
-
407
- def _resolve_email(ctx: typer.Context, email: Optional[str]) -> str:
408
- resolved = (email or _email_from_ctx(ctx) or "").strip()
409
- if not resolved:
410
- console.print("[red]Provide --email / -e for the target user.[/red]")
411
- raise typer.Exit(1)
412
- return resolved
413
-
414
-
415
- def _email_opt() -> Any:
416
- return typer.Option(None, "--email", "-e", help="Target user's email")
417
-
418
-
419
- @user_info_grp.callback(invoke_without_command=True)
420
- def user_info(
421
- ctx: typer.Context,
422
- email: Optional[str] = typer.Option(None, "--email", "-e", help="Target user's email"),
423
- ):
424
- """Show a user's account details and quota."""
425
- ctx.ensure_object(dict)
426
- if email:
427
- ctx.obj["email"] = email.strip()
428
- if ctx.invoked_subcommand is not None:
429
- return
430
- if not email:
431
- email = typer.prompt("Email")
432
- ctx.obj["email"] = email.strip()
433
- _print_user_info(email)
434
-
435
-
436
- @run_grp.callback(invoke_without_command=True)
437
- def _admin_run_callback(ctx: typer.Context) -> None:
438
- ctx.ensure_object(dict)
439
- parent_email = _email_from_ctx(ctx)
440
- if parent_email:
441
- ctx.obj["email"] = parent_email
442
- if ctx.invoked_subcommand is None:
443
- typer.echo(ctx.get_help())
444
- raise typer.Exit(0)
445
-
446
-
447
- @files_grp.callback(invoke_without_command=True)
448
- def _admin_files_callback(ctx: typer.Context) -> None:
449
- ctx.ensure_object(dict)
450
- parent_email = _email_from_ctx(ctx)
451
- if parent_email:
452
- ctx.obj["email"] = parent_email
453
- if ctx.invoked_subcommand is None:
454
- typer.echo(ctx.get_help())
455
- raise typer.Exit(0)
456
-
457
-
458
- @run_grp.command("list", cls=_BareDefaultCommand)
459
- def admin_run_list(
460
- ctx: typer.Context,
461
- email: Optional[str] = _email_opt(),
462
- limit: int = typer.Option(20, "--limit", "-n", help="Max number of analyses to show"),
463
- after: Optional[str] = typer.Option(None, "--after", help="Show analyses after date (YYYY-MM-DD)"),
464
- before: Optional[str] = typer.Option(None, "--before", help="Show analyses before date (YYYY-MM-DD)"),
465
- week: Optional[str] = typer.Option(
466
- None, "--week", "-w",
467
- help="Week filter: 0=this week; 1-52=ISO week; negative=-k; W1-W2=range.",
468
- ),
469
- month: Optional[str] = typer.Option(
470
- None, "--month", "-m",
471
- help="Month filter: 0=this month; 1-12; negative=-k; M-N=range.",
472
- ),
473
- year: Optional[str] = typer.Option(
474
- None, "--year", "-y",
475
- help="Year filter: 0=this year; positive=absolute year; negative=-k; Y1-Y2=range.",
476
- ),
477
- all_: bool = typer.Option(False, "--all", "-a", help="Show all analyses (no date filter)"),
478
- as_json: bool = typer.Option(False, "--json", "-j", help="Output as JSON"),
479
- ):
480
- """List the user's analyses.
481
-
482
- Same flags as ``ops run list``. Example: ops admin user-info run list -e alice@test.com
483
- """
484
- with api.acting_as(_resolve_email(ctx, email)):
485
- run_list(
486
- limit=limit,
487
- after=after,
488
- before=before,
489
- week=week,
490
- month=month,
491
- year=year,
492
- all_=all_,
493
- as_json=as_json,
494
- )
495
-
496
-
497
- @run_grp.command("status")
498
- def admin_run_status(
499
- ctx: typer.Context,
500
- id: Optional[str] = typer.Argument(None, help="Analysis ID (omit to list running analyses)"),
501
- range_: Optional[str] = typer.Argument(None, help="Task range: index, start-end, or 'all'"),
502
- email: Optional[str] = _email_opt(),
503
- as_json: bool = typer.Option(False, "--json", "-j", help="Output as JSON"),
504
- ):
505
- """Show the user's analysis or task status."""
506
- with api.acting_as(_resolve_email(ctx, email)):
507
- run_status(id=id, range_=range_, as_json=as_json)
508
-
509
-
510
- @run_grp.command("output")
511
- def admin_run_output(
512
- ctx: typer.Context,
513
- id: str = typer.Argument(..., help="Analysis ID"),
514
- range_: Optional[str] = typer.Argument(None, help="Task range: index, start-end, or 'all'"),
515
- email: Optional[str] = _email_opt(),
516
- ):
517
- """Show the user's printed output (stdout)."""
518
- with api.acting_as(_resolve_email(ctx, email)):
519
- run_output(id=id, range_=range_)
520
-
521
-
522
- @run_grp.command("stats")
523
- def admin_run_stats(
524
- ctx: typer.Context,
525
- id: str = typer.Argument(..., help="Analysis ID"),
526
- range_: Optional[str] = typer.Argument(None, help="Task range: index, start-end, or 'all'"),
527
- email: Optional[str] = _email_opt(),
528
- ):
529
- """Show the user's task execution stats."""
530
- with api.acting_as(_resolve_email(ctx, email)):
531
- run_stats(id=id, range_=range_)
532
-
533
-
534
- @run_grp.command("data")
535
- def admin_run_data(
536
- ctx: typer.Context,
537
- id: str = typer.Argument(..., help="Analysis ID"),
538
- range_: Optional[str] = typer.Argument(None, help="Task range: index, start-end, or 'all'"),
539
- email: Optional[str] = _email_opt(),
540
- download: Optional[str] = typer.Option(
541
- None, "--download", "-d", metavar="PATH",
542
- help="Download mode (omit to list only). Same as ``ops run data -d``.",
543
- ),
544
- output_dir: str = typer.Option(
545
- ".", "--output", "-o",
546
- help="Directory to write downloaded files.",
547
- ),
548
- ):
549
- """List or download the user's task data files."""
550
- with api.acting_as(_resolve_email(ctx, email)):
551
- run_data(id=id, range_=range_, download=download, output_dir=output_dir)
552
-
553
-
554
- @files_grp.command("list")
555
- def admin_files_list(
556
- ctx: typer.Context,
557
- folder: Optional[str] = typer.Argument(
558
- None,
559
- help="Only list files in this folder (and its subfolders)",
560
- ),
561
- email: Optional[str] = _email_opt(),
562
- as_json: bool = typer.Option(False, "--json", "-j", help="Emit JSON instead of a table"),
563
- ):
564
- """List the user's files."""
565
- email = _resolve_email(ctx, email)
566
- console.print(f"[dim]Files for {email}[/dim]")
567
- with api.acting_as(email):
568
- files_list(folder=folder, as_json=as_json)
569
-
570
-
571
- @files_grp.command("download")
572
- def admin_files_download(
573
- ctx: typer.Context,
574
- remote_paths: List[str] = typer.Argument(..., help="Remote file path(s) or glob pattern(s)"),
575
- email: Optional[str] = _email_opt(),
576
- output: Optional[Path] = typer.Option(None, "--output", "-o", help="Local output path"),
577
- ):
578
- """Download file(s) from the user's file system."""
579
- with api.acting_as(_resolve_email(ctx, email)):
580
- files_download(remote_paths=remote_paths, output=output)
581
-
582
-
583
- user_info_grp.add_typer(run_grp, name="run")
584
- user_info_grp.add_typer(files_grp, name="files")
585
- app.add_typer(user_info_grp, name="user-info")
586
-
587
-
@@ -1,296 +0,0 @@
1
- """Tests for ops admin subcommands — one test per command, using admin creds."""
2
-
3
- from unittest.mock import patch
4
-
5
- from opensees_cli.main import app
6
-
7
-
8
- class TestListUsers:
9
- def test_list_users(self, cli_runner, admin_creds, patch_httpx, mock_router):
10
- mock_router.add("GET", "/prod/admin/users", json={
11
- "users": [
12
- {
13
- "email": "alice@test.com",
14
- "status": "CONFIRMED",
15
- "enabled": True,
16
- "is_admin": False,
17
- "last_login_at": "2025-01-01T00:00:00Z",
18
- "last_activity_at": "",
19
- "last_cli_version": "0.2.1",
20
- "openseespy_version": "3.7.1.0",
21
- },
22
- ]
23
- })
24
- result = cli_runner.invoke(app, ["admin", "list-users"])
25
- assert result.exit_code == 0
26
- assert "alice@test.com" in result.output
27
- assert "3.7.1.0" in result.output
28
- assert "0.2.1" in result.output
29
- assert "CLI" in result.output
30
- assert "Pinned" in result.output
31
- from opensees_cli import __version__
32
- assert f"current CLI {__version__}" in result.output
33
-
34
- def test_list_users_empty(self, cli_runner, admin_creds, patch_httpx, mock_router):
35
- mock_router.add("GET", "/prod/admin/users", json={"users": []})
36
- result = cli_runner.invoke(app, ["admin", "list-users"])
37
- assert result.exit_code == 0
38
- assert "No users" in result.output
39
-
40
-
41
- class TestDisableUser:
42
- def test_disable_user(self, cli_runner, admin_creds, patch_httpx, mock_router):
43
- mock_router.add("POST", "/prod/admin/disable-user", json={"message": "User disabled."})
44
- result = cli_runner.invoke(app, ["admin", "disable-user", "-e", "alice@test.com"])
45
- assert result.exit_code == 0
46
- assert "disabled" in result.output.lower()
47
-
48
-
49
- class TestEnableUser:
50
- def test_enable_user(self, cli_runner, admin_creds, patch_httpx, mock_router):
51
- mock_router.add("POST", "/prod/admin/enable-user", json={"message": "User enabled."})
52
- result = cli_runner.invoke(app, ["admin", "enable-user", "-e", "alice@test.com"])
53
- assert result.exit_code == 0
54
- assert "enabled" in result.output.lower()
55
-
56
-
57
- class TestDeleteUser:
58
- def test_delete_user_confirmed(self, cli_runner, admin_creds, patch_httpx, mock_router):
59
- mock_router.add("POST", "/prod/admin/delete-user", json={"message": "User deleted."})
60
- result = cli_runner.invoke(app, ["admin", "delete-user", "-e", "alice@test.com"], input="y\n")
61
- assert result.exit_code == 0
62
- assert "deleted" in result.output.lower()
63
-
64
- def test_delete_user_cancelled(self, cli_runner, admin_creds, patch_httpx, mock_router):
65
- result = cli_runner.invoke(app, ["admin", "delete-user", "-e", "alice@test.com"], input="n\n")
66
- assert result.exit_code == 0
67
- assert "Cancelled" in result.output
68
-
69
-
70
- class TestUserInfo:
71
- def test_user_info(self, cli_runner, admin_creds, patch_httpx, mock_router):
72
- mock_router.add("POST", "/prod/admin/user-info", json={
73
- "email": "alice@test.com",
74
- "is_admin": False,
75
- "is_enabled": True,
76
- "openseespy_version": "3.7.1.0",
77
- "last_cli_version": "0.2.2",
78
- "quota": {
79
- "max_concurrent_runs": 5,
80
- "max_tasks_per_analysis": 100,
81
- "max_monthly_runtime": 3600,
82
- "monthly_runtime_used": 0,
83
- "monthly_runtime_remaining": 3600,
84
- "max_monthly_storage": 1073741824,
85
- "storage_used": 0,
86
- },
87
- "analyses_total": 2,
88
- "analyses_running": 1,
89
- "analyses": [
90
- {
91
- "analysis_id": "aaa11111-0000-0000-0000-000000000000",
92
- "status": "running",
93
- "filename": "Truss.py",
94
- "type": "fast",
95
- "total_tasks": 1,
96
- "created_at": "2026-09-01T00:00:00Z",
97
- },
98
- ],
99
- "files_total": 1,
100
- "files_size": 128,
101
- "files": [
102
- {"path": "Truss.py", "size": 128, "last_modified": "2026-09-01T00:00:00Z"},
103
- ],
104
- })
105
- result = cli_runner.invoke(app, ["admin", "user-info", "-e", "alice@test.com"])
106
- assert result.exit_code == 0
107
- assert "alice@test.com" in result.output
108
- assert "3.7.1.0" in result.output
109
- assert "pinned" in result.output.lower()
110
- assert "0.2.2" in result.output
111
- assert "CLI" in result.output
112
- assert "Analyses" not in result.output
113
- assert "Files" not in result.output
114
-
115
- def test_user_info_not_pinned(self, cli_runner, admin_creds, patch_httpx, mock_router):
116
- mock_router.add("POST", "/prod/admin/user-info", json={
117
- "email": "bob@test.com",
118
- "is_admin": False,
119
- "is_enabled": True,
120
- "openseespy_version": None,
121
- })
122
- result = cli_runner.invoke(app, ["admin", "user-info", "-e", "bob@test.com"])
123
- assert result.exit_code == 0
124
- assert "not pinned" in result.output.lower()
125
- assert "No analyses" not in result.output
126
- assert "No files" not in result.output
127
-
128
-
129
- class TestSetQuota:
130
- def test_set_quota_runtime(self, cli_runner, admin_creds, patch_httpx, mock_router):
131
- mock_router.add("POST", "/prod/admin/set-quota", json={"message": "Quota updated."})
132
- result = cli_runner.invoke(app, ["admin", "set-quota", "-e", "alice@test.com", "-r", "2h"])
133
- assert result.exit_code == 0
134
- assert "updated" in result.output.lower()
135
-
136
- def test_set_quota_no_flags(self, cli_runner, admin_creds, patch_httpx, mock_router):
137
- result = cli_runner.invoke(app, ["admin", "set-quota", "-e", "alice@test.com"])
138
- assert result.exit_code == 0
139
- assert "Provide at least one" in result.output
140
-
141
- def test_set_quota_invalid_runtime(self, cli_runner, admin_creds, patch_httpx, mock_router):
142
- result = cli_runner.invoke(app, ["admin", "set-quota", "-e", "a@t.com", "-r", "abc"])
143
- assert result.exit_code == 1
144
- assert "Invalid" in result.output
145
-
146
- def test_set_quota_storage(self, cli_runner, admin_creds, patch_httpx, mock_router):
147
- mock_router.add("POST", "/prod/admin/set-quota", json={"message": "Quota updated."})
148
- result = cli_runner.invoke(app, ["admin", "set-quota", "-e", "a@t.com", "-s", "10mb"])
149
- assert result.exit_code == 0
150
- assert "updated" in result.output.lower()
151
-
152
-
153
- def _query_of(url: str) -> dict:
154
- from urllib.parse import parse_qs, urlparse
155
- return {k: v[0] for k, v in parse_qs(urlparse(url).query).items()}
156
-
157
-
158
- def _get_calls(mock_router, path_suffix: str) -> list:
159
- return [
160
- c for c in mock_router.calls
161
- if c["method"] == "GET" and path_suffix in c["url"].split("?")[0]
162
- ]
163
-
164
-
165
- class TestAdminRun:
166
- def test_not_top_level(self, cli_runner, admin_creds, patch_httpx, mock_router):
167
- result = cli_runner.invoke(app, ["admin", "run", "list", "-e", "alice@test.com"])
168
- assert result.exit_code != 0
169
-
170
- def test_help_lists_read_commands(self, cli_runner, admin_creds, patch_httpx, mock_router):
171
- result = cli_runner.invoke(app, ["admin", "user-info", "--help"])
172
- assert result.exit_code == 0
173
- assert "run" in result.output
174
- assert "files" in result.output
175
-
176
- def test_run_help_is_read_only(self, cli_runner, admin_creds, patch_httpx, mock_router):
177
- result = cli_runner.invoke(app, ["admin", "user-info", "run", "--help"])
178
- assert result.exit_code == 0
179
- assert "list" in result.output
180
- assert "status" in result.output
181
- assert "submit" not in result.output
182
- assert "cancel" not in result.output
183
-
184
- def test_submit_not_a_command(self, cli_runner, admin_creds, patch_httpx, mock_router):
185
- result = cli_runner.invoke(
186
- app, ["admin", "user-info", "run", "submit", "-e", "alice@test.com", "model.py"]
187
- )
188
- assert result.exit_code != 0
189
-
190
- def test_list_sends_as_user(self, cli_runner, admin_creds, patch_httpx, mock_router):
191
- mock_router.add("GET", "/prod/run/list", json={"analyses": [], "as_user": "alice@test.com"})
192
- result = cli_runner.invoke(
193
- app, ["admin", "user-info", "run", "list", "-e", "alice@test.com", "--all"]
194
- )
195
- assert result.exit_code == 0
196
- calls = _get_calls(mock_router, "/prod/run/list")
197
- assert calls
198
- assert _query_of(calls[0]["url"])["as_user"] == "alice@test.com"
199
-
200
- def test_list_parent_email(self, cli_runner, admin_creds, patch_httpx, mock_router):
201
- mock_router.add("GET", "/prod/run/list", json={"analyses": [], "as_user": "alice@test.com"})
202
- result = cli_runner.invoke(
203
- app, ["admin", "user-info", "-e", "alice@test.com", "run", "list", "--all"]
204
- )
205
- assert result.exit_code == 0
206
- calls = _get_calls(mock_router, "/prod/run/list")
207
- assert calls
208
- assert _query_of(calls[0]["url"])["as_user"] == "alice@test.com"
209
-
210
- def test_list_requires_email(self, cli_runner, admin_creds, patch_httpx, mock_router):
211
- result = cli_runner.invoke(app, ["admin", "user-info", "run", "list"])
212
- assert result.exit_code != 0
213
-
214
- def test_status_sends_as_user(self, cli_runner, admin_creds, patch_httpx, mock_router):
215
- mock_router.add("GET", "/prod/run/status", json={
216
- "task_id": "ttt55555",
217
- "analysis_id": "aaa55555",
218
- "status": "completed",
219
- "filename": "model.py",
220
- "type": "fast",
221
- "total_tasks": 1,
222
- "as_user": "alice@test.com",
223
- })
224
- result = cli_runner.invoke(
225
- app, ["admin", "user-info", "run", "status", "aaa55555", "-e", "alice@test.com"]
226
- )
227
- assert result.exit_code == 0
228
- calls = _get_calls(mock_router, "/prod/run/status")
229
- assert calls
230
- q = _query_of(calls[0]["url"])
231
- assert q["as_user"] == "alice@test.com"
232
- assert q["id"] == "aaa55555"
233
-
234
-
235
- class TestAdminFiles:
236
- def test_not_top_level(self, cli_runner, admin_creds, patch_httpx, mock_router):
237
- result = cli_runner.invoke(app, ["admin", "files", "list", "-e", "alice@test.com"])
238
- assert result.exit_code != 0
239
-
240
- def test_help_is_read_only(self, cli_runner, admin_creds, patch_httpx, mock_router):
241
- result = cli_runner.invoke(app, ["admin", "user-info", "files", "--help"])
242
- assert result.exit_code == 0
243
- assert "list" in result.output
244
- assert "download" in result.output
245
- assert "upload" not in result.output
246
- assert "delete" not in result.output
247
-
248
- def test_list_sends_as_user(self, cli_runner, admin_creds, patch_httpx, mock_router):
249
- mock_router.add("GET", "/prod/files/list", json={
250
- "files": [{"path": "model.py", "size": 10, "last_modified": "2026-01-01T00:00:00Z"}],
251
- "as_user": "alice@test.com",
252
- })
253
- result = cli_runner.invoke(
254
- app, ["admin", "user-info", "files", "list", "-e", "alice@test.com"]
255
- )
256
- assert result.exit_code == 0
257
- assert "model.py" in result.output
258
- calls = _get_calls(mock_router, "/prod/files/list")
259
- assert calls
260
- assert _query_of(calls[0]["url"])["as_user"] == "alice@test.com"
261
- assert "Files for alice@test.com" in result.output
262
-
263
- def test_list_old_api_does_not_show_caller_files(
264
- self, cli_runner, admin_creds, patch_httpx, mock_router
265
- ):
266
- mock_router.add("GET", "/prod/files/list", json={
267
- "files": [{"path": "mine.py", "size": 10, "last_modified": "2026-01-01T00:00:00Z"}],
268
- })
269
- result = cli_runner.invoke(
270
- app, ["admin", "user-info", "files", "list", "-e", "alice@test.com"]
271
- )
272
- assert result.exit_code == 1
273
- assert "mine.py" not in result.output
274
- assert "Deploy the API" in result.output
275
-
276
- def test_download_sends_as_user(self, cli_runner, admin_creds, patch_httpx, mock_router, tmp_path):
277
- mock_router.add("GET", "/prod/files/list", json={
278
- "files": [{"path": "model.py", "size": 5, "last_modified": "2026-01-01T00:00:00Z"}],
279
- "as_user": "alice@test.com",
280
- })
281
- mock_router.add("GET", "/prod/files/download", json={
282
- "download_url": "https://s3.example.com/presigned-get?sig=abc",
283
- "as_user": "alice@test.com",
284
- })
285
- mock_router.add_any_url("GET", status=200, content=b"hello")
286
- out = tmp_path / "model.py"
287
- result = cli_runner.invoke(
288
- app,
289
- ["admin", "user-info", "files", "download", "model.py", "-e", "alice@test.com", "-o", str(out)],
290
- )
291
- assert result.exit_code == 0
292
- list_calls = _get_calls(mock_router, "/prod/files/list")
293
- dl_calls = _get_calls(mock_router, "/prod/files/download")
294
- assert list_calls and dl_calls
295
- assert _query_of(list_calls[0]["url"])["as_user"] == "alice@test.com"
296
- assert _query_of(dl_calls[0]["url"])["as_user"] == "alice@test.com"
File without changes
File without changes