Skip to content

Commit

Permalink
fix types
Browse files Browse the repository at this point in the history
  • Loading branch information
callebtc committed Nov 24, 2024
1 parent a55165e commit 248b77d
Show file tree
Hide file tree
Showing 8 changed files with 114 additions and 32 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/tests_redis_cache.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,14 @@ jobs:
MINT_PORT: 3337
MINT_TEST_DATABASE: ${{ inputs.mint-database }}
TOR: false
MINT_REDIS_CACHE_ENABLE: true
MINT_REDIS_CACHE_ENABLED: true
MINT_REDIS_CACHE_URL: redis://localhost:6379
run: |
poetry run pytest tests/test_mint_api_cache.py -v --cov=mint --cov-report=xml
- name: Stop and clean up Docker Compose
run: |
docker-compose -f docker/docker-compose.yml down
docker compose -f docker/docker-compose.yml down
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v3
6 changes: 5 additions & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,8 @@ repos:
rev: v1.6.0
hooks:
- id: mypy
args: [--ignore-missing, --check-untyped-defs]
args:
- --ignore-missing
- --check-untyped-defs
additional_dependencies:
- types-redis
50 changes: 30 additions & 20 deletions cashu/mint/cache.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import asyncio
import functools
import json

from fastapi import Request
from loguru import logger
from pydantic import BaseModel
from redis.asyncio import from_url
from redis.exceptions import ConnectionError

Expand All @@ -15,42 +18,49 @@ def __init__(self):
if settings.mint_redis_cache_url is None:
raise CashuError("Redis cache url not provided")
self.redis = from_url(settings.mint_redis_cache_url)
# PING
try:
self.redis.ping()
logger.info("PONG from redis ✅")
except ConnectionError as e:
logger.error("redis connection error 💀")
raise e
asyncio.run(self.test_connection())

async def test_connection(self):
# PING
try:
await self.redis.ping()
logger.success("Redis caching server running")
except ConnectionError as e:
logger.error("Redis connection error")
raise e

def cache(self, expire):
def passthrough(func):
@functools.wraps(func)
async def wrapper(*args, **kwargs):
logger.debug(f"cache wrapper on route {func.__name__}")
logger.trace(f"cache wrapper on route {func.__name__}")
result = await func(*args, **kwargs)
return result

return wrapper

def decorator(func):
@functools.wraps(func)
async def wrapper(request, payload):
logger.debug(f"cache wrapper on route {func.__name__}")
async def wrapper(request: Request, payload: BaseModel):
logger.trace(f"cache wrapper on route {func.__name__}")
key = request.url.path + payload.json()
logger.debug(f"KEY: {key}")
logger.trace(f"KEY: {key}")
# Check if we have a value under this key
if await self.redis.exists(key):
logger.info("Returning a cached response...")
return json.loads(await self.redis.get(key))
logger.trace("Returning a cached response...")
resp = await self.redis.get(key)
if resp:
return json.loads(resp)
else:
raise Exception(f"Found no cached response for key {key}")
result = await func(request, payload)
# Cache a successful result for `expire` seconds
await self.redis.setex(key, expire, result.json())
return result

return wrapper
return (
passthrough
if not settings.mint_redis_cache_enabled
else decorator
)


return passthrough if not settings.mint_redis_cache_enabled else decorator

async def disconnect(self):
await self.redis.close()
await self.redis.close()
2 changes: 1 addition & 1 deletion cashu/mint/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

from fastapi import APIRouter, Request, WebSocket, WebSocketDisconnect
from loguru import logger
from starlette.requests import Request

from ..core.errors import KeysetNotFoundError
from ..core.models import (
Expand Down Expand Up @@ -35,6 +34,7 @@
router = APIRouter()
redis = RedisCache()


@router.get(
"/v1/info",
name="Mint information",
Expand Down
7 changes: 4 additions & 3 deletions cashu/wallet/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,10 +171,11 @@ async def send(
await wallet.set_reserved(send_proofs, reserved=True)
return wallet.available_balance, token


def check_payment_preimage(
payment_hash: str,
preimage: str,
) -> bool:
return bytes.fromhex(payment_hash) == hashlib.sha256(
bytes.fromhex(preimage)
).digest()
return (
bytes.fromhex(payment_hash) == hashlib.sha256(bytes.fromhex(preimage)).digest()
)
57 changes: 56 additions & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ respx = "^0.21.1"
ruff = "^0.7.1"
mypy = "^1.13.0"
pre-commit = "^4.0.1"
types-redis = "^4.6.0"

[build-system]
requires = ["poetry-core>=1.0.0"]
Expand Down
19 changes: 15 additions & 4 deletions tests/test_mint_api_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
BASE_URL = "http://localhost:3337"
invoice_32sat = "lnbc320n1pnsuamsdqqxqrrsssp5w3tlpw2zss396qh28l3a07u35zdx8nmknzryk89ackn23eywdu2spp5ckt298t835ejzh2xepyxlg57f54q27ffc2zjsjh3t5pmx4wghpcqne0vycw5dfalx5y45d2jtwqfwz437hduyccn9nxk2feay0ytxldjpf3fcjrcf5k2s56q3erj86ymlqdp703y89vt4lr4lun5z5duulcqwuwutn"


@pytest_asyncio.fixture(scope="function")
async def wallet(ledger: Ledger):
wallet1 = await Wallet.with_db(
Expand Down Expand Up @@ -49,6 +50,7 @@ async def test_api_mint_cached_responses(wallet: Wallet):
assert response1.status_code == 200, f"{response1.status_code = }"
assert response.text == response1.text


@pytest.mark.asyncio
@pytest.mark.skipif(
not settings.mint_redis_cache_enabled,
Expand All @@ -57,7 +59,7 @@ async def test_api_mint_cached_responses(wallet: Wallet):
async def test_api_swap_cached_responses(wallet: Wallet):
quote = await wallet.request_mint(64)
await pay_if_regtest(quote.request)

minted = await wallet.mint(64, quote.quote)
secrets, rs, derivation_paths = await wallet.generate_secrets_from_to(10010, 10011)
outputs, rs = wallet._construct_outputs([32, 32], secrets, rs)
Expand All @@ -77,6 +79,7 @@ async def test_api_swap_cached_responses(wallet: Wallet):
assert response1.status_code == 200, f"{response1.status_code = }"
assert response.text == response1.text


@pytest.mark.asyncio
@pytest.mark.skipif(
not settings.mint_redis_cache_enabled,
Expand All @@ -96,14 +99,22 @@ async def test_api_melt_cached_responses(wallet: Wallet):
outputs_payload = [o.dict() for o in outputs]
response = httpx.post(
f"{BASE_URL}/v1/melt/bolt11",
json={"quote": melt_quote.quote, "inputs": inputs_payload, "outputs": outputs_payload},
json={
"quote": melt_quote.quote,
"inputs": inputs_payload,
"outputs": outputs_payload,
},
timeout=None,
)
response1 = httpx.post(
f"{BASE_URL}/v1/melt/bolt11",
json={"quote": melt_quote.quote, "inputs": inputs_payload, "outputs": outputs_payload},
json={
"quote": melt_quote.quote,
"inputs": inputs_payload,
"outputs": outputs_payload,
},
timeout=None,
)
assert response.status_code == 200, f"{response.status_code = }"
assert response1.status_code == 200, f"{response1.status_code = }"
assert response.text == response1.text
assert response.text == response1.text

0 comments on commit 248b77d

Please sign in to comment.