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

Notifications refactoring #567

Merged
merged 8 commits into from
Sep 14, 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
27 changes: 17 additions & 10 deletions caster-back/gencaster/distributor.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from dataclasses import asdict, dataclass, field
from typing import AsyncGenerator, Awaitable, Callable, List, Optional, Union

from channels.layers import get_channel_layer
from channels_redis.core import RedisChannelLayer
from strawberry.channels import GraphQLWSConsumer

Expand Down Expand Up @@ -70,30 +71,36 @@ def __init__(self) -> None:
pass

@staticmethod
async def send_graph_update(layer: RedisChannelLayer, graph_uuid: uuid.UUID):
def _get_layer() -> RedisChannelLayer:
if layer := get_channel_layer():
return layer
raise Exception("Could not obtain redis channel layer")

@staticmethod
async def send_graph_update(graph_uuid: uuid.UUID):
return await GenCasterChannel.send_message(
layer=layer,
layer=GenCasterChannel._get_layer(),
message=GraphUpdateMessage(uuid=str(graph_uuid)),
)

@staticmethod
async def send_node_update(layer: RedisChannelLayer, node_uuid: uuid.UUID):
async def send_node_update(node_uuid: uuid.UUID):
return await GenCasterChannel.send_message(
layer=layer, message=NodeUpdateMessage(uuid=str(node_uuid))
layer=GenCasterChannel._get_layer(),
message=NodeUpdateMessage(uuid=str(node_uuid)),
)

@staticmethod
async def send_log_update(
layer: RedisChannelLayer, stream_log_message: "StreamLogUpdateMessage"
):
async def send_log_update(stream_log_message: "StreamLogUpdateMessage"):
return await GenCasterChannel.send_message(
layer=layer, message=stream_log_message
layer=GenCasterChannel._get_layer(), message=stream_log_message
)

@staticmethod
async def send_streams_update(layer: RedisChannelLayer, stream_uuid: str):
async def send_streams_update(stream_uuid: str):
return await GenCasterChannel.send_message(
layer=layer, message=StreamsUpdateMessage(uuid=str(stream_uuid))
layer=GenCasterChannel._get_layer(),
message=StreamsUpdateMessage(uuid=str(stream_uuid)),
)

@staticmethod
Expand Down
108 changes: 24 additions & 84 deletions caster-back/gencaster/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
ScriptCell,
ScriptCellInputCreate,
ScriptCellInputUpdate,
UpdateGraphInput,
create_python_highlight_string,
)
from stream.exceptions import NoStreamAvailableException
Expand Down Expand Up @@ -220,7 +221,7 @@ async def update_audio_file(
audio_file.name = update_audio_file.name
if update_audio_file.description:
audio_file.description = update_audio_file.description
await sync_to_async(audio_file.save)()
await audio_file.asave()
return audio_file # type: ignore

@strawberry.mutation
Expand All @@ -242,14 +243,7 @@ async def add_node(self, info: Info, new_node: NodeCreate) -> None:
if new_value := getattr(new_node, field):
setattr(node, field, new_value)

# asave not yet implemented in django 4.1
await sync_to_async(node.save)()

await GenCasterChannel.send_graph_update(
layer=info.context.channel_layer,
graph_uuid=graph.uuid,
)

await node.asave()
return None

@strawberry.mutation
Expand All @@ -267,18 +261,7 @@ async def update_node(self, info: Info, node_update: NodeUpdate) -> None:
if new_value := getattr(node_update, field):
setattr(node, field, new_value)

await sync_to_async(node.save)()

await GenCasterChannel.send_graph_update(
layer=info.context.channel_layer,
graph_uuid=node.graph.uuid,
)

await GenCasterChannel.send_node_update(
layer=info.context.channel_layer,
node_uuid=node.uuid,
)

await node.asave()
return None

@strawberry.mutation
Expand All @@ -298,57 +281,19 @@ async def add_edge(self, info: Info, new_edge: EdgeInput) -> Edge:
in_node_door=in_node_door,
out_node_door=out_node_door,
)
await GenCasterChannel.send_graph_update(
layer=info.context.channel_layer,
graph_uuid=in_node_door.node.graph.uuid,
)
return edge # type: ignore

@strawberry.mutation
async def delete_edge(self, info, edge_uuid: uuid.UUID) -> None:
"""Deletes a given :class:`~story_graph.models.Edge`."""
await graphql_check_authenticated(info)
try:
edge: story_graph_models.Edge = (
await story_graph_models.Edge.objects.select_related(
"in_node_door__node__graph"
).aget(uuid=edge_uuid)
)
await story_graph_models.Edge.objects.filter(uuid=edge_uuid).adelete()
except Exception:
raise Exception(f"Could not delete edge {edge_uuid}")
if edge.in_node_door:
await GenCasterChannel.send_graph_update(
layer=info.context.channel_layer,
graph_uuid=edge.in_node_door.node.graph.uuid,
)
return None
await story_graph_models.Edge.objects.filter(uuid=edge_uuid).adelete()

@strawberry.mutation
async def delete_node(self, info, node_uuid: uuid.UUID) -> None:
"""Deletes a given :class:`~story_graph.models.Node`."""
await graphql_check_authenticated(info)
try:
node: story_graph_models.Node = (
await story_graph_models.Node.objects.select_related("graph").aget(
uuid=node_uuid
)
)
await story_graph_models.Node.objects.filter(uuid=node_uuid).adelete()
except Exception:
raise Exception(f"Could delete node {node_uuid}")

