Skip to content

Commit

Permalink
Merge pull request #1311 from Jaseci-Labs/minor/custom-status-code
Browse files Browse the repository at this point in the history
[MINOR]: Custom status code
  • Loading branch information
ChrisIsKing authored Sep 23, 2024
2 parents 594db81 + c8fc253 commit 049877c
Show file tree
Hide file tree
Showing 6 changed files with 228 additions and 10 deletions.
2 changes: 1 addition & 1 deletion jac-cloud/.pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ repos:
- id: check-json
- id: trailing-whitespace
- repo: https://github.com/psf/black
rev: 24.4.2
rev: 24.8.0
hooks:
- id: black
- repo: https://github.com/PyCQA/flake8
Expand Down
9 changes: 6 additions & 3 deletions jac-cloud/jac_cloud/core/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from bson import ObjectId

from fastapi import Request
from fastapi.responses import ORJSONResponse

from jaclang.runtimelib.context import ExecutionContext

Expand Down Expand Up @@ -46,6 +47,7 @@ class JaseciContext(ExecutionContext):

mem: MongoDB
reports: list
status: int
system_root: NodeAnchor
root: NodeAnchor
entry_node: NodeAnchor
Expand All @@ -68,6 +70,7 @@ def create(request: Request, entry: NodeAnchor | None = None) -> "JaseciContext"
ctx.request = request
ctx.mem = MongoDB()
ctx.reports = []
ctx.status = 200

