Exemplo n.º 1
0
        void DumpService(FileDescriptorProto source, ServiceDescriptorProto service, StringBuilder sb)
        {
            sb.AppendLine($"service {service.name} {{");

            foreach (var option in DumpOptions(source, service.options))
            {
                sb.AppendLine($"\toption {option.Key} = {option.Value};");
            }

            foreach (var method in service.method)
            {
                var declaration = $"\trpc {method.name} ({method.input_type}) returns ({method.output_type})";

                var options = DumpOptions(source, method.options);

                if (options.Count == 0)
                {
                    sb.AppendLine($"{declaration};");
                }
                else
                {
                    sb.AppendLine($"{declaration} {{");

                    foreach (var option in options)
                    {
                        sb.AppendLine($"\t\toption {option.Key} = {option.Value};");
                    }

                    sb.AppendLine("\t}");
                }
            }

            sb.AppendLine("}");
            sb.AppendLine();
        }
Exemplo n.º 2
0
 private void AddService(ServiceDescriptorProto serviceDescriptor)
 {
     foreach (var method in serviceDescriptor.Methods)
     {
         _filesBySymbol[method.FullyQualifiedName] = method.GetFile();
     }
     _filesBySymbol[serviceDescriptor.FullyQualifiedName] = serviceDescriptor.GetFile();
 }
Exemplo n.º 3
0
        internal ServiceDescriptor(ServiceDescriptorProto proto, FileDescriptor file, int index)
            : base(file, file.ComputeFullName(null, proto.Name), index)
        {
            this.proto = proto;
            methods    = DescriptorUtil.ConvertAndMakeReadOnly(proto.Method,
                                                               (method, i) => new MethodDescriptor(method, file, this, i));

            file.DescriptorPool.AddSymbol(this);
        }
Exemplo n.º 4
0
        internal ServiceDescriptor(ServiceDescriptorProto proto, FileDescriptor file, int index)
            : base(file, file.ComputeFullName(null, proto.Name), index)
        {
            this.proto = proto;
            methods = DescriptorUtil.ConvertAndMakeReadOnly(proto.Method,
                                                            (method, i) => new MethodDescriptor(method, file, this, i));

            file.DescriptorPool.AddSymbol(this);
        }
        /// <summary>
        /// Suggest a normalized identifier
        /// </summary>
        public virtual string GetName(ServiceDescriptorProto definition)
        {
            var name = definition?.Options?.GetOptions()?.Name;

            if (!string.IsNullOrWhiteSpace(name))
            {
                return(name);
            }
            return("I" + GetName(definition.Name)); // .NET convention
        }
