ivcap-lambda 0.8.6__tar.gz → 0.8.8__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,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ivcap-lambda
3
- Version: 0.8.6
3
+ Version: 0.8.8
4
4
  Summary: Helper functions for building lambda-style services on the IVCAP platform
5
5
  License-File: AUTHORS.md
6
6
  License-File: LICENSE
@@ -65,11 +65,12 @@ class ToolOptions(BaseModel):
65
65
  service_id: str | None = Field(
66
66
  None, description="overriding the default service id"
67
67
  )
68
- is_ready: Callable[[], bool | dict[str, Any]] | None = Field(
68
+ is_ready: Callable[[], bool | dict[str, Any] | BaseModel] | None = Field(
69
69
  None,
70
70
  description=(
71
- "Readiness check. Return a dict of info to report on /_healtz (or True), "
72
- "return False, or raise NotReadyYet(retry_after) while not ready"
71
+ "Readiness check. Return a dict or pydantic model of info to report on "
72
+ "/_healtz (or True), return False, or raise NotReadyYet(retry_after) "
73
+ "while not ready"
73
74
  ),
74
75
  )
75
76
 
@@ -2,18 +2,20 @@ from __future__ import annotations
2
2
 
3
3
  import asyncio
4
4
  import math
5
- import os
6
5
  from collections.abc import Awaitable, Callable
7
6
  from typing import Any
8
7
 
9
8
  from fastapi import FastAPI, HTTPException
9
+ from pydantic import BaseModel
10
10
 
11
11
  from .utils import find_first
12
+ from .version import resolve_service_version
12
13
 
13
- # A readiness check returns True (ready), False (legacy not-ready), or a dict of
14
- # extra info to add to the health reply (ready). Raising NotReadyYet also means
15
- # not-ready. Sync or async.
16
- ReadyFn = Callable[[], bool | dict[str, Any] | Awaitable[bool | dict[str, Any]]]
14
+ # A readiness check returns True (ready), False (legacy not-ready), a dict or a
15
+ # pydantic model of extra info to add to the health reply (ready). Raising
16
+ # NotReadyYet also means not-ready. Sync or async.
17
+ ReadyResult = bool | dict[str, Any] | BaseModel
18
+ ReadyFn = Callable[[], ReadyResult | Awaitable[ReadyResult]]
17
19
 
18
20
  # Global registry of readiness handlers
19
21
  _ready_handlers: list[ReadyFn] = []
@@ -41,14 +43,16 @@ def add_ready_handler(ready_fn: ReadyFn | None) -> None:
41
43
  _ready_handlers.append(ready_fn)
42
44
 
43
45
 
44
- async def healtz_handler() -> dict:
46
+ async def healtz_handler(name: str | None = None, version: str | None = None) -> dict:
45
47
  """
46
48
  Check all registered readiness handlers.
47
49
 
48
- - Dict results are merged into the reply. `version` always wins over a
49
- key of the same name.
50
+ - Dict results are merged into the reply. `name` and `version` always win
51
+ over a key of the same name.
52
+ - `version` is the VERSION env var if set, otherwise the declared service
53
+ version, otherwise "???". `name` is only reported when given.
50
54
  - If every handler is ready (True, a dict, or no handlers at all), return
51
- {"version": ..., **extra_info}.
55
+ {**extra_info, "name": ..., "version": ...}.
52
56
  - If any handler returns False or raises NotReadyYet, raise a 503. When
53
57
  NotReadyYet carries retry_after, the largest value is sent as the
54
58
  `Retry-After` header in whole seconds (rounded up).
@@ -68,6 +72,9 @@ async def healtz_handler() -> dict:
68
72
  retry_after = max(retry_after or 0.0, ex.retry_after)
69
73
  continue
70
74
 
75
+ if isinstance(result, BaseModel):
76
+ result = result.model_dump(by_alias=True)
77
+
71
78
  if isinstance(result, dict):
72
79
  info.update(result)
73
80
  elif not result:
@@ -81,13 +88,29 @@ async def healtz_handler() -> dict:
81
88
  status_code=503, detail="Service Unavailable", headers=headers
82
89
  )
83
90
 
84
- return {**info, "version": os.environ.get("VERSION", "???")}
91
+ identity: dict[str, Any] = {}
92
+ if name is not None:
93
+ identity["name"] = name
94
+ identity["version"] = resolve_service_version(version)
95
+ return {**info, **identity}
85
96
 
86
97
 
87
- def add_health_route(app: FastAPI) -> None:
98
+ def add_health_route(
99
+ app: FastAPI, *, name: str | None = None, version: str | None = None
100
+ ) -> None:
88
101
  """
89
102
  Register `GET /_healtz` backed by `healtz_handler`, unless the app already
90
103
  serves that path.
104
+
105
+ Args:
106
+ app: the FastAPI app to add the route to.
107
+ name: service name to report in the reply.
108
+ version: declared service version. The VERSION env var takes precedence
109
+ when set.
91
110
  """
92
111
  if find_first(app.routes, lambda r: r.path == "/_healtz") is None:
93
- app.add_api_route("/_healtz", healtz_handler, methods=["GET"], tags=["System"])
112
+
113
+ async def _healtz() -> dict:
114
+ return await healtz_handler(name=name, version=version)
115
+
116
+ app.add_api_route("/_healtz", _healtz, methods=["GET"], tags=["System"])
@@ -34,7 +34,7 @@ from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
34
34
  from .builder import tools
35
35
  from .executor import Executor, get_job_context
36
36
  from .health_handler import add_health_route
37
- from .version import get_version
37
+ from .version import get_version, resolve_service_version
38
38
 
39
39
  # shutdown pod cracefully
40
40
  signal(SIGTERM, lambda _1, _2: sys.exit(0))
@@ -78,7 +78,8 @@ def start_lambda_server(
78
78
 
79
79
  app = get_fast_app()
80
80
  app.title = service.name
81
- app.version = service.version or os.environ.get("VERSION", "???")
81
+ service_version = resolve_service_version(service.version)
82
+ app.version = service_version
82
83
  app.contact = dict(service.contact) if service.contact else None
83
84
  app.license_info = dict(service.license) if service.license else None
84
85
 
@@ -202,7 +203,7 @@ def start_lambda_server(
202
203
  init_openobserve_from_env(
203
204
  logger=logger,
204
205
  service_name=service.name,
205
- service_version=service.version,
206
+ service_version=service_version,
206
207
  )
207
208
  except Exception as exc:
208
209
  logger.warning("OpenTelemetry initialization failed: %s", exc)
@@ -236,7 +237,7 @@ def start_lambda_server(
236
237
  run_mcp_stdio(service.name, app.version)
237
238
  return
238
239
 
239
- add_health_route(app)
240
+ add_health_route(app, name=service.name, version=service.version)
240
241
 
241
242
  if args.with_mcp:
242
243
  from .mcp import register_mcp
@@ -253,7 +254,9 @@ def start_lambda_server(
253
254
  from .version import __version__
254
255
 
255
256
  resp = await call_next(request)
256
- resp.headers["Ivcap-AI-Tool-Version"] = __version__
257
+ resp.headers["Ivcap-Lambda-Version"] = __version__
258
+ resp.headers["Ivcap-Service-Name"] = service.name
259
+ resp.headers["Ivcap-Service-Version"] = service_version
257
260
  return resp
258
261
 
259
262
  app.middleware("http")(_add_version)
@@ -0,0 +1,27 @@
1
+ #
2
+ # Copyright (c) 2023 Commonwealth Scientific and Industrial Research Organisation (CSIRO). All rights reserved.
3
+ # Use of this source code is governed by a BSD-style license that can be
4
+ # found in the LICENSE file. See the AUTHORS file for names of contributors.
5
+ #
6
+
7
+ import os
8
+ from importlib.metadata import PackageNotFoundError
9
+ from importlib.metadata import version as _dist_version
10
+
11
+ try:
12
+ __version__ = _dist_version("ivcap-lambda")
13
+ except PackageNotFoundError:
14
+ __version__ = "???"
15
+
16
+
17
+ def resolve_service_version(service_version: str | None) -> str:
18
+ """Return the service version to report.
19
+
20
+ Priority: the `VERSION` environment variable, then the version declared on
21
+ the `Service`, then "???". An empty `VERSION` counts as unset.
22
+ """
23
+ return os.environ.get("VERSION") or service_version or "???"
24
+
25
+
26
+ def get_version():
27
+ return __version__
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "ivcap-lambda"
3
- version = "0.8.6"
3
+ version = "0.8.8"
4
4
  description = "Helper functions for building lambda-style services on the IVCAP platform"
5
5
 
6
6
  authors = ["Max Ott <max.ott@csiro.au>"]
@@ -1,22 +0,0 @@
1
- #
2
- # Copyright (c) 2023 Commonwealth Scientific and Industrial Research Organisation (CSIRO). All rights reserved.
3
- # Use of this source code is governed by a BSD-style license that can be
4
- # found in the LICENSE file. See the AUTHORS file for names of contributors.
5
- #
6
-
7
- __version__ = "???"
8
- try: # Python > 3.8+
9
- from importlib_metadata import version
10
-
11
- __version__ = version("ivcap_lambda")
12
- except ImportError:
13
- try:
14
- import pkg_resources
15
-
16
- __version__ = pkg_resources.get_distribution("ivcap_lambda").version
17
- except Exception:
18
- pass
19
-
20
-
21
- def get_version():
22
- return __version__
File without changes
File without changes
File without changes