urun-cli 0.2.0__tar.gz → 0.3.1__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.
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.0
4
+
5
+ - Implement the `urun org` / `urun org id` command: print the caller's org id
6
+ (resolved via the control-plane org-config endpoint).
7
+ - Implement `urun auth jwks set`: register the org's trusted JWKS for federated
8
+ identity, via `--jwks-url` or `--jwks-json` (file or stdin), with optional
9
+ `--issuer`/`--audience`. This registers a trust relationship only; JWTs are
10
+ issued out of band and the CLI never mints, fetches, or stores one.
11
+ - Add `ApiClient.register_trusted_jwks`, calling `POST /org-config/trusted-jwks`.
12
+
3
13
  ## 0.2.0
4
14
 
5
15
  - Bumped past 0.1.1/0.1.2 because both filenames were occupied by previously-deleted PyPI artifacts.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: urun-cli
3
- Version: 0.2.0
3
+ Version: 0.3.1
4
4
  Summary: End-user CLI for deploying apps to urun
5
5
  Project-URL: Homepage, https://urun.sh
6
6
  Project-URL: Repository, https://github.com/urun-sh/urun-cli
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "urun-cli"
7
- version = "0.2.0"
7
+ version = "0.3.1"
8
8
  description = "End-user CLI for deploying apps to urun"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -35,6 +35,15 @@ class ApiClient:
35
35
  def org_config(self) -> dict[str, Any]:
36
36
  return self._json("GET", "/org-config", None)
37
37
 
38
+ def register_trusted_jwks(self, payload: dict[str, Any]) -> dict[str, Any]:
39
+ """Register this org's trusted JWKS with the control plane.
40
+
41
+ The org is derived server-side from the API key; the payload carries only
42
+ the trusted key source (jwks_url OR jwks_json) plus optional iss/aud. This
43
+ records a trust relationship — it does not mint or fetch a JWT.
44
+ """
45
+ return self._json("POST", "/org-config/trusted-jwks", payload)
46
+
38
47
  def _json(self, method: str, path: str, body: dict[str, Any] | None) -> dict[str, Any]:
39
48
  data = (
40
49
  None
@@ -2,6 +2,7 @@ from __future__ import annotations
2
2
 
3
3
  import argparse
4
4
  import getpass
5
+ import json
5
6
  import os
6
7
  import re
7
8
  import sys
@@ -28,6 +29,10 @@ def main(argv: list[str] | None = None) -> int:
28
29
  return deploy(args)
29
30
  if args.command == "login":
30
31
  return login(args)
32
+ if args.command == "org":
33
+ return org(args)
34
+ if args.command == "auth":
35
+ return auth(args)
31
36
  parser.print_help()
32
37
  return 2
33
38
  except UrunError as exc:
@@ -65,9 +70,81 @@ def build_parser() -> argparse.ArgumentParser:
65
70
  ),
66
71
  )
67
72
  add_deploy_args(run)
73
+
74
+ add_org_parser(sub)
75
+ add_auth_parser(sub)
68
76
  return parser
69
77
 
70
78
 