Exemplo n.º 6
0
        /// <summary>
        /// Emit code representing a service
        /// </summary>
        protected virtual void WriteService(GeneratorContext ctx, ServiceDescriptorProto obj)
        {
            object state = null;

            WriteServiceHeader(ctx, obj, ref state);
            foreach (var inner in obj.Methods)
            {
                WriteServiceMethod(ctx, inner, ref state);
            }
            WriteServiceFooter(ctx, obj, ref state);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Emit code preceeding a set of service methods
        /// </summary>
        protected override void WriteServiceHeader(GeneratorContext ctx, ServiceDescriptorProto service, ref object state)
        {
            var name = ctx.NameNormalizer.GetName(service);
            var tw   = ctx.Write("[global::System.ServiceModel.ServiceContract(");

            if (name != service.Name)
            {
                tw.Write($@"Name = @""{service.Name}""");
            }
            tw.WriteLine(")]");
            WriteOptions(ctx, service.Options);
            ctx.WriteLine($"{GetAccess(GetAccess(service))} interface {Escape(name)}").WriteLine("{").Indent();
        }
Exemplo n.º 8
0
        void DumpService(FileDescriptorProto source, ServiceDescriptorProto service, StringBuilder sb, ref bool marker)
        {
            var innerMarker = false;

            AppendHeadingSpace(sb, ref marker);
            sb.AppendLine($"service {service.name} {{");

            var rootOptions = DumpOptions(source, service.options);

            foreach (var option in rootOptions)
            {
                sb.AppendLine($"\toption {option.Key} = {option.Value};");
            }

            if (rootOptions.Count > 0)
            {
                innerMarker = true;
            }

            foreach (var method in service.method)
            {
                var declaration = $"\trpc {method.name} ({method.input_type}) returns ({method.output_type})";

                var options = DumpOptions(source, method.options);

                AppendHeadingSpace(sb, ref innerMarker);

                if (options.Count == 0)
                {
                    sb.AppendLine($"{declaration};");
                }
                else
                {
                    sb.AppendLine($"{declaration} {{");

                    foreach (var option in options)
                    {
                        sb.AppendLine($"\t\toption {option.Key} = {option.Value};");
                    }

                    sb.AppendLine("\t}");
                    innerMarker = true;
                }
            }

            sb.AppendLine("}");
            marker = true;
        }
Exemplo n.º 9
0
 protected virtual void GenerateClientService(
     FileDescriptorProto file,
     ServiceDescriptorProto service,
     StreamWriter writer,
     List <NameInfo> names)
 {
     writer.WriteLines(
         $"\t/// <summary>",
         $"\t/// The client of the {service.Name} api"
         );
     foreach (var line in Docs.DocFactory.GetComment(Doc.GetServiceDoc()))
     {
         writer.WriteLine($"\t/// <br/>");
         foreach (var part in Docs.DocFactory.SplitNewLines(line, 92))
         {
             writer.WriteLine($"\t/// {part}");
         }
     }
     writer.WriteLines(
         $"\t/// </summary>",
         $"\tpublic class {service.Name}Client : srpc::IApiClientDefinition2",
         $"\t{{",
         $"\t\tevent s::Func<srpc::NetworkRequest, stt::Task<srpc::NetworkResponse>>{Nullable} srpc::IApiClientDefinition.PerformMessage",
         $"\t\t{{",
         $"\t\t\tadd => PerformMessagePrivate += value;",
         $"\t\t\tremove => PerformMessagePrivate -= value;",
         $"\t\t}}",
         $"",
         $"\t\tevent s::Func<srpc::NetworkRequest, st::CancellationToken, stt::Task<srpc::NetworkResponse>>{Nullable} srpc::IApiClientDefinition2.PerformMessage2",
         $"\t\t{{",
         $"\t\t\tadd => PerformMessage2Private += value;",
         $"\t\t\tremove => PerformMessage2Private -= value;",
         $"\t\t}}",
         $"",
         $"\t\tprivate event s::Func<srpc::NetworkRequest, stt::Task<srpc::NetworkResponse>>{Nullable} PerformMessagePrivate;",
         $"",
         $"\t\tprivate event s::Func<srpc::NetworkRequest, st::CancellationToken, stt::Task<srpc::NetworkResponse>>{Nullable} PerformMessage2Private;"
         );
     for (int i = 0; i < service.Method.Count; ++i)
     {
         GenerateClientServiceMethod(file, service, writer, names, service.Method[i], i);
     }
     writer.WriteLines(
         $"\t}}",
         $"");
 }
Exemplo n.º 10
0
        protected override void GenerateServerServiceMethods(
            FileDescriptorProto file,
            ServiceDescriptorProto service,
            StreamWriter writer,
            List <NameInfo> names,
            MethodDescriptorProto method,
            int methodIndex)
        {
            var requestType = names
                              .Where(x => x.ProtoBufName == method.InputType)
                              .Select(x => x.CSharpName)
                              .FirstOrDefault();
            var responseType = names
                               .Where(x => x.ProtoBufName == method.OutputType)
                               .Select(x => x.CSharpName)
                               .FirstOrDefault();

            if (requestType is null)
            {
                Log.WriteError(text: $"c# type for protobuf message {method.InputType} not found",
                               file: file.Name);
                return;
            }
            if (responseType is null)
            {
                Log.WriteError(text: $"c# type for protobuf message {method.OutputType} not found",
                               file: file.Name);
                return;
            }
            var resp = Settings.EmptySupport && method.OutputType == ".google.protobuf.Empty"
                ? ""
                : $"<{responseType}{Nullable}>";
            var req = Settings.EmptySupport && method.InputType == ".google.protobuf.Empty"
                ? ""
                : $"{requestType} request, ";

            writer.WriteLine();
            WriteMethodDoc(writer, false, false, names, method, methodIndex,
                           ("request", "The api request object"),
                           ("cancellationToken", "The token that signals the cancellation of the request")
                           );
            writer.WriteLines(
                $"\t\tpublic abstract stt::Task{resp} {method.Name}({req}st::CancellationToken cancellationToken);"
                );
        }
Exemplo n.º 11
0
        private void ProcessEachService(ServiceDescriptorProto service, StringBuilder sb)
        {
            int  serviceId;
            bool hasServiceId = service.Options.CustomOptions.TryGetInt32(DotBPEOptions.SERVICE_ID, out serviceId);

            if (!hasServiceId || serviceId <= 0)
            {
                throw new Exception("Service=" + service.Name + " ServiceId NOT_FOUND");
            }
            if (serviceId >= ushort.MaxValue)
            {
                throw new Exception("Service=" + service.Name + "ServiceId too large");
            }



            foreach (var method in service.Method)
            {
                int  msgId;
                bool hasMsgId = method.Options.CustomOptions.TryGetInt32(DotBPEOptions.MESSAGE_ID, out msgId);
                if (!hasMsgId || msgId <= 0)
                {
                    throw new Exception("Service" + service.Name + "." + method.Name + " ' MessageId NOT_FINDOUT ");
                }
                if (msgId >= ushort.MaxValue)
                {
                    throw new Exception("Service" + service.Name + "." + method.Name + " is too large");
                }

                bool hasOption = method.Options.CustomOptions.TryGetMessage <DotBPE.Protobuf.HttpApiOption>(DotBPEOptions.HTTP_API_OPTION, out var options);
                if (hasOption)
                {
                    sb.AppendLine("            list.Add(new HttpApiOption()");
                    sb.AppendLine("            {");
                    sb.AppendLine($"                ServiceId = {serviceId},");
                    sb.AppendLine($"                MessageId = {msgId},");
                    sb.AppendLine($"                Path = \"{options.Path}\",");
                    sb.AppendLine($"                Method = \"{options.Method}\",");
                    sb.AppendLine($"                Description = \"{options.Description??""}\"");
                    sb.AppendLine("            });");
                }
            }
        }
Exemplo n.º 12
0
        private void CheckEachService(ServiceDescriptorProto service)
        {
            int  serviceId;
            bool hasServiceId = service.Options.CustomOptions.TryGetInt32(DotBPEOptions.SERVICE_ID, out serviceId);

            if (!hasServiceId || serviceId <= 0)
            {
                throw new Exception("Service=" + service.Name + " ServiceId NOT_FOUND");
            }
            if (serviceId >= ushort.MaxValue)
            {
                throw new Exception("Service=" + service.Name + "ServiceId too large");
            }

            if (_services.Contains(serviceId))
            {
                throw new Exception($" serviceid={serviceId} conflict!");
            }

            _services.Add(serviceId);

            foreach (var method in service.Method)
            {
                int  msgId;
                bool hasMsgId = method.Options.CustomOptions.TryGetInt32(DotBPEOptions.MESSAGE_ID, out msgId);
                if (!hasMsgId || msgId <= 0)
                {
                    throw new Exception("Service" + service.Name + "." + method.Name + " ' MessageId NOT_FINDOUT ");
                }
                if (msgId >= ushort.MaxValue)
                {
                    throw new Exception("Service" + service.Name + "." + method.Name + " is too large");
                }

                string checkKey = $"{serviceId}|{msgId}";
                if (_methods.Contains(checkKey))
                {
                    throw new Exception($" serviceid={serviceId},messageid={msgId} conflict!");
                }
                _methods.Add(checkKey);
            }
        }
Exemplo n.º 13
0
 public virtual void GenerateServiceFile(
     FileDescriptorProto file,
     ServiceDescriptorProto service,
     StreamWriter writer,
     List <NameInfo> names)
 {
     writer.WriteLines(
         $"// <auto-generated>",
         $"// \tGenerated by the sRPC compiler.  DO NOT EDIT!",
         $"// \tsource: {file.Name}",
         $"// </auto-generated>",
         // CS0067: event is newer used. This is a false positive. The events are indeed used by sRPC
         // CS0612: obsolete is accessed (a strategy to work with these is missing)
         // CS1591: xml comment is missing for public member (this feature is in todo)
         $"#pragma warning disable CS0067, CS0612, CS1591",
         $"#region Designer generated code",
         $""
         );
     GenerateFileUsingsHeader(writer);
     if (Settings.Nullable != null)
     {
         writer.WriteLines(
             $"#nullable {(Settings.Nullable.Value ? "enable" : "disable")}",
             $""
             );
     }
     writer.WriteLines(
         $"namespace {file.Options?.CsharpNamespace ?? "Api"}",
         $"{{"
         );
     GenerateClientService(file, service, writer, names);
     GenerateServerService(file, service, writer, names);
     writer.WriteLines(
         $"}}",
         $"",
         $"#endregion Designer generated code"
         );
 }
Exemplo n.º 14
0
        private void GenerateEachService(ServiceDescriptorProto service, StringBuilder sb, int type)
        {
            int  serviceId;
            bool hasServiceId = service.Options.CustomOptions.TryGetInt32(DotBPEOptions.SERVICE_ID, out serviceId);

            if (!hasServiceId || serviceId <= 0)
            {
                throw new Exception("Service=" + service.Name + " ServiceId NOT_FOUND");
            }
            if (serviceId >= ushort.MaxValue)
            {
                throw new Exception("Service=" + service.Name + "ServiceId too large");
            }


            //循环方法
            foreach (var method in service.Method)
            {
                int  msgId;
                bool hasMsgId = method.Options.CustomOptions.TryGetInt32(DotBPEOptions.MESSAGE_ID, out msgId);
                if (!hasMsgId || msgId <= 0)
                {
                    throw new Exception("Service" + service.Name + "." + method.Name + " ' MessageId NOT_FINDOUT ");
                }
                if (msgId >= ushort.MaxValue)
                {
                    throw new Exception("Service" + service.Name + "." + method.Name + " is too large");
                }
                //异步方法


                string typeName = type == 1? Utils.GetTypeName(method.InputType): Utils.GetTypeName(method.OutputType);

                sb.AppendLine("if(serviceId == " + serviceId + " && messageId == " + msgId + "){ return new " + typeName + "() ;\n}");
            }
            //循环方法end
        }
        private static FileDescriptorProto CreateFileDescriptor(string package)
        {
            var serviceList = new List <ServiceDescriptorProto>();

            for (var i = 0; i < ServicesCount; i++)
            {
                var service = new ServiceDescriptorProto {
                    Name = GetServiceName(i)
                };
                for (var j = 0; j < MethodCount; j++)
                {
                    service.Methods.Add(new MethodDescriptorProto {
                        Name = GetMethodName(service.Name, j)
                    });
                }
                serviceList.Add(service);
            }

            var fileDescriptor = new FileDescriptorProto();

            fileDescriptor.Package = package;
            fileDescriptor.Services.AddRange(serviceList);
            return(fileDescriptor);
        }
Exemplo n.º 16
0
 /// <summary>Helper: Serialize into a MemoryStream and return its byte array</summary>
 public static byte[] SerializeToBytes(ServiceDescriptorProto instance)
 {
     using (var ms = new MemoryStream())
     {
         Serialize(ms, instance);
         return ms.ToArray();
     }
 }
Exemplo n.º 17
0
 /// <summary>Helper: Serialize with a varint length prefix</summary>
 public static void SerializeLengthDelimited(Stream stream, ServiceDescriptorProto instance)
 {
     var data = SerializeToBytes(instance);
     global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, (uint)data.Length);
     stream.Write(data, 0, data.Length);
 }
