Skip to content
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

Cache control settings #33

Merged
merged 2 commits into from
Sep 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -86,24 +87,39 @@ 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):
"""
Lists block beginning from a low hash (block id). Note that this function is running on a kaspad and not returning
data from database.
"""
response.headers["Cache-Control"] = "public, max-age=3"

resp = await kaspad_client.request("getBlocksRequest",
params={
"lowHash": lowHash,
Expand All @@ -123,6 +139,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 @@ -174,7 +194,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"])