Upgrade to Pro — share decks privately, control downloads, hide ads and more …

gRPC & Blazor WebAssembly: Ein Traumpaar!?

gRPC & Blazor WebAssembly: Ein Traumpaar!?

Mit Blazor WebAssembly können Entwickler C#-Code für SPAs im Browser schreiben und Code mit der Serverseite ihrer Anwendungen teilen. Normalerweise entwerfen und verwenden wir hier JSON-basierte Web-APIs, um zwischen der Client- und der Serverlogik zu kommunizieren.
In dieser Session demonstriert Christian Weyer, wie man gRPC und gRPC-Web auf eine Code-First-Weise einsetzt, um .NET-Interfaces streng typisiert auf beiden Seiten zu nutzen. Bei diesem Ansatz ist keine Codegenerierung erforderlich, Sie erhalten auf beiden Seiten die gleiche Syntax und volles IntelliSense. Tatsächlich gewinnen Sie die guten Teile, die wir bereits vor viiieeelen Jahren mit WCF hatten, jetzt für das allgegenwärtige und offene Web. Aber: Ist wirklich alles Gold, was glänzt?

Christian Weyer

October 11, 2022
Tweet

More Decks by Christian Weyer

Other Decks in Programming

Transcript

  1. § Cloud-native & serverless architectures § Pragmatic end-to-end solutions §

    Mobile & web-based application architectures § Independent Microsoft Regional Director § Microsoft MVP for Developer Technologies & Azure ASPInsider, AzureInsider § Google GDE for Web Technologies [email protected] @christianweyer https://www.thinktecture.com gRPC & Blazor WebAssembly Ein Traumpaar!? Christian Weyer Co-Founder & CTO @ Thinktecture AG 2
  2. 3 § Server-side [micro]services with APIs § Written in C#

    with ASP.NET Core § Exposing HTTP/ REST/ Web APIs § Web-based smart clients § JavaScript-based SPAs, with Angular, React et. al. § Communication via HTTPS § Sending JSON data gRPC & Blazor WebAssembly Ein Traumpaar!? Typical SPA architectures for modern business applications HTTP API WS API Service D HTTPS HTTPS WebSocket Service A Service B Service C HTTP API
  3. 4 § Building SPAs end-to-end § Often too complex, with

    different stacks involved § Increased needed knowledge & different coding habits → Improving developer productivity § SPA communication with server-side APIs/services § Thinking different in controlled & closed environments → Improving the inner loop gRPC & Blazor WebAssembly Ein Traumpaar!? Beyond our own nose: Reconsidering SPA architectures – in a pragmatic way
  4. 5 gRPC & Blazor WebAssembly Ein Traumpaar!? Two assumptions –

    for controlled environments One programming language & framework Strongly typed client-server communication
  5. 6 gRPC & Blazor WebAssembly Ein Traumpaar!? Two assumptions One

    programming language & framework Strongly typed client-server communication
  6. § Blazor is a family of web technologies § Server

    § WebAssembly § Hybrid § Blazor WebAssembly is an SPA framework § Web, SPA & distributed architectures knowledge § HTML, CSS knowledge § DOM knowledge § JavaScript for DOM interaction & 3rd party integration § C# & .NET Standard for client-side logic → Full-stack C# possible gRPC & Blazor WebAssembly Ein Traumpaar!? Blazor as SPA technology 8
  7. 9 gRPC & Blazor WebAssembly Ein Traumpaar!? Two assumptions One

    programming language & framework Strongly typed client-server communication
  8. 😊 § JSON as major data exchange format § Great

    tooling § Highly interoperable § Can handle arbitrary binary data 🤔 § JSON text format can be verbose § Loosely coupled & typed § Yeah, by design § Open API can help here § RPC-ish in many cases gRPC & Blazor WebAssembly Ein Traumpaar!? Reconsidering Web APIs as service interfaces § Let’s just call them Web APIs, please (“REST”…) 10
  9. 11 gRPC & Blazor WebAssembly Ein Traumpaar!? Open API /

    Swagger code-gen? Web APIs & HttpClient Strongly-typed gRPC services & clients Our journey
  10. 12 gRPC & Blazor WebAssembly Ein Traumpaar!? Open API /

    Swagger code-gen? Service proxy pattern Web APIs & HttpClient Strongly-typed gRPC services & clients Our journey
  11. 14 § Initially created for interoperable synchronous [micro]service-to-[micro]service communication §

    Its presence increases steadily (see GoLang) § Some people like to use gRPC between frontends and backends, as well § Uses HTTP/2 & Protocol Buffers § gRPC is genuinely contract-first gRPC & Blazor WebAssembly Ein Traumpaar!? gRPC
  12. 15 gRPC & Blazor WebAssembly Ein Traumpaar!? Protocol Buffers (ProtoBuf)

    § Language-neutral, platform-neutral, extensible mechanism for describing & serializing structured data § Like XML/XSD, but smaller, faster, and partly simpler § Uses integer tokens to identify members, not names § Support for code generation for many languages, including C# § Also: (binary) serialization format on the wire message Person { required string name = 1; required int32 id = 2; optional string email = 3; }
  13. 16 § gRPC support since .NET Core 3.0 § Always

    contract-first: write .proto file first § Implement gRPC service based on generated base class § Get typed client proxy generated on the client side based § C# code gets generated when the .proto file changes § “Add Service Reference…” in VS can handle the client side for you gRPC & Blazor WebAssembly Ein Traumpaar!? gRPC in .NET
  14. 17 gRPC & Blazor WebAssembly Ein Traumpaar!? Open API /

    Swagger code-gen? Service proxy pattern gRPC service ? Web APIs & HttpClient Strongly-typed gRPC services & clients Our journey
  15. 1. We are in .NET world on both sides §

    Services § Clients We are in a controlled environment 👉 Let’s do .NET, all the way! 2. (Pure) gRPC does not work for browsers gRPC & Blazor WebAssembly Ein Traumpaar!? OK – This is not what we want 😏 18
  16. 19 § gRPC in .NET without having to write .proto

    files § Improving the inner loop § Open-source community project protobuf-net.Grpc § Implement gRPC service based on .NET interface § Get strongly-typed client proxy at runtime based on .NET interface § Can use WCF contract semantics § ServiceContract, DataContract § Offers its own semantics § Service, ProtoContract gRPC & Blazor WebAssembly Ein Traumpaar!? Code-First gRPC in .NET & Blazor
  17. 20 gRPC & Blazor WebAssembly Ein Traumpaar!? Open API /

    Swagger code-gen? Service proxy pattern gRPC service? Code-first gRPC service Web APIs & HttpClient Strongly-typed gRPC services & clients Our journey
  18. 22 § Native gRPC does not work in browsers §

    Due to restrictions for HTTP/2 framing in browsers § gRPC-Web is slimmed-down implementation of gRPC for browser clients § gRPC-Web clients connect to gRPC services via a gRPC-Web proxy § Available since .NET Core 3.1 § Server-side ASP.NET Core middleware for proxy § .NET client library (beyond JavaScript lib from community) § Unary calls & server-streaming supported gRPC & Blazor WebAssembly Ein Traumpaar!? gRPC-Web
  19. 23 gRPC & Blazor WebAssembly Ein Traumpaar!? Open API /

    Swagger code-gen? Service proxy pattern gRPC service? Code-first gRPC service gRPC-Web facade Web APIs & HttpClient Strongly-typed gRPC services & clients Our journey
  20. 24 gRPC & Blazor WebAssembly Ein Traumpaar!? Open API /

    Swagger code-gen? Service proxy pattern gRPC service? Code-first gRPC service gRPC-Web facade Code-first gRPC-Web client Web APIs & HttpClient Strongly-typed gRPC services & clients Our journey
  21. 25 gRPC & Blazor WebAssembly Ein Traumpaar!? Open API /

    Swagger code-gen? Service proxy pattern gRPC service? Code-first gRPC service gRPC-Web facade Code-first gRPC-Web client Web APIs & HttpClient Strongly-typed gRPC services & clients Our journey
  22. 26 § gRPC has basic built-in error handling based on

    simple status codes and metadata § In service: throw new RpcException(new Status(StatusCode.PermissionDenied, "Permission denied"), metadata); // metadata is your DTO § In client: catch (RpcException ex) when (ex.StatusCode == StatusCode.PermissionDenied) { var userEntry = ex.Trailers.FirstOrDefault(e => e.Key == "User"); Console.WriteLine($"User '{userEntry.Value}’ does not have permission to view this portfolio."); } gRPC & Blazor WebAssembly Ein Traumpaar!? Errors & exceptions
  23. 27 § In contract-first world, you share the .proto files

    § In code-first, you share .NET code § For testing and debugging tools, we need runtime information from the gRPC services § gRPC server reflection protocol is a standard § gRPCurl, gRPCui, Postman are prominent testing tools § protobuf-net.Grpc has reflection support § builder.Services.AddCodeFirstGrpcReflection(); § app.MapCodeFirstGrpcReflectionService(); gRPC & Blazor WebAssembly Ein Traumpaar!? Reflection & testing with gRPC code-first
  24. 28 § Authentication and authorization are not gRPC-Web’s business §

    Usually, OAuth2- / OIDC-based token § Use ASP.NET Core’s features as with Web APIs § app.UseAuthentication(); § app.UseAuthorization(); § [Authorize] § In Blazor, use AuthorizationMessageHandler to add bearer token to gRPC-Web requests gRPC & Blazor WebAssembly Ein Traumpaar!? Authentication & authorization for gRPC-Web
  25. 29 § Transferring a stream of data over a longer

    period of time § Only server streaming supported in gRPC-Web § Can be used for real-time push § Server with protobuf-net.Grpc § IAsyncEnumerable<T> and CallContext in service interface § Client with protobuf-net.Grpc § Use CallOptions to enable cancellation with CancellationTokenSource gRPC & Blazor WebAssembly Ein Traumpaar!? Streaming data with gRPC-Web code-first
  26. 30 § No native support in browsers § gRPC-Web Developer

    Tools as Chrome extension § https://github.com/ SafetyCulture/ grpc-web-devtools § Blazor WASM integration PoC § https://github.com/thinktecture-labs/blazor-grpc-web-devtooling gRPC & Blazor WebAssembly Ein Traumpaar!? Developer tooling in browser
  27. 31 § gRPC / gRPC-Web in Blazor WASM can be

    really fast § Comparing JSON and gRPC-Web requests § With AOT § JSON is 6 times faster § gRPC is 10 times faster § gRPC deserializes 10,000 items in 0.03 seconds § https://grpcblazorperf.azurewebsites.net gRPC & Blazor WebAssembly Ein Traumpaar!? Performance & size https://twitter.com/JamesNK/status/1399496670958604292
  28. 33 gRPC & Blazor WebAssembly Ein Traumpaar!? .NET SPA-to-API communication

    – in controlled scenarios Web API gRPC (-Web) SignalR Different API styles possible (RPC, REST, GraphQL, OData etc.) RPC Bi-directional RPC HTTP HTTP/2 WebSockets (transport protocol fallbacks) Stateless Stateless Stateful Code-first Contract-first with external tooling Contract-first Code-first with 3rd party lib Code-first Code sharing of DTOs Code-gen possible Full code sharing w/ Code-First Code-gen with Contract-first Not intended for code sharing No client lib needed (fetch) Needs client lib Needs client lib Usually request-response Push possible (e.g., via long polling) Can do streaming Several message exchange patterns Push possible Efficient data streaming Dual one-way Optimized for push Broadcast possible Strong tooling ecosystem Evolving tooling ecosystem No tooling ecosystem
  29. 😊 § Code-first: Strongly-typed, full fidelity for .NET developers §

    ProtoBuf binary data is very compact § gRPC can be significantly faster than Web APIs 🤔 § gRPC tooling not yet as good as for Web APIs § gRPC errors & exceptions story could be improved gRPC & Blazor WebAssembly Ein Traumpaar!? gRPC-Web & Blazor – a match made in heaven? 34