-
-
Notifications
You must be signed in to change notification settings - Fork 190
Support disk/embedded/remote store via libsql #272
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
Open
aausch
wants to merge
10
commits into
long2ice:main
Choose a base branch
from
aausch:aausch/libsql_backend_support
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
1491db1
Support disk/embedded/remote store via libsql
aausch 51e8426
* Switch to using parametrized queries where possible, to protect aga…
aausch c26857a
scrub table name for SQL injection. sqlite doesn't accept parameteriz…
aausch b2f90a3
revert CHANGELOG changes, since 2.2 upgrade isn't included in this pr
aausch e7c0942
Now that the queries are parametrized and the table name is sanitized…
aausch f226ac2
Merge commit '3b78f211b2a6374d7fb04c8a8f4cc99103b00dc1' into aausch/l…
aausch 3405de6
Return rows affected instead of row countt when deleting
aausch 498d5a5
Merge commit '24c1f3d187d23359bee0c95f230b5371840785cd' into aausch/l…
aausch d1132c9
Merge branch 'main' into aausch/libsql_backend_support
aausch ab43df3
Merge branch 'main' into aausch/libsql_backend_support
aausch File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| import codecs | ||
| import time | ||
| from typing import Any, Optional, Tuple | ||
|
|
||
| import libsql_client | ||
| from libsql_client import ResultSet | ||
|
|
||
| from fastapi_cache.types import Backend | ||
|
|
||
| EmptyResultSet = ResultSet( | ||
| columns=(), | ||
| rows=[], | ||
| rows_affected=0, | ||
| last_insert_rowid=0) | ||
|
|
||
| # see https://gist.github.com/jeremyBanks/1083518 | ||
| def quote_identifier(s:str, errors:str ="strict") -> str: | ||
| encodable = s.encode("utf-8", errors).decode("utf-8") | ||
|
|
||
| nul_index = encodable.find("\x00") | ||
|
|
||
| if nul_index >= 0: | ||
| error = UnicodeEncodeError("utf-8", encodable, nul_index, nul_index + 1, "NUL not allowed") | ||
| error_handler = codecs.lookup_error(errors) | ||
| replacement, _ = error_handler(error) | ||
| encodable = encodable.replace("\x00", replacement) # type: ignore | ||
|
|
||
| return "\"" + encodable.replace("\"", "\"\"") + "\"" | ||
|
|
||
|
|
||
| class LibsqlBackend(Backend): | ||
| """ | ||
| libsql backend provider | ||
|
|
||
| This backend requires a table name to be passed during initialization. The table | ||
| will be created if it does not exist. If the table does exists, it will be emptied during init | ||
|
|
||
| Note that this backend does not fully support TTL. It will only delete outdated objects on get. | ||
|
|
||
| Usage: | ||
| >> libsql_url = "file:local.db" | ||
| >> cache = LibsqlBackend(libsql_url=libsql_url, table_name="your-cache") | ||
| >> cache.create_and_flush() | ||
| >> FastAPICache.init(cache) | ||
| """ | ||
|
|
||
| # client: libsql_client.Client | ||
| table_name: str | ||
| libsql_url: str | ||
|
|
||
| def __init__(self, libsql_url: str, table_name: str): | ||
| self.libsql_url = libsql_url | ||
| self.table_name = quote_identifier(table_name) | ||
|
|
||
| @property | ||
| def now(self) -> int: | ||
| return int(time.time()) | ||
|
|
||
| async def _make_request(self, request: str, params: Any = None) -> ResultSet: | ||
| # TODO: Exception handling. Return EmptyResultSet on error? | ||
| async with libsql_client.create_client(self.libsql_url) as client: | ||
| return await client.execute(request, params) | ||
|
|
||
|
|
||
| async def create_and_flush(self) -> None: | ||
| await self._make_request(f"CREATE TABLE IF NOT EXISTS {self.table_name} " | ||
| "(key STRING PRIMARY KEY, value BLOB , expire INTEGER)") # noqa: S608 | ||
| await self._make_request(f"DELETE FROM {self.table_name}") # noqa: S608 | ||
|
|
||
| return None | ||
|
|
||
| async def _get(self, key: str) -> Tuple[int, Optional[bytes]]: | ||
| result_set = await self._make_request(f"SELECT * from {self.table_name} WHERE key = ?", # noqa: S608 | ||
| [key]) | ||
| if len(result_set.rows) == 0: | ||
| return (0,None) | ||
|
|
||
| value = result_set.rows[0]["value"] | ||
| ttl_ts = result_set.rows[0]["expire"] | ||
|
|
||
| if not value: | ||
| return (0,None) | ||
| if ttl_ts < self.now: | ||
| await self._make_request(f"DELETE FROM {self.table_name} WHERE key = ?", # noqa: S608 | ||
| [key]) | ||
| return (0, None) | ||
|
|
||
| return(ttl_ts, value) # type: ignore[union-attr,no-any-return] | ||
|
|
||
| async def get_with_ttl(self, key: str) -> Tuple[int, Optional[bytes]]: | ||
| return await self._get(key) | ||
|
|
||
| async def get(self, key: str) -> Optional[bytes]: | ||
| _, value = await self._get(key) | ||
| return value | ||
|
|
||
| async def set(self, key: str, value: bytes, expire: Optional[int] = None) -> None: | ||
| ttl = self.now + expire if expire else 0 | ||
| await self._make_request(f"INSERT OR REPLACE INTO {self.table_name}(\"key\", \"value\", \"expire\") " | ||
| "VALUES(?,?,?)", # noqa: S608 | ||
| [key, value, ttl]) | ||
| return None | ||
|
|
||
| async def clear(self, namespace: Optional[str] = None, key: Optional[str] = None) -> int: | ||
|
|
||
| if namespace: | ||
| result_set = await self._make_request(f"DELETE FROM {self.table_name} WHERE key = ?", # noqa: S608 | ||
| [namespace + '%']) | ||
| return result_set.rows_affected # type: ignore | ||
| elif key: | ||
| result_set = await self._make_request(f"DELETE FROM {self.table_name} WHERE key = ?", # noqa: S608 | ||
| [key]) | ||
| return result_set.rows_affected # type: ignore | ||
| return 0 | ||
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.