zerodock 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.

Potentially problematic release.


This version of zerodock might be problematic. Click here for more details.

zerodock/__init__.py ADDED
@@ -0,0 +1,43 @@
1
+ """ZeroDock - Ultra-lightweight local serverless execution engine."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+ from typing import TYPE_CHECKING, Any
5
+
6
+ if TYPE_CHECKING:
7
+ from zerodock.config.models import GatewayConfig, RouteDefinition, ServerlessConfig
8
+ from zerodock.engine.context import InvocationContext, InvocationResult
9
+ from zerodock.gateway.app import create_app
10
+ from zerodock.gateway.server import run_server
11
+
12
+ try:
13
+ __version__ = version("zerodock")
14
+ except PackageNotFoundError:
15
+ __version__ = "0.1.0"
16
+
17
+ __all__ = [
18
+ "__version__",
19
+ "create_app",
20
+ "run_server",
21
+ "GatewayConfig",
22
+ "RouteDefinition",
23
+ "ServerlessConfig",
24
+ "InvocationContext",
25
+ "InvocationResult",
26
+ ]
27
+
28
+
29
+ def __getattr__(name: str) -> Any:
30
+ """Lazy-load public symbols to preserve sub-millisecond module import times."""
31
+ if name == "create_app":
32
+ from zerodock.gateway.app import create_app
33
+ return create_app
34
+ if name == "run_server":
35
+ from zerodock.gateway.server import run_server
36
+ return run_server
37
+ if name in {"GatewayConfig", "RouteDefinition", "ServerlessConfig"}:
38
+ import zerodock.config.models as models
39
+ return getattr(models, name)
40
+ if name in {"InvocationContext", "InvocationResult"}:
41
+ import zerodock.engine.context as context
42
+ return getattr(context, name)
43
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
zerodock/cli.py ADDED
@@ -0,0 +1,78 @@
1
+ """Command-line interface (CLI) for ZeroDock."""
2
+
3
+ import argparse
4
+ import sys
5
+ from zerodock import __version__
6
+ from zerodock.gateway.server import run_server
7
+
8
+
9
+ def build_parser() -> argparse.ArgumentParser:
10
+ """Creates the top-level argument parser for the zerodock CLI."""
11
+ parser = argparse.ArgumentParser(
12
+ prog="zerodock",
13
+ description="ZeroDock - Ultra-lightweight local serverless execution engine.",
14
+ )
15
+ parser.add_argument(
16
+ "-v", "--version", action="version", version=f"ZeroDock {__version__}"
17
+ )
18
+
19
+ subparsers = parser.add_subparsers(dest="command", help="Available subcommands")
20
+
21
+ # 'dev' command
22
+ dev_parser = subparsers.add_parser("dev", help="Start the local serverless HTTP gateway")
23
+ dev_parser.add_argument(
24
+ "-c",
25
+ "--config",
26
+ default="serverless-local.yaml",
27
+ help="Path to serverless-local.yaml (default: serverless-local.yaml)",
28
+ )
29
+ dev_parser.add_argument(
30
+ "--host",
31
+ default=None,
32
+ help="Host IP to bind (overrides config gateway.host)",
33
+ )
34
+ dev_parser.add_argument(
35
+ "-p",
36
+ "--port",
37
+ type=int,
38
+ default=None,
39
+ help="Port number to bind (overrides config gateway.port)",
40
+ )
41
+ dev_parser.add_argument(
42
+ "--log-level",
43
+ default=None,
44
+ choices=["debug", "info", "warning", "error"],
45
+ help="Logging level verbosity",
46
+ )
47
+
48
+ return parser
49
+
50
+
51
+ def main() -> None:
52
+ """Main entrypoint for zerodock CLI."""
53
+ parser = build_parser()
54
+ args = parser.parse_args()
55
+
56
+ if args.command == "dev" or args.command is None:
57
+ # If no subcommand passed, default to 'dev' if serverless-local.yaml exists
58
+ config_path = getattr(args, "config", "serverless-local.yaml")
59
+ host = getattr(args, "host", None)
60
+ port = getattr(args, "port", None)
61
+ log_level = getattr(args, "log_level", None)
62
+
63
+ try:
64
+ run_server(
65
+ config_path=config_path,
66
+ host=host,
67
+ port=port,
68
+ log_level=log_level,
69
+ )
70
+ except Exception as exc:
71
+ print(f"[ZeroDock Error] {exc}", file=sys.stderr)
72
+ sys.exit(1)
73
+ else:
74
+ parser.print_help()
75
+
76
+
77
+ if __name__ == "__main__":
78
+ main()
@@ -0,0 +1 @@
1
+ """Configuration loader and schema models for ZeroDock."""
@@ -0,0 +1,73 @@
1
+ """Data models for ZeroDock declarative configuration."""
2
+
3
+ from pathlib import Path
4
+ from typing import Dict, List, Literal
5
+ from pydantic import BaseModel, Field, field_validator
6
+
7
+
8
+ class GatewayConfig(BaseModel):
9
+ """Network and runtime configuration for the local gateway."""
10
+
11
+ host: str = Field(default="127.0.0.1", description="Bind IP address")
12
+ port: int = Field(default=8080, ge=1024, le=65535, description="Port number between 1024 and 65535")
13
+ log_level: Literal["debug", "info", "warning", "error"] = Field(
14
+ default="info", description="Logging verbosity"
15
+ )
16
+
17
+
18
+ class RouteDefinition(BaseModel):
19
+ """Configuration definition for a single serverless route."""
20
+
21
+ file: Path = Field(description="Path to Python handler source file")
22
+ handler: str = Field(default="handler", description="Callable entrypoint function name")
23
+ methods: List[str] = Field(
24
+ default_factory=lambda: ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"],
25
+ description="Allowed HTTP methods",
26
+ )
27
+ timeout_seconds: int = Field(
28
+ default=30, ge=1, le=900, description="Execution timeout limit in seconds"
29
+ )
30
+
31
+ @field_validator("methods")
32
+ @classmethod
33
+ def validate_methods(cls, methods: List[str]) -> List[str]:
34
+ valid_methods = {"GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"}
35
+ normalized = [m.upper().strip() for m in methods]
36
+ for m in normalized:
37
+ if m not in valid_methods:
38
+ raise ValueError(f"Invalid HTTP method '{m}'. Allowed: {sorted(valid_methods)}")
39
+ return normalized
40
+
41
+ @field_validator("handler")
42
+ @classmethod
43
+ def validate_handler_name(cls, handler_name: str) -> str:
44
+ name = handler_name.strip()
45
+ if not name.isidentifier():
46
+ raise ValueError(f"Handler '{name}' is not a valid Python identifier.")
47
+ return name
48
+
49
+
50
+ class ServerlessConfig(BaseModel):
51
+ """Top-level configuration schema for serverless-local.yaml."""
52
+
53
+ version: str = Field(default="1.0", description="Configuration schema version")
54
+ gateway: GatewayConfig = Field(
55
+ default_factory=GatewayConfig, description="Gateway network settings"
56
+ )
57
+ routes: Dict[str, RouteDefinition] = Field(
58
+ ..., min_length=1, description="Mapping of route paths to execution definitions"
59
+ )
60
+
61
+ @field_validator("routes")
62
+ @classmethod
63
+ def normalize_route_keys(cls, routes: Dict[str, RouteDefinition]) -> Dict[str, RouteDefinition]:
64
+ normalized = {}
65
+ for path, defn in routes.items():
66
+ # Clean up route path: ensure single leading slash and no trailing slash (unless root "/")
67
+ clean_path = path.strip()
68
+ if not clean_path.startswith("/"):
69
+ clean_path = f"/{clean_path}"
70
+ if len(clean_path) > 1 and clean_path.endswith("/"):
71
+ clean_path = clean_path.rstrip("/")
72
+ normalized[clean_path] = defn
73
+ return normalized
@@ -0,0 +1,74 @@
1
+ """YAML configuration parser and validator for ZeroDock."""
2
+
3
+ from pathlib import Path
4
+ from typing import Union
5
+ import yaml
6
+ from pydantic import ValidationError
7
+
8
+ from zerodock.config.models import ServerlessConfig
9
+
10
+
11
+ class ConfigurationError(Exception):
12
+ """Raised when serverless-local.yaml is missing, malformed, or invalid."""
13
+ pass
14
+
15
+
16
+ def load_config(config_path: Union[str, Path] = "serverless-local.yaml") -> ServerlessConfig:
17
+ """Load and validate serverless-local.yaml from disk.
18
+
19
+ Resolves relative handler file paths against the directory of the config file.
20
+
21
+ Args:
22
+ config_path: Path to the configuration YAML file.
23
+
24
+ Returns:
25
+ Validated ServerlessConfig instance.
26
+
27
+ Raises:
28
+ ConfigurationError: If the file does not exist, cannot be parsed, or fails validation.
29
+ """
30
+ path = Path(config_path).resolve()
31
+
32
+ if not path.exists():
33
+ raise ConfigurationError(f"Configuration file not found at: {path}")
34
+
35
+ try:
36
+ raw_text = path.read_text(encoding="utf-8")
37
+ except Exception as exc:
38
+ raise ConfigurationError(f"Failed to read configuration file: {exc}") from exc
39
+
40
+ try:
41
+ parsed_yaml = yaml.safe_load(raw_text)
42
+ except yaml.YAMLError as exc:
43
+ raise ConfigurationError(f"Malformed YAML in {path.name}: {exc}") from exc
44
+
45
+ if not isinstance(parsed_yaml, dict):
46
+ raise ConfigurationError(
47
+ f"Invalid configuration root in {path.name}: expected mapping, got {type(parsed_yaml).__name__}"
48
+ )
49
+
50
+ try:
51
+ config = ServerlessConfig.model_validate(parsed_yaml)
52
+ except ValidationError as exc:
53
+ error_messages = []
54
+ for err in exc.errors():
55
+ loc = " -> ".join(str(item) for item in err["loc"])
56
+ error_messages.append(f" - [{loc}]: {err['msg']}")
57
+ formatted_errors = "\n".join(error_messages)
58
+ raise ConfigurationError(
59
+ f"Configuration validation failed in {path.name}:\n{formatted_errors}"
60
+ ) from exc
61
+
62
+ # Resolve relative file paths to absolute paths based on config location and verify existence
63
+ config_dir = path.parent
64
+ for route_path, route_defn in config.routes.items():
65
+ if not route_defn.file.is_absolute():
66
+ resolved_file = (config_dir / route_defn.file).resolve()
67
+ route_defn.file = resolved_file
68
+
69
+ if not route_defn.file.exists():
70
+ raise ConfigurationError(
71
+ f"Route '{route_path}' target file does not exist: {route_defn.file}"
72
+ )
73
+
74
+ return config
@@ -0,0 +1 @@
1
+ """Execution engine and dynamic module loader for ZeroDock."""
@@ -0,0 +1,33 @@
1
+ """Invocation runtime context and result structures for ZeroDock."""
2
+
3
+ import time
4
+ import uuid
5
+ from dataclasses import dataclass, field
6
+ from typing import Any, Dict
7
+
8
+
9
+ @dataclass
10
+ class InvocationContext:
11
+ """Runtime context object passed as second parameter to serverless handlers."""
12
+
13
+ function_name: str
14
+ request_id: str = field(default_factory=lambda: f"zd-req-{uuid.uuid4().hex[:12]}")
15
+ memory_limit_in_mb: int = 128
16
+ started_at: float = field(default_factory=time.monotonic)
17
+ timeout_seconds: int = 30
18
+
19
+ def get_remaining_time_in_millis(self) -> int:
20
+ """Returns the number of milliseconds remaining before execution timeout."""
21
+ elapsed = time.monotonic() - self.started_at
22
+ remaining = (self.timeout_seconds - elapsed) * 1000.0
23
+ return max(0, int(remaining))
24
+
25
+
26
+ @dataclass
27
+ class InvocationResult:
28
+ """Normalized output produced by the serverless handler invocation."""
29
+
30
+ status_code: int = 200
31
+ headers: Dict[str, str] = field(default_factory=lambda: {"Content-Type": "application/json"})
32
+ body: Any = ""
33
+ is_base64_encoded: bool = False
@@ -0,0 +1,67 @@
1
+ """HTTP request to cloud event transformer for ZeroDock."""
2
+
3
+ import base64
4
+ import time
5
+ import uuid
6
+ from starlette.requests import Request
7
+ from typing import Any, Dict
8
+
9
+
10
+ async def build_invocation_event(request: Request, route_key: str = "") -> Dict[str, Any]:
11
+ """Converts a Starlette/FastAPI Request into an AWS Lambda API Gateway v2 event.
12
+
13
+ Args:
14
+ request: Incoming HTTP request.
15
+ route_key: Configured route key string (e.g. 'GET /api/users').
16
+
17
+ Returns:
18
+ Structured event dictionary.
19
+ """
20
+ raw_path = request.url.path
21
+ raw_query = request.url.query
22
+
23
+ # Query string parameters mapping
24
+ query_params = dict(request.query_params)
25
+
26
+ # Normalize headers to lowercase keys
27
+ headers = {k.lower(): v for k, v in request.headers.items()}
28
+
29
+ # Read and decode body
30
+ body_bytes = await request.body()
31
+ body_str = None
32
+ is_base64 = False
33
+
34
+ if body_bytes:
35
+ try:
36
+ body_str = body_bytes.decode("utf-8")
37
+ except UnicodeDecodeError:
38
+ body_str = base64.b64encode(body_bytes).decode("ascii")
39
+ is_base64 = True
40
+
41
+ client_ip = request.client.host if request.client else "127.0.0.1"
42
+ req_id = f"zd-req-{uuid.uuid4().hex[:12]}"
43
+
44
+ if not route_key:
45
+ route_key = f"{request.method} {raw_path}"
46
+
47
+ return {
48
+ "version": "2.0",
49
+ "routeKey": route_key,
50
+ "rawPath": raw_path,
51
+ "rawQueryString": raw_query,
52
+ "headers": headers,
53
+ "queryStringParameters": query_params if query_params else None,
54
+ "requestContext": {
55
+ "http": {
56
+ "method": request.method,
57
+ "path": raw_path,
58
+ "protocol": "HTTP/1.1",
59
+ "sourceIp": client_ip,
60
+ "userAgent": headers.get("user-agent", "zerodock-client"),
61
+ },
62
+ "requestId": req_id,
63
+ "timeEpoch": int(time.time() * 1000),
64
+ },
65
+ "body": body_str,
66
+ "isBase64Encoded": is_base64,
67
+ }
@@ -0,0 +1,91 @@
1
+ """Dynamic module loader and function invoker for serverless handlers."""
2
+
3
+ import asyncio
4
+ import hashlib
5
+ import importlib.util
6
+ import inspect
7
+ import sys
8
+ from pathlib import Path
9
+ from typing import Any, Callable, cast
10
+
11
+
12
+ class HandlerLoadError(Exception):
13
+ """Raised when a handler file cannot be imported or callable not found."""
14
+ pass
15
+
16
+
17
+ def load_handler(file_path: Path, handler_name: str) -> Callable[..., Any]:
18
+ """Dynamically loads a Python file and returns the target handler function.
19
+
20
+ Uses an isolated module namespace in sys.modules to prevent collisions across handlers.
21
+
22
+ Args:
23
+ file_path: Absolute or relative Path to target Python file.
24
+ handler_name: Name of the entrypoint callable function.
25
+
26
+ Returns:
27
+ The callable handler object.
28
+
29
+ Raises:
30
+ HandlerLoadError: If file does not exist, syntax fails, or handler missing.
31
+ """
32
+ resolved_path = Path(file_path).resolve()
33
+
34
+ if not resolved_path.exists():
35
+ raise HandlerLoadError(f"File not found: {resolved_path}")
36
+
37
+ # Generate a unique module name based on the file path to avoid sys.modules collisions
38
+ path_hash = hashlib.sha256(str(resolved_path).encode("utf-8")).hexdigest()[:12]
39
+ module_name = f"zerodock.handlers.mod_{path_hash}"
40
+
41
+ try:
42
+ spec = importlib.util.spec_from_file_location(module_name, resolved_path)
43
+ if spec is None or spec.loader is None:
44
+ raise HandlerLoadError(f"Could not load importlib spec for {resolved_path}")
45
+
46
+ module = importlib.util.module_from_spec(spec)
47
+ sys.modules[module_name] = module
48
+ spec.loader.exec_module(module)
49
+ except Exception as exc:
50
+ raise HandlerLoadError(f"Failed to load module from {resolved_path}: {exc}") from exc
51
+
52
+ if not hasattr(module, handler_name):
53
+ raise HandlerLoadError(
54
+ f"Handler function '{handler_name}' not found in module {resolved_path}"
55
+ )
56
+
57
+ handler_fn = getattr(module, handler_name)
58
+ if not callable(handler_fn):
59
+ raise HandlerLoadError(
60
+ f"Target attribute '{handler_name}' in {resolved_path} is not callable."
61
+ )
62
+
63
+ return cast(Callable[..., Any], handler_fn)
64
+
65
+
66
+ def invoke_handler(handler_fn: Callable[..., Any], event: dict, context: Any = None) -> Any:
67
+ """Executes a handler function, handling sync/async and parameter arity.
68
+
69
+ Args:
70
+ handler_fn: Target callable function.
71
+ event: Invocation event dictionary.
72
+ context: Optional InvocationContext runtime object.
73
+
74
+ Returns:
75
+ The handler return value, or a coroutine if async.
76
+ """
77
+ # Inspect callable signature to see if it accepts 1 or 2+ parameters
78
+ sig = inspect.signature(handler_fn)
79
+ params = list(sig.parameters.values())
80
+
81
+ # Check if only accepting event (1 positional arg or kwargs)
82
+ if len(params) == 1:
83
+ result = handler_fn(event)
84
+ else:
85
+ result = handler_fn(event, context)
86
+
87
+ # If the handler is a coroutine or returned a coroutine, return the coroutine
88
+ if inspect.iscoroutine(result):
89
+ return result
90
+
91
+ return result
@@ -0,0 +1 @@
1
+ """HTTP Gateway and route dispatcher for ZeroDock."""
@@ -0,0 +1,115 @@
1
+ """FastAPI application factory and route dispatcher for ZeroDock."""
2
+
3
+ import asyncio
4
+ import inspect
5
+ from pathlib import Path
6
+ from typing import Optional
7
+ from fastapi import FastAPI, Request
8
+ from starlette.exceptions import HTTPException as StarletteHTTPException
9
+ from starlette.responses import JSONResponse, Response
10
+
11
+ from zerodock.config.models import ServerlessConfig
12
+ from zerodock.config.parser import load_config
13
+ from zerodock.engine.context import InvocationContext
14
+ from zerodock.engine.event import build_invocation_event
15
+ from zerodock.engine.loader import load_handler, invoke_handler
16
+ from zerodock.gateway.errors import format_error_response, format_timeout_response
17
+ from zerodock.gateway.response import normalize_response
18
+
19
+
20
+ def create_app(config: Optional[ServerlessConfig] = None) -> FastAPI:
21
+ """Builds and configures the FastAPI gateway application.
22
+
23
+ Args:
24
+ config: Optional pre-loaded ServerlessConfig. If None, loads from serverless-local.yaml.
25
+
26
+ Returns:
27
+ Configured FastAPI application instance.
28
+ """
29
+ if config is None:
30
+ config_file = Path("serverless-local.yaml")
31
+ if config_file.exists():
32
+ config = load_config(config_file)
33
+ else:
34
+ # Fallback for bare imports
35
+ from zerodock.config.models import RouteDefinition
36
+ config = ServerlessConfig(
37
+ routes={"/": RouteDefinition(file=Path("./app.py"))}
38
+ )
39
+
40
+ app = FastAPI(title="ZeroDock Gateway", version="0.1.0")
41
+ app.state.config = config
42
+
43
+ # Register each configured route
44
+ for route_path, route_defn in config.routes.items():
45
+ # Clean path for route registration
46
+ fastapi_path = route_path if route_path.startswith("/") else f"/{route_path}"
47
+
48
+ def make_endpoint(r_path: str, r_defn):
49
+ async def endpoint_handler(request: Request) -> Response:
50
+ req_id = "zd-req-init"
51
+ try:
52
+ # 1. Build the context object
53
+ context = InvocationContext(
54
+ function_name=r_defn.handler,
55
+ timeout_seconds=r_defn.timeout_seconds,
56
+ )
57
+ req_id = context.request_id
58
+
59
+ # 2. Load the target handler function
60
+ handler_fn = load_handler(r_defn.file, r_defn.handler)
61
+
62
+ # 3. Build the AWS-compatible event dictionary
63
+ route_key = f"{request.method} {r_path}"
64
+ event = await build_invocation_event(request, route_key=route_key)
65
+
66
+ # 4. Invoke the handler (with timeout enforcement)
67
+ invocation_task = invoke_handler(handler_fn, event, context)
68
+ if inspect.iscoroutine(invocation_task):
69
+ raw_result = await asyncio.wait_for(
70
+ invocation_task, timeout=r_defn.timeout_seconds
71
+ )
72
+ else:
73
+ raw_result = invocation_task
74
+
75
+ # 5. Normalize and return the HTTP response
76
+ return normalize_response(raw_result)
77
+ except asyncio.TimeoutError:
78
+ return format_timeout_response(
79
+ timeout_seconds=r_defn.timeout_seconds,
80
+ request_id=req_id,
81
+ )
82
+ except Exception as exc:
83
+ return format_error_response(
84
+ exc=exc,
85
+ request_id=req_id,
86
+ )
87
+
88
+ return endpoint_handler
89
+
90
+ app.add_api_route(
91
+ fastapi_path,
92
+ endpoint=make_endpoint(fastapi_path, route_defn),
93
+ methods=route_defn.methods,
94
+ name=f"route_{route_path}",
95
+ )
96
+
97
+ @app.exception_handler(StarletteHTTPException)
98
+ async def custom_http_exception_handler(request: Request, exc: StarletteHTTPException):
99
+ if exc.status_code == 404:
100
+ available_routes = sorted(list(config.routes.keys()))
101
+ return JSONResponse(
102
+ status_code=404,
103
+ content={
104
+ "error": "Not Found",
105
+ "message": f"No serverless route matches '{request.url.path}'",
106
+ "availableRoutes": available_routes,
107
+ },
108
+ )
109
+ return JSONResponse(status_code=exc.status_code, content={"error": exc.detail})
110
+
111
+ return app
112
+
113
+
114
+ # Default app instance for standard ASGI runners (e.g., uvicorn zerodock.gateway.app:app)
115
+ app = create_app()
@@ -0,0 +1,57 @@
1
+ """Error response formatters and traceback visualizer for ZeroDock."""
2
+
3
+ import sys
4
+ import traceback
5
+ from starlette.responses import JSONResponse
6
+
7
+
8
+ def format_error_response(exc: Exception, request_id: str = "") -> JSONResponse:
9
+ """Formats an uncaught handler exception into a standard HTTP 500 response.
10
+
11
+ Also outputs the full unmasked traceback to stderr for developer debugging.
12
+
13
+ Args:
14
+ exc: The caught exception.
15
+ request_id: Unique invocation identifier.
16
+
17
+ Returns:
18
+ JSONResponse with HTTP 500 and diagnostic details.
19
+ """
20
+ # Print clear, unmasked traceback to standard error for developer visibility
21
+ print(f"\n[ZeroDock ERROR] Exception in handler (Request ID: {request_id}):", file=sys.stderr)
22
+ traceback.print_exception(type(exc), exc, exc.__traceback__, file=sys.stderr)
23
+ print("", file=sys.stderr)
24
+
25
+ return JSONResponse(
26
+ status_code=500,
27
+ content={
28
+ "error": "InternalServerError",
29
+ "exceptionType": type(exc).__name__,
30
+ "message": str(exc),
31
+ "requestId": request_id,
32
+ },
33
+ )
34
+
35
+
36
+ def format_timeout_response(timeout_seconds: int, request_id: str = "") -> JSONResponse:
37
+ """Formats an execution timeout into an HTTP 504 Gateway Timeout response.
38
+
39
+ Args:
40
+ timeout_seconds: Configured timeout limit in seconds.
41
+ request_id: Unique invocation identifier.
42
+
43
+ Returns:
44
+ JSONResponse with HTTP 504 and diagnostic details.
45
+ """
46
+ print(
47
+ f"\n[ZeroDock TIMEOUT] Function exceeded limit of {timeout_seconds}s (Request ID: {request_id})",
48
+ file=sys.stderr,
49
+ )
50
+ return JSONResponse(
51
+ status_code=504,
52
+ content={
53
+ "error": "GatewayTimeout",
54
+ "message": f"Function execution timed out after {timeout_seconds} seconds",
55
+ "requestId": request_id,
56
+ },
57
+ )
@@ -0,0 +1,69 @@
1
+ """HTTP response normalizer for ZeroDock handlers."""
2
+
3
+ import json
4
+ from typing import Any
5
+ from starlette.responses import JSONResponse, Response
6
+
7
+
8
+ def normalize_response(result: Any) -> Response:
9
+ """Translates any handler return value into a Starlette/FastAPI Response.
10
+
11
+ Supports:
12
+ - Standard Serverless: {'statusCode': 200, 'headers': {...}, 'body': '...'}
13
+ - Status tuple: (200, {'message': 'ok'})
14
+ - Raw dict/list: {'id': 1} -> HTTP 200 JSON
15
+ - Raw string: "hello" -> HTTP 200 text/plain
16
+ - None: -> HTTP 204 No Content
17
+
18
+ Args:
19
+ result: The raw object returned by the serverless handler.
20
+
21
+ Returns:
22
+ A compliant Starlette Response.
23
+ """
24
+ if isinstance(result, Response):
25
+ return result
26
+
27
+ if result is None:
28
+ return Response(content=b"", status_code=204)
29
+
30
+ # Handle (status_code, body) tuple
31
+ if isinstance(result, tuple) and len(result) == 2 and isinstance(result[0], int):
32
+ status_code, body = result
33
+ if isinstance(body, (dict, list)):
34
+ return JSONResponse(content=body, status_code=status_code)
35
+ return Response(
36
+ content=str(body), status_code=status_code, media_type="text/plain; charset=utf-8"
37
+ )
38
+
39
+ # Handle standard serverless dictionary format: {"statusCode": ..., "body": ...}
40
+ if isinstance(result, dict) and "statusCode" in result:
41
+ status_code = int(result["statusCode"])
42
+ headers = dict(result.get("headers") or {})
43
+ body = result.get("body", "")
44
+
45
+ # If body is already a dict or list, serialize to JSON if needed
46
+ if isinstance(body, (dict, list)):
47
+ serialized_body = json.dumps(body)
48
+ if "content-type" not in {k.lower(): v for k, v in headers.items()}:
49
+ headers["Content-Type"] = "application/json"
50
+ return Response(
51
+ content=serialized_body, status_code=status_code, headers=headers
52
+ )
53
+
54
+ # Body is string or bytes
55
+ body_bytes = body.encode("utf-8") if isinstance(body, str) else bytes(body)
56
+ return Response(content=body_bytes, status_code=status_code, headers=headers)
57
+
58
+ # Handle raw dict or list
59
+ if isinstance(result, (dict, list)):
60
+ return JSONResponse(content=result, status_code=200)
61
+
62
+ # Handle plain string
63
+ if isinstance(result, str):
64
+ return Response(
65
+ content=result, status_code=200, media_type="text/plain; charset=utf-8"
66
+ )
67
+
68
+ # Fallback to string representation
69
+ return Response(content=str(result), status_code=200)
@@ -0,0 +1,44 @@
1
+ """Embedded Uvicorn server runner for ZeroDock."""
2
+
3
+ from pathlib import Path
4
+ from typing import Optional
5
+ import uvicorn
6
+
7
+ from zerodock.config.parser import load_config
8
+ from zerodock.gateway.app import create_app
9
+
10
+
11
+ def run_server(
12
+ config_path: str = "serverless-local.yaml",
13
+ host: Optional[str] = None,
14
+ port: Optional[int] = None,
15
+ log_level: Optional[str] = None,
16
+ ) -> None:
17
+ """Boots the ZeroDock local serverless HTTP gateway.
18
+
19
+ Args:
20
+ config_path: Path to serverless-local.yaml.
21
+ host: Optional host override (e.g. '127.0.0.1').
22
+ port: Optional port override (e.g. 8080).
23
+ log_level: Optional log level override ('info', 'debug', etc.).
24
+ """
25
+ config = load_config(config_path)
26
+
27
+ bind_host = host or config.gateway.host
28
+ bind_port = port or config.gateway.port
29
+ server_log_level = log_level or config.gateway.log_level
30
+
31
+ app = create_app(config)
32
+
33
+ print(f"[ZeroDock] Booting local gateway on http://{bind_host}:{bind_port}")
34
+ print(f"[ZeroDock] Loaded {len(config.routes)} registered route(s):")
35
+ for path, route in config.routes.items():
36
+ methods_str = ", ".join(route.methods)
37
+ print(f" - [{methods_str}] {path} -> {route.file.name}:{route.handler}")
38
+
39
+ uvicorn.run(
40
+ app,
41
+ host=bind_host,
42
+ port=bind_port,
43
+ log_level=server_log_level,
44
+ )
zerodock/py.typed ADDED
@@ -0,0 +1 @@
1
+ # Marker file for PEP 561 type annotation support
@@ -0,0 +1,179 @@
1
+ Metadata-Version: 2.4
2
+ Name: zerodock
3
+ Version: 0.1.0
4
+ Summary: Zero-dependency, ultra-lightweight local execution engine for serverless cloud architectures.
5
+ License: MIT
6
+ License-File: LICENSE
7
+ Keywords: serverless,aws-lambda,local-development,fastapi,docker-compose
8
+ Author: ZeroDock Contributors
9
+ Author-email: contributors@zerodock.dev
10
+ Requires-Python: >=3.10
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Software Development :: Testing
20
+ Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
21
+ Classifier: Typing :: Typed
22
+ Provides-Extra: dev
23
+ Requires-Dist: fastapi (>=0.110.0)
24
+ Requires-Dist: httpx (>=0.27.0) ; extra == "dev"
25
+ Requires-Dist: mypy (>=1.9.0) ; extra == "dev"
26
+ Requires-Dist: pydantic (>=2.6.0)
27
+ Requires-Dist: pytest (>=8.0.0) ; extra == "dev"
28
+ Requires-Dist: pytest-asyncio (>=0.23.0) ; extra == "dev"
29
+ Requires-Dist: pyyaml (>=6.0.1)
30
+ Requires-Dist: ruff (>=0.3.0) ; extra == "dev"
31
+ Requires-Dist: tomli (>=1.1.0) ; (python_version < "3.11") and (extra == "dev")
32
+ Requires-Dist: types-pyyaml (>=6.0.12) ; extra == "dev"
33
+ Requires-Dist: uvicorn (>=0.28.0)
34
+ Project-URL: Documentation, https://github.com/blackright/zerodock#readme
35
+ Project-URL: Homepage, https://github.com/blackright/zerodock
36
+ Project-URL: Issues, https://github.com/blackright/zerodock/issues
37
+ Project-URL: Repository, https://github.com/blackright/zerodock
38
+ Description-Content-Type: text/markdown
39
+
40
+ # ⚑ ZeroDock
41
+
42
+ > **Zero-dependency, ultra-lightweight local execution engine that simulates serverless cloud architectures at the application layer using native asynchronous Python.**
43
+
44
+ [![PyPI: zerodock](https://img.shields.io/pypi/v/zerodock.svg)](https://pypi.org/project/zerodock/)
45
+ [![CI: Status](https://github.com/blackright/zerodock/actions/workflows/ci.yml/badge.svg)](https://github.com/blackright/zerodock/actions)
46
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
47
+ [![Python: 3.10+](https://img.shields.io/badge/Python-3.10%2B-brightgreen.svg)](https://www.python.org/)
48
+ [![Startup: <100ms](https://img.shields.io/badge/Startup-%3C100ms-success.svg)](#)
49
+ [![RAM: <50MB](https://img.shields.io/badge/RAM-%3C50MB-success.svg)](#)
50
+
51
+ ---
52
+
53
+ ## 🚨 The Problem
54
+
55
+ Modern cloud development leans heavily on **Serverless Architectures** (such as AWS Lambda, Google Cloud Functions, and Cloudflare Workers) because they scale effortlessly and cost nothing when idle. However, the local development experience for these platforms is fundamentally broken.
56
+
57
+ To test a simple serverless function locally before deploying it to production, developers are traditionally forced into two bad options:
58
+ 1. **Deploying directly to the cloud to test:** This adds a 30-second to 3-minute feedback loop for every minor typo or code tweak.
59
+ 2. **Running heavy local emulation suites:** Tools like LocalStack, AWS SAM, or multi-container Docker setups mimic entire cloud infrastructure stacks.
60
+
61
+ These existing solutions introduce massive friction into a developer's daily workflow: **massive resource bloat** (hogging 2GB+ of RAM), **sluggish startup times**, a **"black box" debugging nightmare**, and a **high barrier to entry** for contributors who just want to run a function locally.
62
+
63
+ ---
64
+
65
+ ## πŸ’‘ The Solution
66
+
67
+ Instead of simulating the cloud at the *infrastructure layer* using virtual machines and containers, **ZeroDock** simulates the cloud at the *application layer* using native, asynchronous Python.
68
+
69
+ It acts as a **"Docker-Compose without Docker"** tailored specifically for serverless handlers.
70
+
71
+ * ⚑ **Featherweight & Instant:** Built on native `asyncio` and `FastAPI`, it boots up in under 100 milliseconds and uses less than 50MB of RAM.
72
+ * πŸ“¦ **Containerless Isolation:** Leverages Python’s built-in `importlib` and `sys.modules` manipulation to dynamically inject event data, run the handler function, and keep the execution context clean.
73
+ * πŸ› **Native Debugging Integration:** Because code runs natively on your host machine's Python runtime, you can set standard breakpoints (`breakpoint()` or a red dot in VS Code) anywhere in your serverless code and step through line by line instantly.
74
+ * πŸ“„ **Declarative Infrastructure:** Define your API endpoints, routing paths, and target Python files in a single, human-readable `serverless-local.yaml` file.
75
+
76
+ ---
77
+
78
+ ## πŸš€ Quick Start
79
+
80
+ ### πŸ“¦ 1. Installation via pip (Recommended)
81
+
82
+ Install ZeroDock directly from PyPI into your active virtual environment:
83
+ ```bash
84
+ pip install zerodock
85
+ ```
86
+ *(Or if using `uv`)*:
87
+ ```bash
88
+ uv add zerodock
89
+ ```
90
+
91
+ ---
92
+
93
+ ### πŸ’» 2. Installing from Source (For Contributors)
94
+
95
+ Clone the repository and install dependencies:
96
+ ```bash
97
+ git clone https://github.com/blackright/zerodock.git
98
+ cd zerodock
99
+ pip install -e ".[dev]"
100
+ ```
101
+ *(Or if using `uv`)*:
102
+ ```bash
103
+ uv sync
104
+ ```
105
+
106
+ ### 3. Define Your Infrastructure (`serverless-local.yaml`)
107
+ Create a configuration file in your project root to map routes to your local Python serverless files:
108
+ ```yaml
109
+ version: "1.0"
110
+ gateway:
111
+ host: "127.0.0.1"
112
+ port: 8080
113
+ routes:
114
+ api/hello:
115
+ file: "./functions/hello.py"
116
+ handler: "lambda_handler"
117
+ methods: ["GET", "POST"]
118
+ ```
119
+
120
+ ### 4. Create a Sample Handler (`functions/hello.py`)
121
+ ```python
122
+ def lambda_handler(event, context):
123
+ name = event.get("queryStringParameters", {}).get("name", "World")
124
+ return {
125
+ "statusCode": 200,
126
+ "body": {"message": f"Hello, {name}! Sent natively from ZeroDock."}
127
+ }
128
+ ```
129
+
130
+ ### 5. Run the Simulator
131
+ Start the ZeroDock local gateway:
132
+ ```bash
133
+ python -m zerodock.cli dev
134
+ # or
135
+ uvicorn zerodock.gateway.app:app --port 8080
136
+ ```
137
+
138
+ Your mock serverless API gateway is now running at `http://localhost:8080`.
139
+
140
+ Test your endpoint:
141
+ ```bash
142
+ curl "http://localhost:8080/api/hello?name=OpenSource"
143
+ ```
144
+
145
+ ---
146
+
147
+ ## πŸ—ΊοΈ Feature Roadmap & Wishlist
148
+
149
+ We welcome contributions! These roadmap features are explicitly designed so community developers can jump in:
150
+
151
+ ### βš™οΈ Core Engine & Performance
152
+ * **Hot-Reloading File Watcher:** Background file watcher that automatically clears the `sys.modules` cache when a function file is saved, enabling real-time code updates without restarting the gateway.
153
+ * **Dynamic Middleware Pipeline:** Execute pre-handler and post-handler logic mimicking cloud middleware (e.g., AWS Lambda Layers or Cloudflare Advanced Routing).
154
+ * **Multi-Language Execution Layers:** Lightweight bindings (like Node.js via subprocess or Pyodide) to simulate JavaScript/TypeScript handlers alongside Python functions.
155
+
156
+ ### 🌐 Cloud Platform Contexts
157
+ * **AWS Lambda Payload Wrapper:** Transformer that formats incoming HTTP requests into valid AWS Lambda `event` and `context` schemas (including Cognito auth contexts).
158
+ * **Cloudflare Workers Runtime Wrapper:** Environment injector that mimics the `env`, `ctx`, and Fetch API behavior specific to Cloudflare Workers.
159
+ * **Google Cloud Functions Event Mocks:** Support for CloudEvent formats used by GCP functions.
160
+
161
+ ### πŸ”Œ Simulated Cloud Integration Plugins (The "Mock" Ecosystem)
162
+ * **Local Secret & Env Loader:** Read and inject `.env` files dynamically based on active routes, simulating cloud environment variable configurations.
163
+ * **Mock Key-Value (KV) Store:** Simple, memory-based or SQLite-backed local Key-Value storage engine mimicking Cloudflare KV or AWS DynamoDB.
164
+ * **Mock Object Storage:** Directory-backed local S3 bucket simulation.
165
+ * **Cron & Scheduled Trigger Simulator:** Internal loop system that reads `cron:` syntax from `serverless-local.yaml` and executes functions at designated intervals.
166
+ * **Mock Pub/Sub Queue Event Bus:** In-memory queue system to simulate message broker events triggering functions asynchronously (like AWS SQS or GCP Pub/Sub).
167
+
168
+ ---
169
+
170
+ ## 🀝 Contributing
171
+
172
+ We love contributions! Please read our [CONTRIBUTING.md](CONTRIBUTING.md) for full guidelines on code standards, local development, and how to submit a Pull Request.
173
+
174
+ ---
175
+
176
+ ## πŸ“„ License
177
+
178
+ This project is open-source software licensed under the [MIT License](LICENSE).
179
+
@@ -0,0 +1,20 @@
1
+ zerodock/__init__.py,sha256=fKCxtBJmTIWe_LrFpZXgB9qcWvFCm_EXNORYLtvB0tg,1455
2
+ zerodock/cli.py,sha256=w1KJq1AUEOco-fu51xIyxVS_GMy7njUN_5fF0_lc2tw,2295
3
+ zerodock/config/__init__.py,sha256=YhkS82TVY1J_qJz6fHvPuX-jxTO0BQthaa7UBSKX2js,59
4
+ zerodock/config/models.py,sha256=nEW1--179QVVYqByieVxRrBD2ySee0jtJoiC34dooh0,2982
5
+ zerodock/config/parser.py,sha256=NcOussOo1QZusIGspKOk7YSvWW8JvFLZ3TiWJqwtcA4,2541
6
+ zerodock/engine/__init__.py,sha256=Ymj_9liY4DTGEvschA5CcDi3-TIB9K0yLfmtT-EWTTM,63
7
+ zerodock/engine/context.py,sha256=hMNoPv_Oiierw1ZCv-K8bf0QDeq3AMWMZ05mjA-q2w0,1106
8
+ zerodock/engine/event.py,sha256=J_cbUxul8f6J0YhSWa_Ppl6YXLetVQkwi-S_E9I8lH0,1999
9
+ zerodock/engine/loader.py,sha256=xgDzeqQNL4pwJZhScNqVH92A9n7GHix7ozb4le5huVU,3099
10
+ zerodock/gateway/__init__.py,sha256=d9MbJ_voN4Ovf2gHstgbdW0p_9gmwyXAZwUhLiXeN54,54
11
+ zerodock/gateway/app.py,sha256=VSIlYgd5eE0gKl3_KuX3ElIVh8pil_bHb2-FlqfVjhM,4577
12
+ zerodock/gateway/errors.py,sha256=JZMJW3oOlx2RMLJmEC9Fg3pBfREtJgECfHqvh3_K4Wo,1879
13
+ zerodock/gateway/response.py,sha256=dNRqecpda4huVLW_y8yOCKk6pRiw_dwWrZ6TbDCAECE,2558
14
+ zerodock/gateway/server.py,sha256=93hsa25g5vaGCz1bef1xK16O2vVJA_OpNGfv7YpWkwI,1367
15
+ zerodock/py.typed,sha256=yg6ApBF77Z3ylO5DWhOSJkQlzJIdtdPdaOT-TDeydNY,50
16
+ zerodock-0.1.0.dist-info/METADATA,sha256=tbAy53K2-XZDYdJwxIp1IyxH6hAddvqj8uheLyNKYZU,8334
17
+ zerodock-0.1.0.dist-info/WHEEL,sha256=L-WvLdSBvJWHXv5zrQxDvNRnIgoBzLUpcbuiw19KCuQ,88
18
+ zerodock-0.1.0.dist-info/entry_points.txt,sha256=kw19jiBHdiD3VQvbZG2uU0H2-SB5kJhT6FujGV2lNWc,46
19
+ zerodock-0.1.0.dist-info/licenses/LICENSE,sha256=WDZnnwBJbgeQmeb5repcW0BSnu5BAFFKBqG3-vAmv8Y,1078
20
+ zerodock-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 2.5.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ zerodock=zerodock.cli:main
3
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ZeroDock Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.