ClientConnection.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. /*
  2. * Copyright 2019, 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 Foundation
  17. import Logging
  18. import NIO
  19. import NIOHTTP2
  20. import NIOSSL
  21. import NIOTLS
  22. import NIOTransportServices
  23. import SwiftProtobuf
  24. /// Provides a single, managed connection to a server which is guaranteed to always use the same
  25. /// `EventLoop`.
  26. ///
  27. /// The connection to the server is provided by a single channel which will attempt to reconnect to
  28. /// the server if the connection is dropped. When either the client or server detects that the
  29. /// connection has become idle -- that is, there are no outstanding RPCs and the idle timeout has
  30. /// passed (5 minutes, by default) -- the underlying channel will be closed. The client will not
  31. /// idle the connection if any RPC exists, even if there has been no activity on the RPC for the
  32. /// idle timeout. Long-lived, low activity RPCs may benefit from configuring keepalive (see
  33. /// `ClientConnectionKeepalive`) which periodically pings the server to ensure that the connection
  34. /// is not dropped. If the connection is idle a new channel will be created on-demand when the next
  35. /// RPC is made.
  36. ///
  37. /// The state of the connection can be observed using a `ConnectivityStateDelegate`.
  38. ///
  39. /// Since the connection is managed, and may potentially spend long periods of time waiting for a
  40. /// connection to come up (cellular connections, for example), different behaviors may be used when
  41. /// starting a call. The different behaviors are detailed in the `CallStartBehavior` documentation.
  42. ///
  43. /// ### Channel Pipeline
  44. ///
  45. /// The `NIO.ChannelPipeline` for the connection is configured as such:
  46. ///
  47. /// ┌──────────────────────────┐
  48. /// │ DelegatingErrorHandler │
  49. /// └──────────▲───────────────┘
  50. /// HTTP2Frame│
  51. /// │ ⠇ ⠇ ⠇ ⠇
  52. /// │ ┌┴─▼┐ ┌┴─▼┐
  53. /// │ │ | │ | HTTP/2 streams
  54. /// │ └▲─┬┘ └▲─┬┘
  55. /// │ │ │ │ │ HTTP2Frame
  56. /// ┌─┴────────────────┴─▼───┴─▼┐
  57. /// │ HTTP2StreamMultiplexer |
  58. /// └─▲───────────────────────┬─┘
  59. /// HTTP2Frame│ │HTTP2Frame
  60. /// ┌─┴───────────────────────▼─┐
  61. /// │ GRPCIdleHandler │
  62. /// └─▲───────────────────────┬─┘
  63. /// HTTP2Frame│ │HTTP2Frame
  64. /// ┌─┴───────────────────────▼─┐
  65. /// │ NIOHTTP2Handler │
  66. /// └─▲───────────────────────┬─┘
  67. /// ByteBuffer│ │ByteBuffer
  68. /// ┌─┴───────────────────────▼─┐
  69. /// │ NIOSSLHandler │
  70. /// └─▲───────────────────────┬─┘
  71. /// ByteBuffer│ │ByteBuffer
  72. /// │ ▼
  73. ///
  74. /// The 'GRPCIdleHandler' intercepts HTTP/2 frames and various events and is responsible for
  75. /// informing and controlling the state of the connection (idling and keepalive). The HTTP/2 streams
  76. /// are used to handle individual RPCs.
  77. public class ClientConnection {
  78. private let connectionManager: ConnectionManager
  79. /// HTTP multiplexer from the underlying channel handling gRPC calls.
  80. internal func getMultiplexer() -> EventLoopFuture<HTTP2StreamMultiplexer> {
  81. return self.connectionManager.getHTTP2Multiplexer()
  82. }
  83. /// The configuration for this client.
  84. internal let configuration: Configuration
  85. /// The scheme of the URI for each RPC, i.e. 'http' or 'https'.
  86. internal let scheme: String
  87. /// The authority of the URI for each RPC.
  88. internal let authority: String
  89. /// A monitor for the connectivity state.
  90. public let connectivity: ConnectivityStateMonitor
  91. /// The `EventLoop` this connection is using.
  92. public var eventLoop: EventLoop {
  93. return self.connectionManager.eventLoop
  94. }
  95. /// Creates a new connection from the given configuration. Prefer using
  96. /// `ClientConnection.secure(group:)` to build a connection secured with TLS or
  97. /// `ClientConnection.insecure(group:)` to build a plaintext connection.
  98. ///
  99. /// - Important: Users should prefer using `ClientConnection.secure(group:)` to build a connection
  100. /// with TLS, or `ClientConnection.insecure(group:)` to build a connection without TLS.
  101. public init(configuration: Configuration) {
  102. self.configuration = configuration
  103. self.scheme = configuration.tlsConfiguration == nil ? "http" : "https"
  104. self.authority = configuration.tlsConfiguration?.hostnameOverride ?? configuration.target.host
  105. let monitor = ConnectivityStateMonitor(
  106. delegate: configuration.connectivityStateDelegate,
  107. queue: configuration.connectivityStateDelegateQueue
  108. )
  109. self.connectivity = monitor
  110. self.connectionManager = ConnectionManager(
  111. configuration: configuration,
  112. connectivityDelegate: monitor,
  113. logger: configuration.backgroundActivityLogger
  114. )
  115. }
  116. /// Closes the connection to the server.
  117. public func close() -> EventLoopFuture<Void> {
  118. return self.connectionManager.shutdown()
  119. }
  120. /// Populates the logger in `options` and appends a request ID header to the metadata, if
  121. /// configured.
  122. /// - Parameter options: The options containing the logger to populate.
  123. private func populateLogger(in options: inout CallOptions) {
  124. // Get connection metadata.
  125. self.connectionManager.appendMetadata(to: &options.logger)
  126. // Attach a request ID.
  127. let requestID = options.requestIDProvider.requestID()
  128. if let requestID = requestID {
  129. options.logger[metadataKey: MetadataKey.requestID] = "\(requestID)"
  130. // Add the request ID header too.
  131. if let requestIDHeader = options.requestIDHeader {
  132. options.customMetadata.add(name: requestIDHeader, value: requestID)
  133. }
  134. }
  135. }
  136. }
  137. extension ClientConnection: GRPCChannel {
  138. public func makeCall<Request: Message, Response: Message>(
  139. path: String,
  140. type: GRPCCallType,
  141. callOptions: CallOptions,
  142. interceptors: [ClientInterceptor<Request, Response>]
  143. ) -> Call<Request, Response> {
  144. var options = callOptions
  145. self.populateLogger(in: &options)
  146. let multiplexer = self.getMultiplexer()
  147. let eventLoop = callOptions.eventLoopPreference.exact ?? multiplexer.eventLoop
  148. return Call(
  149. path: path,
  150. type: type,
  151. eventLoop: eventLoop,
  152. options: options,
  153. interceptors: interceptors,
  154. transportFactory: .http2(
  155. multiplexer: multiplexer,
  156. authority: self.authority,
  157. scheme: self.scheme,
  158. maximumReceiveMessageLength: self.configuration.maximumReceiveMessageLength,
  159. errorDelegate: self.configuration.errorDelegate
  160. )
  161. )
  162. }
  163. public func makeCall<Request: GRPCPayload, Response: GRPCPayload>(
  164. path: String,
  165. type: GRPCCallType,
  166. callOptions: CallOptions,
  167. interceptors: [ClientInterceptor<Request, Response>]
  168. ) -> Call<Request, Response> {
  169. var options = callOptions
  170. self.populateLogger(in: &options)
  171. let multiplexer = self.getMultiplexer()
  172. let eventLoop = callOptions.eventLoopPreference.exact ?? multiplexer.eventLoop
  173. return Call(
  174. path: path,
  175. type: type,
  176. eventLoop: eventLoop,
  177. options: options,
  178. interceptors: interceptors,
  179. transportFactory: .http2(
  180. multiplexer: multiplexer,
  181. authority: self.authority,
  182. scheme: self.scheme,
  183. maximumReceiveMessageLength: self.configuration.maximumReceiveMessageLength,
  184. errorDelegate: self.configuration.errorDelegate
  185. )
  186. )
  187. }
  188. }
  189. // MARK: - Configuration structures
  190. /// A target to connect to.
  191. public struct ConnectionTarget {
  192. internal enum Wrapped {
  193. case hostAndPort(String, Int)
  194. case unixDomainSocket(String)
  195. case socketAddress(SocketAddress)
  196. }
  197. internal var wrapped: Wrapped
  198. private init(_ wrapped: Wrapped) {
  199. self.wrapped = wrapped
  200. }
  201. /// The host and port.
  202. public static func hostAndPort(_ host: String, _ port: Int) -> ConnectionTarget {
  203. return ConnectionTarget(.hostAndPort(host, port))
  204. }
  205. /// The path of a Unix domain socket.
  206. public static func unixDomainSocket(_ path: String) -> ConnectionTarget {
  207. return ConnectionTarget(.unixDomainSocket(path))
  208. }
  209. /// A NIO socket address.
  210. public static func socketAddress(_ address: SocketAddress) -> ConnectionTarget {
  211. return ConnectionTarget(.socketAddress(address))
  212. }
  213. var host: String {
  214. switch self.wrapped {
  215. case let .hostAndPort(host, _):
  216. return host
  217. case let .socketAddress(.v4(address)):
  218. return address.host
  219. case let .socketAddress(.v6(address)):
  220. return address.host
  221. case .unixDomainSocket, .socketAddress(.unixDomainSocket):
  222. return "localhost"
  223. }
  224. }
  225. }
  226. /// The connectivity behavior to use when starting an RPC.
  227. public struct CallStartBehavior: Hashable {
  228. internal enum Behavior: Hashable {
  229. case waitsForConnectivity
  230. case fastFailure
  231. }
  232. internal var wrapped: Behavior
  233. private init(_ wrapped: Behavior) {
  234. self.wrapped = wrapped
  235. }
  236. /// Waits for connectivity (that is, the 'ready' connectivity state) before attempting to start
  237. /// an RPC. Doing so may involve multiple connection attempts.
  238. ///
  239. /// This is the preferred, and default, behaviour.
  240. public static let waitsForConnectivity = CallStartBehavior(.waitsForConnectivity)
  241. /// The 'fast failure' behaviour is intended for cases where users would rather their RPC failed
  242. /// quickly rather than waiting for an active connection. The behaviour depends on the current
  243. /// connectivity state:
  244. ///
  245. /// - Idle: a connection attempt will be started and the RPC will fail if that attempt fails.
  246. /// - Connecting: a connection attempt is already in progress, the RPC will fail if that attempt
  247. /// fails.
  248. /// - Ready: a connection is already active: the RPC will be started using that connection.
  249. /// - Transient failure: the last connection or connection attempt failed and gRPC is waiting to
  250. /// connect again. The RPC will fail immediately.
  251. /// - Shutdown: the connection is shutdown, the RPC will fail immediately.
  252. public static let fastFailure = CallStartBehavior(.fastFailure)
  253. }
  254. extension ClientConnection {
  255. /// Configuration for a `ClientConnection`. Users should prefer using one of the
  256. /// `ClientConnection` builders: `ClientConnection.secure(_:)` or `ClientConnection.insecure(_:)`.
  257. public struct Configuration {
  258. /// The target to connect to.
  259. public var target: ConnectionTarget
  260. /// The event loop group to run the connection on.
  261. public var eventLoopGroup: EventLoopGroup
  262. /// An error delegate which is called when errors are caught. Provided delegates **must not
  263. /// maintain a strong reference to this `ClientConnection`**. Doing so will cause a retain
  264. /// cycle. Defaults to `LoggingClientErrorDelegate`.
  265. public var errorDelegate: ClientErrorDelegate? = LoggingClientErrorDelegate.shared
  266. /// A delegate which is called when the connectivity state is changed. Defaults to `nil`.
  267. public var connectivityStateDelegate: ConnectivityStateDelegate?
  268. /// The `DispatchQueue` on which to call the connectivity state delegate. If a delegate is
  269. /// provided but the queue is `nil` then one will be created by gRPC. Defaults to `nil`.
  270. public var connectivityStateDelegateQueue: DispatchQueue?
  271. /// TLS configuration for this connection. `nil` if TLS is not desired.
  272. ///
  273. /// - Important: `tls` is deprecated; use `tlsConfiguration` or one of
  274. /// the `ClientConnection.withTLS` builder functions.
  275. @available(*, deprecated, renamed: "tlsConfiguration")
  276. public var tls: TLS? {
  277. get {
  278. return self.tlsConfiguration?.asDeprecatedClientConfiguration
  279. }
  280. set {
  281. self.tlsConfiguration = newValue.map { .init(transforming: $0) }
  282. }
  283. }
  284. /// TLS configuration for this connection. `nil` if TLS is not desired.
  285. public var tlsConfiguration: GRPCTLSConfiguration?
  286. /// The connection backoff configuration. If no connection retrying is required then this should
  287. /// be `nil`.
  288. public var connectionBackoff: ConnectionBackoff? = ConnectionBackoff()
  289. /// The connection keepalive configuration.
  290. public var connectionKeepalive = ClientConnectionKeepalive()
  291. /// The amount of time to wait before closing the connection. The idle timeout will start only
  292. /// if there are no RPCs in progress and will be cancelled as soon as any RPCs start.
  293. ///
  294. /// If a connection becomes idle, starting a new RPC will automatically create a new connection.
  295. ///
  296. /// Defaults to 30 minutes.
  297. public var connectionIdleTimeout: TimeAmount = .minutes(30)
  298. /// The behavior used to determine when an RPC should start. That is, whether it should wait for
  299. /// an active connection or fail quickly if no connection is currently available.
  300. ///
  301. /// Defaults to `waitsForConnectivity`.
  302. public var callStartBehavior: CallStartBehavior = .waitsForConnectivity
  303. /// The HTTP/2 flow control target window size. Defaults to 65535.
  304. public var httpTargetWindowSize = 65535
  305. /// The HTTP protocol used for this connection.
  306. public var httpProtocol: HTTP2FramePayloadToHTTP1ClientCodec.HTTPProtocol {
  307. return self.tlsConfiguration == nil ? .http : .https
  308. }
  309. /// The maximum size in bytes of a message which may be received from a server. Defaults to 4MB.
  310. public var maximumReceiveMessageLength: Int = 4 * 1024 * 1024 {
  311. willSet {
  312. precondition(newValue >= 0, "maximumReceiveMessageLength must be positive")
  313. }
  314. }
  315. /// A logger for background information (such as connectivity state). A separate logger for
  316. /// requests may be provided in the `CallOptions`.
  317. ///
  318. /// Defaults to a no-op logger.
  319. public var backgroundActivityLogger = Logger(
  320. label: "io.grpc",
  321. factory: { _ in SwiftLogNoOpLogHandler() }
  322. )
  323. /// A channel initializer which will be run after gRPC has initialized each channel. This may be
  324. /// used to add additional handlers to the pipeline and is intended for debugging.
  325. ///
  326. /// - Warning: The initializer closure may be invoked *multiple times*.
  327. public var debugChannelInitializer: ((Channel) -> EventLoopFuture<Void>)?
  328. /// Create a `Configuration` with some pre-defined defaults. Prefer using
  329. /// `ClientConnection.secure(group:)` to build a connection secured with TLS or
  330. /// `ClientConnection.insecure(group:)` to build a plaintext connection.
  331. ///
  332. /// - Parameter target: The target to connect to.
  333. /// - Parameter eventLoopGroup: The event loop group to run the connection on.
  334. /// - Parameter errorDelegate: The error delegate, defaulting to a delegate which will log only
  335. /// on debug builds.
  336. /// - Parameter connectivityStateDelegate: A connectivity state delegate, defaulting to `nil`.
  337. /// - Parameter connectivityStateDelegateQueue: A `DispatchQueue` on which to call the
  338. /// `connectivityStateDelegate`.
  339. /// - Parameter tls: TLS configuration, defaulting to `nil`.
  340. /// - Parameter connectionBackoff: The connection backoff configuration to use.
  341. /// - Parameter connectionKeepalive: The keepalive configuration to use.
  342. /// - Parameter connectionIdleTimeout: The amount of time to wait before closing the connection, defaulting to 30 minutes.
  343. /// - Parameter callStartBehavior: The behavior used to determine when a call should start in
  344. /// relation to its underlying connection. Defaults to `waitsForConnectivity`.
  345. /// - Parameter httpTargetWindowSize: The HTTP/2 flow control target window size.
  346. /// - Parameter backgroundActivityLogger: A logger for background information (such as
  347. /// connectivity state). Defaults to a no-op logger.
  348. /// - Parameter debugChannelInitializer: A channel initializer will be called after gRPC has
  349. /// initialized the channel. Defaults to `nil`.
  350. @available(*, deprecated, renamed: "default(target:eventLoopGroup:)")
  351. public init(
  352. target: ConnectionTarget,
  353. eventLoopGroup: EventLoopGroup,
  354. errorDelegate: ClientErrorDelegate? = LoggingClientErrorDelegate(),
  355. connectivityStateDelegate: ConnectivityStateDelegate? = nil,
  356. connectivityStateDelegateQueue: DispatchQueue? = nil,
  357. tls: Configuration.TLS? = nil,
  358. connectionBackoff: ConnectionBackoff? = ConnectionBackoff(),
  359. connectionKeepalive: ClientConnectionKeepalive = ClientConnectionKeepalive(),
  360. connectionIdleTimeout: TimeAmount = .minutes(30),
  361. callStartBehavior: CallStartBehavior = .waitsForConnectivity,
  362. httpTargetWindowSize: Int = 65535,
  363. backgroundActivityLogger: Logger = Logger(
  364. label: "io.grpc",
  365. factory: { _ in SwiftLogNoOpLogHandler() }
  366. ),
  367. debugChannelInitializer: ((Channel) -> EventLoopFuture<Void>)? = nil
  368. ) {
  369. self.target = target
  370. self.eventLoopGroup = eventLoopGroup
  371. self.errorDelegate = errorDelegate
  372. self.connectivityStateDelegate = connectivityStateDelegate
  373. self.connectivityStateDelegateQueue = connectivityStateDelegateQueue
  374. self.tlsConfiguration = tls.map { GRPCTLSConfiguration(transforming: $0) }
  375. self.connectionBackoff = connectionBackoff
  376. self.connectionKeepalive = connectionKeepalive
  377. self.connectionIdleTimeout = connectionIdleTimeout
  378. self.callStartBehavior = callStartBehavior
  379. self.httpTargetWindowSize = httpTargetWindowSize
  380. self.backgroundActivityLogger = backgroundActivityLogger
  381. self.debugChannelInitializer = debugChannelInitializer
  382. }
  383. private init(eventLoopGroup: EventLoopGroup, target: ConnectionTarget) {
  384. self.eventLoopGroup = eventLoopGroup
  385. self.target = target
  386. }
  387. /// Make a new configuration using default values.
  388. ///
  389. /// - Parameters:
  390. /// - target: The target to connect to.
  391. /// - eventLoopGroup: The `EventLoopGroup` providing an `EventLoop` for the connection to
  392. /// run on.
  393. /// - Returns: A configuration with default values set.
  394. public static func `default`(
  395. target: ConnectionTarget,
  396. eventLoopGroup: EventLoopGroup
  397. ) -> Configuration {
  398. return .init(eventLoopGroup: eventLoopGroup, target: target)
  399. }
  400. }
  401. }
  402. // MARK: - Configuration helpers/extensions
  403. extension ClientBootstrapProtocol {
  404. /// Connect to the given connection target.
  405. ///
  406. /// - Parameter target: The target to connect to.
  407. func connect(to target: ConnectionTarget) -> EventLoopFuture<Channel> {
  408. switch target.wrapped {
  409. case let .hostAndPort(host, port):
  410. return self.connect(host: host, port: port)
  411. case let .unixDomainSocket(path):
  412. return self.connect(unixDomainSocketPath: path)
  413. case let .socketAddress(address):
  414. return self.connect(to: address)
  415. }
  416. }
  417. }
  418. extension ChannelPipeline.SynchronousOperations {
  419. internal func configureNIOSSLForGRPCClient(
  420. sslContext: Result<NIOSSLContext, Error>,
  421. serverHostname: String?,
  422. customVerificationCallback: NIOSSLCustomVerificationCallback?,
  423. logger: Logger
  424. ) throws {
  425. let sslContext = try sslContext.get()
  426. let sslClientHandler: NIOSSLClientHandler
  427. if let customVerificationCallback = customVerificationCallback {
  428. sslClientHandler = try NIOSSLClientHandler(
  429. context: sslContext,
  430. serverHostname: serverHostname,
  431. customVerificationCallback: customVerificationCallback
  432. )
  433. } else {
  434. sslClientHandler = try NIOSSLClientHandler(
  435. context: sslContext,
  436. serverHostname: serverHostname
  437. )
  438. }
  439. try self.addHandler(sslClientHandler)
  440. try self.addHandler(TLSVerificationHandler(logger: logger))
  441. }
  442. internal func configureHTTP2AndGRPCHandlersForGRPCClient(
  443. channel: Channel,
  444. connectionManager: ConnectionManager,
  445. connectionKeepalive: ClientConnectionKeepalive,
  446. connectionIdleTimeout: TimeAmount,
  447. httpTargetWindowSize: Int,
  448. errorDelegate: ClientErrorDelegate?,
  449. logger: Logger
  450. ) throws {
  451. // We could use 'configureHTTP2Pipeline' here, but we need to add a few handlers between the
  452. // two HTTP/2 handlers so we'll do it manually instead.
  453. try self.addHandler(NIOHTTP2Handler(mode: .client))
  454. let h2Multiplexer = HTTP2StreamMultiplexer(
  455. mode: .client,
  456. channel: channel,
  457. targetWindowSize: httpTargetWindowSize,
  458. inboundStreamInitializer: nil
  459. )
  460. // The multiplexer is passed through the idle handler so it is only reported on
  461. // successful channel activation - with happy eyeballs multiple pipelines can
  462. // be constructed so it's not safe to report just yet.
  463. try self.addHandler(GRPCIdleHandler(
  464. connectionManager: connectionManager,
  465. multiplexer: h2Multiplexer,
  466. idleTimeout: connectionIdleTimeout,
  467. keepalive: connectionKeepalive,
  468. logger: logger
  469. ))
  470. try self.addHandler(h2Multiplexer)
  471. try self.addHandler(DelegatingErrorHandler(logger: logger, delegate: errorDelegate))
  472. }
  473. }
  474. extension Channel {
  475. func configureGRPCClient(
  476. errorDelegate: ClientErrorDelegate?,
  477. logger: Logger
  478. ) -> EventLoopFuture<Void> {
  479. return self.configureHTTP2Pipeline(mode: .client, inboundStreamInitializer: nil).flatMap { _ in
  480. self.pipeline.addHandler(DelegatingErrorHandler(logger: logger, delegate: errorDelegate))
  481. }
  482. }
  483. }
  484. extension TimeAmount {
  485. /// Creates a new `TimeAmount` from the given time interval in seconds.
  486. ///
  487. /// - Parameter timeInterval: The amount of time in seconds
  488. static func seconds(timeInterval: TimeInterval) -> TimeAmount {
  489. return .nanoseconds(Int64(timeInterval * 1_000_000_000))
  490. }
  491. }
  492. extension String {
  493. var isIPAddress: Bool {
  494. // We need some scratch space to let inet_pton write into.
  495. var ipv4Addr = in_addr()
  496. var ipv6Addr = in6_addr()
  497. return self.withCString { ptr in
  498. inet_pton(AF_INET, ptr, &ipv4Addr) == 1 ||
  499. inet_pton(AF_INET6, ptr, &ipv6Addr) == 1
  500. }
  501. }
  502. }