sitegoose 0.3.3 → 0.3.4

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,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "json"
4
+ require "strscan"
4
5
 
5
6
  # Database queries with their values taken out (sdk/protocols/queries.md):
6
7
  # the one rule every server package applies before a query leaves the
@@ -17,22 +18,13 @@ module SiteGoose
17
18
  MAX_STATEMENT = 1000
18
19
  OTHER_STATEMENT = "(other)"
19
20
  # The databases a row may name; anything else is "other".
20
- DATABASES = %w[postgresql mysql mariadb sqlite mssql oracle mongodb other].freeze
21
+ DATABASES = %w[postgresql mysql mariadb sqlite mssql oracle clickhouse mongodb other].freeze
21
22
 
22
23
  # JavaScript's \s (and what its trim() removes).
23
24
  SPACE = "\\t\\n\\v\\f\\r \\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff"
24
- SPACE_CHAR = /\A[#{SPACE}]\z/.freeze
25
25
  TRIM = /\A[#{SPACE}]+|[#{SPACE}]+\z/.freeze
26
- # A digit right after one of these is part of a name or a placeholder
27
- # (table2, $1, @p1, :1), not a value. ASCII only, in every package.
28
- WORD = /\A[A-Za-z0-9_$@:]\z/.freeze
29
- DIGIT = /\A[0-9]\z/.freeze
30
- PREFIX_LETTER = /\A[EeNnXxBb]\z/.freeze
31
- NAME_CHAR = /\A[A-Za-z0-9_]\z/.freeze
32
26
  NUMBER = /\A(?:0[xX][0-9a-fA-F]+|(?:[0-9]+\.?[0-9]*|\.[0-9]+)(?:[eE][+-]?[0-9]+)?)/.freeze
33
- # The only characters NUMBER can match.
34
- NUMBER_CHAR = /\A[0-9a-fA-FxX.eE+-]\z/.freeze
35
- DOLLAR_TAG = /\A\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$/.freeze
27
+ DOLLAR_TAG_AT = /\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$/.freeze
36
28
  PLACEHOLDER = "(?:\\?|\\$[0-9]+|:[A-Za-z0-9_]+|@[A-Za-z0-9_]+)"
37
29
  LIST = /\([#{SPACE}]*#{PLACEHOLDER}(?:[#{SPACE}]*,[#{SPACE}]*#{PLACEHOLDER})*[#{SPACE}]*\)/.freeze
38
30
  ROWS = /\(\?\)(?:[#{SPACE}]*,[#{SPACE}]*\(\?\))+/.freeze
@@ -59,97 +51,146 @@ module SiteGoose
59
51
  return text if text == OTHER_STATEMENT
60
52
 
61
53
  db = database_of(db)
62
- cut(db == "mongodb" ? mongo_statement(text) : sql_shape(text, db))
54
+ shaped = if db == "mongodb"
55
+ mongo_statement(text)
56
+ elsif db == "other" && text.include?("\\")
57
+ # A database we don't know may or may not take a backslash as an
58
+ # escape, and each reading leaks what the other hides. When they
59
+ # disagree the query keeps its timing under (other) and its text is
60
+ # left out.
61
+ escaped = sql_shape(text, db, false)
62
+ escaped == sql_shape(text, db, true) ? escaped : OTHER_STATEMENT
63
+ else
64
+ sql_shape(text, db)
65
+ end
66
+ cut(shaped)
63
67
  end
64
68
 
65
69
  def cut(text)
66
70
  text.length > MAX_STATEMENT ? trim(text[0, MAX_STATEMENT]) : text
67
71
  end
68
72
 
69
- # The first index at or after from where chars holds seq (an array of
70
- # characters), or nil.
71
- def index_of(chars, seq, from)
72
- last = chars.size - seq.size
73
- i = from
74
- while i <= last
75
- return i if chars[i, seq.size] == seq
76
-
77
- i += 1
78
- end
79
- nil
73
+ # The word characters: a digit right after one is part of a name or a
74
+ # placeholder (table2, $1, @p1, :1), not a value. ASCII only, in every
75
+ # package, so no byte of a multi-byte character is one.
76
+ WORD_BYTE = Array.new(256, false).tap do |table|
77
+ [*"A".."Z", *"a".."z", *"0".."9", "_", "$", "@", ":"].each { |c| table[c.ord] = true }
78
+ end
79
+ NAME_BYTE = Array.new(256, false).tap do |table|
80
+ [*"A".."Z", *"a".."z", *"0".."9", "_"].each { |c| table[c.ord] = true }
81
+ end
82
+ PREFIX_BYTES = "EeNnXxBb".bytes.freeze
83
+ QUOTE = 39 # '
84
+ DOUBLE_QUOTE = 34 # "
85
+ BACKTICK = 96 # `
86
+ DOLLAR = 36 # $
87
+ BACKSLASH = 92
88
+ SPACE_BYTE = 32
89
+ DIGIT_BYTE = Array.new(256, false).tap { |table| ("0".."9").each { |c| table[c.ord] = true } }
90
+ NAME_START_BYTE = Array.new(256, false).tap do |table|
91
+ [*"A".."Z", *"a".."z", "_", "@", ":"].each { |c| table[c.ord] = true }
80
92
  end
93
+ DASH = 45
94
+ HASH = 35
95
+ SLASH = 47
96
+ STAR = 42
97
+ DOT = 46
98
+ # The runs the scan copies or skips whole; each stops where a character
99
+ # of another rule starts.
100
+ TO_LINE_END = /[^\n]*/.freeze
101
+ BLOCK_END = %r{\*/}.freeze
102
+ SPACE_RUN = /[#{SPACE}]+/.freeze
103
+ # A letter, _, @ or : is copied, and so is every word character after
104
+ # one: a digit or $ that follows a word character is part of the name.
105
+ NAME_RUN = /[A-Za-z_@:][A-Za-z0-9_$@:]*/.freeze
106
+ NUMBER_AT = /(?:0[xX][0-9a-fA-F]+|(?:[0-9]+\.?[0-9]*|\.[0-9]+)(?:[eE][+-]?[0-9]+)?)/.freeze
107
+ # A number is read from at most this many characters, as the reference does.
108
+ NUMBER_MAX = 400
109
+ TAG_MAX = 64
110
+ QUOTE_STOPS = {}.tap do |stops|
111
+ [QUOTE, DOUBLE_QUOTE, BACKTICK].each do |byte|
112
+ quote = Regexp.escape(byte.chr)
113
+ stops[[byte, true]] = /[#{quote}\\]/
114
+ stops[[byte, false]] = /#{quote}/
115
+ end
116
+ end.freeze
117
+
118
+ # Moves the scanner past a quoted run starting at the opening quote: past
119
+ # the closing quote, or to the end. A doubled quote escapes, and a
120
+ # backslash too unless backslash is false.
121
+ def skip_quoted(scanner, quote, backslash)
122
+ text = scanner.string
123
+ stop = QUOTE_STOPS[[quote, backslash]]
124
+ scanner.pos += 1
125
+ loop do
126
+ return scanner.terminate unless scanner.skip_until(stop)
81
127
 
82
- # The end of a quoted run starting at start (the opening quote): the
83
- # index after the closing quote, or the text's length. A doubled quote
84
- # and a backslash both escape.
85
- def quote_end(chars, start, quote)
86
- i = start + 1
87
- while i < chars.size
88
- c = chars[i]
89
- if c == "\\"
90
- i += 2
91
- elsif c == quote
92
- return i + 1 unless chars[i + 1] == quote
93
-
94
- i += 2
128
+ if text.getbyte(scanner.pos - 1) == BACKSLASH
129
+ scanner.getch
130
+ elsif text.getbyte(scanner.pos) == quote
131
+ scanner.pos += 1
95
132
  else
96
- i += 1
133
+ return
97
134
  end
98
135
  end
99
- chars.size
100
136
  end
101
137
 
102
- NEWLINE = ["\n"].freeze
103
- COMMENT_END = ["*", "/"].freeze
104
-
105
- def sql_shape(sql, db)
138
+ # The scan below reads runs with StringScanner rather than character by
139
+ # character, one step per token: time grows with the text, never faster
140
+ # (an 800 KB bulk insert of 27,000 rows takes about 0.4 s, 0.2 s with
141
+ # YJIT). The rules are the table's, in its order; "the character
142
+ # before" is always the input's.
143
+ def sql_shape(sql, db, backslash_literal = nil)
106
144
  mysql = %w[mysql mariadb].include?(db)
107
- chars = sql.chars
108
- out = []
109
- space = -> { out << " " if !out.empty? && out[-1] != " " }
110
- i = 0
111
- while i < chars.size
112
- c = chars[i]
113
- nxt = chars[i + 1]
114
- prev = i.positive? ? chars[i - 1] : ""
115
- if (c == "-" && nxt == "-") || (c == "#" && mysql)
116
- i = index_of(chars, NEWLINE, i) || chars.size
117
- space.call
118
- elsif c == "/" && nxt == "*"
119
- ends = index_of(chars, COMMENT_END, i + 2)
120
- i = ends ? ends + 2 : chars.size
121
- space.call
122
- elsif c == "'" || (c == '"' && mysql)
123
- out.pop if out[-1]&.match?(PREFIX_LETTER) && (out.size == 1 || !out[-2].match?(NAME_CHAR))
124
- i = quote_end(chars, i, c)
145
+ postgres = db == "postgresql"
146
+ # Where a backslash in a string is just a character: PostgreSQL's plain
147
+ # strings (standard_conforming_strings, on since 9.1), SQLite, SQL
148
+ # Server and Oracle. Read as an escape there, 'C:\' ends late and lets
149
+ # what follows out. MySQL, MariaDB, ClickHouse and unknown databases
150
+ # escape.
151
+ literal = backslash_literal.nil? ? (postgres || %w[sqlite mssql oracle].include?(db)) : backslash_literal
152
+ scanner = StringScanner.new(sql)
153
+ out = +""
154
+ until scanner.eos?
155
+ at = scanner.pos
156
+ byte = sql.getbyte(at)
157
+ word_before = at.positive? && WORD_BYTE[sql.getbyte(at - 1)]
158
+ if (byte == DASH && sql.getbyte(at + 1) == DASH) || (byte == HASH && mysql)
159
+ scanner.skip(TO_LINE_END)
160
+ out << " " unless out.empty? || out.getbyte(-1) == SPACE_BYTE
161
+ elsif byte == SLASH && sql.getbyte(at + 1) == STAR
162
+ scanner.pos += 2
163
+ scanner.terminate unless scanner.skip_until(BLOCK_END)
164
+ out << " " unless out.empty? || out.getbyte(-1) == SPACE_BYTE
165
+ elsif byte == QUOTE || (byte == DOUBLE_QUOTE && mysql)
166
+ last = out.getbyte(-1)
167
+ prefixed = PREFIX_BYTES.include?(last) && (out.bytesize == 1 || !NAME_BYTE[out.getbyte(-2)])
168
+ # Only PostgreSQL's E'..' escapes with a backslash where it is literal.
169
+ escapes = !literal || (postgres && prefixed && (last == 69 || last == 101))
170
+ out.chop! if prefixed
171
+ skip_quoted(scanner, byte, escapes)
125
172
  out << "?"
126
- elsif c == '"' || c == "`"
127
- ends = quote_end(chars, i, c)
128
- out.concat(chars[i...ends])
129
- i = ends
130
- elsif c == "$" && !prev.match?(WORD) && (tag = chars[i, 64].join[DOLLAR_TAG])
131
- tag_chars = tag.chars
132
- ends = index_of(chars, tag_chars, i + tag_chars.size)
133
- i = ends ? ends + tag_chars.size : chars.size
173
+ elsif byte == DOUBLE_QUOTE || byte == BACKTICK
174
+ skip_quoted(scanner, byte, !literal)
175
+ out << sql.byteslice(at, scanner.pos - at)
176
+ elsif byte == DOLLAR && !word_before && (tag = scanner.check(DOLLAR_TAG_AT)) && tag.size <= TAG_MAX
177
+ scanner.pos += tag.bytesize
178
+ scanner.terminate unless scanner.skip_until(/#{Regexp.escape(tag)}/)
134
179
  out << "?"
135
- elsif (c.match?(DIGIT) || (c == "." && nxt.to_s.match?(DIGIT))) && !prev.match?(WORD)
136
- run = +""
137
- j = i
138
- while j < chars.size && j < i + 400 && chars[j].match?(NUMBER_CHAR)
139
- run << chars[j]
140
- j += 1
141
- end
142
- i += run[NUMBER].length
180
+ elsif !word_before && (DIGIT_BYTE[byte] || (byte == DOT && DIGIT_BYTE[sql.getbyte(at + 1).to_i]))
181
+ # Past NUMBER_MAX characters the number is read from those alone.
182
+ length = scanner.skip(NUMBER_AT)
183
+ scanner.pos = at + sql.byteslice(at, NUMBER_MAX).b[NUMBER].bytesize if length > NUMBER_MAX
143
184
  out << "?"
144
- elsif c.match?(SPACE_CHAR)
145
- i += 1
146
- space.call
185
+ elsif (byte <= SPACE_BYTE || byte >= 128) && scanner.skip(SPACE_RUN)
186
+ out << " " unless out.empty? || out.getbyte(-1) == SPACE_BYTE
187
+ elsif NAME_START_BYTE[byte]
188
+ out << scanner.scan(NAME_RUN)
147
189
  else
148
- out << c
149
- i += 1
190
+ out << scanner.getch
150
191
  end
151
192
  end
152
- trim(out.join.gsub(LIST, "(?)").gsub(ROWS, "(?)"))
193
+ trim(out.gsub(LIST, "(?)").gsub(ROWS, "(?)"))
153
194
  end
154
195
 
155
196
  # A Mongo filter or pipeline's shape: keys kept, every value "?", and an
@@ -162,7 +203,9 @@ module SiteGoose
162
203
  items = value.map { |item| mongo_shape(item, depth + 1) }
163
204
  items.map { |item| JSON.generate(item) }.uniq.size == 1 ? [items[0]] : items
164
205
  when Hash
165
- pairs = value.map { |key, item| [key.to_s, item] }
206
+ # JavaScript's out[key] = ... sets the prototype for "__proto__",
207
+ # which its JSON.stringify then leaves out.
208
+ pairs = value.map { |key, item| [key.to_s, item] }.reject { |key, _| key == "__proto__" }
166
209
  index, named = pairs.partition { |key, _| key.match?(INDEX_KEY) && key.to_i < 4_294_967_295 }
167
210
  (index.sort_by { |key, _| key.to_i } + named).each_with_object({}) do |(key, item), out|
168
211
  out[key] = mongo_shape(item, depth + 1)
@@ -171,14 +214,24 @@ module SiteGoose
171
214
  end
172
215
  end
173
216
 
174
- # Ruby's parser takes comments and raw control characters that
175
- # JavaScript's JSON.parse refuses: text with either is not JSON here.
217
+ # Ruby's parser takes comments, raw control characters and unknown
218
+ # escapes (\x) that JavaScript's JSON.parse refuses: text with any is
219
+ # not JSON here.
176
220
  def strict_json?(text)
177
221
  quoted = false
178
222
  escaped = false
223
+ hex = 0
179
224
  text.each_char do |c|
180
- if quoted
181
- if escaped then escaped = false
225
+ if hex.positive?
226
+ return false unless c.match?(/\h/)
227
+
228
+ hex -= 1
229
+ elsif quoted
230
+ if escaped
231
+ return false unless '"\\/bfnrtu'.include?(c)
232
+
233
+ escaped = false
234
+ hex = 4 if c == "u"
182
235
  elsif c == "\\" then escaped = true
183
236
  elsif c == '"' then quoted = false
184
237
  elsif c.ord < 0x20 then return false
@@ -190,6 +243,28 @@ module SiteGoose
190
243
  true
191
244
  end
192
245
 
246
+ # JavaScript takes a lone surrogate (\ud800) and writes it back escaped;
247
+ # Ruby refuses it. Each is read as a code point of U+100000..U+1007FF
248
+ # instead and written back as JavaScript does: text that already has one
249
+ # of those can't be told apart, and isn't JSON here.
250
+ ESCAPE = /\\(?:u([dD][89abAB]\h\h\\u[dD][c-fC-F]\h\h)|u([dD][89a-fA-F]\h\h)|.)/m.freeze
251
+ STAND_IN = 0x100000 - 0xD800
252
+ STAND_INS = /[\u{100000}-\u{1007ff}]/.freeze
253
+
254
+ def stand_in_surrogates(text)
255
+ return text unless text.include?("\\u")
256
+
257
+ out = text.gsub(ESCAPE) do
258
+ lone = Regexp.last_match(2)
259
+ lone ? (lone.hex + STAND_IN).chr(Encoding::UTF_8) : Regexp.last_match(0)
260
+ end
261
+ out == text || !text.match?(STAND_INS) ? out : nil
262
+ end
263
+
264
+ def written_surrogates(json)
265
+ json.gsub(STAND_INS) { |c| format("\\u%04x", c.ord - STAND_IN) }
266
+ end
267
+
193
268
  # "find users {...}": the command, the collection, and the filter's shape.
194
269
  def mongo_statement(text)
195
270
  match = MONGO.match(trim(text))
@@ -202,9 +277,11 @@ module SiteGoose
202
277
  collection = nil
203
278
  end
204
279
  shape = ""
205
- if rest && strict_json?(rest)
280
+ json = rest && strict_json?(rest) ? stand_in_surrogates(rest) : nil
281
+ if json
206
282
  begin
207
- shape = JSON.generate(mongo_shape(JSON.parse(rest, max_nesting: false)))
283
+ shape = JSON.generate(mongo_shape(JSON.parse(json, max_nesting: false)))
284
+ shape = written_surrogates(shape) unless json == rest
208
285
  rescue JSON::ParserError, JSON::GeneratorError, EncodingError, TypeError
209
286
  shape = ""
210
287
  end
@@ -0,0 +1,192 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Job queues (sdk/protocols/queues.md), part of Server speed: once a minute,
4
+ # one row per queue to POST /events/server-queues, for Health -> Server
5
+ # speed -> Jobs: how many jobs wait, run, are delayed and are kept as
6
+ # failed, how long the oldest waiting one has waited (gauges, read from the
7
+ # queue's readers), and how many jobs this process added and finished
8
+ # (its own counters, shared: false). Rides on the performance module's
9
+ # switch; queues: false leaves them out.
10
+ #
11
+ # A reader (SiteGoose::Sidekiq's) answers read with the gauges of every
12
+ # queue it can see; a reading that fails is a gap for that minute, never a
13
+ # zero. Counters are counted by the integration's middleware. Nothing runs
14
+ # until a reader or a counter is added.
15
+
16
+ require "securerandom"
17
+
18
+ module SiteGoose
19
+ class Queues
20
+ SAMPLE_EVERY = 60
21
+ MAX_QUEUES = 100
22
+ MAX_ROWS = 500
23
+ SYSTEMS = %w[bullmq bull sidekiq laravel celery rq hangfire asynq rabbitmq other].freeze
24
+ GAUGES = %w[waiting running delayed failed oldest_s].freeze
25
+
26
+ attr_reader :sender, :entries
27
+
28
+ def initialize(core, server_name: nil)
29
+ @core = core
30
+ @server_name = SiteGoose.text(server_name || SiteGoose.hostname, 100)
31
+ # This process, so the collector can tell a reading resent after a
32
+ # failed answer from another process's on the same machine.
33
+ @sender = SecureRandom.hex(8)
34
+ # [system, broker, queue] -> { added:, finished:, counts: [:added, :finished] }
35
+ @entries = {}
36
+ @readers = []
37
+ @lock = Mutex.new
38
+ @job = nil
39
+ Forking.register(self)
40
+ end
41
+
42
+ def on?
43
+ @core.on?("performance")
44
+ end
45
+
46
+ # Reads this reader's queues once a minute from now on.
47
+ def watch(reader)
48
+ @lock.synchronize { @readers << reader unless @readers.include?(reader) }
49
+ start
50
+ reader
51
+ end
52
+
53
+ # One job added to (kind :added) or finished from (:finished) a queue by
54
+ # this process. A queue past MAX_QUEUES isn't counted.
55
+ def count(system, broker, queue, kind)
56
+ return unless on?
57
+
58
+ @lock.synchronize do
59
+ entry = entry_for(system, broker, queue)
60
+ next unless entry
61
+
62
+ entry[:counts] |= [kind]
63
+ entry[kind] += 1
64
+ end
65
+ start
66
+ end
67
+
68
+ # This process counts kind for the queue even in a minute with none
69
+ # (a Sidekiq process its queues' finished jobs): 0, not unknown.
70
+ def counting(system, broker, queue, kind)
71
+ @lock.synchronize do
72
+ entry = entry_for(system, broker, queue)
73
+ entry[:counts] |= [kind] if entry
74
+ end
75
+ start
76
+ end
77
+
78
+ # [system, broker, queue] as sent.
79
+ def self.key(system, broker, queue)
80
+ [SYSTEMS.include?(system.to_s) ? system.to_s : "other", SiteGoose.text(broker, 200), SiteGoose.text(queue, 200)]
81
+ end
82
+
83
+ # Under @lock.
84
+ def entry_for(system, broker, queue)
85
+ key = Queues.key(system, broker, queue)
86
+ found = @entries[key]
87
+ return found if found
88
+ return nil if @entries.size >= MAX_QUEUES
89
+
90
+ @entries[key] = { added: 0, finished: 0, counts: [] }
91
+ end
92
+ private :entry_for
93
+
94
+ # One reading of every queue: a row each, sent at once. -> the rows.
95
+ def sample
96
+ return [] unless on?
97
+
98
+ readers = @lock.synchronize { @readers.dup }
99
+ gauges = {}
100
+ readers.each do |reader|
101
+ Array(reader.read).each do |reading|
102
+ gauges[Queues.key(reading[:system], reading[:broker], reading[:queue])] = reading
103
+ end
104
+ rescue StandardError => e
105
+ # A gap for this minute, never zeros.
106
+ @core.log("queues", "could not read the queues:", e.message)
107
+ end
108
+ minute = Time.at(MinuteRows.minute).utc.iso8601(3)
109
+ rows = @lock.synchronize do
110
+ gauges.each_key { |key| entry_for(*key) }
111
+ @entries.filter_map do |key, entry|
112
+ reading = gauges[key]
113
+ take_row(minute, key, entry, reading) if reading || !entry[:counts].empty?
114
+ end
115
+ end
116
+ send_rows(rows)
117
+ rows
118
+ end
119
+
120
+ # Under @lock: the queue's row, its gauges from reading (nil: unknown),
121
+ # and the counts since the last row, which start again from 0.
122
+ def take_row(minute, key, entry, reading)
123
+ row = { "minute" => minute, "system" => key[0], "broker" => key[1], "queue" => key[2] }
124
+ GAUGES.each { |name| row[name] = Queues.gauge(reading && reading[name.to_sym]) }
125
+ row["added"] = entry[:counts].include?(:added) ? entry[:added] : nil
126
+ row["finished"] = entry[:counts].include?(:finished) ? entry[:finished] : nil
127
+ row["shared"] = false
128
+ entry[:added] = 0
129
+ entry[:finished] = 0
130
+ row
131
+ end
132
+ private :take_row
133
+
134
+ # A whole count, or nil for one the system couldn't give.
135
+ def self.gauge(value)
136
+ return nil unless value.is_a?(Numeric) && value.finite?
137
+
138
+ [value.round, 0].max
139
+ end
140
+
141
+ def send_rows(rows)
142
+ rows.each_slice(MAX_ROWS) do |batch|
143
+ @core.request("queues", "/events/server-queues", auth: :bearer,
144
+ body: { "site_id" => @core.site_id, "server_name" => @server_name, "runtime" => RUNTIME,
145
+ "sender" => @sender, "rows" => batch })
146
+ end
147
+ end
148
+ private :send_rows
149
+
150
+ # What was counted since the last reading (Sidekiq's shutdown, exit):
151
+ # counter rows only, no gauges.
152
+ def flush
153
+ return unless on?
154
+
155
+ minute = Time.at(MinuteRows.minute).utc.iso8601(3)
156
+ rows = @lock.synchronize do
157
+ @entries.filter_map do |key, entry|
158
+ take_row(minute, key, entry, nil) unless entry[:added].zero? && entry[:finished].zero?
159
+ end
160
+ end
161
+ send_rows(rows)
162
+ end
163
+
164
+ def start
165
+ return if @job || !@core.valid?
166
+
167
+ @lock.synchronize do
168
+ @job ||= Periodic.new(SAMPLE_EVERY) do
169
+ sample
170
+ SAMPLE_EVERY
171
+ end
172
+ end
173
+ end
174
+ private :start
175
+
176
+ # A forked worker is another process: its own sender and counts.
177
+ def after_fork_in_child
178
+ @lock = Mutex.new
179
+ @sender = SecureRandom.hex(8)
180
+ @entries.each_value do |entry|
181
+ entry[:added] = 0
182
+ entry[:finished] = 0
183
+ end
184
+ end
185
+
186
+ def close
187
+ @job&.stop
188
+ Forking.unregister(self)
189
+ flush
190
+ end
191
+ end
192
+ end
@@ -356,35 +356,49 @@ module SiteGoose
356
356
  end
357
357
  end
358
358
 
359
- # The first rule that matches, or nil. target is the request target as
360
- # the server received it, query string and all.
361
- def match(rules, method = "", target = "", user_agent = "")
362
- return nil if rules.nil? || rules.empty?
363
-
359
+ # The request's parts, prepared once for every rule and page limit:
360
+ # method upper-cased, path raw/decoded/routed, query raw/decoded, ua.
361
+ # target is the request target as the server received it, query string and all.
362
+ def prepare(method = "", target = "", user_agent = "")
364
363
  target = SiteGoose.text(target)
365
364
  mark = target.index("?")
366
365
  path_part = mark ? target[0, mark] : target
367
366
  query = mark ? target[(mark + 1)..] : ""
368
- raw_path = normalize_path(path_part[0, MAX_TEXT])
369
367
  query = query[0, MAX_TEXT]
370
- raw_query = query.downcase
371
368
  ua = SiteGoose.text(user_agent)[0, MAX_TEXT].downcase
372
- decoded_path = normalize_path(decode_once(path_part[0, MAX_TEXT])[0, MAX_TEXT])
373
- # And as the router reads it: "/x;y/../admin" is "/admin" there, so a
374
- # rule on "/admin" catches it; a hit on any of the three counts.
375
- routed_path = router_path(path_part[0, MAX_TEXT])[0, MAX_TEXT]
376
- # Lower-cased after decoding: %55NION decodes to "UNION", which a
377
- # lower-cased "union select" rule would otherwise never see.
378
- decoded_query = decode_once(query)[0, MAX_TEXT].downcase
379
- upper = method.to_s.upcase
380
- rules.find do |rule|
381
- next false if !rule["methods"].empty? && !rule["methods"].include?(upper)
382
- next false if rule["path"] && !hits?(rule["path"], raw_path, decoded_path, routed_path)
383
- next false if rule["query"] && !hits?(rule["query"], raw_query, decoded_query)
384
- next false if rule["ua"] && !hits?(rule["ua"], ua, ua)
385
-
386
- true
387
- end
369
+ {
370
+ method: method.to_s.upcase,
371
+ raw_path: normalize_path(path_part[0, MAX_TEXT]),
372
+ decoded_path: normalize_path(decode_once(path_part[0, MAX_TEXT])[0, MAX_TEXT]),
373
+ # And as the router reads it: "/x;y/../admin" is "/admin" there, so a
374
+ # rule on "/admin" catches it; a hit on any of the three counts.
375
+ routed_path: router_path(path_part[0, MAX_TEXT])[0, MAX_TEXT],
376
+ raw_query: query.downcase,
377
+ # Lower-cased after decoding: %55NION decodes to "UNION", which a
378
+ # lower-cased "union select" rule would otherwise never see.
379
+ decoded_query: decode_once(query)[0, MAX_TEXT].downcase,
380
+ ua: ua
381
+ }
382
+ end
383
+
384
+ # True when every section the rule names matches the prepared request.
385
+ def matches?(rule, req)
386
+ return false if !rule["methods"].empty? && !rule["methods"].include?(req[:method])
387
+ return false if rule["path"] && !hits?(rule["path"], req[:raw_path], req[:decoded_path], req[:routed_path])
388
+ return false if rule["query"] && !hits?(rule["query"], req[:raw_query], req[:decoded_query])
389
+ return false if rule["ua"] && !hits?(rule["ua"], req[:ua], req[:ua])
390
+
391
+ true
392
+ end
393
+
394
+ # The first rule that matches, or nil. target is the request target as
395
+ # the server received it, query string and all; prepared, when given, is
396
+ # prepare() of the same request.
397
+ def match(rules, method = "", target = "", user_agent = "", prepared = nil)
398
+ return nil if rules.nil? || rules.empty?
399
+
400
+ req = prepared || prepare(method, target, user_agent)
401
+ rules.find { |rule| matches?(rule, req) }
388
402
  end
389
403
  end
390
404
  end