flagnetic 0.1.1 → 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.
@@ -0,0 +1,356 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Flagnetic
4
+ # Eval is the evaluator; see flagnetic/eval.rb.
5
+ module Eval
6
+ module Regex
7
+ # CharSet is a set of code points: inclusive [lo, hi] ranges and Unicode
8
+ # properties, or everything else when negated. It answers membership in
9
+ # constant time for ASCII and in logarithmic time otherwise.
10
+ class CharSet
11
+ attr_reader :ranges
12
+
13
+ def initialize(ranges, props, negated)
14
+ @ranges = ranges.freeze
15
+ @los = ranges.map(&:first).freeze
16
+ @his = ranges.map(&:last).freeze
17
+ @props = props.freeze
18
+ @negated = negated
19
+ @ascii = Array.new(128) { |cp| member?(cp) }.freeze
20
+ freeze
21
+ end
22
+
23
+ # single reports the one code point the set holds, or nil.
24
+ def single
25
+ @ranges[0][0] if !@negated && @props.empty? && @ranges.size == 1 && @ranges[0][0] == @ranges[0][1]
26
+ end
27
+
28
+ def include?(cp)
29
+ cp < 128 ? @ascii[cp] : member?(cp)
30
+ end
31
+
32
+ private
33
+
34
+ def member?(cp)
35
+ found = in_ranges?(cp) || @props.any? { |prop| prop.include?(cp) }
36
+ found != @negated
37
+ end
38
+
39
+ def in_ranges?(cp)
40
+ i = @his.bsearch_index { |hi| hi >= cp }
41
+ !i.nil? && @los[i] <= cp
42
+ end
43
+ end
44
+
45
+ # Property is a \p or \P class: the code points with the Unicode
46
+ # property name, or without it when negated, and, under (?i), those
47
+ # an orbit of simple case folding ties to one that has it (extra).
48
+ class Property
49
+ def initialize(name, negated, extra)
50
+ @pattern = Regexp.new("\\p{#{name}}")
51
+ @negated = negated
52
+ @extra = extra.to_h { |cp| [cp, true] }.freeze
53
+ freeze
54
+ end
55
+
56
+ def include?(cp)
57
+ has = @pattern.match?([cp].pack("U")) || @extra.key?(cp)
58
+ has != @negated
59
+ end
60
+ end
61
+
62
+ # Node is a node of the parse tree. need is the smallest repeat budget
63
+ # Go's repeatIsValid accepts for the subtree, size its approximate
64
+ # length in instructions.
65
+ class Node
66
+ CHAR = 0
67
+ ASSERT = 1
68
+ CAT = 2
69
+ ALT = 3
70
+ REPEAT = 4
71
+
72
+ attr_reader :kind, :set, :what, :subs, :lo, :hi, :need, :size
73
+
74
+ def initialize(kind, set: nil, what: 0, subs: [], lo: 0, hi: 0, counted: false)
75
+ @kind = kind
76
+ @set = set
77
+ @what = what
78
+ @subs = subs
79
+ @lo = lo
80
+ @hi = hi
81
+ @need = 0
82
+ @size = 1
83
+ measure(counted)
84
+ freeze
85
+ end
86
+
87
+ private
88
+
89
+ def measure(counted)
90
+ case @kind
91
+ when CAT
92
+ @need = @subs.map(&:need).max || 0
93
+ @size = @subs.sum(&:size)
94
+ when ALT
95
+ @need = @subs.map(&:need).max || 0
96
+ @size = @subs.sum(&:size) + @subs.size - 1
97
+ when REPEAT
98
+ measure_repeat(@subs[0], counted)
99
+ end
100
+ end
101
+
102
+ def measure_repeat(inner, counted)
103
+ if counted
104
+ bound = @hi >= 0 ? @hi : @lo
105
+ @need = bound.zero? ? 0 : bound * [inner.need, 1].max
106
+ @size = (inner.size * [@hi >= 0 ? @hi : @lo + 1, 1].max) + 3
107
+ else
108
+ @need = inner.need
109
+ @size = inner.size + 2
110
+ end
111
+ end
112
+ end
113
+
114
+ # Program is a compiled pattern: parallel arrays of an opcode, two
115
+ # operands and a set per instruction.
116
+ Program = Struct.new(:ops, :x, :y, :sets)
117
+
118
+ # Compiler turns a parse tree into the instructions of a Pike VM.
119
+ # LIT matches one code point (operand x), SET one of a set, SPLIT forks
120
+ # to x and y, JMP goes to x, ASSERT checks the assertion x and goes on
121
+ # to the next instruction, MATCH ends.
122
+ class Compiler
123
+ LIT = 0
124
+ SET = 1
125
+ SPLIT = 2
126
+ JMP = 3
127
+ ASSERT = 4
128
+ MATCH = 5
129
+
130
+ def self.compile(root)
131
+ new.compile(root)
132
+ end
133
+
134
+ def initialize
135
+ @program = Program.new([], [], [], [])
136
+ end
137
+
138
+ # compile walks the tree with a work list, not recursion: a tree can
139
+ # be a few thousand levels deep, more than the stack of a thread or a
140
+ # fiber holds. An entry is a Node to emit or a Proc to run, such as
141
+ # one patching a jump once its target is known.
142
+ def compile(root)
143
+ @work = [root]
144
+ until @work.empty?
145
+ item = @work.pop
146
+ item.is_a?(Node) ? emit_node(item) : item.call
147
+ end
148
+ emit(MATCH)
149
+ @program.each(&:freeze)
150
+ @program.freeze
151
+ end
152
+
153
+ private
154
+
155
+ def emit(op, x = 0, y = 0, set = nil)
156
+ @program.ops << op
157
+ @program.x << x
158
+ @program.y << y
159
+ @program.sets << set
160
+ @program.ops.size - 1
161
+ end
162
+
163
+ def here = @program.ops.size
164
+
165
+ # schedule queues steps to run in the order given, before anything
166
+ # queued earlier.
167
+ def schedule(steps)
168
+ @work.concat(steps.reverse)
169
+ end
170
+
171
+ def emit_node(node)
172
+ case node.kind
173
+ when Node::CHAR then emit_char(node.set)
174
+ when Node::ASSERT then emit(ASSERT, node.what)
175
+ when Node::CAT then schedule(node.subs)
176
+ when Node::ALT then emit_alternation(node.subs)
177
+ else emit_repeat(node)
178
+ end
179
+ end
180
+
181
+ def emit_char(set)
182
+ cp = set.single
183
+ cp ? emit(LIT, cp) : emit(SET, 0, 0, set)
184
+ end
185
+
186
+ # split(a, L1); a; jmp end; L1: split(b, L2); b; jmp end; L2: c
187
+ def emit_alternation(subs)
188
+ exits = []
189
+ steps = []
190
+ subs.each_with_index do |sub, k|
191
+ next steps << sub if k == subs.size - 1
192
+
193
+ fork = nil
194
+ steps << -> { fork = emit(SPLIT, here + 1) }
195
+ steps << sub
196
+ steps << lambda {
197
+ exits << emit(JMP)
198
+ @program.y[fork] = here
199
+ }
200
+ end
201
+ steps << -> { exits.each { |e| @program.x[e] = here } }
202
+ schedule(steps)
203
+ end
204
+
205
+ def emit_repeat(node)
206
+ sub = node.subs[0]
207
+ steps = Array.new(node.lo, sub)
208
+ if node.hi.negative?
209
+ loop_steps(sub, steps)
210
+ else
211
+ # Each optional copy may skip to the end: the language of x{lo,hi}.
212
+ forks = []
213
+ (node.hi - node.lo).times do
214
+ steps << -> { forks << emit(SPLIT, here + 1) }
215
+ steps << sub
216
+ end
217
+ steps << -> { forks.each { |f| @program.y[f] = here } }
218
+ end
219
+ schedule(steps)
220
+ end
221
+
222
+ # L: split(body, out); body; jmp L
223
+ def loop_steps(sub, steps)
224
+ fork = nil
225
+ steps << -> { fork = emit(SPLIT, here + 1) }
226
+ steps << sub
227
+ steps << lambda {
228
+ emit(JMP, fork)
229
+ @program.y[fork] = here
230
+ }
231
+ end
232
+ end
233
+
234
+ # Vm is a Pike VM: it matches in time linear in the input for a given
235
+ # program, whatever the pattern, so nothing a context carries can make a
236
+ # match take longer.
237
+ module Vm
238
+ LIT = Compiler::LIT
239
+ SET = Compiler::SET
240
+ SPLIT = Compiler::SPLIT
241
+ JMP = Compiler::JMP
242
+ ASSERT = Compiler::ASSERT
243
+ MATCH = Compiler::MATCH
244
+
245
+ BEGIN_TEXT = 0
246
+ END_TEXT = 1
247
+ BEGIN_LINE = 2
248
+ END_LINE = 3
249
+ WORD_BOUNDARY = 4
250
+ NOT_WORD_BOUNDARY = 5
251
+
252
+ NEWLINE = 0x0A
253
+ REPLACEMENT_CHARACTER = 0xFFFD
254
+
255
+ module_function
256
+
257
+ # search reports whether program matches anywhere in cps, the code
258
+ # points of the text. Every thread advances in lockstep over them;
259
+ # the first to reach MATCH decides, as only whether it matches is
260
+ # asked.
261
+ def search(program, cps)
262
+ state = State.new(program, cps)
263
+ pos = 0
264
+ loop do
265
+ state.add(state.current, 0, pos) # unanchored: a new thread at every position
266
+ return true if state.step(pos)
267
+ return false if pos >= cps.size
268
+
269
+ pos += 1
270
+ state.advance
271
+ end
272
+ end
273
+
274
+ # State holds the threads of one search.
275
+ class State
276
+ attr_reader :current
277
+
278
+ def initialize(program, cps)
279
+ @ops = program.ops
280
+ @x = program.x
281
+ @y = program.y
282
+ @sets = program.sets
283
+ @cps = cps
284
+ @mark = Array.new(@ops.size, -1)
285
+ @current = []
286
+ @following = []
287
+ @stack = []
288
+ @gen = 0
289
+ end
290
+
291
+ def advance
292
+ @gen += 1
293
+ @current, @following = @following, @current
294
+ @following.clear
295
+ end
296
+
297
+ # step runs every thread on the code point at pos and queues the
298
+ # survivors; true when one has matched.
299
+ def step(pos)
300
+ cp = pos < @cps.size ? @cps[pos] : -1
301
+ @current.each do |pc|
302
+ op = @ops[pc]
303
+ return true if op == MATCH
304
+ next if cp.negative?
305
+
306
+ add(@following, pc + 1, pos + 1, @gen + 1) if consumes?(op, pc, cp)
307
+ end
308
+ false
309
+ end
310
+
311
+ # add queues the threads reachable from pc without consuming input.
312
+ def add(threads, pc, pos, gen = @gen)
313
+ @stack.push(pc)
314
+ until @stack.empty?
315
+ pc = @stack.pop
316
+ next if @mark[pc] == gen
317
+
318
+ @mark[pc] = gen
319
+ case @ops[pc]
320
+ when JMP then @stack.push(@x[pc])
321
+ when SPLIT then @stack.push(@y[pc], @x[pc])
322
+ when ASSERT then @stack.push(pc + 1) if holds?(@x[pc], pos)
323
+ else threads << pc
324
+ end
325
+ end
326
+ end
327
+
328
+ private
329
+
330
+ def consumes?(op, pc, cp)
331
+ op == LIT ? cp == @x[pc] : op == SET && @sets[pc].include?(cp)
332
+ end
333
+
334
+ # \b and \B read ASCII word characters, as RE2 does.
335
+ def holds?(assertion, pos)
336
+ n = @cps.size
337
+ case assertion
338
+ when BEGIN_TEXT then pos.zero?
339
+ when END_TEXT then pos == n
340
+ when BEGIN_LINE then pos.zero? || @cps[pos - 1] == NEWLINE
341
+ when END_LINE then pos == n || @cps[pos] == NEWLINE
342
+ else (word?(pos - 1) != word?(pos)) == (assertion == WORD_BOUNDARY)
343
+ end
344
+ end
345
+
346
+ def word?(pos)
347
+ return false if pos.negative? || pos >= @cps.size
348
+
349
+ cp = @cps[pos]
350
+ cp == 0x5F || cp.between?(0x30, 0x39) || cp.between?(0x41, 0x5A) || cp.between?(0x61, 0x7A)
351
+ end
352
+ end
353
+ end
354
+ end
355
+ end
356
+ end
@@ -88,6 +88,15 @@ module Flagnetic
88
88
  @index.unsupported
