GRPCServer

A gRPC server.

GRPCServer.swift:78
final class GRPCServer<Transport> where Transport : ServerTransport

The server accepts connections from clients and listens on each connection for new streams which are initiated by the client. Each stream maps to a single RPC. The server routes accepted streams to a service to handle the RPC or rejects them with an appropriate error if no service can handle the RPC.

A GRPCServer listens with a specific transport implementation (for example, HTTP/2 or in-process), and routes requests from the transport to the service instance. You can also use “interceptors”, to implement cross-cutting logic which apply to all accepted RPCs. Example uses of interceptors include request filtering, authentication, and logging. Once requests have been intercepted they are passed to a handler which in turn returns a response to send back to the client.

Configuring and starting a server

The following example demonstrates how to create and run a server.

// Create a transport
let transport = SomeServerTransport()

// Create the 'Greeter' and 'Echo' services.
let greeter = GreeterService()
let echo = EchoService()

// Create an interceptor.
let statsRecorder = StatsRecordingServerInterceptors()

// Run the server.
try await withGRPCServer(
  transport: transport,
  services: [greeter, echo],
  interceptors: [statsRecorder]
) { server in
  // ...
  // The server begins shutting down when this closure returns
  // ...
}

Creating a client manually

If the with-style methods for creating a server isn’t suitable for your application then you can create and run it manually. This requires you to call the serve method in a task which instructs the server to start its transport and listen for new RPCs. A RuntimeError is thrown if the transport can’t be started or encounters some other runtime error.

// Start running the server.
try await server.serve()

The serve method won’t return until the server has finished handling all requests. You can signal to the server that it should stop accepting new requests by calling beginGracefulShutdown. This allows the server to drain existing requests gracefully. To stop the server more abruptly you can cancel the task running your server. If your application requires additional resources that need their lifecycles managed you should consider using Swift Service Lifecycle and the GRPCServiceLifecycle module provided by gRPC Swift Extras.