Skip to content
This repository was archived by the owner on Apr 15, 2024. It is now read-only.

Commit 1cbeb0d

Browse files
committed
Add tests for new ttl
. Fix lock file
1 parent aec51de commit 1cbeb0d

File tree

12 files changed

+318
-728
lines changed

12 files changed

+318
-728
lines changed

Makefile

Lines changed: 5 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ clean:
1212

1313
dev.install:
1414
pip install poetry
15+
poetry self add "poetry-dynamic-versioning[plugin]"
1516
poetry install
1617

1718
ifdef ALPHA_BUILD
@@ -23,26 +24,13 @@ docker:
2324
docker build -t c12e/cortex-python .
2425

2526
build.alpha: clean
26-
python setup.py egg_info --tag-build a$(shell \
27-
curl https://pypi.org/pypi/${DISTRIBUTION_NAME}/json | \
28-
jq '[ \
29-
.releases | \
30-
to_entries[] | \
31-
.key | \
32-
select(. | contains("${DISTRIBUTION_VERSION}a")) | \
33-
ltrimstr("${DISTRIBUTION_VERSION}a") \
34-
] | \
35-
last // "0" | \
36-
tonumber + 1' \
37-
) sdist bdist_wheel
38-
27+
poetry version alpha
28+
poetry build
3929
build.release: clean
40-
python setup.py sdist bdist_wheel
30+
poetry build
4131

4232
dev.test:
43-
poetry run pylint --recursive=y cortex
44-
poetry run pytest --cache-clear --html=coverage/test-report.html --self-contained-html --cov=cortex/ --cov-report=html:coverage --cov-report=xml:coverage.xml --cov-report=term test/unit
45-
33+
poetry run tox -epython3.10
4634
test:
4735
poetry run tox -r # tox runs make dev.test internally
4836

README.md

Lines changed: 49 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -9,39 +9,56 @@ Refer to the Cortex documentation for details on how to use the library:
99
## Installation
1010

1111
To install:
12-
```
13-
> pip install cortex-python
12+
13+
```bash
14+
pip install cortex-python
1415
```
1516

1617
or from source code:
17-
```
18-
> git clone git@github.com:CognitiveScale/cortex-python.git
19-
> cd cortex-python
20-
> pip install -e .
18+
19+
```bash
20+
git clone git@github.com:CognitiveScale/cortex-python.git
21+
cd cortex-python
22+
pip install -e .
2123
```
2224

2325
To install the optional components:
26+
27+
When developing models using jupyter within notebooks
28+
29+
```bash
30+
poetry install cortex-python[models_dev]
2431
```
25-
> pip install cortex-python[viz]
26-
> pip install cortex-python[jupyter]
32+
33+
When using model SDK using jupyter within notebooks
34+
35+
```bash
36+
poetry install cortex-python[models_dev]
37+
```
38+
39+
When
40+
41+
```bash
42+
poetry install cortex-python[models_dev]
2743
```
2844

2945
## Development
3046

3147
### Setup
3248

3349
When developing, it's a best practice to work in a virtual environment. Create and activate a virtual environment:
34-
```
35-
> virtualenv --python=python3.10 _venv
36-
> source _venv/bin/activate
50+
51+
```bash
52+
poetry install
53+
poetry shell
3754
```
3855

3956
Install developer dependencies:
4057

41-
```
42-
> git clone git@github.com:CognitiveScale/cortex-python.git
43-
> cd cortex-python
44-
> make dev.install
58+
```bash
59+
git clone git@github.com:CognitiveScale/cortex-python.git
60+
cd cortex-python
61+
make dev.install
4562
```
4663

4764
Run Developer test and linting tasks:
@@ -84,33 +101,38 @@ After contributing to the library, and before you submit changes as a PR, please
84101
### Documentation
85102

86103
Activate your virtual environment:
87-
```
88-
> source _venv/bin/activate
104+
105+
```bash
106+
poetry shell
89107
```
90108

91109
Set up your environment, if you have not done so:
92-
```
93-
> make dev.install
110+
111+
```bash
112+
make dev.install
94113
```
95114

96115
The package documentation is built with Sphinx and generates versioned documentation for all tag matching the `release/X.Y.Z` pattern and for the `master` branch. To build the documentation:
97116

