neocompute 0.1.0__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.
Files changed (59) hide show
  1. neocompute/__init__.py +103 -0
  2. neocompute/__main__.py +3 -0
  3. neocompute/_sync.py +45 -0
  4. neocompute/admin.py +335 -0
  5. neocompute/api/__init__.py +0 -0
  6. neocompute/api/app.py +80 -0
  7. neocompute/api/function.py +435 -0
  8. neocompute/api/image.py +55 -0
  9. neocompute/api/quotas.py +29 -0
  10. neocompute/api/volume.py +196 -0
  11. neocompute/checkpoint.py +151 -0
  12. neocompute/cli.py +518 -0
  13. neocompute/config.py +157 -0
  14. neocompute/core/__init__.py +0 -0
  15. neocompute/core/bundle.py +112 -0
  16. neocompute/core/job.py +76 -0
  17. neocompute/core/jobcontext.py +208 -0
  18. neocompute/core/quota.py +160 -0
  19. neocompute/core/resources.py +177 -0
  20. neocompute/core/scheduler.py +314 -0
  21. neocompute/core/state.py +320 -0
  22. neocompute/core/volumes.py +206 -0
  23. neocompute/core/workload.py +131 -0
  24. neocompute/credentials.py +345 -0
  25. neocompute/dashboard/__init__.py +218 -0
  26. neocompute/dashboard/static/index.html +812 -0
  27. neocompute/errors.py +73 -0
  28. neocompute/providers/__init__.py +87 -0
  29. neocompute/providers/_local_launcher.py +66 -0
  30. neocompute/providers/base.py +140 -0
  31. neocompute/providers/colab.py +661 -0
  32. neocompute/providers/gcp.py +600 -0
  33. neocompute/providers/huggingface.py +291 -0
  34. neocompute/providers/kaggle.py +289 -0
  35. neocompute/providers/lightning.py +308 -0
  36. neocompute/providers/local.py +514 -0
  37. neocompute/providers/modal.py +369 -0
  38. neocompute/providers/thunder.py +423 -0
  39. neocompute/py.typed +0 -0
  40. neocompute/runtime/__init__.py +1 -0
  41. neocompute/runtime/bootstrap.py +114 -0
  42. neocompute/runtime/context.py +155 -0
  43. neocompute/runtime/modal_entry.py +52 -0
  44. neocompute/runtime/paths.py +34 -0
  45. neocompute/runtime/serialization.py +108 -0
  46. neocompute/runtime/volumes.py +516 -0
  47. neocompute/runtime/worker.py +257 -0
  48. neocompute/storage/__init__.py +44 -0
  49. neocompute/storage/artifacts.py +40 -0
  50. neocompute/storage/base.py +100 -0
  51. neocompute/storage/gcs.py +37 -0
  52. neocompute/storage/huggingface.py +53 -0
  53. neocompute/storage/local.py +20 -0
  54. neocompute/storage/s3.py +42 -0
  55. neocompute-0.1.0.dist-info/METADATA +221 -0
  56. neocompute-0.1.0.dist-info/RECORD +59 -0
  57. neocompute-0.1.0.dist-info/WHEEL +4 -0
  58. neocompute-0.1.0.dist-info/entry_points.txt +2 -0
  59. neocompute-0.1.0.dist-info/licenses/LICENSE +21 -0