89
89
  end
90
90
 
91
+ # invalid_conditions reports, by flag key, why conditions of each flag
92
+ # cannot be evaluated by this evaluator, apart from the unsupported
93
+ # constructs unsupported_rules reports: a pattern outside what it
94
+ # reads, an undeclared attribute, a value of the wrong type. Each
95
+ # reason comes once, in document order; a flag with none is absent.
96
+ def invalid_conditions
97
+ @index.invalid
98
+ end
99
+
91
100
  # evaluate computes one flag for a context. It never reads a clock,
92
101
  # never records an exposure and never fails: problems are results with
93
102
  # reason error.
@@ -184,6 +184,23 @@ module Flagnetic
184
184
  Tirhuta Todhri Tolong_Siki Toto Tulu_Tigalari Ugaritic Vai Vithkuqi Wancho Warang_Citi Yezidi Yi Z
185
185
  Zanabazar_Square Zl Zp Zs
186
186
  ].freeze
187
+
188
+ # CATEGORY_ALIASES maps the long names of categories (Letter,
189
+ # Decimal_Number, cntrl) to the category they stand for.
190
+ CATEGORY_ALIASES = {
191
+ "Cased_Letter" => "LC", "Close_Punctuation" => "Pe", "Combining_Mark" => "M",
192
+ "Connector_Punctuation" => "Pc", "Control" => "Cc", "Currency_Symbol" => "Sc",
193
+ "Dash_Punctuation" => "Pd", "Decimal_Number" => "Nd", "Enclosing_Mark" => "Me",
194
+ "Final_Punctuation" => "Pf", "Format" => "Cf", "Initial_Punctuation" => "Pi", "Letter" => "L",
195
+ "Letter_Number" => "Nl", "Line_Separator" => "Zl", "Lowercase_Letter" => "Ll", "Mark" => "M",
196
+ "Math_Symbol" => "Sm", "Modifier_Letter" => "Lm", "Modifier_Symbol" => "Sk",
197
+ "Nonspacing_Mark" => "Mn", "Number" => "N", "Open_Punctuation" => "Ps", "Other" => "C",
198
+ "Other_Letter" => "Lo", "Other_Number" => "No", "Other_Punctuation" => "Po", "Other_Symbol" => "So",
199
+ "Paragraph_Separator" => "Zp", "Private_Use" => "Co", "Punctuation" => "P", "Separator" => "Z",
200
+ "Space_Separator" => "Zs", "Spacing_Mark" => "Mc", "Surrogate" => "Cs", "Symbol" => "S",
201
+ "Titlecase_Letter" => "Lt", "Unassigned" => "Cn", "Uppercase_Letter" => "Lu", "cntrl" => "Cc",
202
+ "digit" => "Nd", "punct" => "P",
203
+ }.freeze
187
204
  end
