Skip to content

Commit 1f43012

Browse files
committed
Provide direct transition into closed state.
1 parent 70b1e0b commit 1f43012

File tree

2 files changed

+22
-30
lines changed

2 files changed

+22
-30
lines changed

lib/protocol/websocket/connection.rb

Lines changed: 21 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -55,21 +55,30 @@ def flush
5555
@framer.flush
5656
end
5757

58-
def closed?
59-
@state == :closed
58+
def open!
59+
@state = :open
60+
61+
return self
6062
end
6163

62-
def close(code = Error::NO_ERROR, reason = "")
63-
unless closed?
64+
def close!(...)
65+
unless @state == :closed
66+
@state = :closed
67+
6468
begin
65-
send_close(code, reason)
69+
send_close(...)
6670
rescue
6771
# Ignore.
6872
end
69-
70-
@state = :closed
7173
end
72-
74+
end
75+
76+
def closed?
77+
@state == :closed
78+
end
79+
80+
def close(...)
81+
self.close!(...)
7382
@framer.close
7483
end
7584

@@ -88,11 +97,11 @@ def read_frame
8897

8998
return frame
9099
rescue ProtocolError => error
91-
send_close(error.code, error.message)
100+
close!(error.code, error.message)
92101

93102
raise
94103
rescue
95-
send_close(Error::PROTOCOL_ERROR, $!.message)
104+
close!(Error::PROTOCOL_ERROR, $!.message)
96105

97106
raise
98107
end
@@ -132,12 +141,7 @@ def receive_close(frame)
132141

133142
# If we're already closed, then we don't need to send a close frame. Otherwise, according to the RFC, we should echo the close frame. However, it's possible it will fail to send if the connection is already closed.
134143
unless @state == :closed
135-
@state = :closed
136-
begin
137-
send_close(code, reason)
138-
rescue
139-
# Ignore.
140-
end
144+
close!(code, reason)
141145
end
142146

143147
if code and code != Error::NO_ERROR
@@ -156,18 +160,6 @@ def send_ping(data = "")
156160
end
157161
end
158162

159-
def open!
160-
@state = :open
161-
162-
return self
163-
end
164-
165-
def close!
166-
@state = :closed
167-
168-
return self
169-
end
170-
171163
def receive_ping(frame)
172164
if @state != :closed
173165
write_frame(frame.reply(mask: @mask))
@@ -249,7 +241,7 @@ def read(**options)
249241
end
250242
end
251243
rescue ProtocolError => error
252-
send_close(error.code, error.message)
244+
close!(error.code, error.message)
253245

254246
raise
255247
end

test/protocol/websocket/connection.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@
156156
connection.read_frame
157157
end.to raise_exception(EOFError, message: be =~ /Fake error/)
158158

159-
expect(connection).not.to be(:closed?)
159+
expect(connection).to be(:closed?)
160160

161161
frame = client.read_frame
162162
expect(frame).to be_a(Protocol::WebSocket::CloseFrame)

0 commit comments

Comments
 (0)