98-
```
99-
> make docs.multi
117+
```bash
118+
make docs.multi
100119
```
101120
The documentation will be rendered in HTML format under the `docs/_build/${VERSION}` directory.
102121

103122
### Pre-release to staging
104123

105124
1. Create and push an alpha release:
106-
```
107-
> make dev.push
108-
```
125+
126+
```bash
127+
make dev.push
128+
```
109129
This will build an alpha-tagged package.
110130
2. Merge `develop` to `staging` branch:
111-
```
112-
> make stage
113-
```
131+
132+
```bash
133+
make stage
134+
```
135+
114136
3. In GitHub, create a pull request from `staging` to `master`.
115137

116138

c12e-ci.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ builder:
33
ALPHA_BUILD: "${ALPHA_BUILD}"
44
image: python:3.11-bullseye
55
command: bash -cx 'apt-get update
6+
&& git config --system --add safe.directory '/work'
67
&& apt-get install -y jq
78
&& make dev.install
89
&& make test

cortex/__version__.py

Lines changed: 0 additions & 11 deletions
This file was deleted.

cortex/models.py

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import os
2121
from typing import Optional, Dict, Any
2222
from cortex.serviceconnector import _Client
23+
from cortex.utils import generate_token
2324

2425
try:
2526
import mlflow
@@ -42,32 +43,27 @@ class ModelClient(_Client):
4243
Client for model registry, this class requires the `models_sdk` extras to be installed
4344
"""
4445

45-
def __init__(self, *args, **kwargs):
46-
super().__init__(*args, **kwargs)
47-
# Setup model registry by default
48-
if mlflow is not None:
49-
self._setup_model_client()
50-
51-
def _setup_model_client(self):
46+
def _setup_model_client(self, verify_ssl_cert=True, ttl="2h"):
5247
# Generate a JWT, this call stores the JWT in `_serviceconnector.jwt` ( meh )
53-
self._serviceconnector._construct_headers({}) # pylint: disable=protected-access
54-
48+
token = generate_token(self._serviceconnector._config, verify_ssl_cert=verify_ssl_cert, validity=ttl) # pylint: disable=protected-access
5549
mlflow.set_tracking_uri(self._serviceconnector.url)
5650
os.environ['MLFLOW_TRACKING_URI'] = self._serviceconnector.url
57-
os.environ['MLFLOW_TRACKING_TOKEN'] = self._serviceconnector.token
51+
os.environ['MLFLOW_TRACKING_TOKEN'] = token
5852
# detect cortex client setting to avoid invalid SSL cert errors
5953
# os.environ['MLFLOW_TRACKING_TOKEN']='true'
6054
# os.environ['MLFLOW_TRACKING_CLIENT_CERT_PATH']=
6155
# Need api to fetch serverside userid..
6256
# os.environ['MLFLOW_TRACKING_USERNAME']=_Client.???
6357

64-
def login(self):
58+
59+
def login(self, ttl: Optional[str|int]='2h'):
6560
"""
6661
Configure connection settings for model registry.
67-
This also setup by `Cortex.client()`
62+
:param ttl: Time to live, DEFAULT: 2h
63+
:param project: Project name to use for experiments
6864
"""
6965
check_installed()
70-
self._setup_model_client()
66+
self._setup_model_client(ttl=ttl)
7167
print("Configuring connection for model registry")
7268

7369
def create_experiment(self,

cortex/serviceconnector.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,20 +21,18 @@
2121
import requests
2222
from requests.adapters import HTTPAdapter
2323
from urllib3.util.retry import Retry
24-
24+
from importlib_metadata import metadata
2525
from .constant import VERSION
26-
from .__version__ import __version__, __title__
27-
2826
from .utils import get_logger, get_cortex_profile, verify_JWT, generate_token
2927
from .utils import raise_for_status_with_detail
3028

3129
log = get_logger(__name__)
3230

3331
JSONType = Union[str, int, float, bool, None, Dict[str, Any], List[Any]]
3432
T = TypeVar("T", bound="_Client")
35-
33+
package_meta = metadata('cortex-python')
3634
userAgent = (
37-
f"{__title__}/{__version__} ({sys.platform};"
35+
f"{package_meta.get('Name')}/{package_meta.get('Version')} ({sys.platform};"
3836
f"{platform.architecture()[0]}; {platform.release()})"
3937
)
4038

cortex/utils.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,13 @@
2020
import logging
2121
import urllib.parse
2222
from collections import namedtuple
23-
from datetime import datetime, timedelta, timezone
23+
from datetime import datetime, timezone
2424
from pathlib import Path
2525
from typing import Union
2626

2727
import python_jwt as py_jwt
2828
import jwcrypto.jwk as jwkLib
29+
from pytimeparse2 import parse
2930
from requests.exceptions import HTTPError
3031
from requests import request
3132
from .exceptions import BadTokenException, AuthenticationHeaderError
@@ -152,14 +153,15 @@ def _get_fabric_server_ts(config: dict, verify_ssl_cert: Union[bool, str]=True):
152153
return _get_fabric_info(config, verify_ssl_cert).get("serverTs")
153154

154155

155-
def generate_token(config, verify_ssl_cert: Union[bool, str]=True, validity=2):
156+
def generate_token(config, verify_ssl_cert: Union[bool, str, None]=True, validity: Union[int, str, None]='2m'):
156157
"""
157158
Use the Personal Access Token (JWK) obtained from Cortex's console
158159
to generate JWTs to access cortex services..
159160
160161
:param verify_ssl_cert: (optional) Either a boolean, in which case it controls whether we verify
161162
the server's TLS certificate, or a string, in which case it must be a path
162163
to a CA bundle to use. Defaults to ``True``.
164+
:param validity: (optional) Token validity duration. Defaults to `2m`
163165
"""
164166
try:
165167
server_ts = int(
@@ -174,8 +176,7 @@ def generate_token(config, verify_ssl_cert: Union[bool, str]=True, validity=2):
174176
}
175177

176178
server_ts_dt = datetime.fromtimestamp(server_ts, tz=timezone.utc)
177-
178-
expiry = server_ts_dt + timedelta(minutes=validity)
179+
expiry = server_ts_dt + parse(validity, as_timedelta=True)
179180

180181
token = py_jwt.generate_jwt(
181182
claims=token_payload,

0 commit comments

Comments
 (0)