188
205
  end
189
206
  end
@@ -34,7 +34,10 @@ module Flagnetic
34
34
  # endpoint accepts: at most 500 events, and under 1 MiB decoded
35
35
  # together with the envelope. An event too large on its own still
36
36
  # becomes a batch of one, which the platform answers 413 and the
37
- # caller drops.
37
+ # caller drops. An event that does not encode (a value that is no JSON
38
+ # value, a string that survived scrubbing as invalid) is left out of
39
+ # every batch and handed to the block with the error, so it costs the
40
+ # flush that event alone and not every event packed with it.
38
41
  def pack(events, identity)
39
42
  budget = MAX_BATCH_BYTES - overhead(identity)
40
43
  batches = []
@@ -49,11 +52,40 @@ module Flagnetic
49
52
  end
50
53
  current << e
51
54
  size += cost
55
+ rescue StandardError => err
56
+ yield e, err if block_given?
52
57
  end
53
58
  batches << current if current.any?
54
59
  batches
55
60
  end
56
61
 
62
+ # scrub returns value with every string, hash keys included, valid
63
+ # UTF-8: JSON.generate refuses any other, and a unit ID is whatever a
64
+ # caller took from a request (a crafted cookie, say). Invalid bytes
65
+ # become U+FFFD, as Go's encoder writes them. A binary string, which is
66
+ # how a Rack string arrives, is read as UTF-8 rather than refused for
67
+ # its encoding label; a string in another encoding is transcoded. The
68
+ # argument is never modified.
69
+ def scrub(value)
70
+ case value
71
+ when String then scrub_string(value)
72
+ when Hash then value.to_h { |k, v| [scrub(k), scrub(v)] }
73
+ when Array then value.map { |v| scrub(v) }
74
+ else value
75
+ end
76
+ end
77
+
78
+ def scrub_string(string)
79
+ case string.encoding
80
+ when Encoding::UTF_8 then string.valid_encoding? ? string : string.scrub
81
+ when Encoding::BINARY then string.dup.force_encoding(Encoding::UTF_8).scrub
82
+ else string.encode(Encoding::UTF_8, invalid: :replace, undef: :replace)
83
+ end
84
+ rescue StandardError
85
+ # An encoding Ruby cannot convert from: nothing of it is worth sending.
86
+ ""
87
+ end
88
+
57
89
  # send_batch posts one batch through transport, bounding the call by
