NameResolvers.swift 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
  19. extension NameResolver {
  20. static func `static`(
  21. endpoints: [Endpoint],
  22. serviceConfig: ServiceConfig? = nil
  23. ) -> Self {
  24. let result = NameResolutionResult(
  25. endpoints: endpoints,
  26. serviceConfig: serviceConfig.map { .success($0) }
  27. )
  28. return NameResolver(
  29. names: RPCAsyncSequence(wrapping: ConstantAsyncSequence(element: result)),
  30. updateMode: .pull
  31. )
  32. }
  33. static func `dynamic`(
  34. updateMode: UpdateMode
  35. ) -> (Self, AsyncThrowingStream<NameResolutionResult, any Error>.Continuation) {
  36. let (stream, continuation) = AsyncThrowingStream.makeStream(of: NameResolutionResult.self)
  37. let resolver = NameResolver(names: RPCAsyncSequence(wrapping: stream), updateMode: updateMode)
  38. return (resolver, continuation)
  39. }
  40. }
  41. @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
  42. struct ConstantAsyncSequence<Element: Sendable>: AsyncSequence, Sendable {
  43. private let result: Result<Element, any Error>
  44. init(element: Element) {
  45. self.result = .success(element)
  46. }
  47. init(error: any Error) {
  48. self.result = .failure(error)
  49. }
  50. func makeAsyncIterator() -> AsyncIterator {
  51. AsyncIterator(result: self.result)
  52. }
  53. struct AsyncIterator: AsyncIteratorProtocol {
  54. private let result: Result<Element, any Error>
  55. fileprivate init(result: Result<Element, any Error>) {
  56. self.result = result
  57. }
  58. func next() async throws -> Element? {
  59. try self.result.get()
  60. }
  61. }
  62. }