Skip to content

Commit

Permalink
test restructure
Browse files Browse the repository at this point in the history
  • Loading branch information
Ellenn-A committed May 20, 2024
1 parent f1f420d commit 6a88c98
Show file tree
Hide file tree
Showing 11 changed files with 531 additions and 291 deletions.
84 changes: 11 additions & 73 deletions app/main.py
Original file line number Diff line number Diff line change
@@ -1,77 +1,15 @@
from typing import Optional, List, Any
from datetime import datetime
from enum import IntEnum, StrEnum
import requests
from fastapi import FastAPI, HTTPException
from uagents import Model
import httpx
from fastapi import FastAPI
from routes import router as api_router

veritableUrl = "http://localhost:3010"
peerUrl="http://localhost:3001/api"

class TestRequest(Model):
message: str

class DrpcRequestObject(Model):
jsonrpc: str
method: str
params: Optional[List | object]
id: Optional[str| int ]

class DrpcErrorCode(IntEnum):
METHOD_NOT_FOUND = -32601, # make all stuff inside enums lowercase
PARSE_ERROR = -32700,
INVALID_REQUEST = -32600,
INVALID_PARAMS = -32602,
INTERNAL_ERROR = -32603,
SERVER_ERROR = -32000,

class DrpcResponseError(Model):
code: DrpcErrorCode
message: str
data: Optional[Any]

class DrpcResponseObject(Model):
jsonrpc: str
result: Optional[Any]
error: Optional[DrpcResponseError]
id: Optional[str| int ]

class DrpcRole(StrEnum):
Client = 'client',
Server = 'server',

class DrpcState(StrEnum):
RequestSent = 'request-sent',
RequestReceived = 'request-received',
Completed = 'completed',

class Query(Model):
message: dict

# RPC Response example
# --> {"jsonrpc": "2.0", "method": "subtract", "params": [23, 42], "id": 2}
# <-- {"jsonrpc": "2.0", "result": -19, "id": 2}
class Response(Model):
message: dict

class DrpcEvent(Model):
createdAt: datetime
request: Optional[DrpcRequestObject| List[DrpcRequestObject]]
response: Optional[DrpcResponseObject]
connectionId: str
role: DrpcRole
state: DrpcState
threadId: str
id:str
_tags:dict

app = FastAPI()
def get_application() -> FastAPI:
"""
Controller to setup the application and return an Application
instance to Uvicorn.
"""
application = FastAPI()
application.include_router(api_router)

return application


# def start():
# uvicorn.run(app, host="0.0.0.0", port=8000)

# if __name__ == "__main__":
# start()
app = get_application()
171 changes: 124 additions & 47 deletions app/routes/posts.py
Original file line number Diff line number Diff line change
@@ -1,70 +1,147 @@
from fastapi import APIRouter,HTTPException
from typing import Optional, List, Any
from datetime import datetime
from enum import IntEnum, StrEnum
from fastapi.responses import JSONResponse
from pydantic import BaseModel
import httpx
import requests
from uagents import Model

veritableUrl = "http://localhost:3010"
peerUrl="http://localhost:3001/api"


class Query(BaseModel):
message: dict

class DrpcRequestObject(Model):
jsonrpc: str
method: str
params: Optional[List | object]
id: Optional[str| int ]

class DrpcErrorCode(IntEnum):
method_not_found = -32601,
parse_error = -32700,
invalid_request = -32600,
invalid_params = -32602,
internal_error = -32603,
server_error = -32000,

class DrpcResponseError(Model):
code: DrpcErrorCode
message: str
data: Optional[Any]

class DrpcResponseObject(Model):
jsonrpc: str
result: Optional[Any]
error: Optional[DrpcResponseError]
id: Optional[str| int ]

class DrpcRole(StrEnum):
Client = 'client',
Server = 'server',

class DrpcState(StrEnum):
RequestSent = 'request-sent',
RequestReceived = 'request-received',
Completed = 'completed',

class Query(Model):
message: dict

# RPC Response example
# --> {"jsonrpc": "2.0", "method": "subtract", "params": [23, 42], "id": 2}
# <-- {"jsonrpc": "2.0", "result": -19, "id": 2}
class Response(Model):
message: dict

class DrpcEvent(Model):
createdAt: datetime
request: Optional[DrpcRequestObject| List[DrpcRequestObject]]
response: Optional[DrpcResponseObject]
connectionId: str
role: DrpcRole
state: DrpcState
threadId: str
id:str
_tags:dict


router = APIRouter()


async def postToVeritable(req:Query)-> JSONResponse:
req_dict = dict(req)
async with httpx.AsyncClient() as client:
response = await client.post(f"{veritableUrl}/drcp/request", json=req_dict)
return response