Exemplo n.º 18
0
        /// <summary>Serialize the instance into the stream</summary>
        public static void Serialize(Stream stream, ServiceDescriptorProto instance)
        {
            if (instance.Name != null)
            {
                // Key for field: 1, LengthDelimited
                stream.WriteByte(10);
                global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(instance.Name));
            }
            if (instance.Method != null)
            {
                foreach (var i2 in instance.Method)
                {
                    // Key for field: 2, LengthDelimited
                    stream.WriteByte(18);
                    using (var ms2 = new MemoryStream())
                    {
                        Google.protobuf.MethodDescriptorProto.Serialize(ms2, i2);
                        // Length delimited byte array
                        uint ms2Length = (uint)ms2.Length;
                        global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, ms2Length);
                        stream.Write(ms2.GetBuffer(), 0, (int)ms2Length);
                    }

                }
            }
            if (instance.Options != null)
            {
                // Key for field: 3, LengthDelimited
                stream.WriteByte(26);
                using (var ms3 = new MemoryStream())
                {
                    Google.protobuf.ServiceOptions.Serialize(ms3, instance.Options);
                    // Length delimited byte array
                    uint ms3Length = (uint)ms3.Length;
                    global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, ms3Length);
                    stream.Write(ms3.GetBuffer(), 0, (int)ms3Length);
                }

            }
        }
