"""Save beside cloudsign_request.py as cloudsign_examples.py. Uses read-only requests.""" import argparse import re import time from cloudsign_request import ApiError, request def iter_apps(module="enterprise", *, limit=50, max_pages=20): """Keep module/limit unchanged and send the returned cursor back verbatim.""" if module not in ("enterprise", "distribution") or not 1 <= limit <= 100 or max_pages < 1: raise ValueError("Use a supported module, limit 1..100 and a positive max_pages") cursor = None seen = set() for _ in range(max_pages): params = {"module": module, "limit": limit} if cursor is not None: params["cursor"] = cursor data = request("GET", "/api/v1/apps", params)["data"] items, next_cursor = data.get("items"), data.get("next_cursor") if not isinstance(items, list) or (next_cursor is not None and (not isinstance(next_cursor, str) or not re.fullmatch(r"A[a-f0-9]{32}", next_cursor))): raise ValueError("Invalid application page") if next_cursor is not None and (not items or next_cursor in seen): raise ValueError("Pagination cursor did not advance") yield from items if next_cursor is None: return seen.add(next_cursor) cursor = next_cursor raise RuntimeError(f"Stopped at max_pages={max_pages}; next cursor={cursor}") def wait_task(app_id, task_id, *, timeout=300, interval=3, max_attempts=60): """Returns every terminal result, including failures. Check status/state afterwards.""" if not re.fullmatch(r"A[a-f0-9]{32}", app_id) or not re.fullmatch(r"[JU][a-f0-9]{32}", task_id): raise ValueError("Use the complete A ID and J (signing) or U (upload) ID") if timeout <= 0 or interval < 1 or max_attempts < 1: raise ValueError("Use positive time/attempt limits and interval >= 1 second") jobs = task_id.startswith("J") resource = f"/api/v1/apps/{app_id}/{'jobs' if jobs else 'uploads'}/{task_id}" deadline = time.monotonic() + timeout for attempt in range(max_attempts): remaining = deadline - time.monotonic() if remaining <= 0: break try: data = request("GET", resource, timeout=min(15, remaining))["data"] except ApiError as error: if error.status != 429: raise delay = max(interval, error.retry_after) else: if data.get("app_id") != app_id or data.get("id") != task_id: raise ValueError("Response belongs to another application or task") state = data.get("status" if jobs else "state") terminal = state in {"succeeded", "failed", "cancelled", "superseded"} if terminal and (not jobs or data.get("terminal") is True): return data delay = interval remaining = deadline - time.monotonic() if attempt + 1 >= max_attempts or delay >= remaining: break time.sleep(delay) raise TimeoutError(f"Polling stopped; query the saved task later: {app_id}/{task_id}") if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) commands = parser.add_subparsers(dest="operation", required=True) apps = commands.add_parser("apps", help="Read all pages within a fixed page limit") apps.add_argument("--module", choices=["enterprise", "distribution"], default="enterprise") apps.add_argument("--max-pages", type=int, default=20) wait = commands.add_parser("wait", help="Wait for a saved J/U task without resubmitting it") wait.add_argument("app_id") wait.add_argument("task_id") args = parser.parse_args() try: if args.operation == "apps": for app in iter_apps(args.module, max_pages=args.max_pages): print(app["id"], app["name"]) else: data = wait_task(args.app_id, args.task_id) state = data.get("status", data.get("state")) if state != "succeeded": raise SystemExit(f"Task finished with state={state}; inspect its error field in the console") print("succeeded", data["id"], data.get("version_id") or "") except (ApiError, ValueError, RuntimeError, TimeoutError) as error: raise SystemExit(str(error)) from None