flagnetic 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,20 +1,36 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "digest"
4
+ require "json"
5
+
3
6
  module Flagnetic
4
- # FileStore keeps the last good ruleset in one file: the ruleset document
5
- # exactly as the endpoint served it, so the file also works as an offline
6
- # document. Its modification time is when the ruleset was received.
7
+ # FileStore keeps the last good ruleset in one file: a header line naming
8
+ # the key the ruleset was received under, then the ruleset document exactly
9
+ # as the endpoint served it. The header holds a digest of the SDK key, never
10
+ # the key. Without it, a process restarted with another environment's key on
11
+ # the same path would serve that environment's ruleset as last_good, and
12
+ # refuse the right one as a downgrade whenever the old version was higher.
13
+ # The file's modification time is when the ruleset was received.
7
14
  # Writes go to a unique temporary file renamed over the target, so
8
15
  # processes sharing the path (Puma workers) never read a torn file.
9
16
  class FileStore
10
- def initialize(path)
17
+ FORMAT = 1
18
+
19
+ # Refused is raised for a file this client may not serve from: one written
20
+ # under no key, under another key or in another format.
21
+ class Refused < StandardError; end
22
+
23
+ def initialize(path, sdk_key)
11
24
  @path = path.to_s
25
+ @digest = Digest::SHA256.hexdigest(sdk_key.to_s)
12
26
  end
13
27
 
14
- # load returns [json, received_at], or nil when there is no file.
28
+ # load returns [json, received_at], or nil when there is no file. It
29
+ # raises Refused for a file written under no key or another key.
15
30
  def load
16
- json = File.binread(@path)
17
- [json, File.mtime(@path)]
31
+ content = File.binread(@path)
32
+ received_at = File.mtime(@path)
33
+ [document_of(content), received_at]
18
34
  rescue Errno::ENOENT
19
35
  nil
20
36
  end
@@ -22,13 +38,41 @@ module Flagnetic
22
38
  def save(json)
23
39
  tmp = "#{@path}.#{Process.pid}.#{Thread.current.object_id}.tmp"
24
40
  # The server ruleset holds private segments: readable by the owner only.
25
- File.open(tmp, File::WRONLY | File::CREAT | File::TRUNC | File::BINARY, 0o600) { |f| f.write(json) }
41
+ File.open(tmp, File::WRONLY | File::CREAT | File::TRUNC | File::BINARY, 0o600) do |f|
42
+ f.write(header, "\n", json)
43
+ end
26
44
  File.rename(tmp, @path)
27
45
  ensure
28
46
  File.delete(tmp) if tmp && File.exist?(tmp)
29
47
  end
30
48
 
31
49
  def to_s = @path
50
+
51
+ private
52
+
53
+ def header = JSON.generate({ "flagnetic_store" => FORMAT, "key" => @digest })
54
+
55
+ def document_of(content)
56
+ line, newline, document = content.partition("\n".b)
57
+ head = newline.empty? ? nil : parse_header(line)
58
+ raise Refused, "the store was written under no key" unless head.is_a?(Hash) && head.key?("flagnetic_store")
59
+
60
+ unless format?(head["flagnetic_store"])
61
+ raise Refused,
62
+ "the store was written in a format this client does not read"
63
+ end
64
+ raise Refused, "the store was written under another key" unless head["key"] == @digest
65
+
66
+ document
67
+ end
68
+
69
+ def format?(value) = value.is_a?(Integer) && value == FORMAT
70
+
71
+ def parse_header(line)
72
+ JSON.parse(line.dup.force_encoding(Encoding::UTF_8))
73
+ rescue JSON::ParserError, EncodingError
74
+ nil
75
+ end
32
76
  end
33
77
  private_constant :FileStore
34
78
  end
@@ -155,7 +155,7 @@ module Flagnetic
155
155
  end
156
156
 
157
157
  wire_events = events.map { |e| wire(e) }
158
- batches = EventBatch.pack(wire_events, @transport.identity)
158
+ batches = EventBatch.pack(wire_events, @transport.identity) { |_, err| report_unserialisable(err) }
159
159
  batches.each_with_index do |group, i|
160
160
  result = attempt(group, deadline)
161
161
  case result.kind
@@ -188,6 +188,8 @@ module Flagnetic
188
188
  events
189
189
  end
190
190
 
191
+ # wire scrubs the document because a flag key is whatever the caller
192
+ # passed to a getter, so it can be a string that is no UTF-8.
191
193
  def wire(event)
