Skip to content

Commit

Permalink
Cache control settings (#33)
Browse files Browse the repository at this point in the history
* setting up cache control for Cloudflare

* 3s cache for 404
  • Loading branch information
lAmeR1 authored Sep 25, 2023
1 parent 4a9f480 commit 1fc94bd
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 8 deletions.
28 changes: 25 additions & 3 deletions endpoints/get_blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from sqlalchemy import select

from dbsession import async_session
from endpoints.get_virtual_chain_blue_score import current_blue_score_data
from models.Block import Block
from models.Transaction import Transaction, TransactionOutput, TransactionInput
from server import app, kaspad_client
Expand Down Expand Up @@ -84,18 +85,31 @@ async def get_block(response: Response,

if not requested_block:
# Still did not get the block
raise HTTPException(status_code=404, detail="Block not found")
print("hier")
raise HTTPException(status_code=404, detail="Block not found", headers={
"Cache-Control": "public, max-age=3"
})

# We found the block, now we guarantee it contains the transactions
# It's possible that the block from kaspad does not contain transactions
if 'transactions' not in requested_block or not requested_block['transactions']:
requested_block['transactions'] = await get_block_transactions(blockId)

if int(requested_block["header"]["blueScore"]) > current_blue_score_data["blue_score"] - 20:
response.headers["Cache-Control"] = "public, max-age=3"

elif int(requested_block["header"]["blueScore"]) > current_blue_score_data["blue_score"] - 60:
response.headers["Cache-Control"] = "public, max-age=60"

else:
response.headers["Cache-Control"] = "public, max-age=600"

return requested_block


@app.get("/blocks", response_model=BlockResponse, tags=["Kaspa blocks"])
async def get_blocks(lowHash: str = Query(regex="[a-f0-9]{64}"),
async def get_blocks(response: Response,
lowHash: str = Query(regex="[a-f0-9]{64}"),
includeBlocks: bool = False,
includeTransactions: bool = False):
"""
Expand All @@ -105,6 +119,8 @@ async def get_blocks(lowHash: str = Query(regex="[a-f0-9]{64}"),
Additionally the fields in verboseData: isChainBlock, childrenHashes and transactionIds can't be filled.
"""
response.headers["Cache-Control"] = "public, max-age=3"

resp = await kaspad_client.request("getBlocksRequest",
params={
"lowHash": lowHash,
Expand All @@ -124,6 +140,10 @@ async def get_blocks_from_bluescore(response: Response,
data from database.
"""
response.headers["X-Data-Source"] = "Database"

if blueScore > current_blue_score_data["blue_score"] - 20:
response.headers["Cache-Control"] = "no-store"

blocks = await get_blocks_from_db_by_bluescore(blueScore)

return [{
Expand Down Expand Up @@ -175,7 +195,9 @@ async def get_block_from_db(blockId):
try:
requested_block = requested_block.first()[0] # type: Block
except TypeError:
raise HTTPException(status_code=404, detail="Block not found")
raise HTTPException(status_code=404, detail="Block not found", headers={
"Cache-Control": "public, max-age=3"
})

if requested_block:
return {
Expand Down
9 changes: 6 additions & 3 deletions endpoints/get_transactions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from enum import Enum
from typing import List

from fastapi import Path, HTTPException, Query
from fastapi import Path, HTTPException, Query, Response
from pydantic import BaseModel, parse_obj_as
from sqlalchemy import Integer
from sqlalchemy.future import select
Expand Down Expand Up @@ -81,7 +81,8 @@ class PreviousOutpointLookupMode(str, Enum):
tags=["Kaspa transactions"],
response_model_exclude_unset=True)
@sql_db_only
async def get_transaction(transactionId: str = Path(regex="[a-f0-9]{64}"),
async def get_transaction(response: Response,
transactionId: str = Path(regex="[a-f0-9]{64}"),
inputs: bool = True,
outputs: bool = True,
resolve_previous_outpoints: PreviousOutpointLookupMode =
Expand Down Expand Up @@ -154,7 +155,9 @@ async def get_transaction(transactionId: str = Path(regex="[a-f0-9]{64}"),
"inputs": parse_obj_as(List[TxInput], tx_inputs) if tx_inputs else None
}
else:
raise HTTPException(status_code=404, detail="Transaction not found")
raise HTTPException(status_code=404, detail="Transaction not found", headers={
"Cache-Control": "public, max-age=3"
})


@app.post("/transactions/search",
Expand Down
15 changes: 13 additions & 2 deletions endpoints/get_virtual_chain_blue_score.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
# encoding: utf-8
from typing import List

from fastapi_utils.tasks import repeat_every
from pydantic import BaseModel

from server import app, kaspad_client

current_blue_score_data = {
"blue_score": 0
}


class BlockdagResponse(BaseModel):
blueScore: int = 260890
Expand All @@ -17,3 +20,11 @@ async def get_virtual_selected_parent_blue_score():
"""
resp = await kaspad_client.request("getVirtualSelectedParentBlueScoreRequest")
return resp["getVirtualSelectedParentBlueScoreResponse"]


@app.on_event("startup")
@repeat_every(seconds=5)
async def update_blue_score():
global current_blue_score_data
resp = await kaspad_client.request("getVirtualSelectedParentBlueScoreRequest")
current_blue_score_data["blue_score"] = int(resp["getVirtualSelectedParentBlueScoreResponse"]["blueScore"])

0 comments on commit 1fc94bd

Please sign in to comment.