ls-api-clients 0.3.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) 2023 LightSolver Internal
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,21 @@
1
+ Metadata-Version: 2.1
2
+ Name: ls-api-clients
3
+ Version: 0.3.0
4
+ Summary: A package for laser-mind clients
5
+ Author-email: Assaf Kalinski <assaf@lightsolver.com>
6
+ Project-URL: Homepage, https://lightsolver.com
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Operating System :: OS Independent
10
+ Requires-Python: >=3.8
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: urllib3==1.26.13
14
+ Requires-Dist: requests>=2.23
15
+ Requires-Dist: msgpack>=1.0.0
16
+ Requires-Dist: ls-cred-storage>=0.1.9
17
+ Requires-Dist: laser-mind-client-meta>=0.0.9
18
+
19
+ Lightsolver internal package.
20
+ API clients for logging into LightSolver's API servers
21
+ and for requesting tokens.
@@ -0,0 +1,3 @@
1
+ Lightsolver internal package.
2
+ API clients for logging into LightSolver's API servers
3
+ and for requesting tokens.
@@ -0,0 +1 @@
1
+ from ls_api_clients.ls_api_client import LSAPIClient
@@ -0,0 +1,248 @@
1
+ import os
2
+ import logging
3
+ import requests
4
+ import json
5
+ import time
6
+ import msgpack
7
+ from ls_cred_storage import LSCredStorage
8
+ from laser_mind_client_meta import MessageKeys
9
+
10
+
11
+ class LSAPIClient:
12
+
13
+ USER_KEY = 'user'
14
+ USER_ID_KEY = 'userId'
15
+ TIMESTAMP_KEY = 'timestamp'
16
+ SESSION_TOKEN_KEY = 'sessionToken'
17
+ ACCESS_TOKEN_KEY = 'accessToken'
18
+ MAX_TOKEN_RETENTION_TIME_SECS = 3500
19
+
20
+ SOLVER_REQUEST_HEADERS = {'accept' : 'application/octet-stream',
21
+ 'content-type' : 'application/octet-stream',
22
+ 'accept-encoding' : 'gzip, deflate, br'}
23
+
24
+ SOLUTION_REQUEST_HEADERS = {
25
+ 'accept' : 'application/msgpack',
26
+ 'content-type' : 'application/msgpack',
27
+ 'accept-encoding' : 'gzip, deflate, br'
28
+ }
29
+
30
+ URL_REQUEST_HEADERS = {
31
+ 'accept' : 'application/msgpack',
32
+ 'content-type' : 'application/msgpack',
33
+ 'accept-encoding' : 'gzip, deflate, br'
34
+ }
35
+
36
+ def __init__(self, username = None, password = None, printTiming = False, logLevel = logging.INFO, authEnabled = True):
37
+ self.LS_API_RUN_URL = os.environ['LS_API_RUN_URL'] if 'LS_API_RUN_URL' in os.environ else 'http://solve.lightsolver.com/api/v1/commands/run'
38
+ self.LS_API_RUN_SECURED_URL = os.environ['LS_API_RUN_SECURED_URL'] if 'LS_API_RUN_SECURED_URL' in os.environ else 'https://solve.lightsolver.com/api/v1/commands/run'
39
+ self.LS_API_GET_PRESIGNED_URL = os.environ['LS_API_GET_PRESIGNED_URL'] if 'LS_API_GET_PRESIGNED_URL' in os.environ else 'https://solve.lightsolver.com/api/v1/getposturl'
40
+ self.LS_AUTH_URL = os.environ['LS_AUTH_URL'] if 'LS_AUTH_URL' in os.environ else 'https://auth.devfront.lightsolver.com/authorize-solver-usage'
41
+ self.LS_REQUEST_URL = os.environ['LS_REQUEST_URL'] if 'LS_REQUEST_URL' in os.environ else 'https://solve.lightsolver.com/api/v1/getsolution'
42
+
43
+ logging.basicConfig(
44
+ filename="laser-mind.log",
45
+ level=logLevel,
46
+ format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %H:%M:%S')
47
+ self.printTiming = printTiming
48
+ self.authEnabled = authEnabled
49
+ if authEnabled:
50
+ if username == None or password == None:
51
+ raise ValueError("You must input a username and password when authREnabled = True")
52
+ self.username = username
53
+ self.password = password
54
+ self.credStorage = LSCredStorage()
55
+ token_dic = self.check_and_get_persisted_tokens() #TODO @markin is this duplication with check_is_token_valid() in refresh_tokens_if_needed?
56
+
57
+ if token_dic == None:
58
+ self.refresh_tokens_if_needed()
59
+ logging.info('Got new session/access tokens')
60
+ logging.info('LSAPIClient created,connection is authenticated and authorized')
61
+ else:
62
+ logging.info('LSAPIClient created, authentication disabled')
63
+
64
+ def msgpack_encode(self, x):
65
+ v = msgpack.packb(x)
66
+ return v
67
+
68
+ def msgpack_decode(self, x):
69
+ try:
70
+ v = msgpack.unpackb(x)
71
+ except Exception as e:
72
+ return None
73
+ return v
74
+
75
+ def refresh_tokens_if_needed(self):
76
+ if self.authEnabled and not self.check_is_token_valid():
77
+ newTokenDic = self.GetTokensFromServer()
78
+ logging.info(f'got tokens for user {self.username}')
79
+ self.credStorage.update_current_token(newTokenDic)
80
+ self.credStorage.store_token(self.username, newTokenDic)
81
+
82
+ def GetTokensFromServer(self):
83
+ data = {
84
+ 'user' : f'{self.username}',
85
+ 'password' : f'{self.password}'
86
+ }
87
+
88
+ headers = {
89
+ 'accept' : 'application/json',
90
+ 'content-type' : 'application/json',
91
+ }
92
+ req = requests.post(self.LS_AUTH_URL, headers=headers, data=json.dumps(data))
93
+ req.raise_for_status()
94
+ token = req.json()
95
+ token_dic = self.create_token_data_for_user(token)
96
+ return token_dic
97
+
98
+ def create_token_data_for_user(self, token):
99
+ dic = {
100
+ self.TIMESTAMP_KEY : time.time(),
101
+ self.USER_KEY : self.username,
102
+ self.SESSION_TOKEN_KEY : token[self.SESSION_TOKEN_KEY],
103
+ self.ACCESS_TOKEN_KEY : token[self.ACCESS_TOKEN_KEY],
104
+ self.USER_ID_KEY : token[self.USER_ID_KEY]
105
+ }
106
+ return dic
107
+
108
+ def check_and_get_persisted_tokens(self):
109
+ storedToken = self.credStorage.get_stored_token(self.username)
110
+ if storedToken != None:
111
+ if self.check_is_token_valid():
112
+ return storedToken
113
+ return None
114
+
115
+ def check_is_token_valid(self):
116
+ if self.credStorage.currentTokenDic != None:
117
+ return time.time() - self.credStorage.currentTokenDic[self.TIMESTAMP_KEY] < self.MAX_TOKEN_RETENTION_TIME_SECS
118
+ return False
119
+
120
+ def MakeDataForSolveRequest(self, commandName, param):
121
+ data = {
122
+ 'name' : commandName,
123
+ 'param' : param,
124
+ 'creationTime' : time.time()
125
+ }
126
+ if self.authEnabled:
127
+ data['username'] = self.credStorage.currentTokenDic[self.USER_KEY]
128
+ data['userId'] = self.credStorage.currentTokenDic[self.USER_ID_KEY]
129
+ data['sessionToken'] = self.credStorage.currentTokenDic[self.SESSION_TOKEN_KEY]
130
+ data['accessToken'] = self.credStorage.currentTokenDic[self.ACCESS_TOKEN_KEY]
131
+ return self.msgpack_encode(data)
132
+
133
+ def MakeDataForUploadRequest(self, toUpload):
134
+ data = {
135
+ 'param' : toUpload,
136
+ 'creationTime' : time.time()
137
+ }
138
+ if self.authEnabled:
139
+ data['username'] = self.credStorage.currentTokenDic[self.USER_KEY]
140
+ data['userId'] = self.credStorage.currentTokenDic[self.USER_ID_KEY]
141
+ data['sessionToken'] = self.credStorage.currentTokenDic[self.SESSION_TOKEN_KEY]
142
+ data['accessToken'] = self.credStorage.currentTokenDic[self.ACCESS_TOKEN_KEY]
143
+ return self.msgpack_encode(data)
144
+
145
+ def MakeDataForResultRequest(self, solutionId):
146
+ data = {
147
+ 'solId' : solutionId,
148
+ 'creationTime' : time.time(),
149
+ 'userId' : 0
150
+ }
151
+ if self.authEnabled:
152
+ data['username'] = self.credStorage.currentTokenDic[self.USER_KEY]
153
+ data['userId'] = self.credStorage.currentTokenDic[self.USER_ID_KEY]
154
+ data['sessionToken'] = self.credStorage.currentTokenDic[self.SESSION_TOKEN_KEY]
155
+ data['accessToken'] = self.credStorage.currentTokenDic[self.ACCESS_TOKEN_KEY]
156
+ return self.msgpack_encode(data)
157
+
158
+ def MakeDataForGetURLRequest(self, inputPath = None):
159
+ data = {
160
+ 'creationTime' : time.time()
161
+ }
162
+
163
+ if self.authEnabled:
164
+ data['userId'] = self.credStorage.currentTokenDic[self.USER_ID_KEY]
165
+ data['sessionToken'] = self.credStorage.currentTokenDic[self.SESSION_TOKEN_KEY]
166
+ data['accessToken'] = self.credStorage.currentTokenDic[self.ACCESS_TOKEN_KEY]
167
+
168
+ if inputPath != None:
169
+ data[MessageKeys.QUBO_INPUT_PATH] = inputPath
170
+
171
+ return self.msgpack_encode(data)
172
+
173
+ def ValidateResponse(self, response):
174
+ if MessageKeys.ERROR_KEY in response:
175
+ raise Exception(response[MessageKeys.ERROR_KEY])
176
+ return True
177
+
178
+ def SendCommandRequest(self, commandName, input, secured = True):
179
+ if self.authEnabled:
180
+ if not self.credStorage.is_cached_user(self.username):
181
+ raise SystemError("username doesn't match stored token, please reconnect LightSolver service")
182
+ self.refresh_tokens_if_needed()
183
+ if self.printTiming:
184
+ startTime = time.time()
185
+ data = self.MakeDataForSolveRequest(commandName, input)
186
+ headers = self.SOLVER_REQUEST_HEADERS
187
+ req_url = self.LS_API_RUN_SECURED_URL if secured else self.LS_API_RUN_URL
188
+ response = requests.post(url = req_url, headers = headers, data = data)
189
+ response.raise_for_status()
190
+ dicResponse = self.msgpack_decode(response._content)
191
+ self.ValidateResponse(dicResponse)
192
+ if self.printTiming:
193
+ totalTime = time.time() - startTime
194
+ return dicResponse
195
+
196
+ def SendResultRequest(self, solutionId, timestamp):
197
+ self.refresh_tokens_if_needed()
198
+ id_str = f'{solutionId}_{timestamp}'
199
+ logging.info(f"getting {id_str}")
200
+ if self.printTiming:
201
+ startTime = time.time()
202
+ data = self.MakeDataForResultRequest(id_str)
203
+ headers = self.SOLUTION_REQUEST_HEADERS
204
+ req_url = self.LS_REQUEST_URL
205
+ response = requests.post(url = req_url, headers = headers, data = data)
206
+ if self.printTiming:
207
+ totalTime = time.time() - startTime
208
+ if response.status_code == 404:
209
+ return None
210
+
211
+ response.raise_for_status()
212
+ dicResponse = self.msgpack_decode(response._content)
213
+
214
+ if not isinstance(dicResponse, dict):
215
+ raise Exception("response is not a dictionary!")
216
+ if MessageKeys.ERROR_KEY in dicResponse:
217
+ raise Exception(dicResponse[MessageKeys.ERROR_KEY])
218
+ if MessageKeys.WARNING_KEY in dicResponse:
219
+ logging.warning(f"Warning: solver encountered \"{dicResponse[MessageKeys.WARNING_KEY]}\"")
220
+ return dicResponse
221
+
222
+ def SendGetURLRequest(self, urlPath = None):
223
+ self.refresh_tokens_if_needed()
224
+ logging.info(f"getting url")
225
+ if self.printTiming:
226
+ startTime = time.time()
227
+ data = self.MakeDataForGetURLRequest(urlPath)
228
+ headers = self.URL_REQUEST_HEADERS
229
+ req_url = self.LS_API_GET_PRESIGNED_URL
230
+ response = requests.post(url = req_url, headers = headers, data = data)
231
+ if self.printTiming:
232
+ totalTime = time.time() - startTime
233
+ print(f"{totalTime=}")
234
+ if response.status_code == 404:
235
+ return None
236
+ response.raise_for_status()
237
+
238
+ return self.msgpack_decode(response._content)
239
+
240
+ def SendUploadRequest(self, toUpload, url):
241
+ payload = self.MakeDataForUploadRequest(toUpload)
242
+ response = requests.put(url, data=payload)
243
+ response.raise_for_status()
244
+
245
+ def upload_command_input(self, data, inputPath = None):
246
+ urlResponse = self.SendGetURLRequest(inputPath)
247
+ self.SendUploadRequest(data, urlResponse['url'])
248
+ return urlResponse['reqId']
@@ -0,0 +1,21 @@
1
+ Metadata-Version: 2.1
2
+ Name: ls-api-clients
3
+ Version: 0.3.0
4
+ Summary: A package for laser-mind clients
5
+ Author-email: Assaf Kalinski <assaf@lightsolver.com>
6
+ Project-URL: Homepage, https://lightsolver.com
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Operating System :: OS Independent
10
+ Requires-Python: >=3.8
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: urllib3==1.26.13
14
+ Requires-Dist: requests>=2.23
15
+ Requires-Dist: msgpack>=1.0.0
16
+ Requires-Dist: ls-cred-storage>=0.1.9
17
+ Requires-Dist: laser-mind-client-meta>=0.0.9
18
+
19
+ Lightsolver internal package.
20
+ API clients for logging into LightSolver's API servers
21
+ and for requesting tokens.
@@ -0,0 +1,10 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ ls_api_clients/__init__.py
5
+ ls_api_clients/ls_api_client.py
6
+ ls_api_clients.egg-info/PKG-INFO
7
+ ls_api_clients.egg-info/SOURCES.txt
8
+ ls_api_clients.egg-info/dependency_links.txt
9
+ ls_api_clients.egg-info/requires.txt
10
+ ls_api_clients.egg-info/top_level.txt
@@ -0,0 +1,5 @@
1
+ urllib3==1.26.13
2
+ requests>=2.23
3
+ msgpack>=1.0.0
4
+ ls-cred-storage>=0.1.9
5
+ laser-mind-client-meta>=0.0.9
@@ -0,0 +1 @@
1
+ ls_api_clients
@@ -0,0 +1,33 @@
1
+ [build-system]
2
+ requires = ["setuptools"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "ls-api-clients"
7
+ version = "0.3.0"
8
+ authors = [
9
+ { name="Assaf Kalinski", email="assaf@lightsolver.com" },
10
+ ]
11
+ description = "A package for laser-mind clients"
12
+ readme = "README.md"
13
+ requires-python = ">=3.8"
14
+ dependencies = [
15
+ 'urllib3==1.26.13',
16
+ 'requests>=2.23',
17
+ 'msgpack>=1.0.0',
18
+ 'ls-cred-storage>=0.1.9',
19
+ 'laser-mind-client-meta>=0.0.9'
20
+ ]
21
+ classifiers = [
22
+ "Programming Language :: Python :: 3",
23
+ "License :: OSI Approved :: MIT License",
24
+ "Operating System :: OS Independent",
25
+ ]
26
+
27
+ [project.urls]
28
+ "Homepage" = "https://lightsolver.com"
29
+
30
+
31
+ [tool.setuptools.packages.find]
32
+ include = ["ls_api_clients"]
33
+
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+