if not isinstance(system_root := ctx.mem.find_by_id(SUPER_ROOT), NodeAnchor):
system_root = NodeAnchor(
Expand Down Expand Up @@ -130,9 +133,9 @@ def get_root() -> Root: # type: ignore[override]
"""Get current root."""
return cast(Root, JaseciContext.get().root.architype)

def response(self, returns: list[Any], status: int = 200) -> ContextResponse:
def response(self, returns: list[Any]) -> ORJSONResponse:
"""Return serialized version of reports."""
resp: ContextResponse = {"status": status, "returns": returns}
resp: ContextResponse = {"status": self.status, "returns": returns}

if self.reports:
for key, val in enumerate(self.reports):
Expand All @@ -145,7 +148,7 @@ def response(self, returns: list[Any], status: int = 200) -> ContextResponse:
if not SHOW_ENDPOINT_RETURNS:
resp.pop("returns")

return resp
return ORJSONResponse(resp, status_code=self.status)

def clean_response(
self, key: str | int, val: Any, obj: list | dict # noqa: ANN401
Expand Down
2 changes: 1 addition & 1 deletion jac-cloud/jac_cloud/plugin/jaseci.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ def api_entry(
if jctx.validate_access():
wlk.spawn_call(jctx.entry_node)
jctx.close()
return ORJSONResponse(jctx.response(wlk.returns))
return jctx.response(wlk.returns)
else:
jctx.close()
raise HTTPException(
Expand Down
125 changes: 125 additions & 0 deletions jac-cloud/jac_cloud/tests/openapi_specs.json
Original file line number Diff line number Diff line change
Expand Up @@ -4356,6 +4356,118 @@
}
}
}
},
"/walker/custom_status_code": {
"post": {
"tags": [
"walker",
"walker"
],
"summary": "/custom_status_code",
"operationId": "api_root_walker_custom_status_code_post",
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/custom_status_code_body_model"
}
}
},
"required": true
},
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ContextResponse"
}
}
}
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
}
}
},
"security": [
{
"HTTPBearer": []
}
]
}
},
"/walker/custom_status_code/{node}": {
"post": {
"tags": [
"walker",
"walker"
],
"summary": "/custom_status_code/{node}",
"operationId": "api_entry_walker_custom_status_code__node__post",
"security": [
{
"HTTPBearer": []
}
],
"parameters": [
{
"name": "node",
"in": "path",
"required": true,
"schema": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"title": "Node"
}
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/custom_status_code_body_model"
}
}
}
},
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ContextResponse"
}
}
}
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
}
}
}
}
}
},
"components": {
Expand Down Expand Up @@ -4761,6 +4873,19 @@
],
"title": "combination2_body_model"
},
"custom_status_code_body_model": {
"properties": {
"status": {
"type": "integer",
"title": "Status"
}
},
"type": "object",
"required": [
"status"
],
"title": "custom_status_code_body_model"
},
"disallow_other_root_access_body_model": {
"properties": {
"root_id": {
Expand Down
18 changes: 13 additions & 5 deletions jac-cloud/jac_cloud/tests/simple_graph.jac
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ walker manual_create_nested_node {
here.__jac__.apply();

# simulate no auto save
jsrc = JaseciContext.get().mem;
jsrc = Jac.get_context().mem;
jsrc.__mem__.clear();
jsrc.__gc__.clear();

Expand All @@ -269,7 +269,7 @@ walker manual_update_nested_node {
nested.__jac__.apply();

# simulate no auto save
jsrc = JaseciContext.get().mem;
jsrc = Jac.get_context().mem;
jsrc.__mem__.clear();
jsrc.__gc__.clear();

Expand All @@ -285,7 +285,7 @@ walker manual_detach_nested_node {
nested.__jac__.apply();

# simulate no auto save
jsrc = JaseciContext.get().mem;
jsrc = Jac.get_context().mem;
jsrc.__mem__.clear();
jsrc.__gc__.clear();

Expand All @@ -310,7 +310,7 @@ walker manual_delete_nested_node {
nested.__jac__.apply();

# simulate no auto save
jsrc = JaseciContext.get().mem;
jsrc = Jac.get_context().mem;
jsrc.__mem__.clear();
jsrc.__gc__.clear();

Expand All @@ -334,7 +334,7 @@ walker manual_delete_nested_edge {
nested_edge.__jac__.apply();

# simulate no auto save
jsrc = JaseciContext.get().mem;
jsrc = Jac.get_context().mem;
jsrc.__mem__.clear();
jsrc.__gc__.clear();

Expand Down Expand Up @@ -475,4 +475,12 @@ walker post_with_body_and_file {
class __specs__ {
has auth: bool = False;
}
}

walker custom_status_code {
has status: int;

can enter with `root entry {
Jac.get_context().status = self.status;
}
}
82 changes: 82 additions & 0 deletions jac-cloud/jac_cloud/tests/test_simple_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -505,6 +505,82 @@ async def nested_count_should_be(self, node: int, edge: int) -> None:
),
)

async def trigger_custom_status_code(self) -> None:
"""Test custom status code."""
for acceptable_code in [200, 201, 202, 203, 205, 206, 207, 208, 226]:
res = self.post_api("custom_status_code", {"status": acceptable_code})
self.assertEqual(acceptable_code, res["status"])
self.assertEqual([None], res["returns"])

for error_code in [
400,
401,
402,
403,
404,
405,
406,
407,
408,
409,
410,
411,
412,
413,
414,
415,
416,
417,
418,
421,
422,
423,
424,
425,
426,
428,
429,
431,
451,
500,
501,
502,
503,
504,
505,
506,
507,
508,
510,
511,
]:
self.assertEqual(
error_code,
self.post_api(
"custom_status_code", {"status": error_code}, expect_error=True
),
)

for invalid_code in [
100,
101,
102,
103,
204,
300,
301,
302,
303,
304,
305,
306,
307,
308,
]:
self.assertRaises(
Exception, self.post_api, "custom_status_code", {"status": invalid_code}
)

async def test_all_features(self) -> None:
"""Test Full Features."""
self.trigger_openapi_specs_test()
Expand Down Expand Up @@ -576,3 +652,9 @@ async def test_all_features(self) -> None:
self.trigger_access_validation_test(
give_access_to_full_graph=True, via_all=True
)

###################################################
# CUSTOM STATUS #
###################################################

await self.trigger_custom_status_code()

0 comments on commit 049877c

Please sign in to comment.