192
194
  doc = { "type" => "evaluation_summary", "event_id" => event.event_id,
193
195
  "interval_start" => EventBatch.format_time(event.interval_start),
@@ -197,7 +199,7 @@ module Flagnetic
197
199
  { "flag" => r[:flag], "variation" => r[:variation], "reason" => r[:reason].to_s, "count" => r[:count] }
198
200
  end }
199
201
  doc["app_version"] = @app_version if @app_version
200
- doc
202
+ EventBatch.scrub(doc)
201
203
  end
202
204
 
203
205
  def public_summary(event)
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Flagnetic
4
- VERSION = "0.1.0"
4
+ VERSION = "0.1.2"
5
5
 
6
6
  # The schema_version range of the documents this SDK reads and the SDK API
7
7
  # path it speaks. A ruleset outside the range is a fallback chain failure,
@@ -10,17 +10,21 @@ module Flagnetic
10
10
  # their intervals. The stream
11
11
  # itself is read by a Stream thread that posts what happens to the
12
12
  # worker's inbox, which the worker waits on together with its next
13
- # deadline. It never raises: a failure is a log event and a later attempt.
13
+ # deadline. It never raises: a failure is a log event and a later attempt,
14
+ # whatever the failure is, and a thread that dies anyway is logged and
15
+ # started again after a backoff, because it is the only thing keeping the
16
+ # process's ruleset current.
14
17
  class Worker
15
18
  def initialize(client, transport, timing, stream:)
16
19
  @client = client
17
20
  @transport = transport
18
21
  @timing = timing
22
+ @random = timing.random || Random.new
19
23
  @stream_enabled = stream
20
24
  @inbox = Queue.new
21
25
  @stop = false
22
26
  @stream_ids = 0
23
- @thread = Thread.new { run }
27
+ @thread = Thread.new { supervise }
24
28
  @thread.name = "flagnetic"
25
29
  @thread.report_on_exception = false
26
30
  end
@@ -37,6 +41,15 @@ module Flagnetic
37
41
  # A killed thread still runs its ensure, which closes the stream; it
38
42
  # is not waited for, so close returns within timeout.
39
43
  @thread.kill unless @thread.join([timeout, 0].max)
44
+ nil
45
+ rescue Exception # rubocop:disable Lint/RescueException
46
+ # join re-raises what the thread died of; that was logged when it
47
+ # happened and is not the host's to handle. Anything else came into
48
+ # the caller while it waited (an Interrupt, a Timeout) and is the
49
+ # host's: a thread that is still alive, or ended normally, did not
50
+ # raise it.
51
+ raise unless @thread.status.nil?
52
+
40
53
  nil
41
54
  end
42
55
 
@@ -59,18 +72,39 @@ module Flagnetic
59
72
 
60
73
  def now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
61
74
 
75
+ # supervise runs the loop and starts it again, after a backoff, when it
76
+ # ends by an exception: step already absorbs failures of one turn, so
77
+ # this is for what escapes it (a failure in the loop's own setup, or an
78
+ # exception step re-raised). A backoff that is not reset by a long
79
+ # enough run keeps a crash loop from spinning.
80
+ def supervise
81
+ deaths = Backoff.new(base: @timing.fetch_base, cap: @timing.fetch_cap)
82
+ until @stop
83
+ started = now
84
+ begin
85
+ run
86
+ rescue Exception => e # rubocop:disable Lint/RescueException
87
+ @client.__send__(:log, :error, :worker_died, cause: "#{e.class}: #{e.message}")
88
+ deaths.reset if now - started >= @timing.worker_stable
89
+ sleep deaths.next_delay unless @stop
90
+ end
91
+ end
92
+ end
93
+
62
94
  def run
63
95
  @fetch_backoff = Backoff.new(base: @timing.fetch_base, cap: @timing.fetch_cap)
64
- @stream_backoff = Backoff.new(base: @timing.stream_base, cap: @timing.stream_cap)
96
+ @stream_backoff = Backoff.new(base: @timing.stream_base, cap: @timing.stream_cap, random: @random)
65
97
  @refused_backoff = Backoff.new(base: @timing.fetch_base, cap: @timing.unauthorized_cap)
66
98
  @next_fetch = now
67
99
  @stream_due = @stream_enabled ? now : nil
68
100
  @connected = false
101
+ @stable = false
69
102
  @want = nil
70
103
  @event_retry = 0