Exemplo n.º 19
0
 /// <summary>Helper: create a new instance to deserializing into</summary>
 public static ServiceDescriptorProto DeserializeLengthDelimited(Stream stream)
 {
     ServiceDescriptorProto instance = new ServiceDescriptorProto();
     DeserializeLengthDelimited(stream, instance);
     return instance;
 }
Exemplo n.º 20
0
 /// <summary>Helper: create a new instance to deserializing into</summary>
 public static ServiceDescriptorProto DeserializeLength(Stream stream, int length)
 {
     ServiceDescriptorProto instance = new ServiceDescriptorProto();
     DeserializeLength(stream, length, instance);
     return instance;
 }
 /// <summary>
 /// Starts a service block
 /// </summary>
 protected override void WriteServiceHeader(GeneratorContext ctx, ServiceDescriptorProto service, ref object state)
 {
     ctx.WriteLine($"{GetAccess( GetAccess( service ) )} interface I{Escape( service.Name )}").WriteLine("{").Indent();
 }
        /// <summary>Serialize the instance into the stream</summary>
        public static void Serialize(Stream stream, ServiceDescriptorProto instance)
        {
            var msField = global::SilentOrbit.ProtocolBuffers.ProtocolParser.Stack.Pop();
            if (instance.Name != null)
            {
                // Key for field: 1, LengthDelimited
                stream.WriteByte(10);
                global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(instance.Name));
            }
            if (instance.Method != null)
            {
                foreach (var i2 in instance.Method)
                {
                    // Key for field: 2, LengthDelimited
                    stream.WriteByte(18);
                    msField.SetLength(0);
                    Google.Protobuf.MethodDescriptorProto.Serialize(msField, i2);
                    // Length delimited byte array
                    uint length2 = (uint)msField.Length;
                    global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, length2);
                    msField.WriteTo(stream);

                }
            }
            if (instance.Options != null)
            {
                // Key for field: 3, LengthDelimited
                stream.WriteByte(26);
                msField.SetLength(0);
                Google.Protobuf.ServiceOptions.Serialize(msField, instance.Options);
                // Length delimited byte array
                uint length3 = (uint)msField.Length;
                global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, length3);
                msField.WriteTo(stream);

            }
            global::SilentOrbit.ProtocolBuffers.ProtocolParser.Stack.Push(msField);
        }
 /// <summary>Helper: create a new instance to deserializing into</summary>
 public static ServiceDescriptorProto Deserialize(Stream stream)
 {
     var instance = new ServiceDescriptorProto();
     Deserialize(stream, instance);
     return instance;
 }