79
+ def add_org_parser(sub: argparse._SubParsersAction) -> None:
80
+ org_parser = sub.add_parser(
81
+ "org",
82
+ help="Show the caller's org id",
83
+ description=(
84
+ "Print the organization the authenticating API key belongs to "
85
+ "(resolved via the control plane's org-config endpoint)."
86
+ ),
87
+ )
88
+ org_sub = org_parser.add_subparsers(dest="org_command")
89
+ id_parser = org_sub.add_parser(
90
+ "id",
91
+ help="Print just the org id (machine-readable)",
92
+ description="Print only the org id on stdout, with no other output.",
93
+ )
94
+ add_api_args(id_parser)
95
+ # Allow `urun org` (bare) to behave like `urun org id`.
96
+ add_api_args(org_parser)
97
+
98
+
99
+ def add_auth_parser(sub: argparse._SubParsersAction) -> None:
100
+ auth_parser = sub.add_parser(
101
+ "auth",
102
+ help="Register the org's trusted JWKS for federated identity",
103
+ description=(
104
+ "Register the trusted JWKS the control plane should verify session "
105
+ "JWTs against for this org. JWTs are issued OUT OF BAND by your IdP; "
106
+ "this command only REGISTERS A TRUST RELATIONSHIP — it never mints, "
107
+ "fetches, or stores a JWT, and no new secret is sent."
108
+ ),
109
+ )
110
+ auth_sub = auth_parser.add_subparsers(dest="auth_command")
111
+ jwks_parser = auth_sub.add_parser(
112
+ "jwks",
113
+ help="Manage the org's trusted JWKS",
114
+ description="Manage the trusted JWKS registered for this org.",
115
+ )
116
+ jwks_sub = jwks_parser.add_subparsers(dest="jwks_command")
117
+ set_parser = jwks_sub.add_parser(
118
+ "set",
119
+ help="Register/replace the org's trusted JWKS",
120
+ description=(
121
+ "Register (or replace) the trusted key source the control plane "
122
+ "verifies this org's session JWTs against. Provide EXACTLY ONE of "
123
+ "--jwks-url (a remote JWK Set endpoint) or --jwks-json (an inline JWK "
124
+ "Set from a file or '-' for stdin). Optionally pin the expected token "
125
+ "issuer/audience. This registers trust only; it does not mint a JWT."
126
+ ),
127
+ )
128
+ set_parser.add_argument(
129
+ "--jwks-url",
130
+ help="HTTPS URL of the org's JWK Set (e.g. https://idp.example.com/.well-known/jwks.json)",
131
+ )
132
+ set_parser.add_argument(
133
+ "--jwks-json",
134
+ metavar="FILE",
135
+ help="Path to an inline JWK Set ({\"keys\":[...]}), or '-' to read from stdin",
136
+ )
137
+ set_parser.add_argument(
138
+ "--issuer",
139
+ help="Optional expected JWT `iss` claim; tokens whose iss differs are rejected",
140
+ )
141
+ set_parser.add_argument(
142
+ "--audience",
143
+ help="Optional expected JWT `aud` claim; tokens lacking it are rejected",
144
+ )
145
+ add_api_args(set_parser)
146
+
147
+
71
148
  def add_login_args(parser: argparse.ArgumentParser) -> None:
