Skip to content

Commit f5c3b3d

Browse files
committed
Configure client connections with a builder
Motivation: Configuring a client without TLS is easy to do, since no tls is the default in the client connection configuration. This is bad. The API should make it clearer that the default is insecure. The current API for configuring clients falls a bit short in a number of areas. In no particular order: 1. It can't be easily extended without SemVer major changes (since we'd have to provide a new init whenever new properties are added), 2. Nested configuration (i.e. TLS) is unnecessarily verbose, 3. The initializer requires properties to be passed in the correct order, and 4. TLS is disabled by default (!) and the API doesn't make this clear that this is insecure Modifications: - create a `ClientConnectionBuilder` whose public API is limited to configuring the private properties; this is similar to NIOs bootstraps - provide static methods on `ClientConnection` to provide a `secure` or `insecure` builder - update tests in a couple of places to demonstrate usage Result: - Configuring a connection is less verbose - Not using TLS is more obviously 'insecure'
1 parent 38484c0 commit f5c3b3d

File tree

4 files changed

+198
-24
lines changed

4 files changed

+198
-24
lines changed

Sources/GRPC/ClientConnection.swift

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,9 @@ public class ClientConnection {
101101
}
102102

103103
/// Creates a new connection from the given configuration.
104+
///
105+
/// - Important: Users should prefer using `ClientConnection.secure(group:)` to build a connection
106+
/// with TLS, or `ClientConnection.insecure(group:)` to build a connection without TLS.
104107
public init(configuration: Configuration) {
105108
self.configuration = configuration
106109
self.scheme = configuration.tls == nil ? "http" : "https"
Lines changed: 186 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,186 @@
1+
/*
2+
* Copyright 2020, 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 NIO
17+
import NIOSSL
18+
19+
extension ClientConnection {
20+
/// Returns an insecure `ClientConnection` builder which is *not configured with TLS*.
21+
public static func insecure(group: EventLoopGroup) -> ClientConnectionBuilder {
22+
return ClientConnectionBuilder(group: group)
23+
}
24+
25+
/// Returns a `ClientConnection` builder configured with TLS.
26+
public static func secure(group: EventLoopGroup) -> ClientConnectionBuilder.Secure {
27+
return ClientConnectionBuilder.Secure(group: group)
28+
}
29+
}
30+
31+
public class ClientConnectionBuilder {
32+
private let group: EventLoopGroup
33+
private var maybeTLS: ClientConnection.Configuration.TLS? { return nil }
34+
private var connectionBackoff = ConnectionBackoff()
35+
private var connectionBackoffIsEnabled = true
36+
private var errorDelegate: ClientErrorDelegate?
37+
private var connectivityStateDelegate: ConnectivityStateDelegate?
38+
39+
fileprivate init(group: EventLoopGroup) {
40+
self.group = group
41+
}
42+
43+
public func connect(host: String, port: Int) -> ClientConnection {
44+
let configuration = ClientConnection.Configuration(
45+
target: .hostAndPort(host, port),
46+
eventLoopGroup: self.group,
47+
errorDelegate: self.errorDelegate,
48+
connectivityStateDelegate: self.connectivityStateDelegate,
49+
tls: self.maybeTLS,
50+
connectionBackoff: self.connectionBackoffIsEnabled ? self.connectionBackoff : nil
51+
)
52+
return ClientConnection(configuration: configuration)
53+
}
54+
}
55+
56+
extension ClientConnectionBuilder {
57+
public class Secure: ClientConnectionBuilder {
58+
internal var tls = ClientConnection.Configuration.TLS()
59+
override internal var maybeTLS: ClientConnection.Configuration.TLS? {
60+
return self.tls
61+
}
62+
}
63+
}
64+
65+
extension ClientConnectionBuilder {
66+
/// Sets the initial connection backoff. That is, the initial time to wait before re-attempting to
67+
/// establish a connection. Jitter will *not* be applied to the initial backoff. Defaults to
68+
/// 1 second if not set.
69+
@discardableResult
70+
public func withConnectionBackoff(initial amount: TimeAmount) -> Self {
71+
self.connectionBackoff.initialBackoff = Double(amount.nanoseconds) / Double(1_000_000_000)
72+
return self
73+
}
74+
75+
/// Set the maximum connection backoff. That is, the maximum amount of time to wait before
76+
/// re-attempting to establish a connection. Note that this time amount represents the maximum
77+
/// backoff *before* jitter is applied. Defaults to 120 seconds if not set.
78+
@discardableResult
79+
public func withConnectionBackoff(maximum amount: TimeAmount) -> Self {
80+
self.connectionBackoff.maximumBackoff = Double(amount.nanoseconds) / Double(1_000_000_000)
81+
return self
82+
}
83+
84+
/// Backoff is 'jittered' to randomise the amount of time to wait before re-attempting to
85+
/// establish a connection. The jittered backoff will be no more than `jitter ⨯ unjitteredBackoff`
86+
/// from `unjitteredBackoff`. Defaults to 0.2 if not set.
87+
///
88+
/// - Precondition: `0 <= jitter <= 1`
89+
@discardableResult
90+
public func withConnectionBackoff(jitter: Double) -> Self {
91+
self.connectionBackoff.jitter = jitter
92+
return self
93+
}
94+
95+
/// The multiplier for scaling the unjittered backoff between attempts to establish a connection.
96+
/// Defaults to 1.6 if not set.
97+
@discardableResult
98+
public func withConnectionBackoff(multiplier: Double) -> Self {
99+
self.connectionBackoff.multiplier = multiplier
100+
return self
101+
}
102+
103+
/// The minimum timeout to use when attempting to establishing a connection. The connection
104+
/// timeout for each attempt is the larger of the jittered backoff and the minimum connection
105+
/// timeout. Defaults to 20 seconds if not set.
106+
@discardableResult
107+
public func withConnectionTimeout(minimum amount: TimeAmount) -> Self {
108+
self.connectionBackoff.minimumConnectionTimeout = Double(amount.nanoseconds) / Double(1_000_000_000)
109+
return self
110+
}
111+
112+
/// Sets the initial and maximum backoff to given amount. Disables jitter and sets the backoff
113+
/// multiplier to 1.0.
114+
@discardableResult
115+
public func withConnectionBackoff(fixed amount: TimeAmount) -> Self {
116+
let seconds = Double(amount.nanoseconds) / Double(1_000_000_000)
117+
self.connectionBackoff.initialBackoff = seconds
118+
self.connectionBackoff.maximumBackoff = seconds
119+
self.connectionBackoff.multiplier = 1.0
120+
self.connectionBackoff.jitter = 0.0
121+
return self
122+
}
123+
124+
/// Sets whether the connection should be re-established automatically if it is dropped. Defaults
125+
/// to `true` if not set.
126+
@discardableResult
127+
public func withConnectionReestablishment(enabled: Bool) -> Self {
128+
self.connectionBackoffIsEnabled = enabled
129+
return self
130+
}
131+
}
132+
133+
extension ClientConnectionBuilder {
134+
/// Sets the client error delegate.
135+
@discardableResult
136+
public func withErrorDelegate(_ delegate: ClientErrorDelegate?) -> Self {
137+
self.errorDelegate = delegate
138+
return self
139+
}
140+
}
141+
142+
extension ClientConnectionBuilder {
143+
/// Sets the client connectivity state delegate.
144+
@discardableResult
145+
public func withConnectivityStateDelegate(_ delegate: ConnectivityStateDelegate?) -> Self {
146+
self.connectivityStateDelegate = delegate
147+
return self
148+
}
149+
}
150+
151+
extension ClientConnectionBuilder.Secure {
152+
/// Sets a server hostname override to be used for the TLS Server Name Indication (SNI) extension.
153+
/// The hostname from `connect(host:port)` is for TLS SNI if this value is not set and hostname
154+
/// verification is enabled.
155+
@discardableResult
156+
public func withTLS(serverHostnameOverride: String?) -> Self {
157+
self.tls.hostnameOverride = serverHostnameOverride
158+
return self
159+
}
160+
161+
/// Sets the sources of certificates to offer during negotiation. No certificates are offered
162+
/// during negotiation by default.
163+
@discardableResult
164+
public func withTLS(certificateChain: [NIOSSLCertificate]) -> Self {
165+
// `.certificate` is the only non-deprecated case in `NIOSSLCertificateSource`
166+
self.tls.certificateChain = certificateChain.map { .certificate($0) }
167+
return self
168+
}
169+
170+
/// Sets the private key associated with the leaf certificate.
171+
@discardableResult
172+
public func withTLS(privateKey: NIOSSLPrivateKey) -> Self {
173+
// `.privateKey` is the only non-deprecated case in `NIOSSLPrivateKeySource`
174+
self.tls.privateKey = .privateKey(privateKey)
175+
return self
176+
}
177+
178+
/// Sets the trust roots to use to validate certificates. This only needs to be provided if you
179+
/// intend to validate certificates. Defaults to the system provided trust store (`.default`) if
180+
/// not set.
181+
@discardableResult
182+
public func withTLS(trustRoots: NIOSSLTrustRoots) -> Self {
183+
self.tls.trustRoots = trustRoots
184+
return self
185+
}
186+
}

Tests/GRPCTests/ClientTLSTests.swift

Lines changed: 7 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -50,16 +50,6 @@ class ClientTLSHostnameOverrideTests: GRPCTestCase {
5050
return try Server.start(configuration: configuration).wait()
5151
}
5252

53-
func makeConnection(port: Int, tls: ClientConnection.Configuration.TLS) -> ClientConnection {
54-
let configuration: ClientConnection.Configuration = .init(
55-
target: .hostAndPort("localhost", port),
56-
eventLoopGroup: self.eventLoopGroup,
57-
tls: tls
58-
)
59-
60-
return ClientConnection(configuration: configuration)
61-
}
62-
6353
func doTestUnary() throws {
6454
let client = Echo_EchoServiceClient(channel: self.connection)
6555
let get = client.get(.with { $0.text = "foo" })
@@ -85,12 +75,11 @@ class ClientTLSHostnameOverrideTests: GRPCTestCase {
8575
return
8676
}
8777

88-
let clientTLS: ClientConnection.Configuration.TLS = .init(
89-
trustRoots: .certificates([SampleCertificate.ca.certificate]),
90-
hostnameOverride: "example.com"
91-
)
78+
self.connection = ClientConnection.secure(group: self.eventLoopGroup)
79+
.withTLS(trustRoots: .certificates([SampleCertificate.ca.certificate]))
80+
.withTLS(serverHostnameOverride: "example.com")
81+
.connect(host: "localhost", port: port)
9282

93-
self.connection = self.makeConnection(port: port, tls: clientTLS)
9483
try self.doTestUnary()
9584
}
9685

@@ -108,11 +97,10 @@ class ClientTLSHostnameOverrideTests: GRPCTestCase {
10897
return
10998
}
11099

111-
let clientTLS: ClientConnection.Configuration.TLS = .init(
112-
trustRoots: .certificates([SampleCertificate.ca.certificate])
113-
)
100+
self.connection = ClientConnection.secure(group: self.eventLoopGroup)
101+
.withTLS(trustRoots: .certificates([SampleCertificate.ca.certificate]))
102+
.connect(host: "localhost", port: port)
114103

115-
self.connection = self.makeConnection(port: port, tls: clientTLS)
116104
try self.doTestUnary()
117105
}
118106
}

Tests/GRPCTests/CompressionTests.swift

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -50,12 +50,9 @@ class MessageCompressionTests: GRPCTestCase {
5050
}
5151

5252
func setupClient(encoding: ClientMessageEncoding) {
53-
let configuration = ClientConnection.Configuration(
54-
target: .hostAndPort("localhost", self.server.channel.localAddress!.port!),
55-
eventLoopGroup: self.group
56-
)
53+
self.client = ClientConnection.insecure(group: self.group)
54+
.connect(host: "localhost", port: self.server.channel.localAddress!.port!)
5755

58-
self.client = ClientConnection(configuration: configuration)
5956
self.echo = Echo_EchoServiceClient(
6057
channel: self.client,
6158
defaultCallOptions: CallOptions(messageEncoding: encoding)

0 commit comments

Comments
 (0)