1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
| using Google.Protobuf.Compiler; using Google.Protobuf.Reflection; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text;
namespace DotBPE.ProtobufPlugin { public class DotbpeGen { public static void Generate(CodeGeneratorRequest request, CodeGeneratorResponse response) { foreach (var protofile in request.ProtoFile) { try{ GenerateByProtoFile(protofile, response); } catch(Exception ex){ using (Stream stream = File.Create("./error.txt")) { byte[] err = Encoding.UTF8.GetBytes(ex.Message+ex.StackTrace); stream.Write(err,0,err.Length); } response.Error += ex.Message; } } }
private static void GenerateSourceInfo(FileDescriptorProto protofile, CodeGeneratorResponse response) { bool genericDoc; protofile.Options.CustomOptions.TryGetBool(DotBPEOptions.GENERIC_MARKDOWN_DOC,out genericDoc); if (!genericDoc) { return; } StringBuilder sb = new StringBuilder(); foreach (var location in protofile.SourceCodeInfo.Location) { string path = String.Join(",", location.Path); string span = String.Join(",", location.Span); string leadingDetachedComments = String.Join("\r", location.LeadingDetachedComments); string trailingComments = String.Join("\r", location.TrailingComments); sb.AppendLine("{\"Path\",\""+path+"\",\"Span\",\""+span+"\",\"LeadingComments\",\""+ location.LeadingComments + "\",\"LeadingDetachedComments\",\""+ leadingDetachedComments + "\",\"TrailingComments\",\""+ trailingComments + "\"}"); } var nfile = new CodeGeneratorResponse.Types.File { Name = GetFileName(protofile.Name) + "SI.txt", Content = sb.ToString() }; response.File.Add(nfile); } private static void GenerateByProtoFile(FileDescriptorProto protofile, CodeGeneratorResponse response) { GenerateSourceInfo(protofile, response); GenerateServer(protofile, response); GenerateClient(protofile, response);
} private static void GenerateServer(FileDescriptorProto protofile, CodeGeneratorResponse response) { bool genericServer; protofile.Options.CustomOptions.TryGetBool(DotBPEOptions.DISABLE_GENERIC_SERVICES_SERVER, out genericServer); if (genericServer) { return; } if (protofile.Service == null || protofile.Service.Count <= 0) return; StringBuilder sb = new StringBuilder(); sb.AppendLine("// Generated by the protocol buffer compiler. DO NOT EDIT!"); sb.AppendLine($"// source: {protofile.Name}");
sb.AppendLine("#region Designer generated code"); sb.AppendLine(""); sb.AppendLine("using System; "); sb.AppendLine("using System.Threading.Tasks; "); sb.AppendLine("using DotBPE.Rpc; "); sb.AppendLine("using DotBPE.Protocol.Amp; "); sb.AppendLine("using Google.Protobuf; "); sb.AppendLine("");
string ns = GetFileNamespace(protofile); sb.AppendLine("namespace " + ns + " {"); foreach (ServiceDescriptorProto t in protofile.Service) { t.Options.CustomOptions.TryGetBool(DotBPEOptions.DISABLE_GENERIC_SERVICES_SERVER, out genericServer); if (genericServer) { continue; }
sb.AppendLine(""); sb.AppendLine("//start for class Abstract"+t.Name); GenerateServiceForServer(t, sb); sb.AppendLine("//end for class Abstract"+t.Name); } sb.AppendLine("}\n"); sb.AppendLine("#endregion\n");
var nfile = new CodeGeneratorResponse.Types.File { Name = GetFileName(protofile.Name) + "Server.cs", Content = sb.ToString() }; response.File.Add(nfile); } private static void GenerateClient(FileDescriptorProto protofile, CodeGeneratorResponse response) { bool genericClient; protofile.Options.CustomOptions.TryGetBool(DotBPEOptions.DISABLE_GENERIC_SERVICES_CLIENT, out genericClient); if (genericClient) { return; } if (protofile.Service == null || protofile.Service.Count <= 0) return; StringBuilder sb = new StringBuilder(); sb.AppendLine("// Generated by the protocol buffer compiler. DO NOT EDIT!"); sb.AppendLine($"// source: {protofile.Name}");
sb.AppendLine("#region Designer generated code"); sb.AppendLine(""); sb.AppendLine("using System; "); sb.AppendLine("using System.Threading.Tasks; "); sb.AppendLine("using DotBPE.Rpc; "); sb.AppendLine("using DotBPE.Protocol.Amp; "); sb.AppendLine("using DotBPE.Rpc.Exceptions; "); sb.AppendLine("using Google.Protobuf; "); sb.AppendLine("");
string ns = GetFileNamespace(protofile); sb.AppendLine("namespace " + ns + " {");
foreach (ServiceDescriptorProto t in protofile.Service) { t.Options.CustomOptions.TryGetBool(DotBPEOptions.DISABLE_GENERIC_SERVICES_CLIENT, out genericClient); if (genericClient) { continue; } sb.AppendLine(""); sb.AppendLine("//start for class "+t.Name+"Client"); GenerateServiceForClient(t, sb); sb.AppendLine("//end for class "+t.Name+"Client"); } sb.AppendLine("}"); sb.AppendLine("#endregion");
var nfile = new CodeGeneratorResponse.Types.File { Name = GetFileName(protofile.Name) + "Client.cs", Content = sb.ToString() }; response.File.Add(nfile); }
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("}");
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 = GetTypeName(method.OutputType); string inType = GetTypeName(method.InputType);
sb.AppendLine($"public async Task<{outType}> {method.Name}Asnyc({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 && response.Data !=null)"); sb.AppendLine("{"); sb.AppendLine($"return {outType}.Parser.ParseFrom(response.Data);"); sb.AppendLine("}"); sb.AppendLine("throw new RpcException(\"请求出错,请检查!\");"); sb.AppendLine("}"); sb.AppendLine(); sb.AppendLine("//同步方法"); sb.AppendLine($"public {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 && response.Data !=null)"); sb.AppendLine("{"); sb.AppendLine($"return {outType}.Parser.ParseFrom(response.Data);"); sb.AppendLine("}"); sb.AppendLine("throw new RpcException(\"请求出错,请检查!\");"); sb.AppendLine("}"); }
sb.AppendLine("}");
} 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 : IServiceActor<AmpMessage> \n", service.Name); sb.AppendLine("{"); sb.AppendLine("public string Id => \""+serviceId+"$0\";");
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_FINDOUT "); } if(msgId>=ushort.MaxValue){ throw new Exception("Service" + service.Name+"."+method.Name+" is too large"); } string outType = GetTypeName(method.OutputType); string inType = GetTypeName(method.InputType);
sb.AppendLine("//调用委托"); sb.AppendLine( $"private async Task Receive{method.Name}Async(IRpcContext<AmpMessage> context, AmpMessage req)"); sb.AppendLine("{"); sb.AppendLine($"var request = {inType}.Parser.ParseFrom(req.Data);"); sb.AppendLine($"var data = await {method.Name}Async(request);"); sb.AppendLine("var response = AmpMessage.CreateResponseMessage(req.ServiceId, req.MessageId);"); sb.AppendLine("response.Sequence = req.Sequence;"); sb.AppendLine("response.Data = data.ToByteArray();"); sb.AppendLine("await context.SendAsync(response);"); sb.AppendLine("}");
sb.AppendLine();
sb.AppendLine("//抽象方法"); sb.AppendLine($"public abstract Task<{outType}> {method.Name}Async({inType} request);");
sbIfState.AppendFormat("//方法{0}.{1}\n",service.Name,method.Name); sbIfState.AppendLine("if(req.MessageId == "+msgId+"){return this.Receive"+method.Name+"Async(context, req);}"); } sb.AppendLine("public Task ReceiveAsync(IRpcContext<AmpMessage> context, AmpMessage req)"); sb.AppendLine("{"); sb.Append(sbIfState); sb.AppendLine("return Task.CompletedTask;"); sb.AppendLine("}");
sb.AppendLine("}");
} private static string GetFileNamespace(FileDescriptorProto protofile) { string ns = protofile.Options.CsharpNamespace; if (string.IsNullOrEmpty(ns)) { throw new Exception("" + protofile.Name + ".proto did not set csharp_namespace"); } return ConvertCamelCase(ns); }
private static string GetFileName(string fileProto) { string nomalName = fileProto.Split('.')[0]; return ConvertCamelCase(nomalName); }
private static string ConvertCamelCase(string nomalName) { return String.Join("", nomalName.Split('_').Select(_ => _.Substring(0, 1).ToUpper() + _.Substring(1))); }
private static string GetTypeName(string typeFullName) { return ConvertCamelCase(typeFullName.Split('.').Last()); } } }
|