-
Notifications
You must be signed in to change notification settings - Fork 58
/
partisan_peer_socket.erl
339 lines (272 loc) · 10.4 KB
/
partisan_peer_socket.erl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
%% -------------------------------------------------------------------
%%
%% Copyright (c) 2017 Christopher Meiklejohn. All Rights Reserved.
%%
%% This file is provided to you under the Apache License,
%% Version 2.0 (the "License"); you may not use this file
%% except in compliance with the License. You may obtain
%% a copy of the License at
%%
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing,
%% software distributed under the License is distributed on an
%% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%% -------------------------------------------------------------------
%% -----------------------------------------------------------------------------
%% @doc Wrapper that allows transparent usage of plain TCP or TLS socket
%% for peer connections.
%%
%% This module also implements the monotonic channel functionality.
%% @end
%% -----------------------------------------------------------------------------
-module(partisan_peer_socket).
-record(partisan_peer_socket, {
socket :: gen_tcp:socket() | ssl:sslsocket() | socket:socket(),
transport :: gen_tcp | ssl,
control :: inet | ssl,
monotonic = false :: boolean()
}).
-type t() :: #partisan_peer_socket{}.
-type reason() :: closed | inet:posix().
-type options() :: [gen_tcp:option()] | map().
-export_type([t/0]).
-export([accept/1]).
-export([close/1]).
-export([connect/3]).
-export([connect/4]).
-export([connect/5]).
-export([recv/2]).
-export([recv/3]).
-export([send/2]).
-export([setopts/2]).
-export([socket/1]).
%% =============================================================================
%% API
%% =============================================================================
%% -----------------------------------------------------------------------------
%% @doc Wraps a TCP socket with the appropriate information for
%% transceiving on and controlling the socket later. If TLS/SSL is
%% enabled, this performs the socket upgrade/negotiation before
%% returning the wrapped socket.
%% @end
%% -----------------------------------------------------------------------------
-spec accept(gen_tcp:socket()) -> t().
accept(TCPSocket) ->
case tls_enabled() of
true ->
TLSOpts = partisan_config:get(tls_server_options),
%% as per http://erlang.org/doc/man/ssl.html#ssl_accept-1
%% The listen socket is to be in mode {active, false} before
%% telling the client that the server is ready to upgrade by
%% calling this function, else the upgrade succeeds or does not
%% succeed depending on timing.
inet:setopts(TCPSocket, [{active, false}]),
{ok, TLSSocket} = ssl:handshake(TCPSocket, TLSOpts),
%% restore the expected active once setting
ssl:setopts(TLSSocket, [{active, once}]),
#partisan_peer_socket{
socket = TLSSocket,
transport = ssl,
control = ssl
};
_ ->
#partisan_peer_socket{
socket = TCPSocket,
transport = gen_tcp,
control = inet
}
end.
%% -----------------------------------------------------------------------------
%% @doc
%% @see gen_tcp:send/2
%% @see ssl:send/2
%% @end
%% -----------------------------------------------------------------------------
-spec send(t(), iodata()) -> ok | {error, reason()}.
send(#partisan_peer_socket{monotonic = false} = Conn, Data) ->
Socket = Conn#partisan_peer_socket.socket,
Transport = Conn#partisan_peer_socket.transport,
send(Transport, Socket, Data);
send(#partisan_peer_socket{monotonic = true} = Conn, Data) ->
Socket = Conn#partisan_peer_socket.socket,
Transport = Conn#partisan_peer_socket.transport,
%% Get the current process message queue length.
{message_queue_len, MQLen} = process_info(self(), message_queue_len),
%% Get last transmission time from process dictionary
Time = get(last_transmission_time),
%% Test for whether we should send or not.
case monotonic_should_send(MQLen, Time) of
false ->
ok;
true ->
%% Update last transmission time on process dictionary
put(last_transmission_time, monotonic_now()),
send(Transport, Socket, Data)
end.
%% -----------------------------------------------------------------------------
%% @doc
%% @see gen_tcp:recv/2
%% @see ssl:recv/2
%% @end
%% -----------------------------------------------------------------------------
-spec recv(t(), integer()) -> {ok, iodata()} | {error, reason()}.
recv(Conn, Length) ->
recv(Conn, Length, infinity).
%% -----------------------------------------------------------------------------
%% @doc
%% @see gen_tcp:recv/3
%% @see ssl:recv/3
%% @end
%% -----------------------------------------------------------------------------
-spec recv(t(), integer(), timeout()) ->
{ok, iodata()} | {error, reason()}.
recv(#partisan_peer_socket{socket = Socket, transport = Transport}, Length, Timeout) ->
Transport:recv(Socket, Length, Timeout).
%% -----------------------------------------------------------------------------
%% @doc
%% @see inet:setopts/2
%% @see ssl:setopts/2
%% @end
%% -----------------------------------------------------------------------------
-spec setopts(t(), options()) -> ok | {error, inet:posix()}.
setopts(#partisan_peer_socket{} = Connection, Options) when is_map(Options) ->
setopts(Connection, maps:to_list(Options));
setopts(#partisan_peer_socket{socket = Socket, control = Control}, Options) ->
Control:setopts(Socket, Options).
%% -----------------------------------------------------------------------------
%% @doc
%% @see gen_tcp:close/1
%% @see ssl:close/1
%% @end
%% -----------------------------------------------------------------------------
-spec close(t()) -> ok.
close(#partisan_peer_socket{socket = Socket, transport = Transport}) ->
Transport:close(Socket).
%% -----------------------------------------------------------------------------
%% @doc
%% @see gen_tcp:connect/3
%% @see ssl:connect/3
%% @end
%% -----------------------------------------------------------------------------
-spec connect(
inet:socket_address() | inet:hostname(), inet:port_number(), options()) ->
{ok, t()} | {error, inet:posix()}.
connect(Address, Port, Options) ->
connect(Address, Port, Options, infinity).
%% -----------------------------------------------------------------------------
%% @doc
%% @end
%% -----------------------------------------------------------------------------
-spec connect(
inet:socket_address() | inet:hostname(),
inet:port_number(),
options(),
timeout()) ->
{ok, t()} | {error, inet:posix()}.
connect(Address, Port, Options, Timeout) ->
connect(Address, Port, Options, Timeout, #{}).
%% -----------------------------------------------------------------------------
%% @doc
%% @end
%% -----------------------------------------------------------------------------
-spec connect(
inet:socket_address() | inet:hostname(),
inet:port_number(),
options(),
timeout(),
map() | list()) -> {ok, t()} | {error, inet:posix()}.
connect(Address, Port, Options, Timeout, PartisanOptions)
when is_list(PartisanOptions) ->
connect(Address, Port, Options, Timeout, maps:from_list(PartisanOptions));
connect(Address, Port, Options0, Timeout, PartisanOptions)
when is_map(PartisanOptions) ->
Options = connection_options(Options0),
case tls_enabled() of
true ->
TLSOptions = partisan_config:get(tls_client_options),
do_connect(
Address,
Port,
Options ++ TLSOptions,
Timeout,
ssl,
ssl,
PartisanOptions
);
_ ->
do_connect(
Address,
Port,
Options,
Timeout,
gen_tcp,
inet,
PartisanOptions
)
end.
%% -----------------------------------------------------------------------------
%% @doc Returns the wrapped socket from within the connection.
%% @end
%% -----------------------------------------------------------------------------
-spec socket(t()) -> gen_tcp:socket() | ssl:sslsocket().
socket(Conn) ->
Conn#partisan_peer_socket.socket.
%% =============================================================================
%% PRIVATE
%% =============================================================================
%% @private
do_connect(Address, Port, ConnectOpts, Timeout, Transport, Control, Opts) ->
Monotonic = maps:get(monotonic, Opts, false),
case Transport:connect(Address, Port, ConnectOpts, Timeout) of
{ok, Socket} ->
Connection = #partisan_peer_socket{
socket = Socket,
transport = Transport,
control = Control,
monotonic = Monotonic
},
{ok, Connection};
Error ->
Error
end.
%% @private
connection_options(Options) when is_map(Options) ->
connection_options(maps:to_list(Options));
connection_options(Options) when is_list(Options) ->
Options ++ [{nodelay, true}].
%% @private
tls_enabled() ->
partisan_config:get(tls).
%% @private
monotonic_now() ->
erlang:monotonic_time(millisecond).
%% @private
send(Transport, Socket, Data) ->
%% Transmit the data on the socket.
Transport:send(Socket, Data).
%% Determine if we should transmit:
%%
%% If there's another message in the queue, we can skip
%% sending this message. However, if the arrival rate of
%% messages is too high, we risk starvation where
%% we may never send. Therefore, we must force a transmission
%% after a given period with no transmissions.
%%
%% @private
monotonic_should_send(MessageQueueLen, LastTransmissionTime) ->
case MessageQueueLen > 0 of
true ->
%% Messages in queue; conditional send.
NowTime = monotonic_now(),
Diff = abs(NowTime - LastTransmissionTime),
SendWindow = partisan_config:get(send_window, 1000),
Diff > SendWindow;
false ->
%% No messages in queue; transmit.
true
end.