await GenCasterChannel.send_graph_update(
layer=info.context.channel_layer,
graph_uuid=node.graph.uuid,
)

await GenCasterChannel.send_node_update(
layer=info.context.channel_layer,
node_uuid=node.uuid,
)

return None
await story_graph_models.Node.objects.filter(uuid=node_uuid).adelete()

@strawberry.mutation
async def create_script_cells(
Expand All @@ -366,7 +311,6 @@ async def create_script_cells(
)
except story_graph_models.Node.DoesNotExist as e:
log.error(f"Received update on unknown node {node_uuid}")
# @todo return error
raise e

script_cells: List[story_graph_models.ScriptCell] = []
Expand Down Expand Up @@ -397,9 +341,6 @@ async def create_script_cells(
log.debug(f"Created script cell {script_cell.uuid}")
script_cells.append(script_cell)

await GenCasterChannel.send_node_update(
layer=info.context.channel_layer, node_uuid=node.uuid
)
return script_cells # type: ignore

@strawberry.mutation
Expand Down Expand Up @@ -438,35 +379,17 @@ async def update_script_cells(
).aupdate(**updates)
script_cells.append(script_cell)

# send update to subscription if something was updated
if len(script_cells) > 0:
await GenCasterChannel.send_node_update(
layer=info.context.channel_layer,
node_uuid=await sync_to_async(lambda: script_cells[0].node.uuid)(),
)

return script_cells # type: ignore

@strawberry.mutation
async def delete_script_cell(self, info, script_cell_uuid: uuid.UUID) -> None:
"""Deletes a given :class:`~story_graph.models.ScriptCell`."""
await graphql_check_authenticated(info)

# first get the node before the cell is deleted
node = await story_graph_models.Node.objects.filter(
script_cells__uuid=script_cell_uuid
).afirst()

await story_graph_models.ScriptCell.objects.filter(
uuid=script_cell_uuid
).adelete()

if node:
await GenCasterChannel.send_node_update(
layer=info.context.channel_layer,
node_uuid=node.uuid,
)

@strawberry.mutation
async def add_graph(self, info, graph_input: AddGraphInput) -> Graph:
await graphql_check_authenticated(info)
Expand All @@ -486,6 +409,23 @@ async def add_graph(self, info, graph_input: AddGraphInput) -> Graph:
# https://docs.djangoproject.com/en/4.2/ref/models/instances/#django.db.models.Model.arefresh_from_db
return await story_graph_models.Graph.objects.aget(uuid=graph.uuid) # type: ignore

@strawberry.mutation
async def update_graph(
self, info, graph_input: UpdateGraphInput, graph_uuid: uuid.UUID
) -> Graph:
await graphql_check_authenticated(info)

graph = await story_graph_models.Graph.objects.aget(uuid=graph_uuid)

for key, value in graph_input.__dict__.items():
if value == strawberry.UNSET:
continue
graph.__setattr__(key, value)

await graph.asave()

return graph # type: ignore

@strawberry.mutation
async def add_audio_file(self, info, new_audio_file: AddAudioFile) -> AudioFileUploadResponse: # type: ignore
if new_audio_file.file is None or len(new_audio_file.file) == 0:
Expand Down Expand Up @@ -556,7 +496,7 @@ async def update_node_door(
self,
info,
node_door_input: NodeDoorInputUpdate,
) -> NodeDoorResponse:
) -> NodeDoorResponse: # type: ignore
await graphql_check_authenticated(info)
node_door = await story_graph_models.NodeDoor.objects.aget(
uuid=node_door_input.uuid
Expand Down
5 changes: 2 additions & 3 deletions caster-back/gencaster/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,8 +194,7 @@ async def test_delete_unavailable_edge(self):
variable_values={"edgeUuid": str(uuid.uuid4())},
context_value=self.get_login_context(),
)

self.assertGreaterEqual(len(resp.errors), 1) # type: ignore
self.assertIsNone(resp.data["deleteEdge"]) # type: ignore

NODE_DELETE_MUTATION = """
mutation deleteNode($nodeUuid: UUID!) {
Expand Down Expand Up @@ -226,7 +225,7 @@ async def test_delete_unavailable_node(self):
context_value=self.get_login_context(),
)

self.assertGreaterEqual(len(resp.errors), 1) # type: ignore
self.assertIsNone(resp.data["deleteNode"]) # type: ignore

CREATE_SCRIPT_CELL = """
mutation CreateScriptCells($nodeUuid: UUID!, $scriptCellInputs: [ScriptCellInputCreate!]!) {
Expand Down
28 changes: 28 additions & 0 deletions caster-back/operations.gql
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,25 @@ subscription node($uuid: UUID!) {
}
}

fragment GraphMetaData on Graph {
uuid
templateName
startText
slugName
name
endText
displayName
aboutText
streamAssignmentPolicy
publicVisible
}

query GetGraph($graphUuid:ID!) {
graph(pk: $graphUuid) {
...GraphMetaData
}
}

mutation CreateGraph($graphInput: AddGraphInput!) {
addGraph(graphInput: $graphInput) {
name
Expand All @@ -220,6 +239,15 @@ mutation CreateGraph($graphInput: AddGraphInput!) {
}
}

mutation UpdateGraph($graphUuid:UUID!, $graphUpdate: UpdateGraphInput!) {
updateGraph(
graphInput: $graphUpdate
graphUuid: $graphUuid
) {
uuid
}
}

subscription stream($graphUuid: UUID!) {
streamInfo(graphUuid: $graphUuid) {
__typename
Expand Down
Loading
Loading