sprintapi 0.1.0__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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Lingqiao Zhao
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.
@@ -0,0 +1,11 @@
1
+ Metadata-Version: 2.4
2
+ Name: sprintapi
3
+ Version: 0.1.0
4
+ Summary: Add your description here
5
+ Author-email: Lingqiao Zhao <forever.3g@hotmail.com>
6
+ Requires-Python: >=3.12
7
+ License-File: LICENSE
8
+ Requires-Dist: pydantic>=2
9
+ Requires-Dist: fastapi
10
+ Requires-Dist: uvicorn
11
+ Dynamic: license-file
@@ -0,0 +1,78 @@
1
+ # SprintAPI Framework
2
+
3
+ A lightweight FastAPI-based framework that can be used like Spring Boot, with built-in dependency injection and lifecycle management.
4
+
5
+ ## Core features
6
+ - **Configuration via environment variables** over config file,
7
+ which is friendly to containerized deployments and 12-factor apps;
8
+ - **Built-in dependency injection**, which enables IoC and better handles dependency management for larger apps;
9
+ - **Controller-based API design**, which is more intuitive for developers coming from other languages;
10
+ - **Lifecycle hooks** called on same event loop as the server, and are called in dependency order;
11
+
12
+ ## Requirements
13
+
14
+ - Python 3.12+
15
+
16
+ ## Install (editable)
17
+
18
+ ```bash
19
+ pip install -e .
20
+ ```
21
+
22
+ ## Quick start
23
+
24
+ Below is a minimal example of a controller exposing a single GET endpoint.
25
+
26
+ ```python
27
+ # main.py
28
+
29
+ from sprintapi import SprintApiServer, api_route, get_mapping, Controller
30
+
31
+
32
+ @api_route('/simple')
33
+ class SimpleController(Controller):
34
+ """A minimal controller exposing a single GET endpoint."""
35
+
36
+ @get_mapping('hello')
37
+ async def hello(self):
38
+ """Return a simple greeting."""
39
+ return 'Hello, World!'
40
+
41
+
42
+ def main():
43
+ # Create and run the server; pass `port=8000` to change the default.
44
+ server = SprintApiServer()
45
+ server.run()
46
+
47
+
48
+ if __name__ == '__main__':
49
+ main()
50
+ ```
51
+
52
+ Run it:
53
+
54
+ ```bash
55
+ python main.py
56
+ ```
57
+ This runs a web server listening on `http://localhost:80`.
58
+ Then open `http://localhost/simple/hello` in your browser, you will see:
59
+ ```
60
+ Hello, World!
61
+ ```
62
+
63
+ ## With Dependency Injection
64
+
65
+ ```bash
66
+ > cd examples/with-di
67
+ > export APP_NAME="My Demo"
68
+ > python main.py
69
+ ```
70
+
71
+ Then open `http://localhost/app/name` in your browser and you will see:
72
+ ```
73
+ This app is My Demo
74
+ ```
75
+
76
+ ## License
77
+
78
+ MIT. See `LICENSE`.
@@ -0,0 +1,19 @@
1
+ [project]
2
+ name = "sprintapi"
3
+ version = "0.1.0"
4
+ description = "Add your description here"
5
+ requires-python = ">=3.12"
6
+ dependencies = [
7
+ "pydantic>=2",
8
+ "fastapi",
9
+ "uvicorn"
10
+ ]
11
+ authors = [
12
+ {name = "Lingqiao Zhao", email = "forever.3g@hotmail.com"}
13
+ ]
14
+
15
+ [tool.setuptools]
16
+ package-data = { "gw_luna" = [
17
+ "static/redoc/*",
18
+ "static/swagger-ui/*"
19
+ ] }
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,12 @@
1
+ from .config import Configuration, configuration
2
+ from .controller import (
3
+ Controller,
4
+ api_route,
5
+ get_mapping,
6
+ post_mapping,
7
+ put_mapping,
8
+ delete_mapping
9
+ )
10
+ from .error import *
11
+ from .server import *
12
+ from .service import Service, service
@@ -0,0 +1,36 @@
1
+ import os
2
+
3
+ from pydantic import BaseModel
4
+ from typing import Any, Mapping
5
+
6
+ from .utility.type_registry import get_registry_decorator
7
+
8
+
9
+ __all__ = [
10
+ 'Configuration',
11
+ 'configuration',
12
+ 'get_configuration_types',
13
+ ]
14
+
15
+
16
+ class Configuration(BaseModel):
17
+ @classmethod
18
+ def load(cls):
19
+ config_dict = cls._get_required_dict(os.environ)
20
+ return cls.model_validate(config_dict, by_alias=True)
21
+
22
+ @classmethod
23
+ def _get_required_dict(cls, d: Mapping[str, Any]):
24
+ res = {}
25
+ for key in cls.model_json_schema()['properties']:
26
+ if key in d:
27
+ res[key] = d[key]
28
+ return res
29
+
30
+
31
+ _config_types: set[type[Configuration]] = set()
32
+ configuration = get_registry_decorator(Configuration, _config_types)
33
+
34
+
35
+ def get_configuration_types() -> set[type[Configuration]]:
36
+ return _config_types.copy()
@@ -0,0 +1,126 @@
1
+ import fastapi
2
+ import inspect
3
+
4
+
5
+ __all__ = [
6
+ 'api_route',
7
+ 'get_controller_types',
8
+ 'Controller',
9
+
10
+ 'get_mapping',
11
+ 'post_mapping',
12
+ 'put_mapping',
13
+ 'delete_mapping'
14
+ ]
15
+
16
+
17
+ # APIs
18
+
19
+
20
+ def _method_mapping(method: str, route: str, **kwargs):
21
+ if not route.startswith('/') and len(route) > 0:
22
+ route = '/' + route
23
+
24
+ def _inner(target):
25
+ if not inspect.isfunction(target):
26
+ return target
27
+
28
+ target._sprint_api_type = method
29
+ target._sprint_api_route = route
30
+ target._sprint_api_args = kwargs
31
+
32
+ return target
33
+
34
+ return _inner
35
+
36
+
37
+ def get_mapping(route: str, **kwargs):
38
+ if not isinstance(route, str):
39
+ raise ValueError('Route is not specified.')
40
+ return _method_mapping('GET', route, **kwargs)
41
+
42
+
43
+ def post_mapping(route: str, **kwargs):
44
+ if not isinstance(route, str):
45
+ raise ValueError('Route is not specified.')
46
+ return _method_mapping('POST', route, **kwargs)
47
+
48
+
49
+ def put_mapping(route: str, **kwargs):
50
+ if not isinstance(route, str):
51
+ raise ValueError('Route is not specified.')
52
+ return _method_mapping('PUT', route, **kwargs)
53
+
54
+
55
+ def delete_mapping(route: str, **kwargs):
56
+ if not isinstance(route, str):
57
+ raise ValueError('Route is not specified.')
58
+ return _method_mapping('DELETE', route, **kwargs)
59
+
60
+
61
+ # Controllers
62
+
63
+
64
+ class Controller:
65
+ def get_router(self):
66
+ route_prefix = getattr(self, '_sprint_api_route', '')
67
+ args = getattr(self, '_sprint_api_args', {})
68
+
69
+ router = fastapi.APIRouter(prefix=route_prefix, **args)
70
+
71
+ for method_name in dir(self):
72
+ if method_name.startswith('__'):
73
+ continue
74
+
75
+ method = getattr(self, method_name)
76
+ if not callable(method):
77
+ continue
78
+
79
+ api_type = getattr(method, '_sprint_api_type', None)
80
+ route = getattr(method, '_sprint_api_route', None)
81
+ args = getattr(method, '_sprint_api_args', {})
82
+
83
+ if api_type is None or route is None:
84
+ continue
85
+
86
+ if api_type in ('GET', 'POST', 'PUT', 'DELETE'):
87
+ router.api_route(path=route, methods=[api_type], **args)(method)
88
+
89
+ return router
90
+
91
+
92
+ _controller_types: set[type[Controller]] = set()
93
+
94
+
95
+ def api_route(route: str, **kwargs):
96
+ if not isinstance(route, str):
97
+ raise ValueError('Route is not specified.')
98
+
99
+ if route.endswith('/'):
100
+ route = route[:-1]
101
+
102
+ global _controller_types
103
+
104
+ def _inner(target):
105
+ if inspect.isfunction(target):
106
+ return target
107
+
108
+ if not isinstance(target, type):
109
+ raise TypeError(f'{target} is not a type.')
110
+ if not issubclass(target, Controller):
111
+ raise TypeError(f'{target.__name__} is not a subclass of Controller.')
112
+
113
+ if target in _controller_types:
114
+ raise ValueError(f'Controller class "{target.__name__}" is already registered.')
115
+
116
+ _controller_types.add(target)
117
+ target._sprint_api_route = route
118
+ target._sprint_api_args = kwargs
119
+
120
+ return target
121
+
122
+ return _inner
123
+
124
+
125
+ def get_controller_types() -> set[type[Controller]]:
126
+ return _controller_types.copy()
@@ -0,0 +1,119 @@
1
+ import enum
2
+ from pydantic import BaseModel
3
+
4
+
5
+ __all__ = [
6
+ 'Error',
7
+ 'ErrorCode',
8
+ 'ErrorModel',
9
+
10
+ 'Ok',
11
+ 'AlreadyExistsError',
12
+ 'DeadlineExceededError',
13
+ 'FailedPreconditionError',
14
+ 'InternalError',
15
+ 'InvalidArgumentError',
16
+ 'NotFoundError',
17
+ 'PermissionDeniedError',
18
+ 'TooManyRequestsError',
19
+ 'UnauthenticatedError',
20
+ 'UnimplementedError'
21
+ ]
22
+
23
+
24
+ class ErrorCode(enum.IntEnum):
25
+ """
26
+ 错误代码。定义参照谷歌RPC错误代码定义。
27
+ """
28
+ OK = 0
29
+ CANCELLED = 1
30
+ UNKNOWN = 2
31
+ INVALID_ARGUMENT = 3
32
+ DEADLINE_EXCEEDED = 4
33
+ NOT_FOUND = 5
34
+ ALREADY_EXISTS = 6
35
+ PERMISSION_DENIED = 7
36
+ RESOURCE_EXHAUSTED = 8
37
+ FAILED_PRECONDITION = 9
38
+ ABORTED = 10
39
+ OUT_OF_RANGE = 11
40
+ UNIMPLEMENTED = 12
41
+ INTERNAL = 13
42
+ UNAVAILABLE = 14
43
+ DATA_LOSS = 15
44
+ UNAUTHENTICATED = 16
45
+
46
+
47
+ class ErrorModel(BaseModel):
48
+ code: ErrorCode
49
+ message: str
50
+
51
+
52
+ class Ok(ErrorModel):
53
+ def __init__(self):
54
+ super().__init__(code=ErrorCode.OK, message='Ok.')
55
+
56
+
57
+ class Error(Exception):
58
+ def __init__(self, code: ErrorCode, message: str):
59
+ self.code = code
60
+ self.message = message
61
+
62
+ def json(self):
63
+ return self.model().model_dump_json()
64
+
65
+ def model(self):
66
+ return ErrorModel(
67
+ code=self.code,
68
+ message=self.message
69
+ )
70
+
71
+
72
+ class AlreadyExistsError(Error):
73
+ def __init__(self, message: str = 'Requested resource already exists.'):
74
+ super().__init__(code=ErrorCode.ALREADY_EXISTS, message=message)
75
+
76
+
77
+ class DeadlineExceededError(Error):
78
+ def __init__(self, message: str = 'Deadline exceeded.'):
79
+ super().__init__(code=ErrorCode.DEADLINE_EXCEEDED, message=message)
80
+
81
+
82
+ class FailedPreconditionError(Error):
83
+ def __init__(self, message: str = 'Resource is not in a valid state.'):
84
+ super().__init__(code=ErrorCode.FAILED_PRECONDITION, message=message)
85
+
86
+
87
+ class InternalError(Error):
88
+ def __init__(self, message: str = 'Internal error.'):
89
+ super().__init__(code=ErrorCode.INTERNAL, message=message)
90
+
91
+
92
+ class InvalidArgumentError(Error):
93
+ def __init__(self, message: str = 'Invalid argument.'):
94
+ super().__init__(code=ErrorCode.INVALID_ARGUMENT, message=message)
95
+
96
+
97
+ class NotFoundError(Error):
98
+ def __init__(self, message: str = 'Requested resource does not exist.'):
99
+ super().__init__(code=ErrorCode.NOT_FOUND, message=message)
100
+
101
+
102
+ class PermissionDeniedError(Error):
103
+ def __init__(self, message: str = 'Permission denied.'):
104
+ super().__init__(code=ErrorCode.PERMISSION_DENIED, message=message)
105
+
106
+
107
+ class TooManyRequestsError(Error):
108
+ def __init__(self, message: str = 'Too many requests.'):
109
+ super().__init__(code=ErrorCode.UNAVAILABLE, message=message)
110
+
111
+
112
+ class UnauthenticatedError(Error):
113
+ def __init__(self, message: str = 'Unauthenticated request.'):
114
+ super().__init__(code=ErrorCode.UNAUTHENTICATED, message=message)
115
+
116
+
117
+ class UnimplementedError(Error):
118
+ def __init__(self, message: str = 'Unimplemented method.'):
119
+ super().__init__(code=ErrorCode.UNIMPLEMENTED, message=message)
@@ -0,0 +1,68 @@
1
+ import logging
2
+ import sys
3
+
4
+
5
+ __all__ = [
6
+ 'get_sprintapi_logger',
7
+ 'set_global_level_to_debug',
8
+ 'set_global_level_to_info'
9
+ ]
10
+
11
+
12
+ _log_formatter = logging.Formatter(
13
+ fmt='%(asctime)s.%(msecs)03d [%(levelname)s] [%(name)s] %(message)s',
14
+ datefmt='%Y-%m-%d %H:%M:%S'
15
+ )
16
+
17
+
18
+ _stdout_handler = logging.StreamHandler(sys.stdout)
19
+ _stdout_handler.setFormatter(_log_formatter)
20
+ _stdout_handler.setLevel(logging.DEBUG)
21
+ _stdout_filter = logging.Filter()
22
+ _stdout_filter.filter = lambda record: record.levelno <= logging.INFO
23
+ _stdout_handler.addFilter(_stdout_filter)
24
+
25
+ _stderr_handler = logging.StreamHandler(sys.stderr)
26
+ _stderr_handler.setFormatter(_log_formatter)
27
+ _stderr_handler.setLevel(logging.WARNING)
28
+ _stderr_filter = logging.Filter()
29
+ _stderr_filter.filter = lambda record: record.levelno > logging.INFO
30
+
31
+
32
+ _managed_loggers: dict[str, logging.Logger] = {}
33
+ _current_level = logging.INFO
34
+
35
+
36
+ def get_sprintapi_logger(name: str):
37
+ logger = _managed_loggers.get(name, None)
38
+ if logger is not None:
39
+ return logger
40
+
41
+ logger = logging.getLogger(name)
42
+ logger.propagate = False
43
+ logger.setLevel(_current_level)
44
+ logger.addHandler(_stdout_handler)
45
+ logger.addHandler(_stderr_handler)
46
+ _managed_loggers[name] = logger
47
+
48
+ return logger
49
+
50
+
51
+ _logger = get_sprintapi_logger('LogCtrl')
52
+
53
+
54
+ def _set_global_level(level: int):
55
+ global _current_level
56
+ _current_level = level
57
+
58
+ for logger in _managed_loggers.values():
59
+ _logger.info(f'Logger "{logger.name} set to level: {level}."')
60
+ logger.setLevel(_current_level)
61
+
62
+
63
+ def set_global_level_to_debug():
64
+ _set_global_level(logging.DEBUG)
65
+
66
+
67
+ def set_global_level_to_info():
68
+ _set_global_level(logging.INFO)
@@ -0,0 +1 @@
1
+ from .cors import CorsMiddleware
@@ -0,0 +1,19 @@
1
+ import fastapi
2
+
3
+ from starlette.middleware.base import BaseHTTPMiddleware
4
+
5
+
6
+ __all__ = ['CorsMiddleware']
7
+
8
+
9
+ class CorsMiddleware(BaseHTTPMiddleware):
10
+ async def dispatch(self, request, call_next):
11
+ if request.method != 'OPTIONS':
12
+ response = await call_next(request)
13
+ response.headers['Access-Control-Allow-Origin'] = '*'
14
+ return response
15
+ return fastapi.Response(status_code=200, headers={
16
+ 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
17
+ 'Access-Control-Allow-Headers': 'Authorization, Content-Type',
18
+ 'Access-Control-Allow-Origin': '*',
19
+ })
@@ -0,0 +1,75 @@
1
+ import fastapi
2
+
3
+ from ..error import (
4
+ Error,
5
+ ErrorCode,
6
+ InvalidArgumentError,
7
+ )
8
+ from pydantic import ValidationError
9
+
10
+
11
+ __all__ = [
12
+ 'register_sprintapi_errors'
13
+ ]
14
+
15
+
16
+
17
+ _error_code_map = {
18
+ ErrorCode.OK: 200,
19
+ ErrorCode.CANCELLED: 499,
20
+ ErrorCode.UNKNOWN: 500,
21
+ ErrorCode.INVALID_ARGUMENT: 400,
22
+ ErrorCode.DEADLINE_EXCEEDED: 504,
23
+ ErrorCode.NOT_FOUND: 404,
24
+ ErrorCode.ALREADY_EXISTS: 409,
25
+ ErrorCode.PERMISSION_DENIED: 403,
26
+ ErrorCode.RESOURCE_EXHAUSTED: 429,
27
+ ErrorCode.FAILED_PRECONDITION: 400,
28
+ ErrorCode.ABORTED: 409,
29
+ ErrorCode.OUT_OF_RANGE: 400,
30
+ ErrorCode.UNIMPLEMENTED: 501,
31
+ ErrorCode.INTERNAL: 500,
32
+ ErrorCode.UNAVAILABLE: 503,
33
+ ErrorCode.DATA_LOSS: 500,
34
+ ErrorCode.UNAUTHENTICATED: 401
35
+ }
36
+
37
+
38
+ def _register_sprintapi_error_handler(app: fastapi.FastAPI):
39
+ def _handler(request: fastapi.Request, exc: Error):
40
+ if request.headers.get('accept') == 'text/event-stream':
41
+ return fastapi.Response(
42
+ status_code=200,
43
+ headers={
44
+ 'Content-Type': 'text/event-stream',
45
+ },
46
+ content=f'event: abort\ndata: {exc.json()}\n\n'
47
+ )
48
+ return fastapi.Response(
49
+ status_code=_error_code_map.get(exc.code, 500),
50
+ content=exc.json()
51
+ )
52
+ app.add_exception_handler(Error, _handler)
53
+
54
+
55
+ def _register_pydantic_validation_error(app: fastapi.FastAPI):
56
+ def _handler(request: fastapi.Request, _):
57
+ exc = InvalidArgumentError()
58
+ if request.headers.get('accept') == 'text/event-stream':
59
+ return fastapi.Response(
60
+ status_code=200,
61
+ headers={
62
+ 'Content-Type': 'text/event-stream',
63
+ },
64
+ content=f'event: abort\ndata: {exc.json()}\n\n'
65
+ )
66
+ return fastapi.Response(
67
+ status_code=400,
68
+ content=exc.json()
69
+ )
70
+ app.add_exception_handler(ValidationError, _handler)
71
+
72
+
73
+ def register_sprintapi_errors(app: fastapi.FastAPI):
74
+ _register_sprintapi_error_handler(app)
75
+ _register_pydantic_validation_error(app)
@@ -0,0 +1,133 @@
1
+ import logging
2
+
3
+ import fastapi
4
+ import importlib.resources
5
+ import uvicorn
6
+
7
+ from fastapi.openapi.docs import get_swagger_ui_html, get_redoc_html
8
+ from fastapi.staticfiles import StaticFiles
9
+ from typing import Optional
10
+
11
+ from .config import get_configuration_types
12
+ from .controller import get_controller_types
13
+ from .logging import get_sprintapi_logger
14
+ from .middleware import CorsMiddleware
15
+ from .middleware.error_handler import register_sprintapi_errors
16
+ from .service import get_service_types
17
+ from .utility.di import DependencyContainer
18
+
19
+
20
+ __all__ = ['SprintApiServer']
21
+
22
+
23
+ _logger = get_sprintapi_logger('SprintApiServer')
24
+ _static_dir = importlib.resources.files('sprintapi') / 'static'
25
+
26
+
27
+ class SprintApiServer(uvicorn.Server):
28
+ def __init__(
29
+ self,
30
+ host: str = '0.0.0.0',
31
+ port: int = 80,
32
+ /,
33
+ enable_docs: bool = False,
34
+ app_name: str = None,
35
+ version: str = None,
36
+ uvicorn_log_level: int = logging.INFO
37
+ ):
38
+ super().__init__(config=uvicorn.Config(
39
+ app=self._setup_app(app_name, version),
40
+ host=host,
41
+ port=port,
42
+ log_level=uvicorn_log_level
43
+ ))
44
+ self._app_name = app_name
45
+ self._app.add_middleware(CorsMiddleware)
46
+ self._controller_types = get_controller_types()
47
+
48
+ # component registration
49
+ self._di_container = DependencyContainer()
50
+ for c in get_configuration_types():
51
+ self._di_container.register(c, c.load, is_singleton=True)
52
+ for c in self._controller_types:
53
+ self._di_container.register(c, c, is_singleton=True)
54
+
55
+ service_types = get_service_types()
56
+ for s in service_types:
57
+ self._di_container.register(s, s, is_singleton=True)
58
+
59
+ self._managed_services = self._di_container.resolve_with_order(service_types)
60
+
61
+ # register error handlers
62
+ register_sprintapi_errors(self._app)
63
+
64
+ # bind controllers
65
+ for c in self._controller_types:
66
+ controller = self._di_container.resolve(c)
67
+ router = controller.get_router()
68
+ class_name = controller.__class__.__name__
69
+ self._app.include_router(router)
70
+ _logger.info(f'Bind controller {class_name} with route prefix "{router.prefix}".')
71
+
72
+ # bind static files
73
+ self._app.mount('/static', StaticFiles(directory=_static_dir), name='static')
74
+ if enable_docs:
75
+ self._app.get('/docs', include_in_schema=False)(self._swagger_ui_html)
76
+ self._app.get('/redoc', include_in_schema=False)(self._redoc_ui_html)
77
+
78
+ @property
79
+ def app(self):
80
+ return self._app
81
+
82
+ async def startup(self, sockets = None):
83
+ await self._pre_startup()
84
+ await super().startup(sockets)
85
+
86
+ async def shutdown(self, sockets = None):
87
+ await self._pre_shutdown()
88
+ await super().shutdown(sockets)
89
+ await self._post_shutdown()
90
+
91
+ def _redoc_ui_html(self):
92
+ return get_redoc_html(
93
+ openapi_url=self._app.openapi_url,
94
+ title=f'{self._app_name} - Redoc' if self._app_name else 'Redoc',
95
+ redoc_js_url='/static/redoc/redoc.standalone.js',
96
+ )
97
+
98
+ def _swagger_ui_html(self):
99
+ return get_swagger_ui_html(
100
+ openapi_url=self._app.openapi_url,
101
+ title=f'{self._app_name} - Swagger UI' if self._app_name else 'Swagger UI',
102
+ swagger_favicon_url='/static/swagger-ui/favicon-32x32.png',
103
+ swagger_js_url='/static/swagger-ui/swagger-ui-bundle.js',
104
+ swagger_css_url='/static/swagger-ui/swagger-ui.css',
105
+ )
106
+
107
+ async def _pre_startup(self):
108
+ # init services
109
+ for s in self._managed_services:
110
+ await s.init()
111
+ _logger.info('Managers init complete.')
112
+
113
+ # start services
114
+ for s in self._managed_services:
115
+ await s.start()
116
+ _logger.info('Managers start complete.')
117
+
118
+ async def _pre_shutdown(self):
119
+ pass
120
+
121
+ async def _post_shutdown(self):
122
+ for s in self._managed_services[::-1]:
123
+ await s.stop()
124
+ _logger.info('Managers stop complete.')
125
+
126
+ def _setup_app(self, app_name: Optional[str], version: Optional[str]):
127
+ extra_args = {}
128
+ if app_name:
129
+ extra_args['title'] = app_name
130
+ if version:
131
+ extra_args['version'] = version
132
+ self._app = fastapi.FastAPI(docs_url=None, redoc_url=None, **extra_args)
133
+ return self._app
@@ -0,0 +1,27 @@
1
+ from .utility.type_registry import get_registry_decorator
2
+
3
+
4
+ __all__ = [
5
+ 'Service',
6
+ 'service',
7
+ 'get_service_types',
8
+ ]
9
+
10
+
11
+ class Service:
12
+ async def init(self):
13
+ pass
14
+
15
+ async def start(self):
16
+ pass
17
+
18
+ async def stop(self):
19
+ pass
20
+
21
+
22
+ _service_types: set[type[Service]] = set()
23
+
24
+ service = get_registry_decorator(Service, _service_types)
25
+
26
+ def get_service_types() -> set[type[Service]]:
27
+ return _service_types.copy()
File without changes
@@ -0,0 +1,112 @@
1
+ import inspect
2
+ from collections import defaultdict, deque
3
+ from typing import Any, Callable, Iterable, get_type_hints
4
+
5
+
6
+ __all__ = ['DependencyContainer']
7
+
8
+
9
+ class DependencyContainer:
10
+ def __init__(self):
11
+ self._components: dict[type, tuple[Callable, bool]] = {}
12
+ self._singletons: dict[type, object] = {}
13
+
14
+ def check_circular(self):
15
+ # build indegree map with all related deps
16
+ indegree_map = self._build_indegree_map(self._components.keys())
17
+
18
+ unresolved = deque([c for c, count in indegree_map.items() if count == 0])
19
+ visit_count = 0
20
+
21
+ while unresolved:
22
+ interface = unresolved.popleft()
23
+ visit_count += 1
24
+
25
+ deps = list(self._get_direct_deps(interface).values())
26
+ for dep in deps:
27
+ indegree_map[dep] -= 1
28
+ if indegree_map[dep] == 0:
29
+ unresolved.append(dep)
30
+
31
+ return visit_count != len(indegree_map)
32
+
33
+ def register(self, interface: type[object], impl: Callable, is_singleton: bool = False):
34
+ if interface in self._components:
35
+ raise TypeError(f'Type "{interface.__name__}" already registered."')
36
+ self._components[interface] = (impl, is_singleton)
37
+
38
+ def resolve(self, interface: type):
39
+ deps = self._get_direct_deps(interface)
40
+ dep_impls = {k: self.resolve(v) for k, v in deps.items()}
41
+ impl_info = self._components.get(interface, None)
42
+
43
+ if impl_info is None:
44
+ raise TypeError(f'Failed to resolve dependency of type: "{interface.__name__}".')
45
+
46
+ impl, is_singleton = impl_info
47
+ if is_singleton:
48
+ if interface not in self._singletons:
49
+ self._singletons[interface] = self._create_impl(interface, impl, dep_impls)
50
+ return self._singletons[interface]
51
+ return self._create_impl(interface, impl, dep_impls)
52
+
53
+ def resolve_with_order(self, interfaces: Iterable[type]) -> list[Any]:
54
+ target_interfaces = set(interfaces)
55
+
56
+ # find all related interfaces along the path
57
+ related_interfaces = set()
58
+ unresolved = deque(target_interfaces)
59
+
60
+ while unresolved:
61
+ interface = unresolved.popleft()
62
+ related_interfaces.add(interface)
63
+ for dep in self._get_direct_deps(interface).values():
64
+ if dep not in related_interfaces:
65
+ unresolved.append(dep)
66
+
67
+ indegree_map = self._build_indegree_map(related_interfaces)
68
+
69
+ # start from no deps, simulate population, append node only if indegree depleted (Kahn's algo)
70
+ unresolved = deque([c for c, count in indegree_map.items() if count == 0])
71
+ res_interfaces = []
72
+
73
+ while unresolved:
74
+ interface = unresolved.popleft()
75
+
76
+ if interface in target_interfaces:
77
+ res_interfaces.append(interface)
78
+
79
+ for dep in self._get_direct_deps(interface).values():
80
+ indegree_map[dep] -= 1
81
+ if indegree_map[dep] == 0:
82
+ unresolved.append(dep)
83
+
84
+ return [self.resolve(interface) for interface in res_interfaces[::-1]]
85
+
86
+ def _build_indegree_map(self, interfaces: Iterable[type]) -> dict[type, int]:
87
+ indegree_map = defaultdict(int)
88
+ for c in interfaces:
89
+ indegree_map[c] += 0
90
+ for dep in self._get_direct_deps(c).values():
91
+ indegree_map[dep] += 1
92
+ return indegree_map
93
+
94
+ @staticmethod
95
+ def _create_impl(interface, impl, deps):
96
+ try:
97
+ return impl(**deps)
98
+ except TypeError:
99
+ raise TypeError(f'Failed to resolve dependency of type: "{interface.__name__}".')
100
+
101
+ def _get_direct_deps(self, interface: type) -> dict[str, type]:
102
+ impl_info = self._components.get(interface, None)
103
+ if not impl_info:
104
+ raise TypeError(f'Failed to resolve dependency of type: "{interface.__name__}".')
105
+
106
+ impl_sig, _ = impl_info
107
+ if inspect.isclass(impl_sig):
108
+ type_hints = get_type_hints(impl_sig.__init__)
109
+ else:
110
+ type_hints = get_type_hints(impl_sig)
111
+
112
+ return { name: pt for name, pt in type_hints.items() if name != 'return' }
@@ -0,0 +1,22 @@
1
+ import inspect
2
+
3
+
4
+ __all__ = ['get_registry_decorator']
5
+
6
+
7
+ def get_registry_decorator(base_type: type, registry: set[type]):
8
+ def _inner(target):
9
+ if inspect.isfunction(target):
10
+ return target
11
+
12
+ if not isinstance(target, type):
13
+ raise TypeError(f'{target} is not a type.')
14
+ if not issubclass(target, base_type):
15
+ raise TypeError(f'{target.__name__} is not a subclass of {base_type.__name__}.')
16
+
17
+ if target in registry:
18
+ raise ValueError(f'{base_type.__name__} class "{target.__name__}" is already registered.')
19
+
20
+ registry.add(target)
21
+ return target
22
+ return _inner
@@ -0,0 +1,11 @@
1
+ Metadata-Version: 2.4
2
+ Name: sprintapi
3
+ Version: 0.1.0
4
+ Summary: Add your description here
5
+ Author-email: Lingqiao Zhao <forever.3g@hotmail.com>
6
+ Requires-Python: >=3.12
7
+ License-File: LICENSE
8
+ Requires-Dist: pydantic>=2
9
+ Requires-Dist: fastapi
10
+ Requires-Dist: uvicorn
11
+ Dynamic: license-file
@@ -0,0 +1,21 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/sprintapi/__init__.py
5
+ src/sprintapi/config.py
6
+ src/sprintapi/controller.py
7
+ src/sprintapi/error.py
8
+ src/sprintapi/logging.py
9
+ src/sprintapi/server.py
10
+ src/sprintapi/service.py
11
+ src/sprintapi.egg-info/PKG-INFO
12
+ src/sprintapi.egg-info/SOURCES.txt
13
+ src/sprintapi.egg-info/dependency_links.txt
14
+ src/sprintapi.egg-info/requires.txt
15
+ src/sprintapi.egg-info/top_level.txt
16
+ src/sprintapi/middleware/__init__.py
17
+ src/sprintapi/middleware/cors.py
18
+ src/sprintapi/middleware/error_handler.py
19
+ src/sprintapi/utility/__init__.py
20
+ src/sprintapi/utility/di.py
21
+ src/sprintapi/utility/type_registry.py
@@ -0,0 +1,3 @@
1
+ pydantic>=2
2
+ fastapi
3
+ uvicorn
@@ -0,0 +1 @@
1
+ sprintapi