ReflectionServer.swift 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. * Copyright 2024, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import ArgumentParser
  17. import Foundation
  18. import GRPCCore
  19. import GRPCNIOTransportHTTP2
  20. import GRPCProtobuf
  21. import GRPCReflectionService
  22. @main
  23. struct ReflectionServer: AsyncParsableCommand {
  24. @Option(help: "The port to listen on")
  25. var port: Int = 31415
  26. func run() async throws {
  27. // Find descriptor sets ('*.pb') bundled with this example.
  28. let paths = Bundle.module.paths(forResourcesOfType: "pb", inDirectory: "DescriptorSets")
  29. // Start the server with the reflection service and the echo service.
  30. let server = GRPCServer(
  31. transport: .http2NIOPosix(
  32. address: .ipv4(host: "127.0.0.1", port: self.port),
  33. transportSecurity: .plaintext
  34. ),
  35. services: [
  36. try ReflectionService(descriptorSetFilePaths: paths),
  37. EchoService(),
  38. ]
  39. )
  40. try await withThrowingDiscardingTaskGroup { group in
  41. group.addTask { try await server.serve() }
  42. if let address = try await server.listeningAddress?.ipv4 {
  43. print("Reflection server listening on \(address)")
  44. print(String(repeating: "-", count: 80))
  45. let example = """
  46. If you have grpcurl installed you can query the service to discover services
  47. and make calls against them. You can install grpcurl by following the
  48. instruction in its repository: https://github.com/fullstorydev/grpcurl
  49. Here are some example commands:
  50. List all services:
  51. $ grpcurl -plaintext \(address.host):\(address.port) list
  52. Describe the 'Get' method in the 'echo.Echo' service:
  53. $ grpcurl -plaintext \(address.host):\(address.port) describe echo.Echo.Get
  54. Call the 'echo.Echo.Get' method:
  55. $ grpcurl -plaintext -d '{ "text": "Hello" }' \(address.host):\(address.port) echo.Echo.Get
  56. """
  57. print(example)
  58. }
  59. }
  60. }
  61. }