Skip to content

Commit

Permalink
Used a proper IntEnum class for the sqlite threading mode using for c…
Browse files Browse the repository at this point in the history
…aching.
  • Loading branch information
canismarko committed Feb 21, 2024
1 parent b3fe529 commit 0d1e8ff
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
7 changes: 4 additions & 3 deletions tiled/_tests/test_client_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from ..adapters.array import ArrayAdapter
from ..adapters.mapping import MapAdapter
from ..client import Context, from_context, record_history
from ..client.cache import Cache, CachedResponse, with_thread_lock
from ..client.cache import Cache, CachedResponse, ThreadingMode, with_thread_lock
from ..server.app import build_app

tree = MapAdapter(
Expand Down Expand Up @@ -177,7 +177,7 @@ def test_clear_cache(client):

def test_not_thread_safe(client, monkeypatch):
# Check that writes fail if thread safety is disabled
monkeypatch.setattr(sqlite3, "threadsafety", 0)
monkeypatch.setattr(sqlite3, "threadsafety", ThreadingMode.SINGLE_THREAD)
cache = client.context.cache
# Clear the cache in another thread
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
Expand All @@ -187,7 +187,8 @@ def test_not_thread_safe(client, monkeypatch):


@pytest.mark.skipif(
sqlite3.threadsafety < 2, reason="sqlite not built with thread safe support"
sqlite3.threadsafety != ThreadingMode.SERIALIZED,
reason="sqlite not built with thread safe support",
)
def test_thread_safety(client):
cache = client.context.cache
Expand Down
16 changes: 14 additions & 2 deletions tiled/client/cache.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import enum
import json
import os
import sqlite3
Expand Down Expand Up @@ -162,6 +163,18 @@ def wrapper(obj, *args, **kwargs):
return wrapper


class ThreadingMode(enum.IntEnum):
"""Threading mode used in the sqlite3 package.
https://docs.python.org/3/library/sqlite3.html#sqlite3.threadsafety
"""

SINGLE_THREAD = 0
MULTI_THREAD = 1
SERIALIZED = 3


class Cache:
def __init__(
self,
Expand Down Expand Up @@ -201,9 +214,8 @@ def write_safe(self):
lock (``@with_thread_lock``) to prevent parallel writes.
"""
SERIALIZED = 3 # Could be defined in an enum elsewhere
is_main_thread = threading.current_thread().ident == self._owner_thread
sqlite_is_safe = sqlite3.threadsafety == SERIALIZED
sqlite_is_safe = sqlite3.threadsafety == ThreadingMode.SERIALIZED
return is_main_thread or sqlite_is_safe

def __getstate__(self):
Expand Down

0 comments on commit 0d1e8ff

Please sign in to comment.