71
104
  step until @stop
72
105
  ensure
73
106
  @stream&.close
107
+ @stream = nil
74
108
  end
75
109
 
76
110
  # step opens the stream when due, fetches when due, flushes the
@@ -83,7 +117,12 @@ module Flagnetic
83
117
  drive(@client.__send__(:exposures), @timing.exposure_flush) unless @stop
84
118
  drive(@client.__send__(:summaries), @timing.summary_flush) unless @stop
85
119
  wait unless @stop
86
- rescue StandardError => e
120
+ rescue SystemExit, NoMemoryError
121
+ raise
122
+ rescue Exception => e # rubocop:disable Lint/RescueException
123
+ # Not only StandardError: a SystemStackError from a deeply nested
124
+ # document or a failure raised by a listener must not end the only
125
+ # thread that follows the ruleset.
87
126
  @client.__send__(:log, :error, :worker_failed, cause: "#{e.class}: #{e.message}")
88
127
  sleep 1 unless @stop
89
128
  end
@@ -99,7 +138,9 @@ module Flagnetic
99
138
  return unless queue&.due?(now)
100
139
 
101
140
  queue.flush_once([interval, @timing.request_timeout].min)
102
- rescue StandardError => e
141
+ rescue SystemExit, NoMemoryError
142
+ raise
143
+ rescue Exception => e # rubocop:disable Lint/RescueException
103
144
  @client.__send__(:log, :error, :worker_failed, cause: "#{e.class}: #{e.message}")
104
145
  end
105
146
 
@@ -169,26 +210,37 @@ module Flagnetic
169
210
  def connected
170
211
  @refused_backoff.reset
171
212
  @connected = true
172
- @connected_at = now
213
+ @stable = false
173
214
  @client.__send__(:stream_connected)
174
215
  @next_fetch = now # versions may have been missed while down
175
216
  end
176
217
 
218
+ # close_stream forgets the stream's stability with it: a heartbeat on
219
+ # one stream says nothing of the next, so a failed reconnect after a
220
+ # stable stream still counts toward the backoff.
177
221
  def close_stream
178
222
  @head_pending = false
179
223
  @stream&.close
180
224
  @stream = nil
181
225
  @connected = false
226
+ @stable = false
182
227
  end
183
228
 
184
229
  # drop ends the stream and schedules a reconnect: 0 to close_jitter
185
- # seconds after a server-side close, else the backoff, reset once a
186
- # connection stayed up stream_stable seconds.
230
+ # seconds after a server-side close of a stable stream, else the backoff.
231
+ # A stream is stable once it has delivered a heartbeat, which restarts
232
+ # the backoff from its base; one the server closes before that is a
233
+ # failed connection however it was answered, so that a draining replica
234
+ # or a proxy that ends the stream at once is backed off from.
187
235
  def drop(cause, error:)
188
- @stream_backoff.reset if @connected && now - @connected_at >= @timing.stream_stable
236
+ @stream_backoff.reset if @stable
237
+ if !error && !@stable
238
+ error = true
239
+ cause = "#{cause} before its first heartbeat"
240
+ end
189
241
  close_stream
190
242
  @client.__send__(:log, error ? :warn : :info, :sse_dropped, cause: cause)
191
- delay = error ? @stream_backoff.next_delay : rand * @timing.close_jitter
243
+ delay = error ? @stream_backoff.next_delay : @random.rand * @timing.close_jitter
192
244
  @stream_due = now + delay
193
245
  @next_fetch = [@next_fetch, now + @timing.poll_down].min
194
246
  end
@@ -248,6 +300,7 @@ module Flagnetic
248
300
  end
249
301
 
250
302
  def frame(kind, value)
303
+ @stable = true if kind == :comment
251
304
  return unless kind == :event && value.type == "ruleset"
252
305
 
253
306
  version = begin
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: flagnetic
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0
4
+ version: 0.1.2
5
5
  platform: ruby
6
6
  authors:
7
7
  - Anatolii Zverev
@@ -29,6 +29,7 @@ files:
29
29
  - lib/flagnetic/eval/murmur3.rb
30
30
  - lib/flagnetic/eval/operators.rb
31
31
  - lib/flagnetic/eval/regex.rb
32
+ - lib/flagnetic/eval/regex_vm.rb
32
33
  - lib/flagnetic/eval/ruleset.rb
33
34
  - lib/flagnetic/eval/semver.rb
34
35
  - lib/flagnetic/eval/types.rb