async with httpx.AsyncClient() as client:
response = await client.post(f"{veritableUrl}/drcp/request", json=req)
return [response.status, response.json()]
async def postResponseToVeritable(req: Response)-> JSONResponse:
async with httpx.AsyncClient() as client:
response = client.post(f"{veritableUrl}/drcp/response", json=req)
return [response.status, response.json()]
async def peerReceivesResponse(req: DrpcEvent) -> JSONResponse:
async with httpx.AsyncClient() as client:
response = await client.post(f"{peerUrl}/receive-response", json=req)
return [response.status, response.json()]
async def peerReceivesQuery(req: DrpcEvent) -> JSONResponse:
async with httpx.AsyncClient() as client:
response =await client.post(f"{peerUrl}/receive-query", json=req)
return [response.status, response.json()]

@router.post("/send-query", name="test-name",status_code=202)
async def send_query(req: Query): # need to define Query
try:
response = await postToVeritable(req)
if response.status_code != 202:
print("Error:", response.status_code)
return response.json()
if response[0] != '202':
raise ValueError("Response status is not 202")
return response
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))



# @app.post("/webhooks/drpc") #from veritable cloudagent # need to pay attention to responseState changed and request state changed
# async def drpc_event_handler(req: DrpcEvent):
# try:
# req_dict = dict(req)
# req_dict['createdAt'] = req_dict['createdAt'].isoformat()

# # Convert DrpcRequestObject object to a dictionary
# if req_dict['request']:
# req_dict['request'] = dict(req_dict['request'])
@router.post("/webhooks/drpc", name="webhooks-drpc",status_code=200) #from veritable cloudagent to peerAPI
async def drpc_event_handler(req: DrpcEvent):
try:
req_dict = dict(req)
req_dict['createdAt'] = req_dict['createdAt'].isoformat()
# Convert DrpcRequestObject object to a dictionary
if req_dict['request']:
req_dict['request'] = dict(req_dict['request'])

# # Convert DrpcResponseObject object to a dictionary
# if req_dict['response']:
# req_dict['response'] = dict(req_dict['response'])
# # Convert DrpcResponseError object to a dictionary
# if req_dict['response']['error']:
# req_dict['response']['error'] = dict(req_dict['response']['error'])
# if req_dict['role']=='client':
# # respond to the peer API
# response = requests.post(f"{peerUrl}/receive-response", json=req_dict)
# print('in request')
# if req_dict['role']=='server':
# response = requests.post(f"{peerUrl}/receive-query", json=req_dict)
# if response.status_code != 200:
# print("Error:", response.status_code)
# return response
# except Exception as e:
# raise HTTPException(status_code=500, detail=str(e))
# @app.post("/receive-response") ## this receives response from chainvine and it forwards info to veritable
# async def receive_response(resp: Response): #basic RPC response
# try:
# req_dict = dict(resp)
# # relay stuff to the drcp/response in veritable
# response = requests.post(f"{veritableUrl}/drcp/response", json=req_dict)
# if response.status_code != 200:
# print("Error:", response.status_code)
# return response
# except Exception as e:
# raise HTTPException(status_code=500, detail=str(e))
# Convert DrpcResponseObject object to a dictionary
if req_dict['response']:
req_dict['response'] = dict(req_dict['response'])
# Convert DrpcResponseError object to a dictionary
if req_dict['response']['error']:
req_dict['response']['error'] = dict(req_dict['response']['error'])
request_check = req_dict['request']
response_check = req_dict['response']
role_check = req_dict['role']
if request_check and response_check:
raise ValueError("JSON body cannot contain both 'request' and 'response'")
if request_check and role_check != 'server':
raise ValueError("If 'request' is present, 'role' must be 'server'")
if response_check and role_check != 'client':
raise ValueError("If 'response' is present, 'role' must be 'client'")
if role_check =='client':
response =await peerReceivesResponse(req_dict)
elif role_check =='server':
response = await peerReceivesQuery(req_dict)
else:
raise ValueError("Error in request body.")
if response[0] != '200':
raise ValueError("Response status is not 200")
return response
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))

@router.post("/receive-response", name="receive-response",status_code=200) ## this receives response from chainvine and it forwards info to veritable
async def receive_response(resp: Response): #basic RPC response
try:
response = await postResponseToVeritable(resp)
if response[0] != '200':
raise ValueError("Response status is not 200")
return response
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
26 changes: 0 additions & 26 deletions extra/helper.py

This file was deleted.

30 changes: 0 additions & 30 deletions extra/test_2.py

This file was deleted.

16 changes: 1 addition & 15 deletions poetry.lock

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

1 change: 0 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ flake8 = "^7.0.0"
httpx = "^0.27.0"
asgi-lifespan = "^2.1.0"
pytest-asyncio = "^0.23.6"
respx = "^0.21.1"


[tool.poetry.group.dev.dependencies]
Expand Down
Loading

0 comments on commit 6a88c98

Please sign in to comment.