Skip to content

Commit 0c29466

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 0c29466

File tree

4 files changed

+200
-24
lines changed

4 files changed

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

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)