Exemplo n.º 24
0
 public GrpcServiceDefinition(ServiceDescriptorProto serviceDescriptor, string package)
 {
     Name    = FormatHelper.FormatServiceFullName(package, serviceDescriptor.Name);
     Methods = serviceDescriptor.Methods.Select(m => new GrpcMethodDefinition(Name, m));
 }
Exemplo n.º 25
0
 /// <summary>
 /// Emit code following a set of service methods
 /// </summary>
 protected override void WriteServiceFooter(GeneratorContext ctx, ServiceDescriptorProto service, ref object state)
 {
     ctx.Outdent().WriteLine("}").WriteLine();
 }
Exemplo n.º 26
0
        private static void GenerateServiceForClient(ServiceDescriptorProto service, StringBuilder sb)
        {
            int  serviceId;
            bool hasServiceId = service.Options.CustomOptions.TryGetInt32(DotBPEOptions.SERVICE_ID, out serviceId);

            if (!hasServiceId || serviceId <= 0)
            {
                throw new Exception("Service=" + service.Name + " ServiceId NOT_FOUND");
            }
            if (serviceId >= ushort.MaxValue)
            {
                throw new Exception("Service=" + service.Name + "ServiceId too large");
            }

            sb.AppendFormat("   public sealed class {0}Client : AmpInvokeClient \n", service.Name);
            sb.AppendLine("    {");
            //构造函数
            sb.AppendLine($"        public {service.Name}Client(IRpcClient<AmpMessage> client) : base(client)");
            sb.AppendLine("        {");
            sb.AppendLine("        }");

            sb.AppendLine($"        public {service.Name}Client(string remoteAddress) : base(remoteAddress)");
            sb.AppendLine("        {");
            sb.AppendLine("        }");

            //循环方法
            foreach (var method in service.Method)
            {
                int  msgId;
                bool hasMsgId = method.Options.CustomOptions.TryGetInt32(DotBPEOptions.MESSAGE_ID, out msgId);
                if (!hasMsgId || msgId <= 0)
                {
                    throw new Exception("Service" + service.Name + "." + method.Name + " ' MessageId NOT_FINDOUT ");
                }
                if (msgId >= ushort.MaxValue)
                {
                    throw new Exception("Service" + service.Name + "." + method.Name + " is too large");
                }
                //异步方法
                string outType = Utils.GetTypeName(method.OutputType);
                string inType  = Utils.GetTypeName(method.InputType);

                sb.AppendLine($"        public async Task<RpcResult<{outType}>> {method.Name}Async({inType} request,int timeOut=3000)");
                sb.AppendLine("        {");
                sb.AppendLine($"            AmpMessage message = AmpMessage.CreateRequestMessage({serviceId}, {msgId});");
                sb.AppendLine("            message.Data = request.ToByteArray();");
                sb.AppendLine("            var response = await base.CallInvoker.AsyncCall(message,timeOut);");
                sb.AppendLine("            if (response == null)");
                sb.AppendLine("            {");
                sb.AppendLine("                throw new RpcException(\"error,response is null !\");");
                sb.AppendLine("            }");
                sb.AppendLine($"            var result = new RpcResult<{outType}>();");
                sb.AppendLine("            if (response.Code != 0)");
                sb.AppendLine("            {");
                sb.AppendLine("                result.Code = response.Code;");
                sb.AppendLine("            }");
                sb.AppendLine("            else if (response.Data == null)");
                sb.AppendLine("            {");
                sb.AppendLine("                result.Code = ErrorCodes.CODE_INTERNAL_ERROR;");
                sb.AppendLine("            }");
                sb.AppendLine("            else");
                sb.AppendLine("            {");
                sb.AppendLine($"                result.Data = {outType}.Parser.ParseFrom(response.Data);");
                sb.AppendLine("            }");

                sb.AppendLine("            return result;");
                sb.AppendLine("        }");

                sb.AppendLine();
                sb.AppendLine("        //同步方法");
                sb.AppendLine($"        public RpcResult<{outType}> {method.Name}({inType} request)");
                sb.AppendLine("        {");
                sb.AppendLine($"            AmpMessage message = AmpMessage.CreateRequestMessage({serviceId}, {msgId});");
                sb.AppendLine("            message.Data = request.ToByteArray();");
                sb.AppendLine("            var response =  base.CallInvoker.BlockingCall(message);");
                sb.AppendLine("            if (response == null)");
                sb.AppendLine("            {");
                sb.AppendLine("                throw new RpcException(\"error,response is null !\");");
                sb.AppendLine("            }");
                sb.AppendLine($"            var result = new RpcResult<{outType}>();");
                sb.AppendLine("            if (response.Code != 0)");
                sb.AppendLine("            {");
                sb.AppendLine("                result.Code = response.Code;");
                sb.AppendLine("            }");
                sb.AppendLine("            else if (response.Data == null)");
                sb.AppendLine("            {");
                sb.AppendLine("                result.Code = ErrorCodes.CODE_INTERNAL_ERROR;");
                sb.AppendLine("            }");
                sb.AppendLine("            else");
                sb.AppendLine("            {");
                sb.AppendLine($"                result.Data = {outType}.Parser.ParseFrom(response.Data);");
                sb.AppendLine("            }");

                sb.AppendLine("            return result;");
                sb.AppendLine("         }");
                //循环方法end
            }
            sb.AppendLine("     }");
            //类结束
        }
