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

Lock when synchronization the state store #275

Merged
merged 5 commits into from
Mar 6, 2024
Merged
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
21 changes: 11 additions & 10 deletions cognite/extractorutils/statestore.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,11 +138,13 @@ def __init__(

self._deleted: List[str] = []

def start(self) -> None:
def start(self, initialize: bool = True) -> None:
"""
Start saving state periodically if save_interval is set.
This calls the synchronize method every save_interval seconds.
"""
if initialize and not self._initialized:
self.initialize()
if self.save_interval is not None:
self.thread.start()

Expand Down Expand Up @@ -416,13 +418,13 @@ def impl() -> None:
"""
Upload local state store to CDF
"""
self._cdf_client.raw.rows.insert(db_name=self.database, table_name=self.table, row=self._local_state)
# Create a copy of deleted to facilitate testing (mock library stores list, and as it changes, the
# assertions fail)
self._cdf_client.raw.rows.delete(
db_name=self.database, table_name=self.table, key=[k for k in self._deleted]
)
with self.lock:
self._cdf_client.raw.rows.insert(db_name=self.database, table_name=self.table, row=self._local_state)
# Create a copy of deleted to facilitate testing (mock library stores list, and as it changes, the
# assertions fail)
self._cdf_client.raw.rows.delete(
db_name=self.database, table_name=self.table, key=[k for k in self._deleted]
)
self._deleted.clear()

impl()
Expand Down Expand Up @@ -501,10 +503,9 @@ def synchronize(self) -> None:
"""
Save states to specified JSON file
"""
with open(self._file_path, "w") as f:
json.dump(self._local_state, f, cls=_DecimalEncoder)

with self.lock:
with open(self._file_path, "w") as f:
json.dump(self._local_state, f, cls=_DecimalEncoder)
self._deleted.clear()

def __enter__(self) -> "LocalStateStore":
Expand Down