PickFirstLoadBalancer.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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. /// A load-balancer which has a single subchannel.
  18. ///
  19. /// This load-balancer starts in an 'idle' state and begins connecting when a set of addresses is
  20. /// provided to it with ``updateEndpoint(_:)``. Repeated calls to ``updateEndpoint(_:)`` will
  21. /// update the subchannel gracefully: RPCs will continue to use the old subchannel until the new
  22. /// subchannel becomes ready.
  23. ///
  24. /// You must call ``close()`` on the load-balancer when it's no longer required. This will move
  25. /// it to the ``ConnectivityState/shutdown`` state: existing RPCs may continue but all subsequent
  26. /// calls to ``makeStream(descriptor:options:)`` will fail.
  27. ///
  28. /// To use this load-balancer you must run it in a task:
  29. ///
  30. /// ```swift
  31. /// await withDiscardingTaskGroup { group in
  32. /// // Run the load-balancer
  33. /// group.addTask { await pickFirst.run() }
  34. ///
  35. /// // Update its endpoint.
  36. /// let endpoint = Endpoint(
  37. /// addresses: [
  38. /// .ipv4(host: "127.0.0.1", port: 1001),
  39. /// .ipv4(host: "127.0.0.1", port: 1002),
  40. /// .ipv4(host: "127.0.0.1", port: 1003)
  41. /// ]
  42. /// )
  43. /// pickFirst.updateEndpoint(endpoint)
  44. ///
  45. /// // Consume state update events
  46. /// for await event in pickFirst.events {
  47. /// switch event {
  48. /// case .connectivityStateChanged(.ready):
  49. /// // ...
  50. /// default:
  51. /// // ...
  52. /// }
  53. /// }
  54. /// }
  55. /// ```
  56. @available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *)
  57. struct PickFirstLoadBalancer {
  58. enum Input: Sendable, Hashable {
  59. /// Update the addresses used by the load balancer to the following endpoints.
  60. case updateEndpoint(Endpoint)
  61. /// Close the load balancer.
  62. case close
  63. }
  64. /// Events which can happen to the load balancer.
  65. private let event:
  66. (
  67. stream: AsyncStream<LoadBalancerEvent>,
  68. continuation: AsyncStream<LoadBalancerEvent>.Continuation
  69. )
  70. /// Inputs which this load balancer should react to.
  71. private let input: (stream: AsyncStream<Input>, continuation: AsyncStream<Input>.Continuation)
  72. /// A connector, capable of creating connections.
  73. private let connector: any HTTP2Connector
  74. /// Connection backoff configuration.
  75. private let backoff: ConnectionBackoff
  76. /// The default compression algorithm to use. Can be overridden on a per-call basis.
  77. private let defaultCompression: CompressionAlgorithm
  78. /// The set of enabled compression algorithms.
  79. private let enabledCompression: CompressionAlgorithmSet
  80. /// The state of the load-balancer.
  81. private let state: _LockedValueBox<State>
  82. /// The ID of this load balancer.
  83. internal let id: LoadBalancerID
  84. init(
  85. connector: any HTTP2Connector,
  86. backoff: ConnectionBackoff,
  87. defaultCompression: CompressionAlgorithm,
  88. enabledCompression: CompressionAlgorithmSet
  89. ) {
  90. self.connector = connector
  91. self.backoff = backoff
  92. self.defaultCompression = defaultCompression
  93. self.enabledCompression = enabledCompression
  94. self.id = LoadBalancerID()
  95. self.state = _LockedValueBox(State())
  96. self.event = AsyncStream.makeStream(of: LoadBalancerEvent.self)
  97. self.input = AsyncStream.makeStream(of: Input.self)
  98. // The load balancer starts in the idle state.
  99. self.event.continuation.yield(.connectivityStateChanged(.idle))
  100. }
  101. /// A stream of events which can happen to the load balancer.
  102. var events: AsyncStream<LoadBalancerEvent> {
  103. self.event.stream
  104. }
  105. /// Runs the load balancer, returning when it has closed.
  106. ///
  107. /// You can monitor events which happen on the load balancer with ``events``.
  108. func run() async {
  109. await withDiscardingTaskGroup { group in
  110. for await input in self.input.stream {
  111. switch input {
  112. case .updateEndpoint(let endpoint):
  113. self.handleUpdateEndpoint(endpoint, in: &group)
  114. case .close:
  115. self.handleCloseInput()
  116. }
  117. }
  118. }
  119. if Task.isCancelled {
  120. // Finish the event stream as it's unlikely to have been finished by a regular code path.
  121. self.event.continuation.finish()
  122. }
  123. }
  124. /// Update the addresses used by the load balancer.
  125. ///
  126. /// This may result in new subchannels being created and some subchannels being removed.
  127. func updateEndpoint(_ endpoint: Endpoint) {
  128. self.input.continuation.yield(.updateEndpoint(endpoint))
  129. }
  130. /// Close the load balancer, and all subchannels it manages.
  131. func close() {
  132. self.input.continuation.yield(.close)
  133. }
  134. /// Pick a ready subchannel from the load balancer.
  135. ///
  136. /// - Returns: A subchannel, or `nil` if there aren't any ready subchannels.
  137. func pickSubchannel() -> Subchannel? {
  138. let onPickSubchannel = self.state.withLockedValue { $0.pickSubchannel() }
  139. switch onPickSubchannel {
  140. case .picked(let subchannel):
  141. return subchannel
  142. case .notAvailable(let subchannel):
  143. subchannel?.connect()
  144. return nil
  145. }
  146. }
  147. }
  148. @available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *)
  149. extension PickFirstLoadBalancer {
  150. private func handleUpdateEndpoint(_ endpoint: Endpoint, in group: inout DiscardingTaskGroup) {
  151. if endpoint.addresses.isEmpty { return }
  152. let onUpdate = self.state.withLockedValue { state in
  153. state.updateEndpoint(endpoint) { endpoint, id in
  154. Subchannel(
  155. endpoint: endpoint,
  156. id: id,
  157. connector: self.connector,
  158. backoff: self.backoff,
  159. defaultCompression: self.defaultCompression,
  160. enabledCompression: self.enabledCompression
  161. )
  162. }
  163. }
  164. switch onUpdate {
  165. case .connect(let newSubchannel, close: let oldSubchannel):
  166. self.runSubchannel(newSubchannel, in: &group)
  167. oldSubchannel?.shutDown()
  168. case .none:
  169. ()
  170. }
  171. }
  172. private func runSubchannel(
  173. _ subchannel: Subchannel,
  174. in group: inout DiscardingTaskGroup
  175. ) {
  176. // Start running it and tell it to connect.
  177. subchannel.connect()
  178. group.addTask {
  179. await subchannel.run()
  180. }
  181. group.addTask {
  182. for await event in subchannel.events {
  183. switch event {
  184. case .connectivityStateChanged(let state):
  185. self.handleSubchannelConnectivityStateChange(state, id: subchannel.id)
  186. case .goingAway:
  187. self.handleGoAway(id: subchannel.id)
  188. case .requiresNameResolution:
  189. self.event.continuation.yield(.requiresNameResolution)
  190. }
  191. }
  192. }
  193. }
  194. private func handleSubchannelConnectivityStateChange(
  195. _ connectivityState: ConnectivityState,
  196. id: SubchannelID
  197. ) {
  198. let onUpdateState = self.state.withLockedValue {
  199. $0.updateSubchannelConnectivityState(connectivityState, id: id)
  200. }
  201. switch onUpdateState {
  202. case .close(let subchannel):
  203. subchannel.shutDown()
  204. case .closeAndPublishStateChange(let subchannel, let connectivityState):
  205. subchannel.shutDown()
  206. self.event.continuation.yield(.connectivityStateChanged(connectivityState))
  207. case .publishStateChange(let connectivityState):
  208. self.event.continuation.yield(.connectivityStateChanged(connectivityState))
  209. case .closed:
  210. self.event.continuation.finish()
  211. self.input.continuation.finish()
  212. case .none:
  213. ()
  214. }
  215. }
  216. private func handleGoAway(id: SubchannelID) {
  217. self.state.withLockedValue { state in
  218. state.receivedGoAway(id: id)
  219. }
  220. }
  221. private func handleCloseInput() {
  222. let onClose = self.state.withLockedValue { $0.close() }
  223. switch onClose {
  224. case .closeSubchannels(let subchannel1, let subchannel2):
  225. self.event.continuation.yield(.connectivityStateChanged(.shutdown))
  226. subchannel1.shutDown()
  227. subchannel2?.shutDown()
  228. case .closed:
  229. self.event.continuation.yield(.connectivityStateChanged(.shutdown))
  230. self.event.continuation.finish()
  231. self.input.continuation.finish()
  232. case .none:
  233. ()
  234. }
  235. }
  236. }
  237. @available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *)
  238. extension PickFirstLoadBalancer {
  239. enum State: Sendable {
  240. case active(Active)
  241. case closing(Closing)
  242. case closed
  243. init() {
  244. self = .active(Active())
  245. }
  246. }
  247. }
  248. @available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *)
  249. extension PickFirstLoadBalancer.State {
  250. struct Active: Sendable {
  251. var endpoint: Endpoint?
  252. var connectivityState: ConnectivityState
  253. var current: Subchannel?
  254. var next: Subchannel?
  255. var parked: [SubchannelID: Subchannel]
  256. var isCurrentGoingAway: Bool
  257. init() {
  258. self.endpoint = nil
  259. self.connectivityState = .idle
  260. self.current = nil
  261. self.next = nil
  262. self.parked = [:]
  263. self.isCurrentGoingAway = false
  264. }
  265. }
  266. struct Closing: Sendable {
  267. var parked: [SubchannelID: Subchannel]
  268. init(from state: Active) {
  269. self.parked = state.parked
  270. }
  271. }
  272. }
  273. @available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *)
  274. extension PickFirstLoadBalancer.State.Active {
  275. mutating func updateEndpoint(
  276. _ endpoint: Endpoint,
  277. makeSubchannel: (_ endpoint: Endpoint, _ id: SubchannelID) -> Subchannel
  278. ) -> PickFirstLoadBalancer.State.OnUpdateEndpoint {
  279. if self.endpoint == endpoint { return .none }
  280. let onUpdateEndpoint: PickFirstLoadBalancer.State.OnUpdateEndpoint
  281. let id = SubchannelID()
  282. let newSubchannel = makeSubchannel(endpoint, id)
  283. switch (self.current, self.next) {
  284. case (.some(let current), .none):
  285. if self.connectivityState == .idle {
  286. // Current subchannel is idle and we have a new endpoint, move straight to the new
  287. // subchannel.
  288. self.current = newSubchannel
  289. self.parked[current.id] = current
  290. onUpdateEndpoint = .connect(newSubchannel, close: current)
  291. } else {
  292. // Current subchannel is in a non-idle state, set it as the next subchannel and promote
  293. // it when it becomes ready.
  294. self.next = newSubchannel
  295. onUpdateEndpoint = .connect(newSubchannel, close: nil)
  296. }
  297. case (.some, .some(let next)):
  298. // Current and next subchannel exist. Replace the next subchannel.
  299. self.next = newSubchannel
  300. self.parked[next.id] = next
  301. onUpdateEndpoint = .connect(newSubchannel, close: next)
  302. case (.none, .none):
  303. self.current = newSubchannel
  304. onUpdateEndpoint = .connect(newSubchannel, close: nil)
  305. case (.none, .some(let next)):
  306. self.current = newSubchannel
  307. self.next = nil
  308. self.parked[next.id] = next
  309. onUpdateEndpoint = .connect(newSubchannel, close: next)
  310. }
  311. return onUpdateEndpoint
  312. }
  313. mutating func updateSubchannelConnectivityState(
  314. _ connectivityState: ConnectivityState,
  315. id: SubchannelID
  316. ) -> (PickFirstLoadBalancer.State.OnConnectivityStateUpdate, PickFirstLoadBalancer.State) {
  317. let onUpdate: PickFirstLoadBalancer.State.OnConnectivityStateUpdate
  318. if let current = self.current, current.id == id {
  319. if connectivityState == self.connectivityState {
  320. onUpdate = .none
  321. } else {
  322. self.connectivityState = connectivityState
  323. onUpdate = .publishStateChange(connectivityState)
  324. }
  325. } else if let next = self.next, next.id == id {
  326. // if it becomes ready then promote it
  327. switch connectivityState {
  328. case .ready:
  329. if self.connectivityState != connectivityState {
  330. self.connectivityState = connectivityState
  331. if let current = self.current {
  332. onUpdate = .closeAndPublishStateChange(current, connectivityState)
  333. } else {
  334. onUpdate = .publishStateChange(connectivityState)
  335. }
  336. self.current = next
  337. self.isCurrentGoingAway = false
  338. } else {
  339. // No state change to publish, just roll over.
  340. onUpdate = self.current.map { .close($0) } ?? .none
  341. self.current = next
  342. self.isCurrentGoingAway = false
  343. }
  344. case .idle, .connecting, .transientFailure, .shutdown:
  345. onUpdate = .none
  346. }
  347. } else {
  348. switch connectivityState {
  349. case .idle:
  350. if let subchannel = self.parked[id] {
  351. onUpdate = .close(subchannel)
  352. } else {
  353. onUpdate = .none
  354. }
  355. case .shutdown:
  356. self.parked.removeValue(forKey: id)
  357. onUpdate = .none
  358. case .connecting, .ready, .transientFailure:
  359. onUpdate = .none
  360. }
  361. }
  362. return (onUpdate, .active(self))
  363. }
  364. mutating func receivedGoAway(id: SubchannelID) {
  365. if let current = self.current, current.id == id {
  366. // When receiving a GOAWAY the subchannel will ask for an address to be re-resolved and the
  367. // connection will eventually become idle. At this point we wait: the connection remains
  368. // in its current state.
  369. self.isCurrentGoingAway = true
  370. } else if let next = self.next, next.id == id {
  371. // The next connection is going away, park it.
  372. // connection.
  373. self.next = nil
  374. self.parked[next.id] = next
  375. }
  376. }
  377. mutating func close() -> (PickFirstLoadBalancer.State.OnClose, PickFirstLoadBalancer.State) {
  378. let onClose: PickFirstLoadBalancer.State.OnClose
  379. let nextState: PickFirstLoadBalancer.State
  380. if let current = self.current {
  381. self.parked[current.id] = current
  382. if let next = self.next {
  383. self.parked[next.id] = next
  384. onClose = .closeSubchannels(current, next)
  385. } else {
  386. onClose = .closeSubchannels(current, nil)
  387. }
  388. nextState = .closing(PickFirstLoadBalancer.State.Closing(from: self))
  389. } else {
  390. onClose = .closed
  391. nextState = .closed
  392. }
  393. return (onClose, nextState)
  394. }
  395. func pickSubchannel() -> PickFirstLoadBalancer.State.OnPickSubchannel {
  396. let onPick: PickFirstLoadBalancer.State.OnPickSubchannel
  397. if let current = self.current, !self.isCurrentGoingAway {
  398. switch self.connectivityState {
  399. case .idle:
  400. onPick = .notAvailable(current)
  401. case .ready:
  402. onPick = .picked(current)
  403. case .connecting, .transientFailure, .shutdown:
  404. onPick = .notAvailable(nil)
  405. }
  406. } else {
  407. onPick = .notAvailable(nil)
  408. }
  409. return onPick
  410. }
  411. }
  412. @available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *)
  413. extension PickFirstLoadBalancer.State.Closing {
  414. mutating func updateSubchannelConnectivityState(
  415. _ connectivityState: ConnectivityState,
  416. id: SubchannelID
  417. ) -> (PickFirstLoadBalancer.State.OnConnectivityStateUpdate, PickFirstLoadBalancer.State) {
  418. let onUpdate: PickFirstLoadBalancer.State.OnConnectivityStateUpdate
  419. let nextState: PickFirstLoadBalancer.State
  420. switch connectivityState {
  421. case .idle:
  422. if let subchannel = self.parked[id] {
  423. onUpdate = .close(subchannel)
  424. } else {
  425. onUpdate = .none
  426. }
  427. nextState = .closing(self)
  428. case .shutdown:
  429. if self.parked.removeValue(forKey: id) != nil {
  430. if self.parked.isEmpty {
  431. onUpdate = .closed
  432. nextState = .closed
  433. } else {
  434. onUpdate = .none
  435. nextState = .closing(self)
  436. }
  437. } else {
  438. onUpdate = .none
  439. nextState = .closing(self)
  440. }
  441. case .connecting, .ready, .transientFailure:
  442. onUpdate = .none
  443. nextState = .closing(self)
  444. }
  445. return (onUpdate, nextState)
  446. }
  447. }
  448. @available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *)
  449. extension PickFirstLoadBalancer.State {
  450. enum OnUpdateEndpoint {
  451. case connect(Subchannel, close: Subchannel?)
  452. case none
  453. }
  454. mutating func updateEndpoint(
  455. _ endpoint: Endpoint,
  456. makeSubchannel: (_ endpoint: Endpoint, _ id: SubchannelID) -> Subchannel
  457. ) -> OnUpdateEndpoint {
  458. let onUpdateEndpoint: OnUpdateEndpoint
  459. switch self {
  460. case .active(var state):
  461. onUpdateEndpoint = state.updateEndpoint(endpoint) { endpoint, id in
  462. makeSubchannel(endpoint, id)
  463. }
  464. self = .active(state)
  465. case .closing, .closed:
  466. onUpdateEndpoint = .none
  467. }
  468. return onUpdateEndpoint
  469. }
  470. enum OnConnectivityStateUpdate {
  471. case closeAndPublishStateChange(Subchannel, ConnectivityState)
  472. case publishStateChange(ConnectivityState)
  473. case close(Subchannel)
  474. case closed
  475. case none
  476. }
  477. mutating func updateSubchannelConnectivityState(
  478. _ connectivityState: ConnectivityState,
  479. id: SubchannelID
  480. ) -> OnConnectivityStateUpdate {
  481. let onUpdateState: OnConnectivityStateUpdate
  482. switch self {
  483. case .active(var state):
  484. (onUpdateState, self) = state.updateSubchannelConnectivityState(connectivityState, id: id)
  485. case .closing(var state):
  486. (onUpdateState, self) = state.updateSubchannelConnectivityState(connectivityState, id: id)
  487. case .closed:
  488. onUpdateState = .none
  489. }
  490. return onUpdateState
  491. }
  492. mutating func receivedGoAway(id: SubchannelID) {
  493. switch self {
  494. case .active(var state):
  495. state.receivedGoAway(id: id)
  496. self = .active(state)
  497. case .closing, .closed:
  498. ()
  499. }
  500. }
  501. enum OnClose {
  502. case closeSubchannels(Subchannel, Subchannel?)
  503. case closed
  504. case none
  505. }
  506. mutating func close() -> OnClose {
  507. let onClose: OnClose
  508. switch self {
  509. case .active(var state):
  510. (onClose, self) = state.close()
  511. case .closing, .closed:
  512. onClose = .none
  513. }
  514. return onClose
  515. }
  516. enum OnPickSubchannel {
  517. case picked(Subchannel)
  518. case notAvailable(Subchannel?)
  519. }
  520. func pickSubchannel() -> OnPickSubchannel {
  521. switch self {
  522. case .active(let state):
  523. return state.pickSubchannel()
  524. case .closing, .closed:
  525. return .notAvailable(nil)
  526. }
  527. }
  528. }