Exemplo n.º 27
0
        private static void GenerateServiceForServer(ServiceDescriptorProto service, StringBuilder sb)
        {
            int  serviceId;
            bool hasServiceId = service.Options.CustomOptions.TryGetInt32(DotBPEOptions.SERVICE_ID, out serviceId);

            if (!hasServiceId || serviceId <= 0)
            {
                throw new Exception("Service=" + service.Name + " ServiceId not found");
            }
            if (serviceId >= ushort.MaxValue)
            {
                throw new Exception("Service=" + service.Name + "ServiceId too large");
            }

            sb.AppendFormat("   public abstract class {0}Base : ServiceActor \n", service.Name);
            sb.AppendLine("   {");

            sb.AppendLine("      protected override int ServiceId => " + serviceId + ";");



            StringBuilder sbIfState = new StringBuilder();

            //循环方法
            foreach (var method in service.Method)
            {
                int  msgId;
                bool hasMsgId = method.Options.CustomOptions.TryGetInt32(DotBPEOptions.MESSAGE_ID, out msgId);
                if (!hasMsgId || msgId <= 0)
                {
                    throw new Exception("Service" + service.Name + "." + method.Name + " ' MessageId  not found ");
                }
                if (msgId >= ushort.MaxValue)
                {
                    throw new Exception("Service" + service.Name + "." + method.Name + " is too large");
                }
                //异步方法
                string outType = Utils.GetTypeName(method.OutputType);
                string inType  = Utils.GetTypeName(method.InputType);


                sb.AppendLine("      //调用委托");
                sb.AppendLine($"      private async Task<AmpMessage> Process{method.Name}Async(AmpMessage req)");
                sb.AppendLine("      {");
                //添加判断req.Data == null;
                sb.AppendLine($"         {inType} request = null;");
                sb.AppendLine("");
                sb.AppendLine("         if(req.Data == null ){");
                sb.AppendLine($"            request = new {inType}();");
                sb.AppendLine("         }");
                sb.AppendLine("         else {");
                sb.AppendLine($"            request = {inType}.Parser.ParseFrom(req.Data);");
                sb.AppendLine("         }");
                sb.AppendLine("");
                sb.AppendLine($"         var result = await {method.Name}Async(request);");
                sb.AppendLine("         var response = AmpMessage.CreateResponseMessage(req.ServiceId, req.MessageId);");
                sb.AppendLine("         response.Code = result.Code;");
                sb.AppendLine("         if( result.Data !=null )");
                sb.AppendLine("         {");
                sb.AppendLine("             response.Data = result.Data.ToByteArray();");
                sb.AppendLine("         }");
                sb.AppendLine("         return response;");
                sb.AppendLine("      }");

                sb.AppendLine();


                sb.AppendLine("      //抽象方法");
                sb.AppendLine($"      public abstract Task<RpcResult<{outType}>> {method.Name}Async({inType} request);");

                //拼装if调用语句
                sbIfState.AppendFormat("            //方法{0}.{1}\n", service.Name, method.Name);
                sbIfState.AppendLine("            case " + msgId + ": return this.Process" + method.Name + "Async(req);");
            }

            //循环方法end
            //生成主调用代码
            sb.AppendLine("      public override Task<AmpMessage> ProcessAsync(AmpMessage req)");
            sb.AppendLine("      {");

            sb.AppendLine("         switch(req.MessageId){");
            sb.Append(sbIfState);
            sb.AppendLine("            default: return base.ProcessNotFoundAsync(req);");
            sb.AppendLine("         }"); //end switch case
            sb.AppendLine("      }");


            sb.AppendLine("   }");
            //类结束
        }