58
90
  # timeout seconds, and classifies the answer. It never raises.
59
91
  def send_batch(transport, events, timeout)
@@ -259,8 +259,12 @@ module Flagnetic
259
259
 
260
260
  # enqueue puts one event in the queue, dropping the oldest when the
261
261
  # queue is full, and wakes whatever is waiting for a longer deadline.
262
- # An offline queue hands the event to the Recorder instead.
262
+ # An offline queue hands the event to the Recorder instead. Strings are
263
+ # scrubbed here, where the event is one among those being recorded, so
264
+ # a unit ID that is no UTF-8 is sent with U+FFFD in it instead of
265
+ # failing the flush that carries it.
263
266
  def enqueue(event)
267
+ event = EventBatch.scrub(event)
264
268
  if offline?
265
269
  @record.call(event)
266
270
  return
@@ -299,7 +303,7 @@ module Flagnetic
299
303
  events = take
300
304
  return true if events.empty?
301
305
 
302
- batches = EventBatch.pack(events, @transport.identity)
306
+ batches = EventBatch.pack(events, @transport.identity) { |_, err| report_unserialisable(err) }
303
307
  batches.each_with_index do |group, i|
304
308
  result = attempt(group, deadline)
305
309
  case result.kind
@@ -32,7 +32,8 @@ module Flagnetic
32
32
  end
