mindtrace-services 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,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
@@ -0,0 +1,14 @@
1
+ Metadata-Version: 2.4
2
+ Name: mindtrace-services
3
+ Version: 0.1.0
4
+ Summary: Service layer for Mindtrace
5
+ Author: Mindtrace Team
6
+ License-Expression: Apache-2.0
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Programming Language :: Python :: 3.12
9
+ License-File: LICENSE
10
+ Requires-Dist: gunicorn>=23.0.0
11
+ Requires-Dist: mindtrace-core
12
+ Requires-Dist: structlog>=24.4.0
13
+ Requires-Dist: uvicorn>=0.34.3
14
+ Dynamic: license-file
@@ -0,0 +1,27 @@
1
+ from mindtrace.services.core.connection_manager import ConnectionManager
2
+ from mindtrace.services.core.service import Service
3
+ from mindtrace.services.core.types import (
4
+ EndpointsSchema,
5
+ Heartbeat,
6
+ HeartbeatSchema,
7
+ PIDFileSchema,
8
+ ServerIDSchema,
9
+ ServerStatus,
10
+ ShutdownSchema,
11
+ StatusSchema,
12
+ )
13
+ from mindtrace.services.core.utils import generate_connection_manager
14
+
15
+ __all__ = [
16
+ "ConnectionManager",
17
+ "EndpointsSchema",
18
+ "generate_connection_manager",
19
+ "Heartbeat",
20
+ "HeartbeatSchema",
21
+ "PIDFileSchema",
22
+ "ServerIDSchema",
23
+ "Service",
24
+ "ServerStatus",
25
+ "ShutdownSchema",
26
+ "StatusSchema",
27
+ ]
@@ -0,0 +1,140 @@
1
+ """Client-side helper class for communicating with any ServerBase server."""
2
+
3
+ import asyncio
4
+ from urllib.parse import urljoin
5
+ from uuid import UUID
6
+
7
+ import httpx
8
+ import requests
9
+ from fastapi import HTTPException
10
+ from urllib3.util.url import Url, parse_url
11
+
12
+ from mindtrace.core import Mindtrace, Timeout, ifnone
13
+ from mindtrace.services.core.types import ServerStatus, ShutdownOutput, StatusOutput
14
+
15
+
16
+ class ConnectionManager(Mindtrace):
17
+ """Client-side helper class for communicating with Mindtrace servers."""
18
+
19
+ def __init__(self, url: Url | None = None, server_id: UUID | None = None, server_pid_file: str | None = None):
20
+ super().__init__()
21
+ self.url = ifnone(url, default=parse_url(self.config["MINDTRACE_DEFAULT_HOST_URLS"]["Service"]))
22
+ self._server_id = server_id
23
+ self._server_pid_file = server_pid_file
24
+
25
+ def shutdown(self, block: bool = True):
26
+ """Shutdown the server.
27
+
28
+ This method sends a shutdown request to the server. If block=True, it will also poll the server until it
29
+ becomes unavailable, ensuring the shutdown process is complete.
30
+
31
+ Args:
32
+ block: If True, waits for the server to actually shut down. If False, returns immediately after sending
33
+ the shutdown request.
34
+
35
+ Example::
36
+
37
+ from mindtrace.services import Service, ServerStatus
38
+
39
+ cm = Service.launch()
40
+ assert cm.status == ServerStatus.Available
41
+
42
+ # Wait for shutdown to complete
43
+ cm.shutdown(block=True)
44
+ assert cm.status == ServerStatus.Down
45
+
46
+ # Or send shutdown command and return immediately
47
+ cm.shutdown(block=False)
48
+ """
49
+ # Send the shutdown request
50
+ response = requests.request("POST", urljoin(str(self.url), "shutdown"), timeout=60)
51
+ if response.status_code != 200:
52
+ raise HTTPException(response.status_code, response.content)
53
+
54
+ # If not blocking, return immediately after sending the shutdown request
55
+ if not block:
56
+ return ShutdownOutput(shutdown=True)
57
+
58
+ def check_server_down():
59
+ """Check if server is down by trying to connect to status endpoint."""
60
+ try:
61
+ _ = requests.post(urljoin(str(self.url), "status"), timeout=2)
62
+ # If we get any response, server is still up - raise exception to retry
63
+ raise ConnectionError("Server still responding")
64
+ except requests.exceptions.ConnectionError:
65
+ # Connection failed - server is down, this is what we want
66
+ return True
67
+ except requests.exceptions.Timeout:
68
+ # Timeout - server might be shutting down, this is what we want
69
+ return True
70
+
71
+ timeout_handler = Timeout(
72
+ timeout=30,
73
+ retry_delay=0.2,
74
+ exceptions=(ConnectionError,),
75
+ progress_bar=False, # No progress bar for shutdown
76
+ )
77
+ try:
78
+ timeout_handler.run(check_server_down)
79
+ except TimeoutError:
80
+ self.logger.error(f"Server at {self.url} did not shut down within timeout period.")
81
+ raise TimeoutError(f"Server at {self.url} did not shut down within timeout period.")
82
+
83
+ return ShutdownOutput(shutdown=True)
84
+
85
+ async def ashutdown(self, block: bool = True):
86
+ """Async shutdown of the server."""
87
+ # Run the shutdown in a thread pool to avoid blocking the event loop
88
+ loop = asyncio.get_event_loop()
89
+ return await loop.run_in_executor(None, self.shutdown, block)
90
+
91
+ def status(self):
92
+ """Get the status of the server.
93
+
94
+ Returns ServerStatus.DOWN if the server is unreachable, otherwise returns the actual status.
95
+
96
+ Returns:
97
+ StatusOutput with the current server status.
98
+ """
99
+ try:
100
+ response = requests.post(urljoin(str(self.url), "status"), timeout=10)
101
+ if response.status_code != 200:
102
+ return StatusOutput(status=ServerStatus.DOWN)
103
+
104
+ result = response.json()
105
+ return StatusOutput(**result)
106
+
107
+ except (requests.exceptions.ConnectionError, requests.exceptions.Timeout, requests.exceptions.RequestException):
108
+ return StatusOutput(status=ServerStatus.DOWN)
109
+
110
+ async def astatus(self):
111
+ """Async get the status of the server.
112
+
113
+ Returns ServerStatus.DOWN if the server is unreachable, otherwise returns the actual status.
114
+
115
+ Returns:
116
+ StatusOutput with the current server status.
117
+ """
118
+ try:
119
+ async with httpx.AsyncClient(timeout=10) as client:
120
+ response = await client.post(urljoin(str(self.url), "status"))
121
+
122
+ if response.status_code != 200:
123
+ return StatusOutput(status=ServerStatus.DOWN)
124
+
125
+ result = response.json()
126
+ return StatusOutput(**result)
127
+
128
+ except (httpx.ConnectError, httpx.TimeoutException, httpx.RequestError):
129
+ return StatusOutput(status=ServerStatus.DOWN)
130
+
131
+ def __exit__(self, exc_type, exc_val, exc_tb):
132
+ self.logger.debug(f"Shutting down {self.name} Server.")
133
+ try:
134
+ self.shutdown()
135
+ finally:
136
+ if exc_type is not None:
137
+ info = (exc_type, exc_val, exc_tb)
138
+ self.logger.exception("Exception occurred", exc_info=info)
139
+ return self.suppress
140
+ return False
@@ -0,0 +1,72 @@
1
+ import argparse
2
+ import json
3
+ import logging
4
+ from argparse import RawTextHelpFormatter
5
+ from pathlib import Path
6
+
7
+ from gunicorn.app.base import BaseApplication
8
+
9
+ from mindtrace.core import instantiate_target, setup_logger
10
+
11
+
12
+ class Launcher(BaseApplication):
13
+ """Gunicorn application launcher for Mindtrace services."""
14
+
15
+ def __init__(self, options):
16
+ self.gunicorn_options = {
17
+ "bind": options.bind,
18
+ "workers": options.num_workers,
19
+ "worker_class": options.worker_class,
20
+ "pidfile": options.pid,
21
+ }
22
+
23
+ # Parse init params
24
+ init_params = json.loads(options.init_params) if options.init_params else {}
25
+
26
+ # Create server with initialization parameters
27
+ server = instantiate_target(options.server_class, **init_params)
28
+ server.logger = setup_logger(
29
+ name=server.unique_name,
30
+ stream_level=logging.INFO,
31
+ file_level=logging.DEBUG,
32
+ log_dir=Path(server.config["MINDTRACE_LOGGER_DIR"]),
33
+ )
34
+ self.application = server.app
35
+ server.url = options.bind
36
+ super().__init__()
37
+
38
+ def load_config(self):
39
+ config = {
40
+ key: value for key, value in self.gunicorn_options.items() if key in self.cfg.settings and value is not None
41
+ }
42
+ for key, value in config.items():
43
+ self.cfg.set(key.lower(), value)
44
+
45
+ def load(self):
46
+ return self.application
47
+
48
+
49
+ def main():
50
+ parser = argparse.ArgumentParser(description="MINDTRACE SERVER LAUNCHER\n", formatter_class=RawTextHelpFormatter)
51
+ parser.add_argument(
52
+ "-s",
53
+ "--server_class",
54
+ type=str,
55
+ nargs="?",
56
+ default="mindtrace.services.core.serve.Service",
57
+ help="Server class to launch",
58
+ )
59
+ parser.add_argument("-w", "--num_workers", type=int, default=1, help="Number of workers")
60
+ parser.add_argument(
61
+ "-b", "--bind", type=str, default="127.0.0.1:8080", help="URL address to bind with the application"
62
+ )
63
+ parser.add_argument("-p", "--pid", type=str, default=None)
64
+ parser.add_argument("-k", "--worker_class", type=str, default="uvicorn.workers.UvicornWorker")
65
+ parser.add_argument("--init-params", type=str, help="JSON string of initialization parameters")
66
+ args = parser.parse_args()
67
+
68
+ Launcher(args).run()
69
+
70
+
71
+ if __name__ == "__main__":
72
+ main()
@@ -0,0 +1,456 @@
1
+ """Service base class. Provides unified methods for all Mindtrace (micro)services."""
2
+
3
+ import atexit
4
+ import json
5
+ import logging
6
+ import os
7
+ import signal
8
+ import subprocess
9
+ import uuid
10
+ from contextlib import asynccontextmanager
11
+ from importlib.metadata import version
12
+ from pathlib import Path
13
+ from typing import Type, TypeVar
14
+ from uuid import UUID
15
+
16
+ import fastapi
17
+ import psutil
18
+ import requests
19
+ from fastapi import FastAPI, HTTPException
20
+ from urllib3.util.url import Url, parse_url
21
+
22
+ from mindtrace.core import Mindtrace, TaskSchema, Timeout, ifnone, ifnone_url, named_lambda
23
+ from mindtrace.services.core.connection_manager import ConnectionManager
24
+ from mindtrace.services.core.types import (
25
+ EndpointsSchema,
26
+ Heartbeat,
27
+ HeartbeatSchema,
28
+ PIDFileSchema,
29
+ ServerIDSchema,
30
+ ServerStatus,
31
+ ShutdownSchema,
32
+ StatusSchema,
33
+ )
34
+ from mindtrace.services.core.utils import generate_connection_manager
35
+
36
+ T = TypeVar("T", bound="Service") # A generic variable that can be 'Service', or any subclass.
37
+ C = TypeVar("C", bound="ConnectionManager") # '' '' '' 'ConnectionManager', or any subclass.
38
+
39
+
40
+ class Service(Mindtrace):
41
+ """Base class for all Mindtrace services."""
42
+
43
+ _status = ServerStatus.DOWN
44
+ _endpoints: dict[str, TaskSchema] = {}
45
+ _client_interface: Type[C] | None = None
46
+ _active_servers: dict[UUID, psutil.Process] = {}
47
+
48
+ def __init__(
49
+ self,
50
+ *,
51
+ url: str | Url | None = None,
52
+ host: str | None = None,
53
+ port: int | None = None,
54
+ summary: str | None = None,
55
+ description: str | None = None,
56
+ terms_of_service: str | None = None,
57
+ license_info: str | None = None,
58
+ ):
59
+ """Initialize server instance. This is for internal use by the launch() method.
60
+
61
+ Args:
62
+ url: Full URL string or Url object
63
+ host: Host address (e.g. "localhost" or "192.168.1.100")
64
+ port: Port number
65
+ summary: Summary of the server
66
+ description: Description of the server
67
+ terms_of_service: Terms of service for the server
68
+ license_info: License information for the server
69
+
70
+ Warning: Services should be created via the ServiceClass.launch() method. The __init__ method here should be
71
+ considered private internal use.
72
+ """
73
+ super().__init__()
74
+ self._status: ServerStatus = ServerStatus.AVAILABLE
75
+ self.id, self.pid_file = self._generate_id_and_pid_file()
76
+
77
+ # Build URL with the following priority:
78
+ # 1. Explicit URL parameter
79
+ # 2. Host/port parameters
80
+ # 3. Default URL from config
81
+ self._url = self.build_url(url=url, host=host, port=port)
82
+
83
+ """
84
+ self.logger = default_logger(
85
+ name=self.unique_name,
86
+ stream_level=logging.INFO,
87
+ file_level=logging.DEBUG,
88
+ file_name=self.default_log_file(),
89
+ )
90
+ """
91
+
92
+ description = ifnone(description, default=f"{self.name} server.")
93
+ version_str = "Mindtrace " + version("mindtrace-services")
94
+
95
+ @asynccontextmanager
96
+ async def lifespan(app: FastAPI):
97
+ """Lifespan for the FastAPI app."""
98
+ self.logger.info(f"Server {self.id} starting up.")
99
+ yield
100
+ await self.shutdown_cleanup()
101
+ self.logger.info(f"Server {self.id} shut down.")
102
+
103
+ self.app = FastAPI(
104
+ title=self.name,
105
+ description=description,
106
+ summary=summary,
107
+ version=version_str,
108
+ terms_of_service=terms_of_service,
109
+ license_info=license_info,
110
+ lifespan=lifespan,
111
+ )
112
+ self.add_endpoint(
113
+ path="/endpoints",
114
+ func=named_lambda("endpoints", lambda: {"endpoints": list(self._endpoints.keys())}),
115
+ schema=EndpointsSchema(),
116
+ )
117
+ self.add_endpoint(
118
+ path="/status", func=named_lambda("status", lambda: {"status": self.status.value}), schema=StatusSchema()
119
+ )
120
+ self.add_endpoint(
121
+ path="/heartbeat",
122
+ func=named_lambda("heartbeat", lambda: {"heartbeat": self.heartbeat()}),
123
+ schema=HeartbeatSchema(),
124
+ )
125
+ self.add_endpoint(
126
+ path="/server_id", func=named_lambda("server_id", lambda: {"server_id": self.id}), schema=ServerIDSchema()
127
+ )
128
+ self.add_endpoint(
129
+ path="/pid_file", func=named_lambda("pid_file", lambda: {"pid_file": self.pid_file}), schema=PIDFileSchema()
130
+ )
131
+ self.add_endpoint(
132
+ path="/shutdown", func=self.shutdown, schema=ShutdownSchema(), autolog_kwargs={"log_level": logging.DEBUG}
133
+ )
134
+
135
+ @classmethod
136
+ def _generate_id_and_pid_file(cls, unique_id: UUID | None = None, pid_file: str | None = None) -> tuple[UUID, str]:
137
+ """Generate a unique_id and pid_file for the server.
138
+
139
+ The logic used ensures that the pid_file contains the (human-readable) class name as well as the unique_id.
140
+ """
141
+
142
+ # The following logic assures that the pid_file contains the unique_id
143
+ if unique_id is not None and pid_file is not None:
144
+ if str(unique_id) not in pid_file:
145
+ raise ValueError(f"unique_id {unique_id} not found in pid_file {pid_file}")
146
+ elif unique_id is not None and pid_file is None:
147
+ unique_id = unique_id
148
+ pid_file = cls._server_id_to_pid_file(unique_id)
149
+ elif unique_id is None and pid_file is not None:
150
+ unique_id = cls._pid_file_to_server_id(pid_file)
151
+ pid_file = pid_file
152
+ else: # unique_id is None and pid_file is None
153
+ unique_id = uuid.uuid1()
154
+ pid_file = cls._server_id_to_pid_file(unique_id)
155
+
156
+ Path(pid_file).parent.mkdir(parents=True, exist_ok=True)
157
+ return unique_id, pid_file
158
+
159
+ @classmethod
160
+ def _server_id_to_pid_file(cls, server_id: UUID) -> str:
161
+ return os.path.join(cls.config["MINDTRACE_SERVER_PIDS_DIR_PATH"], f"{cls.__name__}_{server_id}_pid.txt")
162
+
163
+ @classmethod
164
+ def _pid_file_to_server_id(cls, pid_file: str) -> UUID:
165
+ return UUID(pid_file.split("_")[-2])
166
+
167
+ @classmethod
168
+ def status_at_host(cls, url: str | Url, timeout: int = 60) -> ServerStatus:
169
+ """Check the status of the service at the given host url.
170
+
171
+ This command may be used to check if a service (including this one) is available at a given host, useful for
172
+ determining when a service has been successfully launched.
173
+
174
+ Args:
175
+ url: The host URL of the service.
176
+ """
177
+ url = parse_url(url) if isinstance(url, str) else url
178
+ try:
179
+ response = requests.request("POST", str(url) + "/status", timeout=timeout)
180
+ except requests.exceptions.ConnectionError:
181
+ return ServerStatus.DOWN
182
+ if response.status_code != 200:
183
+ return ServerStatus.DOWN
184
+
185
+ status = ServerStatus(response.json()["status"])
186
+ return status
187
+
188
+ @classmethod
189
+ def connect(cls: Type[T], url: str | Url | None = None, timeout: int = 60) -> C:
190
+ """Connect to an existing service.
191
+
192
+ The returned connection manager is determined by the registered connection manager for the service. If one has
193
+ not explicitly been registered, the default connection manager (ConnectionManagerBase) will be used.
194
+
195
+ Args:
196
+ url: The host URL of the service.
197
+
198
+ Returns:
199
+ A connection manager for the service.
200
+
201
+ Raises:
202
+ HTTPException: If the server fails to connect, an HTTPException will be raised with status code 503.
203
+ """
204
+ url = ifnone_url(url, default=cls.default_url())
205
+ host_status = cls.status_at_host(url, timeout=timeout)
206
+ if host_status == ServerStatus.AVAILABLE:
207
+ if cls._client_interface is None:
208
+ return generate_connection_manager(cls)(url=url)
209
+ else:
210
+ return cls._client_interface(url=url)
211
+ raise HTTPException(status_code=503, detail=f"Server failed to connect: {host_status}")
212
+
213
+ @classmethod
214
+ def launch(
215
+ cls: Type[T],
216
+ *,
217
+ url: str | Url | None = None,
218
+ host: str | None = None,
219
+ port: int | None = None,
220
+ block: bool = False,
221
+ num_workers: int = 1,
222
+ wait_for_launch: bool = True,
223
+ timeout: int = 60,
224
+ progress_bar: bool = True,
225
+ **kwargs,
226
+ ):
227
+ """Launch a new server instance.
228
+
229
+ The server can be configured through either explicit URL parameters or through kwargs. All kwargs are passed
230
+ directly to the server instance's __init__ method.
231
+
232
+ Args:
233
+ url: Full URL string or Url object (highest priority)
234
+ host: Host address (used if url not provided)
235
+ port: Port number (used if url not provided)
236
+ block: If True, blocks the calling process and keeps the server running
237
+ num_workers: Number of worker processes
238
+ wait_for_launch: Whether to wait for server startup
239
+ timeout: Timeout for server startup in seconds
240
+ progress_bar: Show progress bar during startup
241
+ **kwargs: Additional parameters passed to the server's __init__ method
242
+ """
243
+ # Build the launch URL with priority
244
+ launch_url = cls.build_url(url=url, host=host, port=port)
245
+
246
+ # Check that there is not already a service at the given URL
247
+ try:
248
+ existing_status = cls.status_at_host(launch_url)
249
+ if existing_status != ServerStatus.DOWN:
250
+ raise HTTPException(
251
+ status_code=400,
252
+ detail=f"Server {cls.unique_name} at {launch_url} is already running with status {existing_status}.",
253
+ )
254
+ except RuntimeError as e:
255
+ cls.logger.warning(f"Another service is already running at {launch_url}. New service was NOT launched.")
256
+ raise e
257
+
258
+ # All kwargs (including URL params) go directly to init_params
259
+ init_params = {"url": str(launch_url), **kwargs}
260
+
261
+ # Create launch command
262
+ server_id = uuid.uuid1()
263
+ launch_command = [
264
+ "python",
265
+ "-m",
266
+ "mindtrace.services.core.launcher",
267
+ "-s",
268
+ cls.unique_name,
269
+ "-w",
270
+ str(num_workers),
271
+ "-b",
272
+ f"{launch_url.host}:{launch_url.port}",
273
+ "-p",
274
+ cls._server_id_to_pid_file(server_id),
275
+ "-k",
276
+ "uvicorn.workers.UvicornWorker",
277
+ "--init-params",
278
+ json.dumps(init_params),
279
+ ]
280
+ cls.logger.warning(f'Launching {cls.unique_name} with command: "{launch_command}"')
281
+ process = subprocess.Popen(launch_command)
282
+
283
+ # Register cleanup if this is the first server
284
+ cls._active_servers[server_id] = process
285
+ if len(cls._active_servers) == 1:
286
+ atexit.register(cls._cleanup_all_servers)
287
+ signal.signal(signal.SIGTERM, lambda sig, frame: cls._cleanup_all_servers())
288
+ signal.signal(signal.SIGINT, lambda sig, frame: cls._cleanup_all_servers())
289
+
290
+ # Wait for server to be available and get connection manager
291
+ connection_manager = None
292
+ if wait_for_launch:
293
+ timeout_handler = Timeout(
294
+ timeout=timeout,
295
+ exceptions=(ConnectionRefusedError, requests.exceptions.ConnectionError, HTTPException),
296
+ progress_bar=progress_bar,
297
+ desc=f"Launching {cls.unique_name.split('.')[-1]} at {launch_url}",
298
+ )
299
+ try:
300
+ connection_manager = timeout_handler.run(cls.connect, url=launch_url)
301
+ except Exception as e:
302
+ cls._cleanup_server(server_id)
303
+ raise e
304
+
305
+ # If blocking is requested, wait for the process
306
+ if block:
307
+ try:
308
+ process.wait()
309
+ except KeyboardInterrupt:
310
+ cls._cleanup_server(server_id)
311
+ raise
312
+ finally:
313
+ cls._cleanup_server(server_id)
314
+
315
+ return connection_manager
316
+
317
+ @property
318
+ def endpoints(self) -> dict[str, TaskSchema]:
319
+ """Return the available commands for the service."""
320
+ return self._endpoints
321
+
322
+ @property
323
+ def status(self) -> ServerStatus:
324
+ """Returns the current status of this service."""
325
+ return self._status
326
+
327
+ def heartbeat(self) -> Heartbeat:
328
+ """Request the server to do a complete heartbeat check."""
329
+ return Heartbeat(
330
+ status=self.status,
331
+ server_id=self.id,
332
+ message="Heartbeat check successful.",
333
+ details=None,
334
+ )
335
+
336
+ @classmethod
337
+ def _cleanup_server(cls, server_id: UUID):
338
+ if server_id in cls._active_servers:
339
+ process = cls._active_servers[server_id]
340
+ try:
341
+ parent = psutil.Process(process.pid)
342
+ children = parent.children(recursive=True)
343
+ for child in children:
344
+ try:
345
+ child.terminate()
346
+ except psutil.NoSuchProcess:
347
+ pass
348
+ try:
349
+ parent.terminate()
350
+ parent.wait(timeout=5)
351
+ except psutil.NoSuchProcess:
352
+ pass
353
+ except (psutil.NoSuchProcess, psutil.TimeoutExpired):
354
+ cls.logger.debug("Process already terminated.")
355
+ finally:
356
+ del cls._active_servers[server_id]
357
+
358
+ @classmethod
359
+ def _cleanup_all_servers(cls):
360
+ """Cleanup the servers."""
361
+ for server_id in list(cls._active_servers.keys()):
362
+ cls._cleanup_server(server_id)
363
+
364
+ @staticmethod
365
+ def shutdown() -> fastapi.Response:
366
+ """HTTP endpoint to shut down the server."""
367
+ os.kill(os.getppid(), signal.SIGTERM) # kill the parent gunicorn process as it will respawn us otherwise
368
+ os.kill(os.getpid(), signal.SIGTERM) # kill ourselves as well
369
+ return fastapi.Response(status_code=200, content="Server shutting down...")
370
+
371
+ async def shutdown_cleanup(self):
372
+ """Cleanup the server.
373
+
374
+ Override this method in subclasses to shut down any additional resources (e.g. db connections) as necessary."""
375
+ try:
376
+ self.logger.debug(f"Successfully released resources for Server {self.id}.")
377
+ except Exception as e:
378
+ self.logger.warning(f"Server did not shut down properly: {e}")
379
+
380
+ @classmethod
381
+ def default_url(cls) -> Url:
382
+ """Get the default URL for this server type from config.
383
+
384
+ Priority:
385
+
386
+ 1. Server-specific URL from config
387
+ 2. Default ServerBase URL from config
388
+ 3. Fallback to localhost:8000
389
+ """
390
+ default_urls = cls.config["MINDTRACE_DEFAULT_HOST_URLS"]
391
+ server_url = default_urls.get(cls.__name__) or default_urls.get("ServerBase", "http://localhost:8000")
392
+ return parse_url(server_url)
393
+
394
+ @classmethod
395
+ def build_url(cls, url: str | Url | None = None, host: str | None = None, port: int | None = None) -> Url:
396
+ """Build a URL with consistent priority logic.
397
+
398
+ Priority:
399
+
400
+ 1. Explicit URL parameter
401
+ 2. Host/port parameters
402
+ 3. Default URL from config
403
+
404
+ Args:
405
+ url: Full URL string or Url object
406
+ host: Host address (e.g. "localhost" or "192.168.1.100")
407
+ port: Port number
408
+
409
+ Returns:
410
+ Parsed URL object
411
+ """
412
+ if url is not None:
413
+ if isinstance(url, str):
414
+ url = url + "/" if not url.endswith("/") else url
415
+ return parse_url(url) if isinstance(url, str) else url
416
+
417
+ if host is not None or port is not None:
418
+ default_url = cls.default_url()
419
+ final_host = host or default_url.host
420
+ final_port = port or default_url.port
421
+ return parse_url(f"http://{final_host}:{final_port}/")
422
+
423
+ return cls.default_url()
424
+
425
+ @classmethod
426
+ def register_connection_manager(cls, connection_manager: Type[ConnectionManager]):
427
+ """Register a connection manager for this server."""
428
+ cls._client_interface = connection_manager
429
+
430
+ @classmethod
431
+ def default_log_file(cls) -> str:
432
+ """Get the default log file for this server type."""
433
+ return os.path.join(cls.config["MINDTRACE_DEFAULT_LOG_DIR"], f"{cls.__name__}_logs.txt")
434
+
435
+ def add_endpoint(
436
+ self,
437
+ path,
438
+ func,
439
+ schema: TaskSchema,
440
+ api_route_kwargs=None,
441
+ autolog_kwargs=None,
442
+ methods: list[str] | None = None,
443
+ scope: str = "public",
444
+ ):
445
+ """Register a new endpoint with optional role."""
446
+ path = path.removeprefix("/")
447
+ api_route_kwargs = ifnone(api_route_kwargs, default={})
448
+ autolog_kwargs = ifnone(autolog_kwargs, default={})
449
+
450
+ self._endpoints[path] = schema
451
+ self.app.add_api_route(
452
+ "/" + path,
453
+ endpoint=Mindtrace.autolog(self=self, **autolog_kwargs)(func),
454
+ methods=ifnone(methods, default=["POST"]),
455
+ **api_route_kwargs,
456
+ )
@@ -0,0 +1,104 @@
1
+ import json
2
+ from dataclasses import dataclass
3
+ from enum import Enum
4
+ from typing import Any, Type
5
+ from uuid import UUID
6
+
7
+ from pydantic import BaseModel
8
+
9
+ from mindtrace.core import TaskSchema
10
+
11
+
12
+ class ServerStatus(Enum):
13
+ DOWN = "Down"
14
+ LAUNCHING = "Launching"
15
+ FAILED_TO_LAUNCH = "FailedToLaunch"
16
+ AVAILABLE = "Available"
17
+ STOPPING = "Stopping"
18
+
19
+
20
+ @dataclass
21
+ class Heartbeat:
22
+ """Heartbeat status of a server.
23
+
24
+ Attributes:
25
+ status: The current status of the server.
26
+ server_id: The unique identifier of the server.
27
+ message: Human-readable message describing the status of the server.
28
+ details: Additional details about the server status. Individual server subclasses may define their own specific
29
+ protocol for this field (though always a dict). A GatewayServer, for instance, will return a
30
+ dict[UUID, Heartbeat], containing the Heartbeats of all connected services, keyed by their unique server
31
+ IDs.
32
+ """
33
+
34
+ status: ServerStatus = ServerStatus.DOWN
35
+ server_id: UUID | None = None
36
+ message: str | None = None
37
+ details: Any = None
38
+
39
+ def __str__(self):
40
+ if isinstance(self.details, dict):
41
+ return (
42
+ f"Server ID: {self.server_id}\n"
43
+ f"Status: {self.status}\n"
44
+ f"Message: {self.message}\n"
45
+ f"Details: {json.dumps(self.details, indent=4)}"
46
+ )
47
+ else:
48
+ return (
49
+ f"Server ID: {self.server_id}\nStatus: {self.status}\nMessage: {self.message}\nDetails: {self.details}"
50
+ )
51
+
52
+
53
+ class EndpointsOutput(BaseModel):
54
+ endpoints: list[str]
55
+
56
+
57
+ class EndpointsSchema(TaskSchema):
58
+ name: str = "endpoints"
59
+ output_schema: Type[EndpointsOutput] = EndpointsOutput
60
+
61
+
62
+ class StatusOutput(BaseModel):
63
+ status: ServerStatus
64
+
65
+
66
+ class StatusSchema(TaskSchema):
67
+ name: str = "status"
68
+ output_schema: Type[StatusOutput] = StatusOutput
69
+
70
+
71
+ class HeartbeatOutput(BaseModel):
72
+ heartbeat: Heartbeat
73
+
74
+
75
+ class HeartbeatSchema(TaskSchema):
76
+ name: str = "heartbeat"
77
+ output_schema: Type[HeartbeatOutput] = HeartbeatOutput
78
+
79
+
80
+ class ServerIDOutput(BaseModel):
81
+ server_id: UUID
82
+
83
+
84
+ class ServerIDSchema(TaskSchema):
85
+ name: str = "server_id"
86
+ output_schema: Type[ServerIDOutput] = ServerIDOutput
87
+
88
+
89
+ class PIDFileOutput(BaseModel):
90
+ pid_file: str
91
+
92
+
93
+ class PIDFileSchema(TaskSchema):
94
+ name: str = "pid_file"
95
+ output_schema: Type[PIDFileOutput] = PIDFileOutput
96
+
97
+
98
+ class ShutdownOutput(BaseModel):
99
+ shutdown: bool
100
+
101
+
102
+ class ShutdownSchema(TaskSchema):
103
+ name: str = "shutdown"
104
+ output_schema: Type[ShutdownOutput] = ShutdownOutput
@@ -0,0 +1,187 @@
1
+ from typing import TYPE_CHECKING, Optional, Type
2
+
3
+ import httpx
4
+ from fastapi import HTTPException
5
+
6
+ if TYPE_CHECKING: # pragma: no cover
7
+ from mindtrace.services import Service
8
+ from mindtrace.core import Mindtrace
9
+ from mindtrace.services.core.connection_manager import ConnectionManager
10
+
11
+
12
+ def add_endpoint(app, path, self: Optional["Service"], **kwargs):
13
+ """Register a new endpoint.
14
+
15
+ This decorator method is functionally identical as calling add_endpoint on a Service instance. It is useful when
16
+ the endpoints are defined in a separate method, such as grouping api routes in a more complicated FastAPI app.
17
+
18
+ Args:
19
+ app: The FastAPI app.
20
+ path: The endpoint path.
21
+ self: The server instance.
22
+ **kwargs: Additional arguments to pass when creating the FastAPI route.
23
+
24
+ Example::
25
+
26
+ from fastapi import FastAPI
27
+ from mindtrace.services import Service
28
+
29
+ class MyServer(Service):
30
+ def __init__(self):
31
+ super().__init__()
32
+
33
+ self.add_endpoint(path="/status_using_method", func=self.status)
34
+ self.create_app()
35
+
36
+ def status(self):
37
+ return {"status": "Available"}
38
+
39
+ def create_app():
40
+ # May put all the endpoints in a single method, and call the method in __init__.
41
+
42
+ @add_endpoint(self.app, "/status_using_decorator", self=self)
43
+ def status():
44
+ return {"status": "Available"}
45
+
46
+ @add_endpoint(self.app, "/another_hundred_endpoints", self=self)
47
+ def another_hundred_endpoints():
48
+ return
49
+
50
+
51
+ """
52
+ self._endpoints.append(path.removeprefix("/"))
53
+
54
+ def wrapper(func):
55
+ app.add_api_route(f"/{path}", endpoint=Mindtrace.autolog(self=self)(func), methods=["POST"], **kwargs)
56
+
57
+ return wrapper
58
+
59
+
60
+ def register_connection_manager(connection_manager: Type["ConnectionManager"]):
61
+ """Register a connection manager for a server class.
62
+
63
+ This decorator is used to register a connection manager for a server class. The connection manager is used to
64
+ communicate with the server. The connection manager must be a subclass of ConnectionManager.
65
+
66
+ Args:
67
+ connection_manager: The connection manager class.
68
+
69
+ Example::
70
+
71
+ import requests
72
+ from mindtrace.services import ConnectionManager, Service
73
+
74
+ class MyConnectionManager(ConnectionManager):
75
+ def __init__(self, url):
76
+ super().__init__(url)
77
+
78
+ def add(arg1, arg2):
79
+ response = requests.request("POST", str(self.url) + "add", json={"arg1": arg1, "arg2": arg2})
80
+ return json.loads(response.content)["sum"]
81
+
82
+ @register_connection_manager(MyConnectionManager)
83
+ class MyService(Service):
84
+ def __init__(self):
85
+ super().__init__()
86
+ self.add_endpoint("add", self.add)
87
+
88
+ def add(self, arg1, arg2):
89
+ return {"sum": arg1 + arg2}
90
+
91
+ cm = MyService.launch() # Returns a MyConnectionManager instance, NOT a MyServer instance
92
+ sum = cm.add(1, 2) # Calls add method in MyConnectionManager
93
+
94
+ """
95
+
96
+ def wrapper(server_class):
97
+ server_class._client_interface = connection_manager
98
+ return server_class
99
+
100
+ return wrapper
101
+
102
+
103
+ def generate_connection_manager(
104
+ service_cls, protected_methods: list[str] = ["shutdown", "ashutdown", "status", "astatus"]
105
+ ):
106
+ """Generates a dedicated ConnectionManager class with one method per endpoint.
107
+
108
+ Args:
109
+ service_cls: The service class to generate a connection manager for.
110
+ protected_methods: A list of methods that should not be overridden by dynamic methods.
111
+
112
+ Returns:
113
+ A ConnectionManager class with one method per endpoint.
114
+ """
115
+
116
+ class_name = f"{service_cls.__name__}ConnectionManager"
117
+
118
+ class ServiceConnectionManager(ConnectionManager):
119
+ pass # Methods will be added dynamically
120
+
121
+ # Create a temporary service instance to get the endpoints
122
+ temp_service = service_cls()
123
+
124
+ # Dynamically define one method per endpoint
125
+ for endpoint_name, endpoint in temp_service._endpoints.items():
126
+ # Skip if this would override an existing method in ConnectionManager
127
+ if endpoint_name in protected_methods:
128
+ continue
129
+
130
+ endpoint_path = f"/{endpoint_name}"
131
+
132
+ def make_method(endpoint_path, input_schema, output_schema):
133
+ def method(self, validate_input: bool = True, validate_output: bool = True, **kwargs):
134
+ if validate_input:
135
+ payload = input_schema(**kwargs).model_dump() if input_schema is not None else {}
136
+ else:
137
+ payload = kwargs
138
+ res = httpx.post(str(self.url).rstrip("/") + endpoint_path, json=payload, timeout=30)
139
+ if res.status_code != 200:
140
+ raise HTTPException(res.status_code, res.text)
141
+
142
+ # Handle empty responses (e.g., from shutdown endpoint)
143
+ try:
144
+ result = res.json()
145
+ except Exception:
146
+ result = {"success": True} # Default response for empty content
147
+
148
+ if not validate_output:
149
+ return result # raw result dict
150
+ return output_schema(**result) if output_schema is not None else result
151
+
152
+ async def amethod(self, validate_input: bool = True, validate_output: bool = True, **kwargs):
153
+ if validate_input:
154
+ payload = input_schema(**kwargs).model_dump() if input_schema is not None else {}
155
+ else:
156
+ payload = kwargs
157
+ async with httpx.AsyncClient(timeout=30) as client:
158
+ res = await client.post(str(self.url).rstrip("/") + endpoint_path, json=payload, timeout=30)
159
+ if res.status_code != 200:
160
+ raise HTTPException(res.status_code, res.text)
161
+
162
+ # Handle empty responses (e.g., from shutdown endpoint)
163
+ try:
164
+ result = res.json()
165
+ except Exception:
166
+ result = {"success": True} # Default response for empty content
167
+
168
+ if not validate_output:
169
+ return result # raw result dict
170
+ return output_schema(**result) if output_schema is not None else result
171
+
172
+ return method, amethod
173
+
174
+ method, amethod = make_method(endpoint_path, endpoint.input_schema, endpoint.output_schema)
175
+
176
+ # Set up sync method
177
+ method.__name__ = endpoint_name
178
+ method.__doc__ = f"Calls the `{endpoint_name}` pipeline at `{endpoint_path}`"
179
+ setattr(ServiceConnectionManager, endpoint_name, method)
180
+
181
+ # Set up async method
182
+ amethod.__name__ = f"a{endpoint_name}"
183
+ amethod.__doc__ = f"Async version: Calls the `{endpoint_name}` pipeline at `{endpoint_path}`"
184
+ setattr(ServiceConnectionManager, f"a{endpoint_name}", amethod)
185
+
186
+ ServiceConnectionManager.__name__ = class_name
187
+ return ServiceConnectionManager
@@ -0,0 +1,35 @@
1
+ import time
2
+
3
+ from pydantic import BaseModel
4
+
5
+ from mindtrace.core import TaskSchema
6
+ from mindtrace.services import Service
7
+
8
+
9
+ class EchoInput(BaseModel):
10
+ message: str
11
+ delay: float = 0.0
12
+
13
+
14
+ class EchoOutput(BaseModel):
15
+ echoed: str
16
+
17
+
18
+ class EchoTaskSchema(TaskSchema):
19
+ name: str = "echo"
20
+ input_schema: type[EchoInput] = EchoInput
21
+ output_schema: type[EchoOutput] = EchoOutput
22
+
23
+
24
+ echo_task = EchoTaskSchema()
25
+
26
+
27
+ class EchoService(Service):
28
+ def __init__(self, *args, **kwargs):
29
+ super().__init__(*args, **kwargs)
30
+ self.add_endpoint("echo", self.echo, schema=echo_task)
31
+
32
+ def echo(self, payload: EchoInput) -> EchoOutput:
33
+ if payload.delay > 0:
34
+ time.sleep(payload.delay)
35
+ return EchoOutput(echoed=payload.message)
@@ -0,0 +1,14 @@
1
+ Metadata-Version: 2.4
2
+ Name: mindtrace-services
3
+ Version: 0.1.0
4
+ Summary: Service layer for Mindtrace
5
+ Author: Mindtrace Team
6
+ License-Expression: Apache-2.0
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Programming Language :: Python :: 3.12
9
+ License-File: LICENSE
10
+ Requires-Dist: gunicorn>=23.0.0
11
+ Requires-Dist: mindtrace-core
12
+ Requires-Dist: structlog>=24.4.0
13
+ Requires-Dist: uvicorn>=0.34.3
14
+ Dynamic: license-file
@@ -0,0 +1,15 @@
1
+ LICENSE
2
+ pyproject.toml
3
+ mindtrace/services/__init__.py
4
+ mindtrace/services/core/__init__.py
5
+ mindtrace/services/core/connection_manager.py
6
+ mindtrace/services/core/launcher.py
7
+ mindtrace/services/core/service.py
8
+ mindtrace/services/core/types.py
9
+ mindtrace/services/core/utils.py
10
+ mindtrace/services/sample/echo_service.py
11
+ mindtrace_services.egg-info/PKG-INFO
12
+ mindtrace_services.egg-info/SOURCES.txt
13
+ mindtrace_services.egg-info/dependency_links.txt
14
+ mindtrace_services.egg-info/requires.txt
15
+ mindtrace_services.egg-info/top_level.txt
@@ -0,0 +1,4 @@
1
+ gunicorn>=23.0.0
2
+ mindtrace-core
3
+ structlog>=24.4.0
4
+ uvicorn>=0.34.3
@@ -0,0 +1,22 @@
1
+ [project]
2
+ name = "mindtrace-services"
3
+ version = "0.1.0"
4
+ description = "Service layer for Mindtrace"
5
+ license = "Apache-2.0"
6
+ authors = [
7
+ {name = "Mindtrace Team"}
8
+ ]
9
+ classifiers = [
10
+ "Programming Language :: Python :: 3",
11
+ "Programming Language :: Python :: 3.12",
12
+ ]
13
+ dependencies = [
14
+ "gunicorn>=23.0.0",
15
+ "mindtrace-core",
16
+ "structlog>=24.4.0",
17
+ "uvicorn>=0.34.3",
18
+ ]
19
+
20
+ [build-system]
21
+ requires = ["setuptools"]
22
+ build-backend = "setuptools.build_meta"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+