neocompute/__init__.py ADDED
@@ -0,0 +1,103 @@
1
+ """neocompute: run decorated Python functions on heterogeneous compute providers.
2
+
3
+ Attributes are loaded lazily so that the worker runtime, which imports
4
+ ``neocompute.runtime.worker`` inside remote environments, only needs
5
+ ``cloudpickle`` and not the client-side dependencies.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import importlib
11
+ from typing import TYPE_CHECKING, Any
12
+
13
+ __version__ = "0.1.0"
14
+
15
+ _EXPORTS: dict[str, str] = {
16
+ "App": "neocompute.api.app",
17
+ "Function": "neocompute.api.function",
18
+ "FunctionCall": "neocompute.api.function",
19
+ "Image": "neocompute.api.image",
20
+ "Volume": "neocompute.api.volume",
21
+ "VolumeInfo": "neocompute.api.volume",
22
+ "list_volumes": "neocompute.api.volume",
23
+ "GPU": "neocompute.core.resources",
24
+ "ResourceSpec": "neocompute.core.resources",
25
+ "ComputeOffer": "neocompute.core.resources",
26
+ "Capabilities": "neocompute.core.resources",
27
+ "Workload": "neocompute.core.workload",
28
+ "JobHandle": "neocompute.core.job",
29
+ "JobState": "neocompute.core.job",
30
+ "JobStatus": "neocompute.core.job",
31
+ "FailureKind": "neocompute.core.job",
32
+ "Config": "neocompute.config",
33
+ "configure": "neocompute.config",
34
+ "get_config": "neocompute.config",
35
+ "resolve_path": "neocompute.runtime.paths",
36
+ "quotas": "neocompute.api.quotas",
37
+ "plan": "neocompute.api.quotas",
38
+ "login": "neocompute.credentials",
39
+ "LoginResult": "neocompute.credentials",
40
+ "QuotaStatus": "neocompute.core.quota",
41
+ "QuotaPolicy": "neocompute.core.quota",
42
+ "ArtifactRef": "neocompute.storage",
43
+ "ArtifactStore": "neocompute.storage",
44
+ "open_storage": "neocompute.storage",
45
+ "ComputeError": "neocompute.errors",
46
+ "ConfigError": "neocompute.errors",
47
+ "UnsupportedCapabilityError": "neocompute.errors",
48
+ "NoEligibleOfferError": "neocompute.errors",
49
+ "InfrastructureError": "neocompute.errors",
50
+ "FunctionTimeoutError": "neocompute.errors",
51
+ "JobCancelledError": "neocompute.errors",
52
+ "JobNotFoundError": "neocompute.errors",
53
+ "RemoteError": "neocompute.errors",
54
+ }
55
+
56
+ _SUBMODULES = {"checkpoint"}
57
+
58
+ __all__ = sorted({*_EXPORTS, *_SUBMODULES})
59
+
60
+
61
+ def __getattr__(name: str) -> Any:
62
+ if name in _SUBMODULES:
63
+ value = importlib.import_module(f"neocompute.{name}")
64
+ globals()[name] = value
65
+ return value
66
+ module = _EXPORTS.get(name)
67
+ if module is None:
68
+ raise AttributeError(f"module 'neocompute' has no attribute {name!r}")
69
+ value = getattr(importlib.import_module(module), name)
70
+ globals()[name] = value
71
+ return value
72
+
73
+
74
+ def __dir__() -> list[str]:
75
+ return sorted(set(globals()) | set(__all__))
76
+
77
+
78
+ if TYPE_CHECKING:
79
+ from neocompute.api.app import App
80
+ from neocompute.api.function import Function, FunctionCall
81
+ from neocompute.api.image import Image
82
+ from neocompute.api.quotas import plan, quotas
83
+ from neocompute import checkpoint
84
+ from neocompute.api.volume import Volume, VolumeInfo, list_volumes
85
+ from neocompute.config import Config, configure, get_config
86
+ from neocompute.core.quota import QuotaPolicy, QuotaStatus
87
+ from neocompute.core.job import FailureKind, JobHandle, JobState, JobStatus
88
+ from neocompute.core.resources import GPU, Capabilities, ComputeOffer, ResourceSpec
89
+ from neocompute.core.workload import Workload
90
+ from neocompute.errors import (
91
+ ComputeError,
92
+ ConfigError,
93
+ FunctionTimeoutError,
94
+ InfrastructureError,
95
+ JobCancelledError,
96
+ JobNotFoundError,
97
+ NoEligibleOfferError,
98
+ RemoteError,
99
+ UnsupportedCapabilityError,
100
+ )
101
+ from neocompute.credentials import LoginResult, login
102
+ from neocompute.runtime.paths import resolve_path
103
+ from neocompute.storage import ArtifactRef, ArtifactStore, open_storage
neocompute/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from neocompute.cli import main
2
+
3
+ main()
neocompute/_sync.py ADDED
@@ -0,0 +1,45 @@
1
+ """Run the async core from synchronous code.
2
+
3
+ Blocking calls go to one background event loop thread, so they also work
4
+ when the caller already has a running loop (Jupyter, async apps).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ import threading
11
+ from collections.abc import Coroutine
12
+ from typing import Any, TypeVar
13
+
14
+ T = TypeVar("T")
15
+
16
+ _lock = threading.Lock()
17
+ _loop: asyncio.AbstractEventLoop | None = None
18
+
19
+
20
+ def _background_loop() -> asyncio.AbstractEventLoop:
21
+ global _loop
22
+ with _lock:
23
+ if _loop is None or _loop.is_closed():
24
+ loop = asyncio.new_event_loop()
25
+ thread = threading.Thread(target=loop.run_forever, name="neocompute-loop", daemon=True)
26
+ thread.start()
27
+ _loop = loop
28
+ return _loop
29
+
30
+
31
+ def run_sync(coro: Coroutine[Any, Any, T]) -> T:
32
+ loop = _background_loop()
33
+ try:
34
+ running = asyncio.get_running_loop()
35
+ except RuntimeError:
36
+ running = None
37
+ if running is loop:
38
+ coro.close()
39
+ raise RuntimeError("Blocking neocompute call made from its own event loop; use the *_async variant.")
40
+ future = asyncio.run_coroutine_threadsafe(coro, loop)
41
+ try:
42
+ return future.result()
43
+ except KeyboardInterrupt:
44
+ future.cancel()
45
+ raise
neocompute/admin.py ADDED
@@ -0,0 +1,335 @@
1
+ """Operations behind the command line and the dashboard.
2
+
3
+ Everything here returns plain, JSON-ready dicts and lists, and works from a
4
+ fresh process: jobs come from the SQLite store and providers are rebuilt
5
+ from the configuration.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import logging
12
+ from datetime import datetime, timedelta, timezone
13
+ from typing import Any
14
+
15
+ from neocompute import __version__
16
+ from neocompute.config import Config, config_path, get_config
17
+ from neocompute.core.job import JobState
18
+ from neocompute.core.state import JobRecord, StateStore, get_store
19
+ from neocompute.errors import JobNotFoundError, UnsupportedCapabilityError
20
+ from neocompute.providers import AUTO, available_providers, get_provider, provider_availability
21
+
22
+ log = logging.getLogger("neocompute.admin")
23
+
24
+
25
+ def _store(config: Config | None = None) -> StateStore:
26
+ return get_store((config or get_config()).state_dir)
27
+
28
+
29
+ def _iso(value: datetime | None) -> str | None:
30
+ return value.astimezone(timezone.utc).isoformat() if value else None
31
+
32
+
33
+ def job_dict(record: JobRecord) -> dict[str, Any]:
34
+ offer = record.offer
35
+ gpu = offer.gpu if offer else None
36
+ end = record.finished_at or (None if not record.state.is_terminal else record.updated_at)
37
+ duration = record.runtime_seconds
38
+ if duration is None:
39
+ duration = ((end or datetime.now(timezone.utc)) - record.created_at).total_seconds()
40
+ return {
41
+ "job_id": record.job_id,
42
+ "call_id": record.call_id or record.job_id,
43
+ "attempt": record.attempt,
44
+ "function": record.function,
45
+ "provider": record.provider,
46
+ "offer": offer.name if offer else None,
47
+ "gpu": f"{gpu.count}x {gpu.type}" if gpu else None,
48
+ "price_per_hour": offer.price_per_hour if offer else None,
49
+ "metered": bool(offer and (offer.cpu_price_per_hour or offer.memory_price_per_gb_hour)),
50
+ "state": record.state.value,
51
+ "failure": record.failure.value if record.failure else None,
52
+ "exit_code": record.exit_code,
53
+ "message": record.message,
54
+ "quota": record.quota_name,
55
+ "consumed": record.consumed,
56
+ "reserved": record.reserved if not record.state.is_terminal else 0.0,
57
+ "timeout": record.timeout,
58
+ "duration_seconds": duration,
59
+ "created_at": _iso(record.created_at),
60
+ "updated_at": _iso(record.updated_at),
61
+ "finished_at": _iso(record.finished_at),
62
+ }
63
+
64
+
65
+ def find_job(identifier: str, config: Config | None = None) -> JobRecord:
66
+ """A job by job id, or the latest attempt of a call by call id."""
67
+ store = _store(config)
68
+ if identifier.startswith("call-"):
69
+ attempts = store.call_jobs(identifier)
70
+ if not attempts:
71
+ raise JobNotFoundError(identifier)
72
+ return attempts[-1]
73
+ return store.get_job(identifier)
74
+
75
+
76
+ # Jobs
77
+
78
+
79
+ async def refresh_job(record: JobRecord, config: Config | None = None) -> JobRecord:
80
+ """Ask the provider for the job's state and record it. Errors leave the record as it was."""
81
+ config = config or get_config()
82
+ if record.state.is_terminal or record.handle is None:
83
+ return record
84
+ try:
85
+ status = await get_provider(record.provider, config).status(record.handle)
86
+ except Exception as exc:
87
+ log.debug("Could not refresh %s: %s", record.job_id, exc)
88
+ return record
89
+ if status.state != record.state or status.state.is_terminal:
90
+ _store(config).update_status(record.job_id, status)
91
+ return _store(config).get_job(record.job_id)
92
+ return record
93
+
94
+
95
+ async def refresh_unfinished(config: Config | None = None, limit: int = 50) -> int:
96
+ """Refresh unfinished jobs (at most ``limit``, oldest first); returns how many changed."""
97
+ config = config or get_config()
98
+ records = _store(config).all_unfinished()[:limit]
99
+ updated = await asyncio.gather(*(refresh_job(r, config) for r in records))
100
+ return sum(1 for old, new in zip(records, updated) if old.state != new.state)
101
+
102
+
103
+ def list_jobs(
104
+ *,
105
+ state: str | None = None,
106
+ provider: str | None = None,
107
+ function: str | None = None,
108
+ limit: int = 100,
109
+ config: Config | None = None,
110
+ ) -> list[dict[str, Any]]:
111
+ records = _store(config).list_jobs(
112
+ state=JobState(state) if state else None, provider=provider, function=function, limit=limit
113
+ )
114
+ return [job_dict(r) for r in records]
115
+
116
+
117
+ async def job_detail(identifier: str, config: Config | None = None) -> dict[str, Any]:
118
+ record = await refresh_job(find_job(identifier, config), config)
119
+ detail = job_dict(record)
120
+ detail["attempts"] = [job_dict(r) for r in _store(config).call_jobs(record.call_id or record.job_id)]
121
+ detail["handle"] = record.handle.model_dump(mode="json") if record.handle else None
122
+ detail["error"] = await _remote_error(record, config) if record.state is JobState.FAILED else None
123
+ return detail
124
+
125
+
126
+ async def _remote_error(record: JobRecord, config: Config | None) -> dict[str, Any] | None:
127
+ """The failure the worker recorded in ``result.pkl``: type, message and traceback, if any.
128
+
129
+ Only the outer result dict is unpickled; it holds strings, and the
130
+ exception object itself stays as bytes.
131
+ """
132
+ from neocompute.runtime import serialization
133
+ from neocompute.runtime.worker import RESULT_FILE
134
+
135
+ if record.handle is None:
136
+ return None
137
+ try:
138
+ outputs = await get_provider(record.provider, config or get_config()).fetch_outputs(record.handle, [RESULT_FILE])
139
+ result = serialization.loads(outputs[RESULT_FILE]) if RESULT_FILE in outputs else None
140
+ except Exception as exc:
141
+ log.debug("Could not read the result of %s: %s", record.job_id, exc)
142
+ return None
143
+ if not isinstance(result, dict) or result.get("ok", True):
144
+ return None
145
+ return {k: result.get(k) for k in ("stage", "exc_type", "message", "traceback")}
146
+
147
+
148
+ async def job_logs(identifier: str, config: Config | None = None) -> str:
149
+ record = find_job(identifier, config)
150
+ if record.handle is None:
151
+ return ""
152
+ return await get_provider(record.provider, config or get_config()).logs(record.handle)
153
+
154
+
155
+ async def cancel_job(identifier: str, config: Config | None = None) -> dict[str, Any]:
156
+ config = config or get_config()
157
+ record = find_job(identifier, config)
158
+ if record.handle is None or record.state.is_terminal:
159
+ return job_dict(record)
160
+ provider = get_provider(record.provider, config)
161
+ await provider.cancel(record.handle)
162
+ _store(config).update_status(record.job_id, await provider.status(record.handle))
163
+ return job_dict(_store(config).get_job(record.job_id))
164
+
165
+
166
+ async def cleanup(
167
+ *,
168
+ older_than: timedelta = timedelta(days=7),
169
+ identifier: str | None = None,
170
+ forget: bool = False,
171
+ config: Config | None = None,
172
+ ) -> list[str]:
173
+ """Release provider resources of finished jobs (job files, remote bundles, instances).
174
+
175
+ With ``identifier``, only that job, running or not (cancelled first if possible).
176
+ With ``forget``, the jobs are also removed from the local history.
177
+ """
178
+ config = config or get_config()
179
+ store = _store(config)
180
+ if identifier:
181
+ records = [find_job(identifier, config)]
182
+ else:
183
+ cutoff = datetime.now(timezone.utc) - older_than
184
+ records = [r for r in store.list_jobs(limit=100_000) if r.state.is_terminal and r.updated_at < cutoff]
185
+ cleaned: list[str] = []
186
+ for record in records:
187
+ if record.handle is not None:
188
+ try:
189
+ await get_provider(record.provider, config).cleanup(record.handle)
190
+ except UnsupportedCapabilityError as exc:
191
+ log.warning("%s: %s", record.job_id, exc)
192
+ except Exception as exc:
193
+ log.warning("Could not clean up %s: %s", record.job_id, exc)
194
+ continue
195
+ if forget:
196
+ store.delete_job(record.job_id)
197
+ cleaned.append(record.job_id)
198
+ return cleaned
199
+
200
+
201
+ # Providers, quotas, volumes
202
+
203
+
204
+ def _caps(caps: Any) -> dict[str, Any]:
205
+ return caps.model_dump(mode="json")
206
+
207
+
208
+ async def providers_overview(config: Config | None = None, with_offers: bool = True) -> list[dict[str, Any]]:
209
+ config = config or get_config()
210
+ auto = list(config.auto_providers) if config.auto_providers is not None else available_providers()
211
+
212
+ async def one(name: str) -> dict[str, Any]:
213
+ entry: dict[str, Any] = {
214
+ "name": name,
215
+ "in_auto": name in auto,
216
+ "default": name == config.provider,
217
+ "available": False,
218
+ "reason": provider_availability(name, config),
219
+ "capabilities": None,
220
+ "offers": [],
221
+ }
222
+ if entry["reason"] is not None:
223
+ return entry
224
+ try:
225
+ provider = get_provider(name, config)
226
+ entry["capabilities"] = _caps(provider.capabilities())
227
+ if with_offers and (entry["in_auto"] or entry["default"]): # only providers you use are queried
228
+ entry["offers"] = [o.model_dump(mode="json") for o in await provider.offers()]
229
+ entry["available"] = True
230
+ except Exception as exc:
231
+ entry["reason"] = f"{type(exc).__name__}: {exc}"
232
+ return entry
233
+
234
+ return list(await asyncio.gather(*(one(n) for n in available_providers())))
235
+
236
+
237
+ async def quotas_overview(config: Config | None = None) -> list[dict[str, Any]]:
238
+ from neocompute.core.scheduler import Scheduler
239
+
240
+ statuses = await Scheduler(config or get_config()).quotas(AUTO)
241
+ return [{**s.model_dump(mode="json"), "remaining": s.remaining} for s in statuses]
242
+
243
+
244
+ async def plan_overview(
245
+ *,
246
+ gpu: Any = None,
247
+ cpu: float | None = None,
248
+ memory: float | None = None,
249
+ timeout: int = 3600,
250
+ provider: str | None = None,
251
+ config: Config | None = None,
252
+ ) -> dict[str, Any]:
253
+ from neocompute.core.resources import GPU, ResourceSpec
254
+ from neocompute.core.scheduler import TIER_NAMES, Scheduler
255
+
256
+ spec = ResourceSpec(gpu=GPU.coerce(gpu), cpu=cpu, memory_gb=memory, timeout=timeout)
257
+ plan = await Scheduler(config or get_config()).plan(spec, provider or AUTO)
258
+ return {
259
+ "candidates": [
260
+ {
261
+ "provider": c.provider.name,
262
+ "offer": c.offer.name,
263
+ "tier": TIER_NAMES[c.tier],
264
+ "hourly_cost": c.hourly_cost,
265
+ "quota": c.quota.name if c.quota else None,
266
+ }
267
+ for c in plan.candidates
268
+ ],
269
+ "rejected": plan.rejected,
270
+ "busy": plan.busy,
271
+ }
272
+
273
+
274
+ def volumes_overview() -> list[dict[str, Any]]:
275
+ from neocompute.api.volume import list_volumes
276
+
277
+ return [v.model_dump(mode="json") for v in list_volumes()]
278
+
279
+
280
+ # Summary
281
+
282
+
283
+ def summary(config: Config | None = None) -> dict[str, Any]:
284
+ """Counts and spend over the last 30 days, and jobs per day for the last 14."""
285
+ config = config or get_config()
286
+ records = _store(config).list_jobs(limit=100_000)
287
+ now = datetime.now(timezone.utc)
288
+ recent = [r for r in records if r.created_at >= now - timedelta(days=30)]
289
+ by_state: dict[str, int] = {}
290
+ for r in recent:
291
+ by_state[r.state.value] = by_state.get(r.state.value, 0) + 1
292
+ by_provider: dict[str, dict[str, float]] = {}
293
+ for r in recent:
294
+ entry = by_provider.setdefault(r.provider, {"jobs": 0, "hours": 0.0, "failed": 0})
295
+ entry["jobs"] += 1
296
+ entry["hours"] += (r.runtime_seconds or 0) / 3600
297
+ entry["failed"] += r.state is JobState.FAILED
298
+ spend = 0.0
299
+ for r in recent:
300
+ if r.offer and r.offer.price_per_hour and r.runtime_seconds:
301
+ spend += r.offer.price_per_hour * r.runtime_seconds / 3600
302
+ days = [(now - timedelta(days=i)).date() for i in range(13, -1, -1)]
303
+ daily = {d.isoformat(): {"succeeded": 0, "failed": 0, "other": 0} for d in days}
304
+ for r in recent:
305
+ key = r.created_at.astimezone(timezone.utc).date().isoformat()
306
+ if key in daily:
307
+ bucket = r.state.value if r.state.value in ("succeeded", "failed") else "other"
308
+ daily[key][bucket] += 1
309
+ return {
310
+ "version": __version__,
311
+ "state_dir": str(config.state_dir),
312
+ "config_file": str(config_path()) if config_path().is_file() else None,
313
+ "default_provider": config.provider,
314
+ "free_only": config.free_only,
315
+ "storage": config.storage,
316
+ "total_jobs": len(records),
317
+ "running": by_state.get("running", 0) + by_state.get("pending", 0) + by_state.get("submitting", 0),
318
+ "by_state": by_state,
319
+ "by_provider": by_provider,
320
+ "list_price_usd_30d": spend,
321
+ "daily": [{"date": d, **v} for d, v in daily.items()],
322
+ }
323
+
324
+
325
+ def config_dict(config: Config | None = None) -> dict[str, Any]:
326
+ """The effective configuration. Provider options whose names suggest credentials are masked."""
327
+ data = (config or get_config()).model_dump(mode="json")
328
+ for options in data.get("providers", {}).values():
329
+ for key in options:
330
+ if any(word in key.lower() for word in ("token", "secret", "key", "password")):
331
+ options[key] = "***"
332
+ for key in list(data.get("storage_options", {})):
333
+ if any(word in key.lower() for word in ("token", "secret", "key", "password")):
334
+ data["storage_options"][key] = "***"
335
+ return data
File without changes
neocompute/api/app.py ADDED
@@ -0,0 +1,80 @@
1
+ """Apps group functions and supply defaults for them."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable, Mapping
6
+ from typing import TYPE_CHECKING, Any, TypeVar, overload
7
+
8
+ from neocompute.api.function import Function
9
+ from neocompute.core.resources import DEFAULT_TIMEOUT, GPU, ResourceSpec
10
+
11
+ if TYPE_CHECKING:
12
+ from neocompute.api.image import Image
13
+ from neocompute.api.volume import Volume
14
+
15
+ F = TypeVar("F", bound=Callable[..., Any])
16
+
17
+
18
+ class App:
19
+ def __init__(self, name: str, *, image: Image | None = None, provider: str | None = None) -> None:
20
+ self.name = name
21
+ self.image = image
22
+ self.provider = provider
23
+ self.functions: dict[str, Function[..., Any]] = {}
24
+
25
+ def __repr__(self) -> str:
26
+ return f"App({self.name!r})"
27
+
28
+ @overload
29
+ def function(self, fn: F, /) -> Function[..., Any]: ...
30
+
31
+ @overload
32
+ def function(
33
+ self,
34
+ *,
35
+ image: Image | None = None,
36
+ gpu: GPU | int | str | bool | None = None,
37
+ cpu: float | None = None,
38
+ memory: float | None = None,
39
+ timeout: int = DEFAULT_TIMEOUT,
40
+ volumes: Mapping[str, Volume] | None = None,
41
+ env: Mapping[str, str] | None = None,
42
+ provider: str | None = None,
43
+ max_attempts: int | None = None,
44
+ ) -> Callable[[F], Function[..., Any]]: ...
45
+
46
+ def function(
47
+ self,
48
+ fn: Callable[..., Any] | None = None,
49
+ /,
50
+ *,
51
+ image: Image | None = None,
52
+ gpu: GPU | int | str | bool | None = None,
53
+ cpu: float | None = None,
54
+ memory: float | None = None,
55
+ timeout: int = DEFAULT_TIMEOUT,
56
+ volumes: Mapping[str, Volume] | None = None,
57
+ env: Mapping[str, str] | None = None,
58
+ provider: str | None = None,
59
+ max_attempts: int | None = None,
60
+ ) -> Any:
61
+ """Register a function. ``memory`` is in GB; ``timeout`` is in seconds.
62
+
63
+ ``max_attempts`` overrides ``Config.max_attempts`` (failover after infrastructure failures)."""
64
+ resources = ResourceSpec(gpu=GPU.coerce(gpu), cpu=cpu, memory_gb=memory, timeout=timeout)
65
+
66
+ def decorate(f: Callable[..., Any]) -> Function[..., Any]:
67
+ function = Function(
68
+ f,
69
+ app=self,
70
+ image=image or self.image,
71
+ resources=resources,
72
+ volumes=volumes,
73
+ env=env,
74
+ provider=provider,
75
+ max_attempts=max_attempts,
76
+ )
77
+ self.functions[f.__qualname__] = function
78
+ return function
79
+
80
+ return decorate(fn) if fn is not None else decorate