Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added context manager for stores #258

Merged
merged 9 commits into from
Aug 26, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion requirements-docs.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
mkdocs==1.1.2
mkdocs-material==5.5.7
mkdocs-material==5.5.8
mkdocs-minify-plugin==0.3.0
mkdocstrings==0.13.0
pymdown-extensions==8.0
6 changes: 3 additions & 3 deletions requirements-testing.txt
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
pre-commit==2.6.0
pre-commit==2.7.1
pytest==6.0.1
pytest-asyncio==0.14.0
pytest-cov==2.10.1
pytest-mock==3.2.0
pytest-mock==3.3.0
moto==1.3.14
pycodestyle==2.6.0
pydocstyle==5.0.2
pydocstyle==5.1.0
flake8==3.8.3
mypy==0.782
mypy-extensions==0.4.3
7 changes: 7 additions & 0 deletions src/maggma/core/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,13 @@ def __setstate__(self, d):
d = MontyDecoder().process_decoded(d)
self.__init__(**d)

def __enter__(self):
self.connect()
return self

def __exit__(self, exception_type, exception_value, traceback):
self.close()


class StoreError(Exception):
""" General Store-related error """
Expand Down
14 changes: 12 additions & 2 deletions src/maggma/stores/aws.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import zlib
from concurrent.futures import wait
from concurrent.futures.thread import ThreadPoolExecutor
import warnings
from typing import Any, Dict, Iterator, List, Optional, Tuple, Union

import msgpack # type: ignore
Expand Down Expand Up @@ -39,6 +40,7 @@ def __init__(
endpoint_url: str = None,
sub_dir: str = None,
s3_workers: int = 1,
key: str = "task_id",
**kwargs,
):
"""
Expand Down Expand Up @@ -66,10 +68,18 @@ def __init__(
self.s3_bucket = None # type: Any
self.s3_workers = s3_workers
# Force the key to be the same as the index
assert isinstance(
index.key, str
), "Since we are using the key as a file name in S3, they key must be a string"
if key != index.key:
warnings.warn(
f'The desired S3Store key "{key}" does not match the index key "{index.key},"'
"the index key will be used",
UserWarning,
)
kwargs["key"] = str(index.key)

self._thread_local = threading.local()

super(S3Store, self).__init__(**kwargs)

def name(self) -> str:
Expand Down Expand Up @@ -279,7 +289,7 @@ def update(self, docs: Union[List[Dict], Dict], key: Union[List, str, None] = No
for sdoc in fs:
search_docs.append(sdoc.result())
# Use store's update to remove key clashes
self.index.update(search_docs)
self.index.update(search_docs, key=self.key)

def get_bucket(self):
if threading.current_thread().name == "MainThread":
Expand Down
22 changes: 19 additions & 3 deletions tests/stores/test_aws.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,13 +63,30 @@ def s3store_multi():
conn = boto3.client("s3")
conn.create_bucket(Bucket="bucket1")

index = MemoryStore("index'")
index = MemoryStore("index")
store = S3Store(index, "bucket1", s3_workers=4)
store.connect()

yield store


def test_keys():
with mock_s3():
conn = boto3.client("s3")
conn.create_bucket(Bucket="bucket1")
index = MemoryStore("index", key=1)
with pytest.raises(AssertionError, match=r"Since we are.*"):
store = S3Store(index, "bucket1", s3_workers=4, key=1)
index = MemoryStore("index", key="key1")
with pytest.warns(UserWarning, match=r"The desired S3Store.*$"):
store = S3Store(index, "bucket1", s3_workers=4, key="key2")
store.connect()
store.update({"key1": "mp-1", "data": "1234"})
with pytest.raises(KeyError):
store.update({"key2": "mp-2", "data": "1234"})
assert store.key == store.index.key == "key1"


def test_multi_update(s3store, s3store_multi):
data = [{"task_id": str(j), "data": "DATA"} for j in range(32)]

Expand Down Expand Up @@ -137,8 +154,7 @@ def tests_msonable_read_write(s3store):
def test_remove(s3store):
s3store.update([{"task_id": "mp-2", "data": "asd"}])
s3store.update([{"task_id": "mp-4", "data": "asd"}])
s3store.update([{"task_id": "mp-5", "data": "aaa"}])

s3store.update({"task_id": "mp-5", "data": "aaa"})
assert s3store.query_one({"task_id": "mp-2"}) is not None
assert s3store.query_one({"task_id": "mp-4"}) is not None

Expand Down