33
33
 
34
34
  # load_store serves a persisted ruleset as last_good before any network
35
- # call. A corrupt file leaves the stage built_in, with a log.
35
+ # call. A corrupt file, or one written under another key, leaves the stage
36
+ # built_in, with a log.
36
37
  def load_store
37
38
  json, received_at = @store.load
38
39
  return unless json
@@ -44,6 +45,8 @@ module Flagnetic
44
45
  end
45
46
 
46
47
  swap(ruleset, received_at: received_at, stage: :last_good, source: "store")
48
+ rescue FileStore::Refused => e
49
+ log(:error, :store_failed, path: @store.to_s, cause: e.message)
47
50
  rescue SystemCallError, IOError => e
48
51
  log(:error, :store_failed, path: @store.to_s, cause: "#{e.class}: #{e.message}")
49
52
  end
@@ -64,7 +67,9 @@ module Flagnetic
64
67
 
65
68
  Eval::Ruleset.decode(json)
66
69
  rescue JSON::ParserError, EncodingError => e
67
- "parse: #{e.message.lines.first&.strip}"
70
+ # The parser quotes the bytes it stopped at, which need not be UTF-8:
71
+ # scrubbed, so building the cause never raises past the caller.
72
+ "parse: #{e.message.scrub.lines.first&.strip}"
68
73
  rescue Eval::DecodeError => e