Exemplo n.º 28
0
 /// <summary>Helper: put the buffer into a MemoryStream and create a new instance to deserializing into</summary>
 public static ServiceDescriptorProto Deserialize(byte[] buffer)
 {
     ServiceDescriptorProto instance = new ServiceDescriptorProto();
     using (var ms = new MemoryStream(buffer))
         Deserialize(ms, instance);
     return instance;
 }
Exemplo n.º 29
0
 /// <summary>
 /// Emit code following preceeding a set of service methods
 /// </summary>
 protected virtual void WriteServiceHeader(GeneratorContext ctx, ServiceDescriptorProto obj, ref object state)
 {
 }
Exemplo n.º 30
0
        static void WorkSingleEntry(Docs.ServiceDocFactory docs, FileDescriptorProto filedesc, ServiceDescriptorProto service, List <NameInfo> names, string sourceFile)
        {
            var targetName = filedesc.Options?.CsharpNamespace ?? "";

            if (targetName.StartsWith(settings.NamespaceBase))
            {
                targetName = targetName.Substring(settings.NamespaceBase.Length);
            }
            else
            {
                log.WriteWarning(text: $"the c# namespace {targetName} has not the base {settings.NamespaceBase}. The namespace will not be shortened.",
                                 file: filedesc.Name);
            }
            if (targetName != null)
            {
                targetName += '.';
            }
            targetName = (targetName + service.Name).Replace('.', '/');
            if (targetName.StartsWith("/"))
            {
                targetName = targetName.Substring(1);
            }
            targetName = Path.Combine(settings.OutputDir + "/", targetName + settings.FileExtension);
            if (settings.Verbose)
            {
                Console.WriteLine($" Generate service for {service.Name} at {targetName}...");
            }
            var fi = new FileInfo(targetName);

            if (!fi.Directory.Exists)
            {
                try { fi.Directory.Create(); }
                catch (IOException e)
                {
                    log.WriteError(text: $"Couldn't create directory for output file {targetName}: {e}",
                                   file: filedesc.Name);
                    return;
                }
            }
            using var writer = new StreamWriter(new FileStream(targetName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite));
            writer.BaseStream.SetLength(0);
            Generator generator = settings.OutputFormat switch
            {
                "1" => new Generator(docs, settings, log),
                "2" => new Generator2(docs, settings, log),
                _ => new Generator(docs, settings, log),
            };

            generator.GenerateServiceFile(filedesc, service, writer, names);
            writer.Flush();

            if (report != null)
            {
                if (settings.BuildProtoc)
                {
                    sourceFile = sourceFile[0..^ 4];