NIOClientBootstrap+SocketAddress.swift 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 GRPCCore
  17. import GRPCHTTP2Core
  18. import NIOCore
  19. import NIOPosix
  20. extension ClientBootstrap {
  21. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  22. func connect<Result>(
  23. to address: GRPCHTTP2Core.SocketAddress,
  24. _ configure: @Sendable @escaping (Channel) -> EventLoopFuture<Result>
  25. ) async throws -> Result {
  26. if let ipv4 = address.ipv4 {
  27. return try await self.connect(to: NIOCore.SocketAddress(ipv4), channelInitializer: configure)
  28. } else if let ipv6 = address.ipv6 {
  29. return try await self.connect(to: NIOCore.SocketAddress(ipv6), channelInitializer: configure)
  30. } else if let uds = address.unixDomainSocket {
  31. return try await self.connect(to: NIOCore.SocketAddress(uds), channelInitializer: configure)
  32. } else if let vsock = address.virtualSocket {
  33. return try await self.connect(to: VsockAddress(vsock), channelInitializer: configure)
  34. } else {
  35. throw RuntimeError(
  36. code: .transportError,
  37. message: """
  38. Unhandled socket address '\(address)', this is a gRPC Swift bug. Please file an issue \
  39. against the project.
  40. """
  41. )
  42. }
  43. }
  44. }
  45. extension NIOCore.SocketAddress {
  46. init(_ address: GRPCHTTP2Core.SocketAddress.IPv4) throws {
  47. try self.init(ipAddress: address.host, port: address.port)
  48. }
  49. init(_ address: GRPCHTTP2Core.SocketAddress.IPv6) throws {
  50. try self.init(ipAddress: address.host, port: address.port)
  51. }
  52. init(_ address: GRPCHTTP2Core.SocketAddress.UnixDomainSocket) throws {
  53. try self.init(unixDomainSocketPath: address.path)
  54. }
  55. }
  56. extension NIOPosix.VsockAddress {
  57. init(_ address: GRPCHTTP2Core.SocketAddress.VirtualSocket) {
  58. self.init(
  59. cid: ContextID(rawValue: address.contextID.rawValue),
  60. port: Port(rawValue: address.port.rawValue)
  61. )
  62. }
  63. }