Skip to content

Commit a2391b9

Browse files
committed
Address comments, add tests.
1 parent 32db31d commit a2391b9

File tree

2 files changed

+52
-4
lines changed

2 files changed

+52
-4
lines changed

kubernetes/spec/watch_spec.rb

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Copyright 2019 The Kubernetes Authors.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
require 'spec_helper'
16+
require 'kubernetes/watch'
17+
18+
describe 'WatchClient' do
19+
it 'should construct correctly' do
20+
Kubernetes::Watch.new(nil)
21+
end
22+
23+
it 'should parse chunks correctly' do
24+
client = Kubernetes::Watch.new(nil)
25+
last = ''
26+
27+
last, data = client.split_lines(last, "foo\nbar\nba")
28+
29+
expect(last).to eq('ba')
30+
expect(data).to eq(%w[foo bar])
31+
32+
last, data = client.split_lines(last, "z\nblah\n")
33+
expect(last).to eq('')
34+
expect(data).to eq(%w[baz blah])
35+
end
36+
end

kubernetes/src/kubernetes/watch.rb

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,14 +26,26 @@ def initialize(client)
2626
def connect(path, &_block)
2727
opts = { auth_names: ['BearerToken'] }
2828
request = @client.build_request('GET', path + '?watch=true', opts)
29+
last = ''
2930
request.on_body do |chunk|
30-
parts = chunk.split(/\n/)
31-
parts.each do |part|
32-
obj = JSON.parse(part)
33-
yield obj
31+
last, pieces = split_lines(last, chunk)
32+
pieces.each do |part|
33+
yield JSON.parse(part)
3434
end
3535
end
3636
request.run
3737
end
38+
39+
def split_lines(last, chunk)
40+
data = chunk
41+
data = last + '' + data
42+
43+
ix = data.rindex("\n")
44+
return [data, []] unless ix
45+
46+
complete = data[0..ix]
47+
last = data[(ix + 1)..data.length]
48+
[last, complete.split(/\n/)]
49+
end
3850
end
3951
end

0 commit comments

Comments
 (0)