public void Serialize() { try { var id = Guid.NewGuid().ToString("N").ToUpper(); IMessageItem message = new MessageItem { ID = id, State = MessageState.Accept, Service = "Topic", Method = "Title", Argument = @"{""Value"": ""Content""}", Result = @"{""Value"": ""Result""}" }; var json = SmartSerializer.SerializeMessage(message); Console.WriteLine(json); var message2 = SmartSerializer.ToMessage(json); Assert.IsTrue(message2.ID == message.ID, json); Assert.IsTrue(message2.State == message.State, json); Assert.IsTrue(message2.Service == message.Service, json); Assert.IsTrue(message2.Argument == message.Argument, json); Assert.IsTrue(message2.Result == message.Result, json); Assert.IsTrue(message2.TraceInfo.LocalMachine == message.TraceInfo.LocalMachine, json); } catch (Exception ex) { Assert.Fail($"发生异常\n{ex}"); } }
/// <summary> /// 还原发送异常文件 /// </summary> /// <returns></returns> private async Task ReQueueErrorMessage() { var file = Path.Combine(BackupFolder, $"{Name}_Backup.msg"); if (!File.Exists(file)) { return; } try { var json = await File.ReadAllTextAsync(file); if (string.IsNullOrEmpty(json)) { return; } var items = SmartSerializer.ToObject <TQueueItem[]>(json); if (items == null || items.Length == 0) { return; } RecordLog(LogLevel.Information, () => $"载入发送错误消息,总数{items.Length}"); foreach (var item in items) { queues.Enqueue(item); } } catch (Exception ex) { RecordLog(LogLevel.Error, () => $"{file} : 消息载入错误.{ex.Message}"); } }
public void Serialize2() { try { var id = Guid.NewGuid().ToString("N").ToUpper(); IMessageItem message = new MessageItem { ID = id, State = MessageState.Accept, Service = "Topic", Method = "Title", Argument = @"{""Value"": ""Content""}", Result = @"{""Value"": ""Result""}" }; SmartSerializer.SerializeMessage(message); DateTime start = DateTime.Now; for (int i = 0; i < short.MaxValue; i++) { SmartSerializer.SerializeMessage(message); } var time = (DateTime.Now - start).TotalSeconds; Console.WriteLine($"{time}s {short.MaxValue / time} qps"); Assert.IsTrue(time < 2, "性能不好"); } catch (Exception ex) { Assert.Fail($"发生异常\n{ex}"); } }
/// <summary> /// 取出队列,全部处理,为空后退出 /// </summary> /// <returns></returns> private async Task <bool> Read() { var id = client.RPopLPush(jobList, bakList); if (string.IsNullOrEmpty(id)) { return(false); } var key = $"msg:{Service.ServiceName}:{id}"; var guard = $"guard:{Service.ServiceName}:{id}"; if (!await client.SetNxAsync(guard, "Guard")) { await Task.Delay(RedisOption.Instance.MessageLockTime); return(true); } client.Expire(guard, RedisOption.Instance.MessageLockTime); var str = client.Get(key); if (string.IsNullOrEmpty(str)) { logger.Warning(() => $"ReadList key empty.{key}"); await client.DelAsync(key); await client.LRemAsync(bakList, 0, id); await client.DelAsync(guard); return(true); } IInlineMessage item; try { item = SmartSerializer.ToMessage(str); } catch (Exception ex) { logger.Warning(() => $"ReadList deserialize error.{ex.Message }.{key} =>{str}"); await client.DelAsync(key); await client.LRemAsync(bakList, 0, id); await client.DelAsync(guard); return(true); } //item.Trace ??= TraceInfo.New(item.ID); item.Service = Service.ServiceName; _ = MessageProcessor.OnMessagePush(Service, item, true, null); return(true); }
public ReturnResult Deserialize(byte[] Data) { ReturnResult obj = new SmartSerializer().Deserialize(Data) as ReturnResult; if (obj != null) { this.ReturnValue = obj.ReturnValue; this.exceptionMessage = obj.exceptionMessage; this.ExceptionOccured = obj.ExceptionOccured; } return(this); }
/// <summary> /// 消息处理 /// </summary> private void OnMessagePush(SubscribeMessageEventArgs args) { try { if (SmartSerializer.TryToMessage(args.Body, out var message)) { message.Service = Service.ServiceName; MessageProcessor.OnMessagePush(Service, message, true, null).Wait(); } } catch (Exception ex) { Logger.Exception(ex); } }
public void HelperJson() { var status = new OperatorStatus { Success = true, Code = 1, Message = "Message", InnerMessage = "InnerMessage", Exception = new System.Exception("Exception") }; var json1 = SmartSerializer.ToInnerString(status); var opt = SmartSerializer.FromInnerString <OperatorStatus>(json1); var json2 = SmartSerializer.ToInnerString(opt); opt = (OperatorStatus)SmartSerializer.FromInnerString(json2, typeof(OperatorStatus)); Assert.IsTrue(opt.Message == "Message", json1); Assert.IsTrue(opt.InnerMessage == null, json1); }
protected override TaskCompletionSource <IMessageResult> DoPost(QueueItem item) { Logger.Trace(() => $"[异步消息投递] {item.ID} 正在投递消息.{RedisOption.Instance.ConnectionString}"); var res = new TaskCompletionSource <IMessageResult>(); client .PublishAsync(item.Message.Service, SmartSerializer.SerializeMessage(item.Message)) .ContinueWith(task => { if (task.IsFaulted) { Logger.Trace(() => $"[异步消息投递] {item.ID} 发生异常({task.Exception.Message})"); res.TrySetResult(new MessageResult { ID = item.Message.ID, Trace = item.Message.TraceInfo, State = MessageState.NetworkError }); } else if (task.IsFaulted) { Logger.Trace(() => $"[异步消息投递] {item.ID} 操作取消"); res.TrySetResult(new MessageResult { ID = item.Message.ID, Trace = item.Message.TraceInfo, State = MessageState.Cancel }); } else { Logger.Trace(() => $"[异步消息投递] {item.ID} 投递成功"); res.TrySetResult(new MessageResult { ID = item.Message.ID, Trace = item.Message.TraceInfo, State = MessageState.Success }); } }); return(res); }
/// <summary> /// 参数校验 /// </summary> /// <param name="action"></param> /// <returns></returns> private bool ArgumentPrepare(IApiAction action) { try { action.RestoreArgument(Message); } catch (Exception ex) { var msg = $"错误 : 还原参数异常{ex.Message}"; FlowTracer.MonitorInfomation(msg); var status = DependencyHelper.GetService <IOperatorStatus>(); status.Code = OperatorStatusCode.BusinessException; status.Message = msg; Message.ResultData = status; Message.RealState = MessageState.FormalError; return(false); } try { if (action.ValidateArgument(Message, out var status)) { return(true); } var msg = $"参数校验失败 : {status.Message}"; FlowTracer.MonitorInfomation(msg); Message.ResultData = status; Message.Result = SmartSerializer.ToInnerString(status); Message.RealState = MessageState.FormalError; return(false); } catch (Exception ex) { var msg = $"错误 : 参数校验异常{ex.Message}"; FlowTracer.MonitorInfomation(msg); var status = DependencyHelper.GetService <IOperatorStatus>(); status.Code = OperatorStatusCode.ArgumentError; status.Message = msg; Message.ResultData = status; Message.RealState = MessageState.FormalError; return(false); } }
/// <summary> /// 生产消息 /// </summary> /// <param name="message">消息</param> /// <returns></returns> Task <IMessageResult> IMessagePoster.Post(IInlineMessage message) { message.Offline(); var item = new ConsulQueueItem { ID = message.ID, Name = message.Topic, }; message.ID = null; message.Topic = null; message.Trace = null; item.Message = SmartSerializer.SerializeMessage(message).ToUtf8Bytes(); redisQueues.Enqueue(item); semaphore.Release(); message.RealState = MessageState.AsyncQueue; LogRecorder.MonitorDetails("[ConsulPoster.Post] 消息已投入发送队列,将在后台静默发送直到成功"); return(Task.FromResult <IMessageResult>(null));//直接使用状态 }
/// <summary> /// 备份消息 /// </summary> /// <param name="item"></param> /// <returns></returns> protected async Task Backup(TQueueItem[] item) { try { Directory.Delete(BackupFolder, true); BackupFolder = IOHelper.CheckPath(ZeroAppOption.Instance.DataFolder, Name); } catch (Exception ex) { RecordLog(LogLevel.Error, () => $"[异步消息投递] 删除碎片文件失败.错误:{ex.Message}.文件名:{BackupFolder}"); } var file = Path.Combine(BackupFolder, $"{Name}_Backup.msg"); try { await File.WriteAllTextAsync(file, SmartSerializer.ToString(item)); } catch (Exception ex) { RecordLog(LogLevel.Error, () => $"[异步消息投递] 记录异常备份文件失败.错误:{ex.Message}.文件名:{file}"); } }
/// <summary> /// 消息处理 /// </summary> private async Task OnMessagePush(UserEvent args) { Interlocked.Increment(ref isBusy); try { if (args.Payload == null) { return; } var json = args.Payload.FromUtf8Bytes(); if (SmartSerializer.TryToMessage(json, out var message)) { message.ID = args.ID; message.Topic = Service.ServiceName; await MessageProcessor.OnMessagePush(Service, message, true, null); } } finally { Interlocked.Decrement(ref isBusy); } }
public void ToMessageResult() { var id = Guid.NewGuid().ToString("N").ToUpper(); IInlineMessage message = new InlineMessage { ID = id, State = MessageState.Accept, Service = "Topic", Method = "Title", Argument = @"{""Value"": ""Content""}", ResultData = new Argument <int> { Value = 1 } }; message.CheckState(); Assert.IsTrue(message.DataState == (MessageDataState.ArgumentOffline | MessageDataState.ResultInline), message.DataState.ToString()); message.OfflineResult(); Assert.IsTrue(message.Result != null, message.Result); Assert.IsTrue(message.DataState == (MessageDataState.ArgumentOffline | MessageDataState.ResultOffline | MessageDataState.ResultInline), message.DataState.ToString()); var result = message.ToMessageResult(true); var json = SmartSerializer.ToString(result); var result2 = SmartSerializer.ToObject <MessageResult>(json); Assert.IsTrue(result2.ID == message.ID, result2.ID); Assert.IsTrue(result2.ResultData == null, result2.ResultData.GetTypeName()); Assert.IsTrue(result2.State == message.State, result2.State.ToString()); Assert.IsTrue(result2.DataState == MessageDataState.ResultOffline, result2.DataState.ToString()); Assert.IsTrue(result2.Result == message.Result, result2.Result); Assert.IsTrue(result2.Trace.LocalMachine == message.TraceInfo.LocalMachine, result2.Trace.LocalMachine); }
/// <summary> /// 备份消息 /// </summary> /// <param name="item"></param> /// <returns></returns> protected async Task Backup(TQueueItem item) { //写入异常文件 ++item.Try; if (item.FileName == null) { item.FileName = Path.Combine(BackupFolder, $"{item.ID}.msg"); RecordLog(LogLevel.Error, () => $"[异步消息投递] {item.ID} 发送失败,记录异常备份文件,{item.FileName}"); try { await File.WriteAllTextAsync(item.FileName, SmartSerializer.ToString(item)); } catch (Exception ex) { item.FileName = null; RecordLog(LogLevel.Error, () => $"[异步消息投递] {item.ID} 发送失败,记录异常备份文件失败.错误:{ex.Message}.文件名:{item.FileName}"); } } if (!ZeroAppOption.Instance.IsClosed) { queues.Enqueue(item); } }
/// <summary> /// 标明调用结束 /// </summary> /// <returns>是否发送成功</returns> internal Task <bool> WriteResult(IInlineMessage message) { if (Session == null || Session.IsDisposed) { return(Task.FromResult(true)); } if (!TcpOption.Instance.IsType(message.Service)) { return(Task.FromResult(true)); } try { Session.Server.UpdateSession(Session); //防止超时 var pipeStream = Session.Stream.ToPipeStream(); var json = SmartSerializer.ToInnerString(message.ToMessageResult(true)); var len = pipeStream.WriteLine(json); Session.Stream.Flush(); } catch (Exception ex) { FlowTracer.MonitorError(() => ex.ToString()); } return(Task.FromResult(true)); }
/// <summary> /// 还原发送异常文件 /// </summary> /// <param name="path"></param> /// <returns></returns> private bool ReQueueErrorMessage(string path) { var files = IOHelper.GetAllFiles(path, "*.msg"); if (files.Count <= 0) { return(false); } Logger.Information(() => $"载入发送提示消息,总数{files.Count}"); foreach (var file in files) { try { var json = File.ReadAllText(file); redisQueues.Enqueue(SmartSerializer.ToObject <ConsulQueueItem>(json)); } catch (Exception ex) { Logger.Warning(() => $"{file} : 消息载入错误.{ex.Message}"); } } return(true); }
private async Task <bool> DoPost(ILogger logger, string path, ConsulQueueItem item) { var state = false; try { var result = await client.Event.Fire(new UserEvent { ID = item.ID, Name = item.Name, Payload = item.Message }); state = result.StatusCode == System.Net.HttpStatusCode.OK; } catch (Exception ex) { logger.Warning(() => $"[异步消息投递] {item.ID} 发送失败.{ex.Message}"); redisQueues.Enqueue(item); state = false; } if (state) { if (item.FileName != null) { try { File.Delete(item.FileName); logger.Warning(() => $"[异步消息投递] {item.ID} 发送成功,删除备份文件,{item.FileName}"); } catch { logger.Warning(() => $"[异步消息投递] {item.ID} 发送成功,删除备份文件失败,{item.FileName}"); } } else { logger.Debug(() => $"[异步消息投递] {item.ID} 发送成功"); } return(true); } //写入异常文件 ++item.Try; if (item.FileName != null) { return(false); } item.FileName = Path.Combine(path, $"{item.ID}.msg"); logger.Warning(() => $"[异步消息投递] {item.ID} 发送失败,记录异常备份文件,{item.FileName}"); try { File.WriteAllText(item.FileName, SmartSerializer.ToString(item)); } catch (Exception ex) { item.FileName = null; logger.Error(() => $"[异步消息投递] {item.ID} 发送失败,记录异常备份文件失败.错误:{ex.Message}.文件名:{item.FileName}"); } return(false); }
public object onRequest(AClient connection, PayloadReader pr) { ReturnResult result = new ReturnResult(null, false); bool isDelegate = false; bool ReadFullHeader = false; try { int SharedClassId = pr.ReadInteger(); int MethodId = pr.ReadInteger(); isDelegate = pr.ReadByte() == 1; int DelegateId = isDelegate ? pr.ReadInteger() : 0; int DelegateClassId = isDelegate ? pr.ReadInteger() : 0; ReadFullHeader = true; if (connection.RemoteSharedClasses.ContainsKey(SharedClassId) || (isDelegate && connection.LocalSharedClasses.ContainsKey(DelegateClassId))) { SharedClass sClass = isDelegate ? connection.LocalSharedClasses[SharedClassId] : connection.RemoteSharedClasses[SharedClassId]; SharedMethod sharedMethod = sClass.GetMethod(MethodId); if (sharedMethod != null) { List<object> args = new List<object>(); List<Type> types = new List<Type>(); SortedList<int, SharedDelegate> SharedDelegates = new SortedList<int, SharedDelegate>(); SmartSerializer serializer = new SmartSerializer(); lock(sharedMethod.Delegates) { if(sharedMethod.Delegates.ContainsKey(DelegateId)) { for (int i = 0; i < sharedMethod.Delegates[DelegateId].sharedMethod.ArgumentTypes.Length; i++) { args.Add(serializer.Deserialize(pr.ReadBytes(pr.ReadInteger()))); } } else { for (int i = 0; i < sharedMethod.ArgumentTypes.Length; i++) { args.Add(serializer.Deserialize(pr.ReadBytes(pr.ReadInteger()))); } } } if (!isDelegate) //atm no support yet for delegate inside another delegate { for (int i = 0; i < sharedMethod.DelegateIndex.Count; i++) { if (pr.ReadByte() == 1) { SharedDelegate del = pr.ReadObject<SharedDelegate>(); del.sharedMethod.sharedClass = sClass; args[sharedMethod.DelegateIndex.Keys[i]] = DynamicDelegateCreator.CreateDelegate(del); SharedDelegates.Add(del.sharedMethod.DelegateId, del); } } } if (isDelegate) { //only show the result and not the actual ReturnResult type return sharedMethod.Delegates[DelegateId].Delegate.DynamicInvoke(args.ToArray()); } else { MethodInfo m = sClass.InitializedClass.GetType().GetMethod(sharedMethod.Name, sharedMethod.ArgumentTypes); if (m.GetCustomAttributes(typeof(RemoteExecutionAttribute), false).Length == 0 && m.GetCustomAttributes(typeof(UncheckedRemoteExecutionAttribute), false).Length == 0) { return null; } result.ReturnValue = m.Invoke(sClass.InitializedClass, args.ToArray()); } } } } catch (Exception ex) { if (isDelegate && ReadFullHeader) throw ex; result.exceptionMessage = ex.InnerException != null ? ex.InnerException.Message : ex.Message; result.ExceptionOccured = true; } return result; }
/// <summary> /// 调用检查 /// </summary> /// <param name="context"></param> public async Task <(bool success, IInlineMessage message)> CheckRequest(HttpContext context) { HttpContext = context; var request = context.Request; //ITokenResolver if (!TryGetHeader(request, "x-zmvc-ver", out var ver)) { Message = new HttpMessage { IsOutAccess = true, HttpContext = context, Uri = request.Path.Value, HttpMethod = request.Method.ToUpper(), ID = Guid.NewGuid().ToString("N").ToUpper() }; if (!CheckApiRoute()) { return(false, null); } CheckTrace(); await Prepare(); return(true, Message); } var content = await ReadContent(); FlowTracer.MonitorDebug(content); if (ver != "v2") { var message = SmartSerializer.FromInnerString <InlineMessage>(content); message.DataState = MessageDataState.ArgumentOffline; return(true, message); } Message = new HttpMessage { ID = GetHeader(context.Request, "x-zmvc-id"), HttpContext = context, Uri = request.Path.Value, HttpMethod = request.Method.ToUpper(), Argument = content, HttpContent = content, ExtensionDictionary = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase), DataState = MessageDataState.ArgumentOffline }; if (!CheckApiRoute()) { return(false, null); } if (TryGetHeader(context.Request, "x-zmvc-trace", out var trace)) { Message.TraceInfo = SmartSerializer.ToObject <TraceInfo>(trace); } if (TryGetHeader(context.Request, "x-zmvc-user", out var user)) { Message.User = SmartSerializer.ToObject <Dictionary <string, string> >(user); } if (TryGetHeader(context.Request, "x-zmvc-ctx", out var ctx)) { Message.Context = SmartSerializer.ToObject <Dictionary <string, string> >(ctx); } return(true, Message); }
private void _Invoke(ref object RetObject, params object[] args) { if (args.Length < ArgumentTypes.Length) //check if a argument is using "params x[] args" throw new Exception("missing arguments"); List<int> usedDelegates = new List<int>(); PayloadWriter pw = new PayloadWriter(); pw.WriteInteger(sharedClass.SharedId); pw.WriteInteger(MethodId); pw.WriteByte(isDelegate ? (byte)1 : (byte)0); if (isDelegate) { pw.WriteInteger(this.DelegateId); pw.WriteInteger(this.sharedClass.SharedId); } SmartSerializer serializer = new SmartSerializer(); for (int i = 0; i < args.Length; i++) { object obj = ArgumentTypes[i].IsByRef ? null : args[i]; if (DelegateIndex.ContainsKey(i)) obj = null; byte[] SerializedObj = serializer.Serialize(obj); pw.WriteInteger(SerializedObj.Length); pw.WriteBytes(SerializedObj); } for (int i = 0; i < DelegateIndex.Count; i++) { Delegate del = args[DelegateIndex.Keys[i]] as Delegate; if (del != null) { if (del.Method == null) throw new Exception("Target delegate is NULL"); int id = rnd.Next(); while(Delegates.ContainsKey(id)) id = rnd.Next(); pw.WriteByte(1); SharedDelegate sharedDel = new SharedDelegate(del.Method, sharedClass, del.GetType(), id, del, this.MethodId); sharedDel.sharedMethod.Unchecked = DelegateIndex.Values[i].isUnchecked; sharedDel.sharedMethod.usePacketQueue = DelegateIndex.Values[i].UsePacketQueue; sharedDel.sharedMethod.useUdp = DelegateIndex.Values[i].UseUDP; sharedDel.sharedMethod.NoWaitingTime = DelegateIndex.Values[i].NoWaitingTime; pw.WriteObject(sharedDel); if (!isDelegate) { Delegates.Add(id, sharedDel); } continue; } pw.WriteByte(0); } if (Unchecked || useUdp) { //just execute the method and don't wait for response sharedClass.connection.Connection.SendMessage(new MsgExecuteMethod(0, pw.ToByteArray(), false)); } else { SyncObject syncObject = null; Random rnd = new Random(); int RequestId = rnd.Next(); lock (sharedClass.connection.MethodRequests) { while(sharedClass.connection.MethodRequests.ContainsKey(RequestId)) RequestId = rnd.Next(); syncObject = new SyncObject(sharedClass.connection.Connection.Connection); sharedClass.connection.MethodRequests.Add(RequestId, syncObject); sharedClass.connection.Connection.SendMessage(new MsgExecuteMethod(RequestId, pw.ToByteArray(), true)); } RetObject = syncObject.Wait<ReturnResult>(null, 0); } /*if (callback != null) { sharedClass.connection.BeginSendRequest(pw, callback, true, this.usePacketQueue); } else { if (Unchecked || useUdp) { //just don't wait till we received something back since it's a VOID anyway sharedClass.connection.BeginSendRequest(pw, (object obj) => { }, false, this.usePacketQueue); } else { RetObject = sharedClass.connection.SendRequest(pw, this.usePacketQueue); } }*/ serializer = null; }
public void MessageLifeCycle() { var id = Guid.NewGuid().ToString("N").ToUpper(); IInlineMessage message = new InlineMessage { ID = id, State = MessageState.Accept, Service = "Topic", Method = "Title", Argument = @"{""Value"": ""Content""}", Result = @"{""Value"": ""Result""}" }; message.CheckState(); Assert.IsTrue(message.DataState == (MessageDataState.ArgumentOffline | MessageDataState.ResultOffline), message.DataState.ToString()); //message.PrepareResult(null, ApiResultHelper.State); message.RestoryContent(DependencyHelper.GetService <IJsonSerializeProxy>(), typeof(Argument));; Assert.IsTrue(message.ArgumentData is Argument, message.ArgumentData.GetTypeName()); Assert.IsTrue(message.DataState == (MessageDataState.ArgumentOffline | MessageDataState.ResultOffline | MessageDataState.ArgumentInline), message.DataState.ToString()); message = new InlineMessage { ID = id, State = MessageState.Accept, Service = "Topic", Method = "Title", Argument = @"{""Value"": ""Content""}", Result = @"{""Value"": ""Result""}" }; message.ResetToRequest(); Assert.IsTrue(message.DataState == MessageDataState.ArgumentOffline, message.DataState.ToString()); Assert.IsTrue(message.Result == null, message.Result); //message.PrepareResult(null, ApiResultHelper.State); message.RestoryContent(DependencyHelper.GetService <IJsonSerializeProxy>(), typeof(Argument));; Assert.IsTrue(message.DataState == (MessageDataState.ArgumentOffline | MessageDataState.ArgumentInline), message.DataState.ToString()); message.ResultData = new Argument <int> { Value = 1 }; Assert.IsTrue(message.DataState == (MessageDataState.ArgumentOffline | MessageDataState.ArgumentInline | MessageDataState.ResultInline), message.DataState.ToString()); message.OfflineResult(); Assert.IsTrue(message.Result != null, message.Result); Assert.IsTrue(message.DataState == (MessageDataState.ArgumentOffline | MessageDataState.ArgumentInline | MessageDataState.ResultOffline | MessageDataState.ResultInline), message.DataState.ToString()); var result = message.ToMessageResult(true); var json = SmartSerializer.ToString(result); var result2 = SmartSerializer.ToObject <MessageResult>(json); Assert.IsTrue(result2.ID == message.ID, result2.ID); Assert.IsTrue(result2.ResultData == result.ResultData, result2.ResultData.GetTypeName()); Assert.IsTrue(result2.State == result.State, result2.State.ToString()); Assert.IsTrue(result2.DataState == result.DataState, result2.DataState.ToString()); Assert.IsTrue(result2.Result == result.Result, result2.Result); Assert.IsTrue(result2.Trace.LocalMachine == message.TraceInfo.LocalMachine, result2.Trace.LocalMachine); }
public override void ProcessPayload(SSPClient client, OperationalSocket OpSocket) { ReturnResult result = new ReturnResult(null, false); LiteCodeClient Client = OpSocket as LiteCodeClient; try { PayloadReader pr = new PayloadReader(Data); SharedClass sClass = null; if (Client.InitializedClasses.TryGetValue(SharedClassId, out sClass)) { SharedMethod sharedMethod = sClass.GetMethod(MethodId); if (sharedMethod != null) { List <object> args = new List <object>(); List <Type> types = new List <Type>(); SortedList <int, SharedDelegate> SharedDelegates = new SortedList <int, SharedDelegate>(); SmartSerializer serializer = new SmartSerializer(); lock (sharedMethod.Delegates) { SharedDelegate sharedDel = null; if (sharedMethod.Delegates.TryGetValue(DelegateId, out sharedDel)) { for (int i = 0; i < sharedDel.sharedMethod.ArgumentTypes.Length; i++) { args.Add(serializer.Deserialize(pr.ReadBytes(pr.ReadInteger()))); } } else { for (int i = 0; i < sharedMethod.ArgumentTypes.Length; i++) { args.Add(serializer.Deserialize(pr.ReadBytes(pr.ReadInteger()))); } } } if (!isDelegate) //atm no support yet for delegate inside another delegate { for (int i = 0; i < sharedMethod.DelegateIndex.Count; i++) { if (pr.ReadByte() == 1) { SharedDelegate del = pr.ReadObject <SharedDelegate>(); del.sharedMethod.sharedClass = sClass; args[sharedMethod.DelegateIndex.Keys[i]] = DynamicDelegateCreator.CreateDelegate(del); SharedDelegates.Add(del.sharedMethod.DelegateId, del); } } } if (isDelegate) { result.ReturnValue = sharedMethod.Delegates[DelegateId].Delegate.DynamicInvoke(args.ToArray()); } else { if (sharedMethod.CallCache == null) { MethodInfo methodInf = sClass.InitializedClass.GetType().GetMethod(sharedMethod.Name, sharedMethod.ArgumentTypes); sharedMethod.CallCache = methodInf.Bind(); } result.ReturnValue = sharedMethod.CallCache(sClass.InitializedClass, args.ToArray()); /*MethodInfo methodInf = sClass.InitializedClass.GetType().GetMethod(sharedMethod.Name, sharedMethod.ArgumentTypes); * result.ReturnValue = methodInf.Invoke(sClass.InitializedClass, args.ToArray());*/ } } } } catch (Exception ex) { result.exceptionMessage = ex.InnerException != null ? ex.InnerException.Message : ex.Message; result.ExceptionOccured = true; client.onException(ex.InnerException != null ? ex.InnerException : ex, ErrorType.UserLand); } if (RequireResultBack) { Client.Send(new MsgExecuteMethodResponse(RequestId, result)); } }
private void _Invoke(ref object RetObject, params object[] args) { if (args.Length < ArgumentTypes.Length) //check if a argument is using "params x[] args" { throw new Exception("missing arguments"); } List <int> usedDelegates = new List <int>(); PayloadWriter pw = new PayloadWriter(); SmartSerializer serializer = new SmartSerializer(); for (int i = 0; i < args.Length; i++) { object obj = ArgumentTypes[i].IsByRef ? null : args[i]; if (DelegateIndex.ContainsKey(i)) { obj = null; } byte[] SerializedObj = serializer.Serialize(obj); pw.WriteInteger(SerializedObj.Length); pw.WriteBytes(SerializedObj); } for (int i = 0; i < DelegateIndex.Count; i++) { Delegate del = args[DelegateIndex.Keys[i]] as Delegate; if (del != null) { if (del.Method == null) { throw new Exception("Target delegate is NULL"); } int id = rnd.Next(); while (Delegates.ContainsKey(id)) { id = rnd.Next(); } pw.WriteBool(true); SharedDelegate sharedDel = new SharedDelegate(del.Method, sharedClass, del.GetType(), id, del, this.MethodId); sharedDel.sharedMethod.Unchecked = this.Unchecked; //DelegateIndex.Values[i].isUnchecked; sharedDel.sharedMethod.usePacketQueue = this.usePacketQueue; //DelegateIndex.Values[i].UsePacketQueue; sharedDel.sharedMethod.useUdp = this.useUdp; //DelegateIndex.Values[i].UseUDP; pw.WriteObject(sharedDel); if (!isDelegate) { Delegates.Add(id, sharedDel); } continue; } pw.WriteBool(false); } try { if (Unchecked || useUdp) { //just execute the method and don't wait for response sharedClass.Client.Send(new MsgExecuteMethod(0, pw.ToByteArray(), false, sharedClass.SharedId, MethodId, this.DelegateId, this.sharedClass.SharedId)); } else { SyncObject syncObject = null; Random rnd = new Random(); int RequestId = rnd.Next(); lock (sharedClass.Client.Requests) { while (sharedClass.Client.Requests.ContainsKey(RequestId)) { RequestId = rnd.Next(); } syncObject = new SyncObject(sharedClass.Client); sharedClass.Client.Requests.Add(RequestId, syncObject); sharedClass.Client.Send(new MsgExecuteMethod(RequestId, pw.ToByteArray(), true, sharedClass.SharedId, MethodId, this.DelegateId, this.sharedClass.SharedId)); } RetObject = syncObject.Wait <ReturnResult>(null, TimeOutLength); if (syncObject.TimedOut) { //copying the object in memory, maybe a strange way todo it but it works RetObject = new ReturnResult(serializer.Deserialize(serializer.Serialize(this.TimeOutValue)), false); } } } catch { //client most likely disconnected and was unable to send the message RetObject = null; } /*if (callback != null) * { * sharedClass.connection.BeginSendRequest(pw, callback, true, this.usePacketQueue); * } * else * { * if (Unchecked || useUdp) * { * //just don't wait till we received something back since it's a VOID anyway * sharedClass.connection.BeginSendRequest(pw, (object obj) => { }, false, this.usePacketQueue); * } * else * { * RetObject = sharedClass.connection.SendRequest(pw, this.usePacketQueue); * } * }*/ serializer = null; }
async Task <bool> IMessageReceiver.Loop(CancellationToken token) { while (!token.IsCancellationRequested) { try { if (KafkaOption.Instance.Message.Concurrency > 0) { await ConcurrencySemaphore.WaitAsync(token); } var cr = consumer.Consume(token); if (cr == null) { if (KafkaOption.Instance.Message.Concurrency > 0) { ConcurrencySemaphore.Release(); } continue; } if (cr.IsPartitionEOF) { if (KafkaOption.Instance.Message.Concurrency > 0) { ConcurrencySemaphore.Release(); } continue; } if (cr.Message.Key == null) { if (KafkaOption.Instance.Message.Concurrency > 0) { ConcurrencySemaphore.Release(); } consumer.Commit(cr); continue; } var message = SmartSerializer.ToObject <InlineMessage>(cr.Message.Key); message.Service = cr.Topic; message.Argument = cr.Message.Value; //try //{ // foreach (var header in cr.Message.Headers) // { // byte[] bytes = header.GetValueBytes(); // if (bytes == null) // continue; // switch (header.Key) // { // case "zid": // message.ID = Encoding.ASCII.GetString(bytes); // break; // case "method": // message.Method = Encoding.ASCII.GetString(bytes); // break; // case "trace": // message.Trace = JsonSerializer.Deserialize<Context.TraceInfo>(bytes); // break; // case "ctx": // message.Context = JsonSerializer.Deserialize<Dictionary<string, string>>(bytes); // break; // case "user": // message.User = JsonSerializer.Deserialize<Dictionary<string, string>>(bytes); // break; // } // } //} //catch (Exception e) //{ // Logger.Exception(e); // continue; //} if (KafkaOption.Instance.Message.Concurrency <= 0) { await MessageProcessor.OnMessagePush(Service, message, true, cr); } else { MessageProcessor.RunOnMessagePush(Service, message, true, cr); } } catch (OperationCanceledException)//取消为正常操作,不记录 { if (KafkaOption.Instance.Message.Concurrency > 0) { ConcurrencySemaphore.Release(); } return(true); } catch (Exception ex) { if (KafkaOption.Instance.Message.Concurrency > 0) { ConcurrencySemaphore.Release(); } Logger.Exception(ex, "KafkaConsumer.Loop"); } } return(true); }
public object onRequest(AClient connection, PayloadReader pr) { ReturnResult result = new ReturnResult(null, false); bool isDelegate = false; bool ReadFullHeader = false; try { int SharedClassId = pr.ReadInteger(); int MethodId = pr.ReadInteger(); isDelegate = pr.ReadByte() == 1; int DelegateId = isDelegate ? pr.ReadInteger() : 0; int DelegateClassId = isDelegate ? pr.ReadInteger() : 0; ReadFullHeader = true; if (connection.RemoteSharedClasses.ContainsKey(SharedClassId) || (isDelegate && connection.LocalSharedClasses.ContainsKey(DelegateClassId))) { SharedClass sClass = isDelegate ? connection.LocalSharedClasses[SharedClassId] : connection.RemoteSharedClasses[SharedClassId]; SharedMethod sharedMethod = sClass.GetMethod(MethodId); if (sharedMethod != null) { List <object> args = new List <object>(); List <Type> types = new List <Type>(); SortedList <int, SharedDelegate> SharedDelegates = new SortedList <int, SharedDelegate>(); SmartSerializer serializer = new SmartSerializer(); lock (sharedMethod.Delegates) { if (sharedMethod.Delegates.ContainsKey(DelegateId)) { for (int i = 0; i < sharedMethod.Delegates[DelegateId].sharedMethod.ArgumentTypes.Length; i++) { args.Add(serializer.Deserialize(pr.ReadBytes(pr.ReadInteger()))); } } else { for (int i = 0; i < sharedMethod.ArgumentTypes.Length; i++) { args.Add(serializer.Deserialize(pr.ReadBytes(pr.ReadInteger()))); } } } if (!isDelegate) //atm no support yet for delegate inside another delegate { for (int i = 0; i < sharedMethod.DelegateIndex.Count; i++) { if (pr.ReadByte() == 1) { SharedDelegate del = pr.ReadObject <SharedDelegate>(); del.sharedMethod.sharedClass = sClass; args[sharedMethod.DelegateIndex.Keys[i]] = DynamicDelegateCreator.CreateDelegate(del); SharedDelegates.Add(del.sharedMethod.DelegateId, del); } } } if (isDelegate) { //only show the result and not the actual ReturnResult type return(sharedMethod.Delegates[DelegateId].Delegate.DynamicInvoke(args.ToArray())); } else { MethodInfo m = sClass.InitializedClass.GetType().GetMethod(sharedMethod.Name, sharedMethod.ArgumentTypes); if (m.GetCustomAttributes(typeof(RemoteExecutionAttribute), false).Length == 0 && m.GetCustomAttributes(typeof(UncheckedRemoteExecutionAttribute), false).Length == 0) { return(null); } result.ReturnValue = m.Invoke(sClass.InitializedClass, args.ToArray()); } } } } catch (Exception ex) { if (isDelegate && ReadFullHeader) { throw ex; } result.exceptionMessage = ex.InnerException != null ? ex.InnerException.Message : ex.Message; result.ExceptionOccured = true; } return(result); }
private void _Invoke(ref object RetObject, params object[] args) { if (args.Length < ArgumentTypes.Length) //check if a argument is using "params x[] args" { throw new Exception("missing arguments"); } List <int> usedDelegates = new List <int>(); PayloadWriter pw = new PayloadWriter(); pw.WriteInteger(sharedClass.SharedId); pw.WriteInteger(MethodId); pw.WriteByte(isDelegate ? (byte)1 : (byte)0); if (isDelegate) { pw.WriteInteger(this.DelegateId); pw.WriteInteger(this.sharedClass.SharedId); } SmartSerializer serializer = new SmartSerializer(); for (int i = 0; i < args.Length; i++) { object obj = ArgumentTypes[i].IsByRef ? null : args[i]; if (DelegateIndex.ContainsKey(i)) { obj = null; } byte[] SerializedObj = serializer.Serialize(obj); pw.WriteInteger(SerializedObj.Length); pw.WriteBytes(SerializedObj); } for (int i = 0; i < DelegateIndex.Count; i++) { Delegate del = args[DelegateIndex.Keys[i]] as Delegate; if (del != null) { if (del.Method == null) { throw new Exception("Target delegate is NULL"); } int id = rnd.Next(); while (Delegates.ContainsKey(id)) { id = rnd.Next(); } pw.WriteByte(1); SharedDelegate sharedDel = new SharedDelegate(del.Method, sharedClass, del.GetType(), id, del, this.MethodId); sharedDel.sharedMethod.Unchecked = DelegateIndex.Values[i].isUnchecked; sharedDel.sharedMethod.usePacketQueue = DelegateIndex.Values[i].UsePacketQueue; sharedDel.sharedMethod.useUdp = DelegateIndex.Values[i].UseUDP; sharedDel.sharedMethod.NoWaitingTime = DelegateIndex.Values[i].NoWaitingTime; pw.WriteObject(sharedDel); if (!isDelegate) { Delegates.Add(id, sharedDel); } continue; } pw.WriteByte(0); } if (Unchecked || useUdp) { //just execute the method and don't wait for response sharedClass.connection.Connection.SendMessage(new MsgExecuteMethod(0, pw.ToByteArray(), false)); } else { SyncObject syncObject = null; Random rnd = new Random(); int RequestId = rnd.Next(); lock (sharedClass.connection.MethodRequests) { while (sharedClass.connection.MethodRequests.ContainsKey(RequestId)) { RequestId = rnd.Next(); } syncObject = new SyncObject(sharedClass.connection.Connection.Connection); sharedClass.connection.MethodRequests.Add(RequestId, syncObject); sharedClass.connection.Connection.SendMessage(new MsgExecuteMethod(RequestId, pw.ToByteArray(), true)); } RetObject = syncObject.Wait <ReturnResult>(null, 0); } /*if (callback != null) * { * sharedClass.connection.BeginSendRequest(pw, callback, true, this.usePacketQueue); * } * else * { * if (Unchecked || useUdp) * { * //just don't wait till we received something back since it's a VOID anyway * sharedClass.connection.BeginSendRequest(pw, (object obj) => { }, false, this.usePacketQueue); * } * else * { * RetObject = sharedClass.connection.SendRequest(pw, this.usePacketQueue); * } * }*/ serializer = null; }
public override void ProcessPayload(IClient client, IPlugin plugin = null) { ReturnResult result = new ReturnResult(null, false); bool isDelegate = false; bool ReadFullHeader = false; SSPClient Client = client as SSPClient; try { PayloadReader pr = new PayloadReader(Data); int SharedClassId = pr.ReadInteger(); int MethodId = pr.ReadInteger(); isDelegate = pr.ReadByte() == 1; int DelegateId = isDelegate ? pr.ReadInteger() : 0; int DelegateClassId = isDelegate ? pr.ReadInteger() : 0; ReadFullHeader = true; if (Client.Connection.InitializedClasses.ContainsKey(SharedClassId)) { SharedClass sClass = Client.Connection.InitializedClasses[SharedClassId]; SharedMethod sharedMethod = sClass.GetMethod(MethodId); if (sharedMethod != null) { List <object> args = new List <object>(); List <Type> types = new List <Type>(); SortedList <int, SharedDelegate> SharedDelegates = new SortedList <int, SharedDelegate>(); SmartSerializer serializer = new SmartSerializer(); lock (sharedMethod.Delegates) { if (sharedMethod.Delegates.ContainsKey(DelegateId)) { for (int i = 0; i < sharedMethod.Delegates[DelegateId].sharedMethod.ArgumentTypes.Length; i++) { args.Add(serializer.Deserialize(pr.ReadBytes(pr.ReadInteger()))); } } else { for (int i = 0; i < sharedMethod.ArgumentTypes.Length; i++) { args.Add(serializer.Deserialize(pr.ReadBytes(pr.ReadInteger()))); } } } if (!isDelegate) //atm no support yet for delegate inside another delegate { for (int i = 0; i < sharedMethod.DelegateIndex.Count; i++) { if (pr.ReadByte() == 1) { SharedDelegate del = pr.ReadObject <SharedDelegate>(); del.sharedMethod.sharedClass = sClass; args[sharedMethod.DelegateIndex.Keys[i]] = DynamicDelegateCreator.CreateDelegate(del); SharedDelegates.Add(del.sharedMethod.DelegateId, del); } } } if (isDelegate) { result.ReturnValue = sharedMethod.Delegates[DelegateId].Delegate.DynamicInvoke(args.ToArray()); } else { MethodInfo methodInf = sClass.InitializedClass.GetType().GetMethod(sharedMethod.Name, sharedMethod.ArgumentTypes); if (methodInf.GetCustomAttributes(typeof(RemoteExecutionAttribute), false).Length == 0 && methodInf.GetCustomAttributes(typeof(UncheckedRemoteExecutionAttribute), false).Length == 0) { //return null; } result.ReturnValue = methodInf.Invoke(sClass.InitializedClass, args.ToArray()); } } } } catch (Exception ex) { //if (isDelegate && ReadFullHeader) // throw ex; result.exceptionMessage = ex.InnerException != null ? ex.InnerException.Message : ex.Message; result.ExceptionOccured = true; client.onException(ex.InnerException != null ? ex.InnerException : ex, ErrorType.UserLand); } if (RequireResultBack) { Client.Connection.SendMessage(new MsgExecuteMethodResponse(RequestId, result), PacketId.LiteCodeResponse); } base.ProcessPayload(client, plugin); }