48 lines
1.6 KiB
C#
48 lines
1.6 KiB
C#
using Google.Protobuf;
|
|
using Google.Protobuf.WellKnownTypes;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Text.RegularExpressions;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace bts.api.core
|
|
{
|
|
internal interface IApiServer
|
|
{
|
|
void dispatch(RequestHeader header, Stream request, Action<byte[]> on_response);
|
|
}
|
|
|
|
internal abstract class ApiServer : IApiServer
|
|
{
|
|
static JsonFormatter _formatter = new JsonFormatter(new JsonFormatter.Settings(true));
|
|
static Regex _fmt_cleanup = new Regex(@"[\s_+]", RegexOptions.Compiled | RegexOptions.Multiline);
|
|
public static string format_qualifier<T>(string method, T arg) where T : IMessage {
|
|
if (arg != null) {
|
|
string arg_fmt = _fmt_cleanup.Replace(_formatter.Format(arg), "");
|
|
return method + arg_fmt;
|
|
}
|
|
return method;
|
|
}
|
|
public abstract void dispatch(RequestHeader header, Stream request, Action<byte[]> on_response);
|
|
|
|
protected void respond<T>(int request_id, Task<T> task, Action<byte[]> on_response) where T : IMessage, IImmutableMessage {
|
|
var header = new ResponseHeader() { RequestId = request_id };
|
|
if (task.IsCanceled || task.IsFaulted) {
|
|
header.Code = ApiError.ServerFault;
|
|
on_response(header.serialize());
|
|
}
|
|
else if (task.IsCompleted) {
|
|
header.Code = ApiError.Success;
|
|
on_response(header.serialize(task.Result));
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|