miggor-StreamGraph/rpc_renderer/rpc_scope.gd

90 lines
2.5 KiB
GDScript3
Raw Normal View History

# (c) 2023-present Eroax
# (c) 2023-present Yagich
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
class_name RPCScope
## An object that can respond to requests and send events.
##
## A scope is a handler for requests sent by remote clients, and events from the API. It is generally related to different areas of the program.
## The name of this scope.
var name: String
# Dictionary[String -> RPCOperation.type, Callable]
## The operation types this scope can handle.
## Map of [member RPCOperation.type] to [Callable]. The function will be called
## with one argument: the [RPCRequest] to handle.
var operation_types: Dictionary
## Emitted when a response to a request is ready to be sent.
signal response(response: RPCRequestResponse)
## Emitted when an event is ready to be sent.
signal event(event: RPCEvent)
## Returns [code]true[/code] if this scope can handle the given request.
func can_handle_request(request: RPCRequest) -> bool:
return request.operation.type in operation_types
## Wrapper function to handle a request. See [param operation_types].
func handle_request(request: RPCRequest) -> void:
var c: Callable = operation_types[request.operation.type]
c.call(request)
## Returns an [RPCRequestResponse] that's set up to respond to the given [param request].
## Does not emit [signal response].
func create_response(request: RPCRequest, data: Variant, error: RPCError = null) -> RPCRequestResponse:
var r := RPCRequestResponse.new(request)
r.for_request = request.id
r.scope = name
r.kept = request.keep
r.peer_id = request.peer_id
if data is RPCFrame:
r.data = data.to_dict()
else:
r.data = data
if error:
r.errors.append(error)
return r
func create_error(request: RPCRequest, error_text: String) -> RPCRequestResponse:
var r := RPCRequestResponse.new(request)
r.for_request = request.id
r.scope = name
r.kept = request.keep
r.peer_id = request.peer_id
r.data = {}
r.errors.append(RPCError.new(error_text))
return r
func create_generic_success(request: RPCRequest) -> RPCRequestResponse:
var r := RPCRequestResponse.new(request)
r.for_request = request.id
r.scope = name
r.kept = request.keep
r.peer_id = request.peer_id
r.data = {
"success": true
}
return r
func create_event(type: String, data: Variant, condition := {}) -> RPCEvent:
return RPCEvent.new(type, name, data, condition)
func reconnect(p_signal: Signal, connect_to: Callable, to_call: Callable) -> void:
p_signal.disconnect(connect_to)
to_call.call()
p_signal.connect(connect_to)