metis-platform-sdk 0.1.1__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.
- metis_platform_sdk-0.1.1/LICENSE +202 -0
- metis_platform_sdk-0.1.1/PKG-INFO +47 -0
- metis_platform_sdk-0.1.1/README.md +30 -0
- metis_platform_sdk-0.1.1/pyproject.toml +25 -0
- metis_platform_sdk-0.1.1/setup.cfg +4 -0
- metis_platform_sdk-0.1.1/src/metis_platform_sdk.egg-info/PKG-INFO +47 -0
- metis_platform_sdk-0.1.1/src/metis_platform_sdk.egg-info/SOURCES.txt +10 -0
- metis_platform_sdk-0.1.1/src/metis_platform_sdk.egg-info/dependency_links.txt +1 -0
- metis_platform_sdk-0.1.1/src/metis_platform_sdk.egg-info/top_level.txt +1 -0
- metis_platform_sdk-0.1.1/src/metis_sdk/__init__.py +5 -0
- metis_platform_sdk-0.1.1/src/metis_sdk/client.py +222 -0
- metis_platform_sdk-0.1.1/tests/test_sdk.py +78 -0
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: metis-platform-sdk
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Metis application runtime SDK
|
|
5
|
+
Author: Vector Metis
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Classifier: Development Status :: 3 - Alpha
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
13
|
+
Requires-Python: >=3.10
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# Metis Python SDK
|
|
19
|
+
|
|
20
|
+
Metis 应用后端 SDK,用于读取统一应用身份、可信请求上下文、声明的 Web/Service 依赖,以及模型和对象存储配置。
|
|
21
|
+
|
|
22
|
+
## 安装
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
python -m pip install metis-platform-sdk
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
from metis_sdk import from_env
|
|
30
|
+
|
|
31
|
+
client = from_env()
|
|
32
|
+
for dependency in client.list_dependencies():
|
|
33
|
+
print(dependency["app_id"])
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
运行环境必须提供 `METIS_PLATFORM_ENDPOINT`、`METIS_APP_ID` 和 `METIS_APP_TOKEN`。本地测试可以向 `Client` 显式传入配置。SDK 不创建厂商模型/存储客户端,也不隐藏重试。
|
|
37
|
+
|
|
38
|
+
## 开发
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
python -m pytest
|
|
42
|
+
python -m build
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## 许可证
|
|
46
|
+
|
|
47
|
+
Apache-2.0,见 [LICENSE](LICENSE)。
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# Metis Python SDK
|
|
2
|
+
|
|
3
|
+
Metis 应用后端 SDK,用于读取统一应用身份、可信请求上下文、声明的 Web/Service 依赖,以及模型和对象存储配置。
|
|
4
|
+
|
|
5
|
+
## 安装
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
python -m pip install metis-platform-sdk
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
```python
|
|
12
|
+
from metis_sdk import from_env
|
|
13
|
+
|
|
14
|
+
client = from_env()
|
|
15
|
+
for dependency in client.list_dependencies():
|
|
16
|
+
print(dependency["app_id"])
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
运行环境必须提供 `METIS_PLATFORM_ENDPOINT`、`METIS_APP_ID` 和 `METIS_APP_TOKEN`。本地测试可以向 `Client` 显式传入配置。SDK 不创建厂商模型/存储客户端,也不隐藏重试。
|
|
20
|
+
|
|
21
|
+
## 开发
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
python -m pytest
|
|
25
|
+
python -m build
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## 许可证
|
|
29
|
+
|
|
30
|
+
Apache-2.0,见 [LICENSE](LICENSE)。
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=75"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "metis-platform-sdk"
|
|
7
|
+
version = "0.1.1"
|
|
8
|
+
description = "Metis application runtime SDK"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "Apache-2.0"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.10"
|
|
13
|
+
authors = [{name = "Vector Metis"}]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 3 - Alpha",
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Programming Language :: Python :: 3.10",
|
|
18
|
+
"Programming Language :: Python :: 3.11",
|
|
19
|
+
"Programming Language :: Python :: 3.12",
|
|
20
|
+
"Programming Language :: Python :: 3.13",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
[tool.pytest.ini_options]
|
|
24
|
+
testpaths = ["tests"]
|
|
25
|
+
pythonpath = ["src"]
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: metis-platform-sdk
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Metis application runtime SDK
|
|
5
|
+
Author: Vector Metis
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Classifier: Development Status :: 3 - Alpha
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
13
|
+
Requires-Python: >=3.10
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# Metis Python SDK
|
|
19
|
+
|
|
20
|
+
Metis 应用后端 SDK,用于读取统一应用身份、可信请求上下文、声明的 Web/Service 依赖,以及模型和对象存储配置。
|
|
21
|
+
|
|
22
|
+
## 安装
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
python -m pip install metis-platform-sdk
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
from metis_sdk import from_env
|
|
30
|
+
|
|
31
|
+
client = from_env()
|
|
32
|
+
for dependency in client.list_dependencies():
|
|
33
|
+
print(dependency["app_id"])
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
运行环境必须提供 `METIS_PLATFORM_ENDPOINT`、`METIS_APP_ID` 和 `METIS_APP_TOKEN`。本地测试可以向 `Client` 显式传入配置。SDK 不创建厂商模型/存储客户端,也不隐藏重试。
|
|
37
|
+
|
|
38
|
+
## 开发
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
python -m pytest
|
|
42
|
+
python -m build
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## 许可证
|
|
46
|
+
|
|
47
|
+
Apache-2.0,见 [LICENSE](LICENSE)。
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/metis_platform_sdk.egg-info/PKG-INFO
|
|
5
|
+
src/metis_platform_sdk.egg-info/SOURCES.txt
|
|
6
|
+
src/metis_platform_sdk.egg-info/dependency_links.txt
|
|
7
|
+
src/metis_platform_sdk.egg-info/top_level.txt
|
|
8
|
+
src/metis_sdk/__init__.py
|
|
9
|
+
src/metis_sdk/client.py
|
|
10
|
+
tests/test_sdk.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
metis_sdk
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
"""只负责应用身份、依赖发现和能力环境解析的最小客户端。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import threading
|
|
9
|
+
import time
|
|
10
|
+
import urllib.error
|
|
11
|
+
import urllib.parse
|
|
12
|
+
import urllib.request
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from typing import Any, Mapping
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class MetisError(Exception):
|
|
18
|
+
"""保存平台稳定错误 reason 与 HTTP 状态码。"""
|
|
19
|
+
|
|
20
|
+
def __init__(self, reason: str, message: str, status: int = 0) -> None:
|
|
21
|
+
super().__init__(message)
|
|
22
|
+
self.reason = reason
|
|
23
|
+
self.status = status
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True)
|
|
27
|
+
class RequestContext:
|
|
28
|
+
"""平台入口覆盖写入的可信调用上下文。"""
|
|
29
|
+
|
|
30
|
+
tenant_id: str = ""
|
|
31
|
+
user_id: str = ""
|
|
32
|
+
role: str = ""
|
|
33
|
+
source_app_id: str = ""
|
|
34
|
+
actor_type: str = ""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def context_from_headers(headers: Mapping[str, str]) -> RequestContext:
|
|
38
|
+
"""只从大小写不敏感的 HTTP headers 读取可信上下文。"""
|
|
39
|
+
|
|
40
|
+
normalized = {key.lower(): value for key, value in headers.items()}
|
|
41
|
+
return RequestContext(
|
|
42
|
+
tenant_id=normalized.get("x-platform-tenant-id", ""),
|
|
43
|
+
user_id=normalized.get("x-platform-user-id", ""),
|
|
44
|
+
role=normalized.get("x-platform-role", ""),
|
|
45
|
+
source_app_id=normalized.get("x-platform-source-app-id", ""),
|
|
46
|
+
actor_type=normalized.get("x-platform-actor-type", ""),
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def context_from_request(request: Any) -> RequestContext:
|
|
51
|
+
"""从具有 headers 属性的框架请求读取可信上下文。"""
|
|
52
|
+
|
|
53
|
+
return context_from_headers(request.headers)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class Client:
|
|
57
|
+
"""调用 Runtime API,并对成功发现结果缓存 30 秒。"""
|
|
58
|
+
|
|
59
|
+
def __init__(
|
|
60
|
+
self,
|
|
61
|
+
platform_endpoint: str | None = None,
|
|
62
|
+
app_id: str | None = None,
|
|
63
|
+
app_token: str | None = None,
|
|
64
|
+
*,
|
|
65
|
+
environment: Mapping[str, str] | None = None,
|
|
66
|
+
cache_ttl: float = 30.0,
|
|
67
|
+
opener: Any = None,
|
|
68
|
+
) -> None:
|
|
69
|
+
env = dict(os.environ if environment is None else environment)
|
|
70
|
+
self.platform_endpoint = (platform_endpoint or env.get("METIS_PLATFORM_ENDPOINT", "")).rstrip("/")
|
|
71
|
+
self.app_id = app_id or env.get("METIS_APP_ID", "")
|
|
72
|
+
self.app_token = app_token or env.get("METIS_APP_TOKEN", "")
|
|
73
|
+
parsed = urllib.parse.urlparse(self.platform_endpoint)
|
|
74
|
+
if not self.platform_endpoint or not self.app_id or not self.app_token:
|
|
75
|
+
raise MetisError("MISSING_CONFIG", "METIS_PLATFORM_ENDPOINT, METIS_APP_ID and METIS_APP_TOKEN are required")
|
|
76
|
+
if parsed.scheme not in ("http", "https") or not parsed.netloc:
|
|
77
|
+
raise MetisError("INVALID_CONFIG", "METIS_PLATFORM_ENDPOINT must be an absolute HTTP URL")
|
|
78
|
+
if cache_ttl < 0:
|
|
79
|
+
raise MetisError("INVALID_CONFIG", "cache_ttl cannot be negative")
|
|
80
|
+
self.environment = env
|
|
81
|
+
self.cache_ttl = cache_ttl
|
|
82
|
+
self.opener = opener or urllib.request.urlopen
|
|
83
|
+
self._cache: dict[str, tuple[float, Any]] = {}
|
|
84
|
+
self._lock = threading.Lock()
|
|
85
|
+
|
|
86
|
+
def list_dependencies(self, refresh: bool = False) -> list[dict[str, Any]]:
|
|
87
|
+
"""返回 manifest 声明顺序中的全部直接依赖。"""
|
|
88
|
+
|
|
89
|
+
return self._get(self._path("dependencies"), refresh).get("dependencies", [])
|
|
90
|
+
|
|
91
|
+
def dependency(self, selector: str, refresh: bool = False) -> dict[str, Any]:
|
|
92
|
+
"""通过 alias 或应用 ID 返回一个直接依赖。"""
|
|
93
|
+
|
|
94
|
+
return self._get(self._path("dependencies", selector), refresh)
|
|
95
|
+
|
|
96
|
+
def web_url(self, selector: str, path: str = "") -> str:
|
|
97
|
+
"""返回 Web 依赖的绝对同源入口地址。"""
|
|
98
|
+
|
|
99
|
+
if "://" in path or path.startswith("//"):
|
|
100
|
+
raise MetisError("INVALID_CONFIG", "dependency path must be relative")
|
|
101
|
+
parsed = urllib.parse.urlsplit(path)
|
|
102
|
+
decoded_path = urllib.parse.unquote(parsed.path)
|
|
103
|
+
if "\\" in decoded_path or any(part in (".", "..") for part in decoded_path.split("/")):
|
|
104
|
+
raise MetisError("INVALID_CONFIG", "dependency path must stay within the application root")
|
|
105
|
+
dependency = self.dependency(selector)
|
|
106
|
+
if not dependency.get("available") or not dependency.get("webBasePath"):
|
|
107
|
+
raise MetisError("DEPENDENCY_UNAVAILABLE", "web dependency is unavailable", 503)
|
|
108
|
+
base = dependency["webBasePath"].rstrip("/") + "/" + parsed.path.lstrip("/")
|
|
109
|
+
return urllib.parse.urljoin(self.platform_endpoint + "/", base.lstrip("/")) + (("?" + parsed.query) if parsed.query else "")
|
|
110
|
+
|
|
111
|
+
def new_web_request(self, selector: str, method: str, path: str = "", data: bytes | None = None) -> urllib.request.Request:
|
|
112
|
+
"""创建携带应用 token 的请求,不自动复制代表用户头。"""
|
|
113
|
+
|
|
114
|
+
return urllib.request.Request(self.web_url(selector, path), data=data, method=method, headers={"Authorization": "Bearer " + self.app_token})
|
|
115
|
+
|
|
116
|
+
def service_endpoint(self, selector: str, endpoint_name: str, refresh: bool = False) -> dict[str, Any]:
|
|
117
|
+
"""返回 Service 依赖的具名 Master 代理地址。"""
|
|
118
|
+
|
|
119
|
+
return self._get(self._path("dependencies", selector, "endpoints", endpoint_name), refresh)
|
|
120
|
+
|
|
121
|
+
def model(self, slot: str) -> dict[str, Any]:
|
|
122
|
+
"""解析模型 slot 配置,不创建厂商客户端。"""
|
|
123
|
+
|
|
124
|
+
parts = slot.split(".")
|
|
125
|
+
if len(parts) != 2 or parts[0] not in ("llm", "embedding", "rerank") or re.fullmatch(r"[0-9]+", parts[1]) is None:
|
|
126
|
+
raise MetisError("INVALID_CONFIG", f"invalid model slot {slot}")
|
|
127
|
+
prefix = f"METIS_{parts[0].upper()}_{parts[1]}_"
|
|
128
|
+
values = {name.removeprefix(prefix): value for name, value in self.environment.items() if name.startswith(prefix)}
|
|
129
|
+
if not values.get("ENDPOINT") or not values.get("MODEL") or not values.get("API_KEY"):
|
|
130
|
+
raise MetisError("MISSING_CONFIG", f"model slot {slot} is incomplete")
|
|
131
|
+
return {"endpoint": values["ENDPOINT"], "model": values["MODEL"], "api_key": values["API_KEY"], "values": values}
|
|
132
|
+
|
|
133
|
+
def object_storage(self) -> dict[str, Any]:
|
|
134
|
+
"""解析应用 S3 配置,不连接存储或刷新凭据。"""
|
|
135
|
+
|
|
136
|
+
get = lambda name: self.environment.get(name, "")
|
|
137
|
+
result = {"endpoint": get("METIS_S3_ENDPOINT"), "region": get("METIS_S3_REGION"), "access_key": get("METIS_S3_ACCESS_KEY"), "secret_key": get("METIS_S3_SECRET_KEY"), "bucket": get("METIS_S3_BUCKET")}
|
|
138
|
+
if not result["endpoint"] or not result["access_key"] or not result["secret_key"] or not result["bucket"]:
|
|
139
|
+
raise MetisError("MISSING_CONFIG", "object storage config is incomplete")
|
|
140
|
+
try:
|
|
141
|
+
shared = json.loads(get("METIS_S3_SHARED_BUCKETS") or "[]")
|
|
142
|
+
except json.JSONDecodeError as error:
|
|
143
|
+
raise MetisError("INVALID_CONFIG", "METIS_S3_SHARED_BUCKETS must be a JSON string array") from error
|
|
144
|
+
if not isinstance(shared, list) or not all(isinstance(item, str) for item in shared):
|
|
145
|
+
raise MetisError("INVALID_CONFIG", "METIS_S3_SHARED_BUCKETS must be a JSON string array")
|
|
146
|
+
result["shared_buckets"] = shared
|
|
147
|
+
return result
|
|
148
|
+
|
|
149
|
+
def application(self) -> dict[str, str]:
|
|
150
|
+
"""返回当前安装的非敏感身份事实。"""
|
|
151
|
+
|
|
152
|
+
return {
|
|
153
|
+
"id": self.app_id,
|
|
154
|
+
"name": self.environment.get("METIS_APP_NAME", ""),
|
|
155
|
+
"version": self.environment.get("METIS_APP_VERSION", ""),
|
|
156
|
+
"platform_endpoint": self.platform_endpoint,
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
def setting(self, key: str) -> str:
|
|
160
|
+
"""按 manifest 原始 key 读取已注入设置。"""
|
|
161
|
+
|
|
162
|
+
if not key.strip():
|
|
163
|
+
raise MetisError("INVALID_CONFIG", "setting key is required")
|
|
164
|
+
name = "METIS_SETTING_" + re.sub(r"[-. ]", "_", key.strip().upper())
|
|
165
|
+
if name not in self.environment:
|
|
166
|
+
raise MetisError("MISSING_CONFIG", f"setting {key!r} is not injected")
|
|
167
|
+
return self.environment[name]
|
|
168
|
+
|
|
169
|
+
def entry_port(self) -> int:
|
|
170
|
+
"""返回 Web 应用的 Worker 本地端口。"""
|
|
171
|
+
|
|
172
|
+
return self._port("METIS_ENTRY_PORT")
|
|
173
|
+
|
|
174
|
+
def endpoint_port(self, name: str) -> int:
|
|
175
|
+
"""返回 Service endpoint 的 Worker 本地端口。"""
|
|
176
|
+
|
|
177
|
+
if not name.strip():
|
|
178
|
+
raise MetisError("INVALID_CONFIG", "endpoint name is required")
|
|
179
|
+
return self._port("METIS_ENDPOINT_" + name.strip().upper().replace("-", "_") + "_PORT")
|
|
180
|
+
|
|
181
|
+
def _port(self, name: str) -> int:
|
|
182
|
+
try:
|
|
183
|
+
port = int(self.environment.get(name, ""))
|
|
184
|
+
except ValueError as error:
|
|
185
|
+
raise MetisError("MISSING_CONFIG", f"{name} is not a valid port") from error
|
|
186
|
+
if not 1 <= port <= 65535:
|
|
187
|
+
raise MetisError("MISSING_CONFIG", f"{name} is not a valid port")
|
|
188
|
+
return port
|
|
189
|
+
|
|
190
|
+
def _path(self, *parts: str) -> str:
|
|
191
|
+
encoded = "/".join(urllib.parse.quote(part.strip(), safe="") for part in parts)
|
|
192
|
+
return f"/api/runtime/v1/apps/{urllib.parse.quote(self.app_id, safe='')}/{encoded}"
|
|
193
|
+
|
|
194
|
+
def _get(self, path: str, refresh: bool) -> Any:
|
|
195
|
+
now = time.monotonic()
|
|
196
|
+
with self._lock:
|
|
197
|
+
cached = self._cache.get(path)
|
|
198
|
+
if not refresh and cached and cached[0] > now:
|
|
199
|
+
return cached[1]
|
|
200
|
+
request = urllib.request.Request(self.platform_endpoint + path, headers={"Authorization": "Bearer " + self.app_token})
|
|
201
|
+
try:
|
|
202
|
+
with self.opener(request) as response:
|
|
203
|
+
try:
|
|
204
|
+
value = json.load(response)
|
|
205
|
+
except (json.JSONDecodeError, UnicodeDecodeError) as error:
|
|
206
|
+
raise MetisError("UPSTREAM_FAILURE", "runtime response is invalid", 502) from error
|
|
207
|
+
except urllib.error.HTTPError as error:
|
|
208
|
+
try:
|
|
209
|
+
payload = json.load(error)
|
|
210
|
+
except (json.JSONDecodeError, UnicodeDecodeError):
|
|
211
|
+
payload = {}
|
|
212
|
+
raise MetisError(payload.get("reason", "UPSTREAM_FAILURE"), payload.get("message", "runtime request failed"), error.code) from error
|
|
213
|
+
if self.cache_ttl > 0:
|
|
214
|
+
with self._lock:
|
|
215
|
+
self._cache[path] = (time.monotonic() + self.cache_ttl, value)
|
|
216
|
+
return value
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def from_env() -> Client:
|
|
220
|
+
"""从进程环境创建客户端。"""
|
|
221
|
+
|
|
222
|
+
return Client()
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import io
|
|
2
|
+
import json
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
|
|
7
|
+
from metis_sdk import Client, MetisError, context_from_headers
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
FIXTURE = json.loads((Path(__file__).parents[1] / "testdata" / "runtime.json").read_text())
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class Response(io.BytesIO):
|
|
14
|
+
def __enter__(self):
|
|
15
|
+
return self
|
|
16
|
+
|
|
17
|
+
def __exit__(self, *_):
|
|
18
|
+
self.close()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def test_shared_contract_cache_refresh_and_config():
|
|
22
|
+
calls = []
|
|
23
|
+
|
|
24
|
+
def open_request(request):
|
|
25
|
+
calls.append(request.full_url)
|
|
26
|
+
payload = FIXTURE["endpoint"] if request.full_url.endswith("/endpoints/database") else FIXTURE["dependencies"]
|
|
27
|
+
return Response(json.dumps(payload).encode())
|
|
28
|
+
|
|
29
|
+
client = Client(environment=FIXTURE["environment"], opener=open_request)
|
|
30
|
+
assert client.list_dependencies()[0]["alias"] == "ui"
|
|
31
|
+
client.list_dependencies()
|
|
32
|
+
assert len(calls) == 1
|
|
33
|
+
client.list_dependencies(refresh=True)
|
|
34
|
+
assert len(calls) == 2
|
|
35
|
+
assert client.service_endpoint("data", "database")["port"] == 31001
|
|
36
|
+
assert client.model("llm.0")["model"] == "example-chat"
|
|
37
|
+
assert client.object_storage()["shared_buckets"] == ["shared-assets"]
|
|
38
|
+
assert context_from_headers(FIXTURE["trustedHeaders"]).tenant_id == "42"
|
|
39
|
+
|
|
40
|
+
for path in ("../admin", "%2e%2e/admin", "..\\admin"):
|
|
41
|
+
with pytest.raises(MetisError) as path_error:
|
|
42
|
+
client.web_url("ui", path)
|
|
43
|
+
assert path_error.value.reason == "INVALID_CONFIG"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def test_explicit_local_config_and_missing_config():
|
|
47
|
+
client = Client("http://localhost:80", "local-app", "token", environment={})
|
|
48
|
+
assert client.app_id == "local-app"
|
|
49
|
+
with pytest.raises(MetisError, match="required"):
|
|
50
|
+
Client(environment={})
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def test_invalid_runtime_and_capability_values_use_stable_errors():
|
|
54
|
+
def open_request(_request):
|
|
55
|
+
return Response(b"gateway failed")
|
|
56
|
+
|
|
57
|
+
client = Client(
|
|
58
|
+
"http://metis.internal",
|
|
59
|
+
"caller-a7x2m",
|
|
60
|
+
"token",
|
|
61
|
+
opener=open_request,
|
|
62
|
+
environment={
|
|
63
|
+
"METIS_S3_ENDPOINT": "http://silo.internal",
|
|
64
|
+
"METIS_S3_ACCESS_KEY": "key",
|
|
65
|
+
"METIS_S3_SECRET_KEY": "secret",
|
|
66
|
+
"METIS_S3_BUCKET": "bucket",
|
|
67
|
+
"METIS_S3_SHARED_BUCKETS": "null",
|
|
68
|
+
},
|
|
69
|
+
)
|
|
70
|
+
with pytest.raises(MetisError) as runtime_error:
|
|
71
|
+
client.list_dependencies()
|
|
72
|
+
assert runtime_error.value.reason == "UPSTREAM_FAILURE"
|
|
73
|
+
with pytest.raises(MetisError) as model_error:
|
|
74
|
+
client.model("llm.-1")
|
|
75
|
+
assert model_error.value.reason == "INVALID_CONFIG"
|
|
76
|
+
with pytest.raises(MetisError) as storage_error:
|
|
77
|
+
client.object_storage()
|
|
78
|
+
assert storage_error.value.reason == "INVALID_CONFIG"
|