69
74
  "parse: #{e.message}"
70
75
  end
@@ -83,6 +88,7 @@ module Flagnetic
83
88
  end
84
89
  log(:info, :ruleset_loaded, source: source, ruleset_version: ruleset.version, flags: ruleset.flags.size)
85
90
  report_unsupported(ruleset)
91
+ report_invalid(ruleset)
86
92
  stage_changed(previous_stage, stage)
87
93
  (Changes.flags(previous&.ruleset, ruleset) | refuse_local_overrides(ruleset)).sort
88
94
  end
@@ -101,11 +107,24 @@ module Flagnetic
101
107
  end
102
108
  end
103
109
 
104
- def first_report?(key, version)
110
+ # report_invalid logs condition_invalid for every flag of ruleset with
111
+ # a condition this evaluator cannot evaluate although the server
112
+ # accepted the ruleset, once per flag and ruleset version: the flag
113
+ # serves its default wherever evaluation reaches the condition, and
114
+ # nothing else says why.
115
+ def report_invalid(ruleset)
116
+ ruleset.invalid_conditions.sort.each do |key, reasons|
117
+ next unless first_report?(key, ruleset.version, @invalid_logged)
118
+
119
+ log(:error, :condition_invalid, flag: key, conditions: reasons, ruleset_version: ruleset.version)
120
+ end
121
+ end
122
+
123
+ def first_report?(key, version, logged = @unsupported_logged)
105
124
  @mutex.synchronize do
106
- next false if @unsupported_logged[key] == version
125
+ next false if logged[key] == version
107
126
 
108
- @unsupported_logged[key] = version
127
+ logged[key] = version
109
128
  true
110
129
  end
111
130
  end
@@ -5,9 +5,9 @@ module Flagnetic
5
5
  # each carries are listed in the README.
6
6
  EVENTS = %i[
7
7
  ruleset_loaded fetch_failed sse_connected sse_dropped stage_changed key_revoked schema_unsupported
8
- rule_unsupported override_set override_refused local_overrides_allowed type_mismatch evaluation_failed
9
- listener_failed store_failed worker_failed queue_dropped exposure_skipped ingest_failed exposures_disabled
10
- client_not_configured
8
+ rule_unsupported condition_invalid override_set override_refused local_overrides_allowed type_mismatch
9
+ evaluation_failed listener_failed store_failed worker_failed queue_dropped exposure_skipped ingest_failed
10
+ exposures_disabled client_not_configured
11
11
  ].freeze
12
12
 
13
13
  # LEVELS are the log levels, lowest first.
@@ -84,6 +84,13 @@ module Flagnetic
84
84
  events: group.map { |e| e["event_id"] }, status: result.status, error: result.error)
85
85
  end
86
86
 
87
+ # report_unserialisable logs an event pack left out because it does not
88
+ # encode. The fault is the error's class alone: its message can quote
89
+ # the value, and a unit ID is not logged.
90
+ def report_unserialisable(error)
91
+ log(:warn, :queue_dropped, kind: kind, cause: "not_serialisable", events: 1, fault: error.class.name)
92
+ end
93
+
87
94
  def log(level, event, **fields)
88
95
  @log.call(level, event, fields.compact)
89
96
  rescue StandardError
@@ -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.1"
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,