72
149
  parser.add_argument(
73
150
  "--api-url",
@@ -132,6 +209,77 @@ def login(args: argparse.Namespace) -> int:
132
209
  return 0
133
210
 
134
211
 
212
+ def org(args: argparse.Namespace) -> int:
213
+ # `urun org` and `urun org id` both print just the org id. There is no other
214
+ # `org` subcommand, so a bare `org` defaults to `id`.
215
+ api_url, api_key = resolve_api_credentials(args)
216
+ config = ApiClient(api_url, api_key).org_config()
217
+ print(config_value(config, "org_id"))
218
+ return 0
219
+
220
+
221
+ def auth(args: argparse.Namespace) -> int:
222
+ if (
223
+ getattr(args, "auth_command", None) != "jwks"
224
+ or getattr(args, "jwks_command", None) != "set"
225
+ ):
226
+ raise UrunError("usage: urun auth jwks set --jwks-url <url> | --jwks-json <file|->")
227
+ return auth_jwks_set(args)
228
+
229
+
230
+ def auth_jwks_set(args: argparse.Namespace) -> int:
231
+ jwks_url = string_value(args.jwks_url)
232
+ jwks_json_arg = string_value(args.jwks_json)
233
+ if bool(jwks_url) == bool(jwks_json_arg):
234
+ raise UrunError("provide exactly one of --jwks-url or --jwks-json")
235
+
236
+ payload: dict[str, Any] = {}
237
+ if jwks_url:
238
+ payload["jwks_url"] = jwks_url
239
+ issuer = string_value(args.issuer)
240
+ audience = string_value(args.audience)
241
+ if issuer:
242
+ payload["expected_issuer"] = issuer
243
+ if audience:
244
+ payload["expected_audience"] = audience
245
+ else:
246
+ payload["jwks_json"] = read_jwks_json(jwks_json_arg)
247
+ issuer = string_value(args.issuer)
248
+ audience = string_value(args.audience)
249
+ if issuer:
250
+ payload["expected_issuer"] = issuer
251
+ if audience:
252
+ payload["expected_audience"] = audience
253
+
254
+ api_url, api_key = resolve_api_credentials(args)
255
+ result = ApiClient(api_url, api_key).register_trusted_jwks(payload)
256
+ org_id = string_value(result.get("org_id")) or "(unknown)"
257
+ print(f"Registered trusted JWKS for org {org_id}.")
258
+ print("This registers a trust relationship only; no JWT was minted or fetched.")
259
+ return 0
260
+
261
+
262
+ def read_jwks_json(source: str) -> dict[str, Any]:
263
+ """Read and validate a JWK Set from a file path, or '-' for stdin."""
264
+ if source == "-":
265
+ raw = sys.stdin.read()
266
+ else:
267
+ path = Path(source)
268
+ if not path.is_file():
269
+ raise UrunError(f"JWKS file not found: {source}")
270
+ raw = path.read_text(encoding="utf-8")
271
+ try:
272
+ parsed = json.loads(raw)
273
+ except json.JSONDecodeError as exc:
274
+ raise UrunError(f"invalid JWK Set JSON: {exc}") from exc
275
+ if not isinstance(parsed, dict):
276
+ raise UrunError("invalid JWK Set: expected a JSON object")
277
+ keys = parsed.get("keys")
278
+ if not isinstance(keys, list) or not keys:
279
+ raise UrunError('invalid JWK Set: must contain a non-empty "keys" array')
280
+ return parsed
281
+
282
+
135
283
  def deploy(args: argparse.Namespace) -> int:
136
284
  api_url, api_key = resolve_api_credentials(args)
137
285
  if args.poll_interval <= 0:
@@ -141,7 +289,8 @@ def deploy(args: argparse.Namespace) -> int:
141
289
 
142
290
  project_root = Path.cwd()
143
291
  entrypoint, files = discover_main_files(args.entrypoint, project_root)
144
- deps, deps_blob, python_version = resolve_deps(project_root)
292
+ entrypoint_path = (project_root / args.entrypoint).resolve()
293
+ deps, deps_blob, python_version = resolve_deps(project_root, entrypoint_path)
145
294
 
146
295
  app_name = args.name or derive_app_name(args.entrypoint)
147
296
  all_blobs = files + ([deps_blob] if deps_blob is not None else [])
@@ -0,0 +1,399 @@
1
+ from __future__ import annotations
2
+
3
+ import ast
4
+ import tempfile
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ from .manifest import FileBlob, file_blob
9
+
10
+ DEFAULT_PYTHON_VERSION = "3.12"
11
+
12
+ # Sentinel returned when the static evaluator cannot determine a value (e.g. an
13
+ # attribute access into config objects that are not statically resolvable). It
14
+ # behaves as an empty-ish value so unioning deps simply skips it.
15
+ _UNKNOWN = object()
16
+
17
+
18
+ class _DepsEvaluator:
19
+ """A tiny, side-effect-free interpreter over a Python *module* AST.
20
+
21
+ It evaluates only the small subset of Python needed to recover the
22
+ ``Dependencies(python=[...], apt=[...], post_install=[...])`` literal that
23
+ apps declare on ``@app.function(deps=...)`` — INCLUDING the common
24
+ indirections used by helios/lingbot:
25
+
26
+ * module-level ``CONFIG = dict(..., deps=Dependencies(...))`` then
27
+ ``@app.function(**CONFIG)`` / ``@app.on(name, **CONFIG)``
28
+ * ``python=_runtime_python_deps()`` — a no-arg local function that builds a
29
+ list with literals, ``.extend([...])`` and ``for``/``if``/``continue``
30
+ filtering using ``str.startswith``.
31
+
32
+ It never imports or executes the module; unknown constructs degrade to an
33
+ ``_UNKNOWN`` sentinel rather than raising, so deps extraction is best-effort
34
+ and robust.
35
+ """
36
+
37
+ def __init__(self, tree: ast.Module) -> None:
38
+ self.tree = tree
39
+ # Module-level symbol table: name -> AST value node (lazily evaluated).
40
+ self.assignments: dict[str, ast.expr] = {}
41
+ self.functions: dict[str, ast.FunctionDef] = {}
42
+ for node in tree.body:
43
+ if isinstance(node, ast.Assign):
44
+ for target in node.targets:
45
+ if isinstance(target, ast.Name):
46
+ self.assignments[target.id] = node.value
47
+ elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
48
+ if node.value is not None:
49
+ self.assignments[node.target.id] = node.value
50
+ elif isinstance(node, ast.FunctionDef):
51
+ self.functions[node.name] = node
52
+
53
+ # -- public API --------------------------------------------------------
54
+
55
+ def collect_dependencies(self) -> dict[str, list[str]]:
56
+ """Union ``deps=Dependencies(...)`` across all app function decorators."""
57
+ out: dict[str, list[str]] = {"python": [], "apt": [], "post_install": []}
58
+ seen: set[tuple[str, str]] = set()
59
+ for deps_call in self._find_deps_calls():
60
+ spec = self._eval_dependencies_call(deps_call)
61
+ if not isinstance(spec, dict):
62
+ continue
63
+ for key in out:
64
+ for item in spec.get(key, []) or []:
65
+ if isinstance(item, str) and (key, item) not in seen:
66
+ seen.add((key, item))
67
+ out[key].append(item)
68
+ return out
69
+
70
+ # -- decorator discovery ----------------------------------------------
71
+
72
+ def _find_deps_calls(self) -> list[ast.Call]:
73
+ calls: list[ast.Call] = []
74
+ for node in ast.walk(self.tree):
75
+ if not isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):
76
+ continue
77
+ for dec in node.decorator_list:
78
+ if isinstance(dec, ast.Call) and self._is_app_decorator(dec.func):
79
+ deps = self._extract_deps_from_call(dec)
80
+ if deps is not None:
81
+ calls.append(deps)
82
+ return calls
83
+
84
+ @staticmethod
85
+ def _is_app_decorator(func: ast.expr) -> bool:
86
+ # Match `app.function(...)`, `app.on(...)`, `something.function(...)`.
87
+ if isinstance(func, ast.Attribute):
88
+ return func.attr in {"function", "on"}
89
+ return False
90
+
91
+ def _extract_deps_from_call(self, call: ast.Call) -> ast.Call | None:
92
+ # Direct keyword: deps=Dependencies(...)
93
+ for kw in call.keywords:
94
+ if kw.arg == "deps":
95
+ return self._as_dependencies_call(kw.value)
96
+ # Indirection via **CONFIG spread.
97
+ for kw in call.keywords:
98
+ if kw.arg is None: # **spread
99
+ config = self._resolve(kw.value)
100
+ if isinstance(config, dict):
101
+ deps_val = config.get("deps")
102
+ if isinstance(deps_val, ast.AST):
103
+ return self._as_dependencies_call(deps_val)
104
+ return None
105
+
106
+ def _as_dependencies_call(self, node: ast.AST) -> ast.Call | None:
107
+ # node may be a Name pointing at a module-level Dependencies(...) call.
108
+ node = self._deref(node)
109
+ if isinstance(node, ast.Call) and self._call_name(node.func) == "Dependencies":
110
+ return node
111
+ return None
112
+
113
+ # -- Dependencies(...) evaluation -------------------------------------
114
+
115
+ def _eval_dependencies_call(self, call: ast.Call) -> dict[str, list[str]]:
116
+ result: dict[str, list[str]] = {"python": [], "apt": [], "post_install": []}
117
+ for kw in call.keywords:
118
+ if kw.arg in result:
119
+ value = self._eval(kw.value, {})
120
+ if isinstance(value, list):
121
+ result[kw.arg] = [v for v in value if isinstance(v, str)]
122
+ return result
123
+
124
+ # -- name resolution helpers ------------------------------------------
125
+
126
+ def _deref(self, node: ast.AST) -> ast.AST:
127
+ """Follow a module-level Name to its assigned value node."""
128
+ while isinstance(node, ast.Name) and node.id in self.assignments:
129
+ node = self.assignments[node.id]
130
+ return node
131
+
132
+ def _resolve(self, node: ast.AST) -> Any:
133
+ """Resolve a possibly-Name node to an evaluated value (module scope)."""
134
+ return self._eval(node, {})
135
+
136
+ @staticmethod
137
+ def _call_name(func: ast.expr) -> str | None:
138
+ if isinstance(func, ast.Name):
139
+ return func.id
140
+ if isinstance(func, ast.Attribute):
141
+ return func.attr
142
+ return None
143
+
144
+ # -- the constrained evaluator ----------------------------------------
145
+
146
+ def _eval(self, node: ast.AST, scope: dict[str, Any]) -> Any:
147
+ if isinstance(node, ast.Constant):
148
+ return node.value
149
+ if isinstance(node, ast.Name):
150
+ if node.id in scope:
151
+ return scope[node.id]
152
+ if node.id in self.assignments:
153
+ return self._eval(self.assignments[node.id], {})
154
+ return _UNKNOWN
155
+ if isinstance(node, ast.List | ast.Tuple | ast.Set):
156
+ out: list[Any] = []
157
+ for elt in node.elts:
158
+ if isinstance(elt, ast.Starred):
159
+ inner = self._eval(elt.value, scope)
160
+ if isinstance(inner, list | tuple | set):
161
+ out.extend(inner)
162
+ else:
163
+ out.append(self._eval(elt, scope))
164
+ return out
165
+ if isinstance(node, ast.Dict):
166
+ result: dict[Any, Any] = {}
167
+ for k, v in zip(node.keys, node.values, strict=True):
168
+ if k is None: # **spread
169
+ inner = self._eval(v, scope)
170
+ if isinstance(inner, dict):
171
+ result.update(inner)
172
+ continue
173
+ result[self._eval(k, scope)] = v # keep value node lazy for dict()
174
+ return result
175
+ if isinstance(node, ast.Call):
176
+ return self._eval_call(node, scope)
177
+ if isinstance(node, ast.BoolOp):
178
+ values = [self._eval(v, scope) for v in node.values]
179
+ if isinstance(node.op, ast.Or):
180
+ result_bool = False
181
+ for v in values:
182
+ if v is True:
183
+ return True
184
+ if v is _UNKNOWN:
185
+ result_bool = _UNKNOWN # type: ignore[assignment]
186
+ return result_bool
187
+ if isinstance(node.op, ast.And):
188
+ for v in values:
189
+ if v is False:
190
+ return False
191
+ if v is _UNKNOWN:
192
+ return _UNKNOWN
193
+ return True
194
+ return _UNKNOWN
195
+ if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
196
+ inner = self._eval(node.operand, scope)
197
+ if inner is True:
198
+ return False
199
+ if inner is False:
200
+ return True
201
+ return _UNKNOWN
202
+ if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
203
+ left = self._eval(node.left, scope)
204
+ right = self._eval(node.right, scope)
205
+ if isinstance(left, list) and isinstance(right, list):
206
+ return left + right
207
+ return _UNKNOWN
208
+ if isinstance(node, ast.Attribute):
209
+ return _UNKNOWN
210
+ return _UNKNOWN
211
+
212
+ def _eval_call(self, node: ast.Call, scope: dict[str, Any]) -> Any:
213
+ name = self._call_name(node.func)
214
+ # dict(...) -> mapping with value nodes kept lazy (so deps stays an AST).
215
+ if name == "dict" and isinstance(node.func, ast.Name):
216
+ mapping: dict[str, Any] = {}
217
+ for kw in node.keywords:
218
+ if kw.arg is None:
219
+ inner = self._eval(kw.value, scope)
220
+ if isinstance(inner, dict):
221
+ mapping.update(inner)
222
+ elif kw.arg == "deps":
223
+ mapping["deps"] = kw.value # keep AST for Dependencies match
224
+ else:
225
+ mapping[kw.arg] = kw.value
226
+ return mapping
227
+ # list(x) / list([...])
228
+ if name == "list" and isinstance(node.func, ast.Name):
229
+ if not node.args:
230
+ return []
231
+ inner = self._eval(node.args[0], scope)
232
+ if isinstance(inner, list | tuple | set):
233
+ return list(inner)
234
+ return _UNKNOWN
235
+ # str.startswith(prefix) for filtering loops.
236
+ if isinstance(node.func, ast.Attribute):
237
+ recv = self._eval(node.func.value, scope)
238
+ attr = node.func.attr
239
+ if isinstance(recv, str) and attr == "startswith":
240
+ args = [self._eval(a, scope) for a in node.args]
241
+ if args and isinstance(args[0], str):
242
+ return recv.startswith(args[0])
243
+ return _UNKNOWN
244
+ # No-arg local function call: interpret its body.
245
+ if isinstance(node.func, ast.Name) and node.func.id in self.functions and not node.args:
246
+ return self._eval_function(self.functions[node.func.id])
247
+ return _UNKNOWN
248
+
249
+ def _eval_function(self, fn: ast.FunctionDef) -> Any:
250
+ """Interpret a no-arg function body that builds and returns a list."""
251
+ scope: dict[str, Any] = {}
252
+ return self._exec_body(fn.body, scope)
253
+
254
+ def _exec_body(self, body: list[ast.stmt], scope: dict[str, Any]) -> Any:
255
+ for stmt in body:
256
+ result = self._exec_stmt(stmt, scope)
257
+ if result is not _NO_RETURN:
258
+ return result
259
+ return _UNKNOWN
260
+
261
+ def _exec_stmt(self, stmt: ast.stmt, scope: dict[str, Any]) -> Any:
262
+ if isinstance(stmt, ast.Return):
263
+ return self._eval(stmt.value, scope) if stmt.value else None
264
+ if isinstance(stmt, ast.Assign):
265
+ value = self._eval(stmt.value, scope)
266
+ for target in stmt.targets:
267
+ if isinstance(target, ast.Name):
268
+ scope[target.id] = value
269
+ return _NO_RETURN
270
+ if isinstance(stmt, ast.AnnAssign) and isinstance(stmt.target, ast.Name):
271
+ if stmt.value is not None:
272
+ scope[stmt.target.id] = self._eval(stmt.value, scope)
273
+ return _NO_RETURN
274
+ if isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Call):
275
+ self._exec_method_call(stmt.value, scope)
276
+ return _NO_RETURN
277
+ if isinstance(stmt, ast.For):
278
+ return self._exec_for(stmt, scope)
279
+ if isinstance(stmt, ast.If):
280
+ test = self._eval(stmt.test, scope)
281
+ branch = stmt.body if test is True else stmt.orelse if test is False else None
282
+ if branch is not None:
283
+ return self._exec_body_or_continue(branch, scope)
284
+ return _NO_RETURN
285
+ return _NO_RETURN
286
+
287
+ def _exec_for(self, stmt: ast.For, scope: dict[str, Any]) -> Any:
288
+ iterable = self._eval(stmt.iter, scope)
289
+ if not isinstance(iterable, list | tuple | set):
290
+ return _NO_RETURN
291
+ if not isinstance(stmt.target, ast.Name):
292
+ return _NO_RETURN
293
+ var = stmt.target.id
294
+ for item in iterable:
295
+ scope[var] = item
296
+ signal = self._exec_loop_body(stmt.body, scope)
297
+ if signal is _CONTINUE:
298
+ continue
299
+ if signal is not _NO_RETURN and signal is not None:
300
+ return signal
301
+ return _NO_RETURN
302
+
303
+ def _exec_loop_body(self, body: list[ast.stmt], scope: dict[str, Any]) -> Any:
304
+ for stmt in body:
305
+ if isinstance(stmt, ast.Continue):
306
+ return _CONTINUE
307
+ if isinstance(stmt, ast.If):
308
+ test = self._eval(stmt.test, scope)
309
+ branch = stmt.body if test is True else stmt.orelse if test is False else []
310
+ signal = self._exec_loop_body(branch, scope)
311
+ if signal is not _NO_RETURN:
312
+ return signal
313
+ continue
314
+ if isinstance(stmt, ast.Return):
315
+ return self._eval(stmt.value, scope) if stmt.value else None
316
+ if isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Call):
317
+ self._exec_method_call(stmt.value, scope)
318
+ continue
319
+ if isinstance(stmt, ast.Assign):
320
+ self._exec_stmt(stmt, scope)
321
+ return _NO_RETURN
322
+
323
+ def _exec_body_or_continue(self, body: list[ast.stmt], scope: dict[str, Any]) -> Any:
324
+ return self._exec_body(body, scope)
325
+
326
+ def _exec_method_call(self, call: ast.Call, scope: dict[str, Any]) -> None:
327
+ # Handle list.append(x) / list.extend([...]) mutating a scope variable.
328
+ if not isinstance(call.func, ast.Attribute):
329
+ return
330
+ target = call.func.value
331
+ attr = call.func.attr
332
+ if not isinstance(target, ast.Name) or target.id not in scope:
333
+ return
334
+ container = scope[target.id]
335
+ if not isinstance(container, list):
336
+ return
337
+ if attr == "append" and call.args:
338
+ container.append(self._eval(call.args[0], scope))
339
+ elif attr == "extend" and call.args:
340
+ extra = self._eval(call.args[0], scope)
341
+ if isinstance(extra, list | tuple | set):
342
+ container.extend(extra)
343
+
344
+
345
+ _NO_RETURN = object()
346
+ _CONTINUE = object()
347
+
348
+
349
+ def extract_app_python_deps(entrypoint: Path) -> dict[str, list[str]]:
350
+ """Statically extract declared app deps from the entrypoint source.
351
+
352
+ Returns a mapping with ``python``/``apt``/``post_install`` string lists.
353
+ Never imports or executes the app; pure ``ast``.
354
+ """
355
+ source = entrypoint.read_text(encoding="utf-8")
356
+ tree = ast.parse(source, filename=str(entrypoint))
357
+ return _DepsEvaluator(tree).collect_dependencies()
358
+
359
+
360
+ def render_requirements_txt(python_deps: list[str]) -> str:
361
+ """Render requirements.txt content matching Dependencies.to_requirements_txt()."""
362
+ return "\n".join(python_deps)
363
+
364
+
365
+ def resolve_deps(
366
+ project_root: Path, entrypoint: Path | None = None
367
+ ) -> tuple[dict[str, Any], FileBlob | None, str]:
368
+ """Resolve app dependencies for the deploy manifest.
369
+
370
+ Dependencies are declared by the urun app via ``@app.function(deps=...)``.
371
+ We extract the python list STATICALLY (no import, no subprocess), render it
372
+ as a requirements.txt, and emit a ``requirements_txt`` deps manifest backed
373
+ by an uploadable FileBlob. If no python deps are declared, fall back to the
374
+ ``app`` kind (no blob) so simple apps still deploy.
375
+ """
376
+ python_version = DEFAULT_PYTHON_VERSION
377
+ if entrypoint is None:
378
+ return {"kind": "app", "python_version": python_version}, None, python_version
379
+
380
+ extracted = extract_app_python_deps(entrypoint)
381
+ python_deps = extracted.get("python", [])
382
+ if not python_deps:
383
+ return {"kind": "app", "python_version": python_version}, None, python_version
384
+
385
+ text = render_requirements_txt(python_deps)
386
+ # Materialize to a real file so the existing blob upload path (which reads
387
+ # blob.source from disk and re-hashes) can ship it.
388
+ tmp_dir = Path(tempfile.mkdtemp(prefix="urun-deps-"))
389
+ req_path = tmp_dir / "requirements.txt"
390
+ req_path.write_text(text, encoding="utf-8")
391
+ blob = file_blob(req_path, tmp_dir, manifest_path="requirements.txt")
392
+
393
+ deps = {
394
+ "kind": "requirements_txt",
395
+ "blob_sha256": blob.sha256,
396
+ "size": blob.size,
397
+ "python_version": python_version,
398
+ }
399
+ return deps, blob, python_version
@@ -1,13 +0,0 @@
1
- from __future__ import annotations
2
-
3
- from pathlib import Path
4
- from typing import Any
5
-
6
- DEFAULT_PYTHON_VERSION = "3.12"
7
-
8
-
9
- def resolve_deps(_project_root: Path) -> tuple[dict[str, Any], None, str]:
10
- # Dependencies are declared by the urun app in app.py, not by project-level
11
- # pyproject.toml or requirements.txt files.
12
- python_version = DEFAULT_PYTHON_VERSION
13
- return {"kind": "app", "python_version": python_version}, None, python_version
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes