Attempt to using Nakama as replacement of Low-Level ENet

This commit is contained in:
2025-12-02 00:58:44 +08:00
parent b27b612989
commit ead155afed
74 changed files with 14205 additions and 23315 deletions
@@ -0,0 +1,112 @@
// Copyright 2022 The Nakama Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Nakama.TinyJson;
using Godot;
namespace Nakama {
/// <summary>
/// An Http adapter which uses Godot's HttpRequest node.
/// </summary>
/// <remarks>
/// Note Content-Type header is always set as 'application/json'.
/// </remarks>
public partial class GodotHttpAdapter : Node, IHttpAdapter {
/// <inheritdoc cref="IHttpAdapter.Logger"/>
public ILogger Logger { get; set; }
/// <inheritdoc cref="IHttpAdapter.TransientExceptionDelegate"/>
public TransientExceptionDelegate TransientExceptionDelegate => IsTransientException;
/// <inheritdoc cref="IHttpAdapter"/>
public async Task<string> SendAsync(string method, Uri uri, IDictionary<string, string> headers,
byte[] body, int timeout, CancellationToken? cancellationToken)
{
var req = new HttpRequest();
req.Timeout = timeout;
if (OS.GetName() != "HTML5") {
req.UseThreads = true;
}
var godot_method = HttpClient.Method.Get;
if (method == "POST") {
godot_method = HttpClient.Method.Post;
}
else if (method == "PUT") {
godot_method = HttpClient.Method.Put;
}
else if (method == "DELETE") {
godot_method = HttpClient.Method.Delete;
}
else if (method == "HEAD") {
godot_method = HttpClient.Method.Head;
}
var headers_array = new String[headers.Count + 1];
headers_array[0] = "Accept: application/json";
int index = 1;
foreach (var item in headers) {
headers_array[index] = item.Key + ": " + item.Value;
index++;
}
string body_string = body != null ? System.Text.Encoding.UTF8.GetString(body) : "";
AddChild(req);
req.Request(uri.ToString(), headers_array, godot_method, body_string);
Logger?.InfoFormat("Send: method='{0}', uri='{1}', body='{2}'", method, uri, body_string);
Variant[] resultObjects = await ToSignal(req, "request_completed");
HttpRequest.Result result = (HttpRequest.Result)(long)resultObjects[0];
long response_code = (long)resultObjects[1];
string response_body = System.Text.Encoding.UTF8.GetString((byte[])resultObjects[3]);
req.QueueFree();
Logger?.InfoFormat("Received: status={0}, contents='{1}'", response_code, response_body);
if (result == HttpRequest.Result.Success && response_code >= 200 && response_code <= 299) {
return response_body;
}
var decoded = response_body.FromJson<Dictionary<string, object>>();
string message = decoded.ContainsKey("message") ? decoded["message"].ToString() : string.Empty;
int grpcCode = decoded.ContainsKey("code") ? (int) decoded["code"] : -1;
var exception = new ApiResponseException(response_code, message, grpcCode);
if (decoded.ContainsKey("error"))
{
IHttpAdapterUtil.CopyResponseError(this, decoded["error"], exception);
}
throw exception;
}
private static bool IsTransientException(Exception e) {
return e is ApiResponseException apiException && (apiException.StatusCode >= 500 || apiException.StatusCode == -1);
}
}
}
@@ -0,0 +1,79 @@
// Copyright 2022 The Nakama Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using Godot;
namespace Nakama {
/// <summary>
/// A logger which prints to the Godot console.
/// </summary>
public class GodotLogger : ILogger {
/// <summary>
/// The log level.
/// </summary>
public enum LogLevel {
NONE,
ERROR,
WARNING,
INFO,
DEBUG,
}
private string module;
private LogLevel level;
/// <summary>
/// Constructs a GodotLogger.
/// </summary>
/// <param name="p_module">The label to use for log entries.</param>
/// <param name="p_level">The log level (or lower) to print to the console.</param>
public GodotLogger(string p_module = "Nakama", LogLevel p_level = LogLevel.ERROR) {
module = p_module;
level = p_level;
}
/// <inheritdoc cref="ILogger"/>
public void ErrorFormat(string format, params object[] args) {
if (level >= LogLevel.ERROR) {
GD.PrintErr("=== " + module + " : ERROR === " + String.Format(format, args));
}
}
/// <inheritdoc cref="ILogger"/>
public void WarnFormat(string format, params object[] args) {
if (level >= LogLevel.WARNING) {
GD.Print("=== " + module + " : WARN === " + String.Format(format, args));
}
}
/// <inheritdoc cref="ILogger"/>
public void InfoFormat(string format, params object[] args) {
if (level >= LogLevel.INFO) {
GD.Print("=== " + module + " : INFO === " + String.Format(format, args));
}
}
/// <inheritdoc cref="ILogger"/>
public void DebugFormat(string format, params object[] args) {
if (level >= LogLevel.DEBUG) {
GD.Print("=== " + module + " : DEBUG === " + String.Format(format, args));
}
}
}
}
@@ -0,0 +1,211 @@
// Copyright 2022 The Nakama Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Threading;
using System.Threading.Tasks;
using Godot;
namespace Nakama
{
/// <summary>
/// An exception that is thrown when the WebSocket is unable to connect.
/// </summary>
public class GodotWebSocketConnectionException : Exception {
public GodotWebSocketConnectionException(string message = "WebSocket unable to connect")
: base(message) { }
}
/// <summary>
/// An exception that is thrown when the WebSocket is unable to send.
/// </summary>
public class GodotWebSocketSendException : Exception {
public GodotWebSocketSendException() : base("Unable to send over WebSocket") { }
}
/// <summary>
/// A socket adapter which uses Godot's WebSocketPeer.
/// </summary>
public partial class GodotWebSocketAdapter : Node, ISocketAdapter
{
/// <inheritdoc cref="ISocketAdapter.Connected"/>
public event Action Connected;
/// <inheritdoc cref="ISocketAdapter.Closed"/>
public event Action Closed;
/// <inheritdoc cref="ISocketAdapter.ReceivedError"/>
public event Action<Exception> ReceivedError;
/// <inheritdoc cref="ISocketAdapter.Received"/>
public event Action<ArraySegment<byte>> Received;
/// <inheritdoc cref="ISocketAdapter.IsConnected"/>
public new bool IsConnected
{
get
{
return ws.GetReadyState() == WebSocketPeer.State.Open;
}
}
/// <inheritdoc cref="ISocketAdapter.IsConnecting"/>
public bool IsConnecting
{
get
{
return ws.GetReadyState() == WebSocketPeer.State.Connecting;
}
}
private WebSocketPeer ws;
private WebSocketPeer.State wsLastState = WebSocketPeer.State.Closed;
private TaskCompletionSource<bool> connectionSource;
private TaskCompletionSource<bool> closeSource;
private int connectionTimeout;
private double connectionStart;
/// <summary>
/// Constructs a GodotWebSocketAdapter.
/// </summary>
public GodotWebSocketAdapter()
{
ws = new WebSocketPeer();
}
/// <inheritdoc cref="ISocketAdaptor.CloseAsync"/>
public Task CloseAsync()
{
if (closeSource == null)
{
closeSource = new TaskCompletionSource<bool>();
}
ws.Close();
return closeSource.Task;
}
/// <inheritdoc cref="ISocketAdaptor.ConnectAsync"/>
public Task ConnectAsync(Uri uri, int timeout)
{
if (connectionSource != null)
{
connectionSource.SetException(new GodotWebSocketConnectionException("Connection attempt aborted due to new connection attempt"));
connectionSource = null;
}
if (ws.GetReadyState() != WebSocketPeer.State.Closed)
{
return Task.FromException(new GodotWebSocketConnectionException("Cannot connect until current socket is closed"));
}
connectionTimeout = timeout;
connectionStart = Time.GetUnixTimeFromSystem();
connectionSource = new TaskCompletionSource<bool>();
var err = ws.ConnectToUrl(uri.ToString());
if (err != Error.Ok)
{
return Task.FromException(new GodotWebSocketConnectionException(String.Format("Error connecting: {0}", Enum.GetName(typeof(Error), err))));
}
wsLastState = WebSocketPeer.State.Closed;
return connectionSource.Task;
}
/// <inheritdoc cref="ISocketAdaptor.SendAsync"/>
public Task SendAsync(ArraySegment<byte> buffer, bool reliable = true, CancellationToken canceller = default)
{
byte[] temp;
if (buffer.Offset != 0 || buffer.Count != buffer.Array.Length)
{
temp = new byte[buffer.Count];
Array.Copy(buffer.Array, buffer.Offset, temp, 0, buffer.Count);
}
else
{
temp = buffer.Array;
}
var err = ws.Send(temp, WebSocketPeer.WriteMode.Text);
if (err == Error.Ok)
{
return Task.CompletedTask;
}
return Task.FromException(new GodotWebSocketSendException());
}
public override void _Process(double delta)
{
if (ws.GetReadyState() != WebSocketPeer.State.Closed)
{
ws.Poll();
}
var state = ws.GetReadyState();
if (wsLastState != state)
{
wsLastState = state;
if (state == WebSocketPeer.State.Open)
{
Connected?.Invoke();
connectionSource.SetResult(true);
connectionSource = null;
}
else if (state == WebSocketPeer.State.Closed)
{
if (connectionSource != null)
{
Exception e = new GodotWebSocketConnectionException("Failed to connect");
ReceivedError?.Invoke(e);
connectionSource.SetException(e);
connectionSource = null;
}
else
{
Closed?.Invoke();
}
if (closeSource != null)
{
closeSource.SetResult(true);
closeSource = null;
}
}
}
if (ws.GetReadyState() == WebSocketPeer.State.Connecting) {
if (connectionStart + (double)connectionTimeout < Time.GetUnixTimeFromSystem())
{
ws.Close();
Exception e = new GodotWebSocketConnectionException("Connection timed out");
ReceivedError?.Invoke(e);
connectionSource.SetException(e);
connectionSource = null;
}
}
while (ws.GetReadyState() == WebSocketPeer.State.Open && ws.GetAvailablePacketCount() > 0)
{
Received?.Invoke(new ArraySegment<byte>(ws.GetPacket()));
}
}
}
}