Skip to content

Commit a2b7df6

Browse files
d-tamirlanTamirlan Dzhemirzoev
and
Tamirlan Dzhemirzoev
authored
add memory storage (#3)
Co-authored-by: Tamirlan Dzhemirzoev <tamirlan.dzhemirzoev@ccsteam.ru>
1 parent 002394c commit a2b7df6

File tree

3 files changed

+61
-5
lines changed

3 files changed

+61
-5
lines changed

botx_fsm/storages/memory.py

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import pickle
2+
from datetime import timedelta
3+
from enum import Enum
4+
from typing import Any, Union
5+
6+
from cachetools import TTLCache
7+
8+
from botx_fsm import Key, unset
9+
from botx_fsm.markers import FSMStateMarker
10+
from botx_fsm.storages.base import BaseStorage, StateInStorage
11+
12+
ONE_WEEK = timedelta(weeks=1).total_seconds()
13+
ONE_MB = 1024 * 1024
14+
15+
16+
class MemoryStorage(BaseStorage):
17+
storage: TTLCache
18+
19+
def __init__(self, maxsize: int = ONE_MB, expire_time: int = ONE_WEEK) -> None:
20+
self.storage = TTLCache(maxsize=maxsize, ttl=expire_time,)
21+
22+
async def get_state(self, key: Key) -> StateInStorage:
23+
saved_value = self.storage.get(key.to_json())
24+
if saved_value is None:
25+
return unset
26+
27+
restored_value = pickle.loads(saved_value) # noqa: S301
28+
if not isinstance(restored_value, StateInStorage):
29+
raise RuntimeError("received not Enum instance from storage")
30+
31+
return restored_value
32+
33+
async def change_state(
34+
self, key: Key, state: Union[Enum, FSMStateMarker], **kwargs: Any
35+
) -> None:
36+
memory_key = key.to_json()
37+
if state is unset:
38+
del self.storage[memory_key]
39+
return
40+
41+
self.storage[memory_key] = pickle.dumps(
42+
StateInStorage(state=state, kwargs=kwargs)
43+
)

poetry.lock

+16-4
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

pyproject.toml

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[tool.poetry]
22
name = "botx-fsm"
3-
version = "0.1.5"
3+
version = "0.1.6"
44
description = "FSM middleware for using with pybotx"
55
authors = ["Nik Sidnev <sidnev.nick@gmail.com>"]
66

@@ -10,6 +10,7 @@ python = "^3.7"
1010
botx = ">=0.17.0, <0.21.0"
1111
aioredis = "^1.3.1"
1212
async_lru = "^1.0.2"
13+
cachetools = "^4.2.2"
1314

1415
[tool.poetry.dev-dependencies]
1516
black = "^19.10b0"

0 commit comments

Comments
 (0)