sitegoose 0.3.3 → 0.3.5

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 redis 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,148 @@ 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 == "redis"
57
+ redis_statement(text)
58
+ elsif db == "other" && text.include?("\\")
59
+ # A database we don't know may or may not take a backslash as an
60
+ # escape, and each reading leaks what the other hides. When they
61
+ # disagree the query keeps its timing under (other) and its text is
62
+ # left out.
63
+ escaped = sql_shape(text, db, false)
64
+ escaped == sql_shape(text, db, true) ? escaped : OTHER_STATEMENT
65
+ else
66
+ sql_shape(text, db)
67
+ end
68
+ cut(shaped)
63
69
  end
64
70
 
65
71
  def cut(text)
66
72
  text.length > MAX_STATEMENT ? trim(text[0, MAX_STATEMENT]) : text
67
73
  end
68
74
 
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
75
+ # The word characters: a digit right after one is part of a name or a
76
+ # placeholder (table2, $1, @p1, :1), not a value. ASCII only, in every
77
+ # package, so no byte of a multi-byte character is one.
78
+ WORD_BYTE = Array.new(256, false).tap do |table|
79
+ [*"A".."Z", *"a".."z", *"0".."9", "_", "$", "@", ":"].each { |c| table[c.ord] = true }
80
+ end
81
+ NAME_BYTE = Array.new(256, false).tap do |table|
82
+ [*"A".."Z", *"a".."z", *"0".."9", "_"].each { |c| table[c.ord] = true }
83
+ end
84
+ PREFIX_BYTES = "EeNnXxBb".bytes.freeze
85
+ QUOTE = 39 # '
86
+ DOUBLE_QUOTE = 34 # "
87
+ BACKTICK = 96 # `
88
+ DOLLAR = 36 # $
89
+ BACKSLASH = 92
90
+ SPACE_BYTE = 32
91
+ DIGIT_BYTE = Array.new(256, false).tap { |table| ("0".."9").each { |c| table[c.ord] = true } }
92
+ NAME_START_BYTE = Array.new(256, false).tap do |table|
93
+ [*"A".."Z", *"a".."z", "_", "@", ":"].each { |c| table[c.ord] = true }
94
+ end
95
+ DASH = 45
96
+ HASH = 35
97
+ SLASH = 47
98
+ STAR = 42
99
+ DOT = 46
100
+ # The runs the scan copies or skips whole; each stops where a character
101
+ # of another rule starts.
102
+ TO_LINE_END = /[^\n]*/.freeze
103
+ BLOCK_END = %r{\*/}.freeze
104
+ SPACE_RUN = /[#{SPACE}]+/.freeze
105
+ # A letter, _, @ or : is copied, and so is every word character after
106
+ # one: a digit or $ that follows a word character is part of the name.
107
+ NAME_RUN = /[A-Za-z_@:][A-Za-z0-9_$@:]*/.freeze
108
+ NUMBER_AT = /(?:0[xX][0-9a-fA-F]+|(?:[0-9]+\.?[0-9]*|\.[0-9]+)(?:[eE][+-]?[0-9]+)?)/.freeze
109
+ # A number is read from at most this many characters, as the reference does.
110
+ NUMBER_MAX = 400
111
+ TAG_MAX = 64
112
+ QUOTE_STOPS = {}.tap do |stops|
113
+ [QUOTE, DOUBLE_QUOTE, BACKTICK].each do |byte|
114
+ quote = Regexp.escape(byte.chr)
115
+ stops[[byte, true]] = /[#{quote}\\]/
116
+ stops[[byte, false]] = /#{quote}/
78
117
  end
79
- nil
80
- end
81
-
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
118
+ end.freeze
119
+
120
+ # Moves the scanner past a quoted run starting at the opening quote: past
121
+ # the closing quote, or to the end. A doubled quote escapes, and a
122
+ # backslash too unless backslash is false.
123
+ def skip_quoted(scanner, quote, backslash)
124
+ text = scanner.string
125
+ stop = QUOTE_STOPS[[quote, backslash]]
126
+ scanner.pos += 1
127
+ loop do
128
+ return scanner.terminate unless scanner.skip_until(stop)
129
+
130
+ if text.getbyte(scanner.pos - 1) == BACKSLASH
131
+ scanner.getch
132
+ elsif text.getbyte(scanner.pos) == quote
133
+ scanner.pos += 1
95
134
  else
96
- i += 1
135
+ return
97
136
  end
98
137
  end
99
- chars.size
100
138
  end
101
139
 
102
- NEWLINE = ["\n"].freeze
103
- COMMENT_END = ["*", "/"].freeze
104
-
105
- def sql_shape(sql, db)
140
+ # The scan below reads runs with StringScanner rather than character by
141
+ # character, one step per token: time grows with the text, never faster
142
+ # (an 800 KB bulk insert of 27,000 rows takes about 0.4 s, 0.2 s with
143
+ # YJIT). The rules are the table's, in its order; "the character
144
+ # before" is always the input's.
145
+ def sql_shape(sql, db, backslash_literal = nil)
106
146
  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)
147
+ postgres = db == "postgresql"
148
+ # Where a backslash in a string is just a character: PostgreSQL's plain
149
+ # strings (standard_conforming_strings, on since 9.1), SQLite, SQL
150
+ # Server and Oracle. Read as an escape there, 'C:\' ends late and lets
151
+ # what follows out. MySQL, MariaDB, ClickHouse and unknown databases
152
+ # escape.
153
+ literal = backslash_literal.nil? ? (postgres || %w[sqlite mssql oracle].include?(db)) : backslash_literal
154
+ scanner = StringScanner.new(sql)
155
+ out = +""
156
+ until scanner.eos?
157
+ at = scanner.pos
158
+ byte = sql.getbyte(at)
159
+ word_before = at.positive? && WORD_BYTE[sql.getbyte(at - 1)]
160
+ if (byte == DASH && sql.getbyte(at + 1) == DASH) || (byte == HASH && mysql)
161
+ scanner.skip(TO_LINE_END)
162
+ out << " " unless out.empty? || out.getbyte(-1) == SPACE_BYTE
163
+ elsif byte == SLASH && sql.getbyte(at + 1) == STAR
164
+ scanner.pos += 2
165
+ scanner.terminate unless scanner.skip_until(BLOCK_END)
166
+ out << " " unless out.empty? || out.getbyte(-1) == SPACE_BYTE
167
+ elsif byte == QUOTE || (byte == DOUBLE_QUOTE && mysql)
168
+ last = out.getbyte(-1)
169
+ prefixed = PREFIX_BYTES.include?(last) && (out.bytesize == 1 || !NAME_BYTE[out.getbyte(-2)])
170
+ # Only PostgreSQL's E'..' escapes with a backslash where it is literal.
171
+ escapes = !literal || (postgres && prefixed && (last == 69 || last == 101))
172
+ out.chop! if prefixed
173
+ skip_quoted(scanner, byte, escapes)
125
174
  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
175
+ elsif byte == DOUBLE_QUOTE || byte == BACKTICK
176
+ skip_quoted(scanner, byte, !literal)
177
+ out << sql.byteslice(at, scanner.pos - at)
178
+ elsif byte == DOLLAR && !word_before && (tag = scanner.check(DOLLAR_TAG_AT)) && tag.size <= TAG_MAX
179
+ scanner.pos += tag.bytesize
180
+ scanner.terminate unless scanner.skip_until(/#{Regexp.escape(tag)}/)
134
181
  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
182
+ elsif !word_before && (DIGIT_BYTE[byte] || (byte == DOT && DIGIT_BYTE[sql.getbyte(at + 1).to_i]))
183
+ # Past NUMBER_MAX characters the number is read from those alone.
184
+ length = scanner.skip(NUMBER_AT)
185
+ scanner.pos = at + sql.byteslice(at, NUMBER_MAX).b[NUMBER].bytesize if length > NUMBER_MAX
143
186
  out << "?"
144
- elsif c.match?(SPACE_CHAR)
145
- i += 1
146
- space.call
187
+ elsif (byte <= SPACE_BYTE || byte >= 128) && scanner.skip(SPACE_RUN)
188
+ out << " " unless out.empty? || out.getbyte(-1) == SPACE_BYTE
189
+ elsif NAME_START_BYTE[byte]
190
+ out << scanner.scan(NAME_RUN)
147
191
  else
148
- out << c
149
- i += 1
192
+ out << scanner.getch
150
193
  end
151
194
  end
152
- trim(out.join.gsub(LIST, "(?)").gsub(ROWS, "(?)"))
195
+ trim(out.gsub(LIST, "(?)").gsub(ROWS, "(?)"))
153
196
  end
154
197
 
155
198
  # A Mongo filter or pipeline's shape: keys kept, every value "?", and an
@@ -162,7 +205,9 @@ module SiteGoose
162
205
  items = value.map { |item| mongo_shape(item, depth + 1) }
163
206
  items.map { |item| JSON.generate(item) }.uniq.size == 1 ? [items[0]] : items
164
207
  when Hash
165
- pairs = value.map { |key, item| [key.to_s, item] }
208
+ # JavaScript's out[key] = ... sets the prototype for "__proto__",
209
+ # which its JSON.stringify then leaves out.
210
+ pairs = value.map { |key, item| [key.to_s, item] }.reject { |key, _| key == "__proto__" }
166
211
  index, named = pairs.partition { |key, _| key.match?(INDEX_KEY) && key.to_i < 4_294_967_295 }
167
212
  (index.sort_by { |key, _| key.to_i } + named).each_with_object({}) do |(key, item), out|
168
213
  out[key] = mongo_shape(item, depth + 1)
@@ -171,14 +216,24 @@ module SiteGoose
171
216
  end
172
217
  end
173
218
 
174
- # Ruby's parser takes comments and raw control characters that
175
- # JavaScript's JSON.parse refuses: text with either is not JSON here.
219
+ # Ruby's parser takes comments, raw control characters and unknown
220
+ # escapes (\x) that JavaScript's JSON.parse refuses: text with any is
221
+ # not JSON here.
176
222
  def strict_json?(text)
177
223
  quoted = false
178
224
  escaped = false
225
+ hex = 0
179
226
  text.each_char do |c|
180
- if quoted
181
- if escaped then escaped = false
227
+ if hex.positive?
228
+ return false unless c.match?(/\h/)
229
+
230
+ hex -= 1
231
+ elsif quoted
232
+ if escaped
233
+ return false unless '"\\/bfnrtu'.include?(c)
234
+
235
+ escaped = false
236
+ hex = 4 if c == "u"
182
237
  elsif c == "\\" then escaped = true
183
238
  elsif c == '"' then quoted = false
184
239
  elsif c.ord < 0x20 then return false
@@ -190,6 +245,161 @@ module SiteGoose
190
245
  true
191
246
  end
192
247
 
248
+ # JavaScript takes a lone surrogate (\ud800) and writes it back escaped;
249
+ # Ruby refuses it. Each is read as a code point of U+100000..U+1007FF
250
+ # instead and written back as JavaScript does: text that already has one
251
+ # of those can't be told apart, and isn't JSON here.
252
+ ESCAPE = /\\(?:u([dD][89abAB]\h\h\\u[dD][c-fC-F]\h\h)|u([dD][89a-fA-F]\h\h)|.)/m.freeze
253
+ STAND_IN = 0x100000 - 0xD800
254
+ STAND_INS = /[\u{100000}-\u{1007ff}]/.freeze
255
+
256
+ def stand_in_surrogates(text)
257
+ return text unless text.include?("\\u")
258
+
259
+ out = text.gsub(ESCAPE) do
260
+ lone = Regexp.last_match(2)
261
+ lone ? (lone.hex + STAND_IN).chr(Encoding::UTF_8) : Regexp.last_match(0)
262
+ end
263
+ out == text || !text.match?(STAND_INS) ? out : nil
264
+ end
265
+
266
+ def written_surrogates(json)
267
+ json.gsub(STAND_INS) { |c| format("\\u%04x", c.ord - STAND_IN) }
268
+ end
269
+
270
+ # ---- Redis: the command and its first key's shape (queries.md, "Redis") ----
271
+ # A key keeps each ":" segment that is only letters and "_" (32 at most);
272
+ # every other segment is "?", so IDs, slugs, emails and hashes never
273
+ # leave the server: user:42:cart -> user:?:cart. ASCII only, read as
274
+ # bytes, so a key that isn't UTF-8 is "?" rather than an error.
275
+ REDIS_WORD = /\A[A-Za-z][A-Za-z0-9_.|-]{0,39}\z/n.freeze
276
+ REDIS_SEGMENT = /\A[A-Za-z_]{1,32}\z/n.freeze
277
+ # Commands whose second word is a subcommand (CLIENT SETNAME, XINFO STREAM).
278
+ REDIS_CONTAINERS = %w[ACL CLIENT CLUSTER COMMAND CONFIG DEBUG FUNCTION LATENCY MEMORY MODULE OBJECT PUBSUB SCRIPT
279
+ SLOWLOG XGROUP XINFO].to_h { |name| [name, true] }.freeze
280
+ # Of those, the ones with a key after the subcommand.
281
+ REDIS_SUB_KEY = %w[OBJECT MEMORY XGROUP XINFO].to_h { |name| [name, true] }.freeze
282
+ # No key: what follows is a password, a message, a number or nothing.
283
+ REDIS_NO_KEY = %w[PING ECHO INFO AUTH HELLO SELECT QUIT RESET MULTI EXEC DISCARD UNWATCH DBSIZE TIME FLUSHDB
284
+ FLUSHALL SAVE BGSAVE BGREWRITEAOF LASTSAVE SCAN RANDOMKEY SWAPDB SHUTDOWN ROLE REPLICAOF SLAVEOF
285
+ READONLY READWRITE LOLWUT FAILOVER PSYNC SYNC REPLCONF MIGRATE].to_h { |name| [name, true] }.freeze
286
+ # Script calls: script or name, then how many keys, then the keys.
287
+ REDIS_SCRIPTS = %w[EVAL EVALSHA EVAL_RO EVALSHA_RO FCALL FCALL_RO].to_h { |name| [name, true] }.freeze
288
+ # How many keys first, then the keys.
289
+ REDIS_NUMKEYS = %w[ZUNION ZINTER ZDIFF SINTERCARD ZINTERCARD LMPOP ZMPOP].to_h { |name| [name, true] }.freeze
290
+ # Waiting, not working: a queue worker sits in these for seconds, so
291
+ # timing them would put every idle worker at the top of the slow list.
292
+ REDIS_WAITING = %w[BLPOP BRPOP BRPOPLPUSH BLMOVE BLMPOP BZPOPMIN BZPOPMAX BZMPOP WAIT WAITAOF SUBSCRIBE PSUBSCRIBE
293
+ SSUBSCRIBE UNSUBSCRIBE PUNSUBSCRIBE SUNSUBSCRIBE MONITOR].to_h { |name| [name, true] }.freeze
294
+ REDIS_PREFIXES = { "PIPELINE" => true, "MULTI" => true }.freeze
295
+ REDIS_SPLIT = /[#{SPACE}]+/.freeze
296
+ # JavaScript's Number() of a string, for "how many keys": decimal, or
297
+ # 0x/0o/0b, or Infinity.
298
+ JS_INFINITY = /\A[+-]?Infinity\z/.freeze
299
+ JS_DECIMAL = /\A[+-]?(?:[0-9]+\.?[0-9]*|\.[0-9]+)(?:[eE][+-]?[0-9]+)?\z/.freeze
300
+ JS_RADIX = /\A0(?:[xX][0-9a-fA-F]+|[oO][0-7]+|[bB][01]+)\z/.freeze
301
+
302
+ def redis_key_shape(key)
303
+ # An empty key is "?" too: "GET " would read back as "GET".
304
+ return "?" if !key.is_a?(String) || key.empty?
305
+
306
+ # split drops trailing empty parts; -1 keeps them, as JavaScript does.
307
+ key.b.split(":", -1).map { |part| part.empty? || part.match?(REDIS_SEGMENT) ? part : "?" }.join(":").force_encoding(Encoding::UTF_8)
308
+ end
309
+
310
+ # Number(value) > 0, as JavaScript reads it.
311
+ def js_positive?(value)
312
+ case value
313
+ when Integer, Float then value.positive?
314
+ when true then true
315
+ when String
316
+ text = trim(SiteGoose.text(value))
317
+ if text.match?(JS_INFINITY) then !text.start_with?("-")
318
+ elsif text.match?(JS_DECIMAL) then text.to_f.positive?
319
+ # Integer() reads the same 0x/0o/0b prefixes.
320
+ elsif text.match?(JS_RADIX) then Integer(text).positive?
321
+ else false
322
+ end
323
+ else false
324
+ end
325
+ end
326
+
327
+ # A Redis word as the rule reads it (upper case), or nil when it isn't one.
328
+ def redis_word(value)
329
+ value.is_a?(String) && value.b.match?(REDIS_WORD) ? value.b.upcase(:ascii).force_encoding(Encoding::UTF_8) : nil
330
+ end
331
+
332
+ # A command as the client sends it (["GET", "user:42"]) -> "GET user:?",
333
+ # or nil for one that isn't timed (blocking, or not a command).
334
+ def redis_command(args)
335
+ return nil unless args.is_a?(Array)
336
+
337
+ name = redis_word(args[0])
338
+ return nil if name.nil? || REDIS_WAITING.key?(name)
339
+
340
+ key = nil
341
+ command = name
342
+ if REDIS_CONTAINERS.key?(name)
343
+ sub = redis_word(args[1])
344
+ if sub
345
+ command = "#{name} #{sub}"
346
+ # Only after a subcommand: "OBJECT user" would read back as OBJECT USER.
347
+ key = 2 if REDIS_SUB_KEY.key?(name)
348
+ end
349
+ elsif name == "XREAD" || name == "XREADGROUP"
350
+ # Its options, then STREAMS and the keys. XREADGROUP's group and
351
+ # consumer come first and may be named anything, as may a stream.
352
+ ((name == "XREADGROUP" ? 4 : 1)...args.size).each do |i|
353
+ arg = args[i]
354
+ next unless arg.is_a?(String)
355
+
356
+ word = arg.b.upcase(:ascii)
357
+ return nil if word == "BLOCK"
358
+
359
+ if word == "STREAMS"
360
+ key = i + 1
361
+ break
362
+ end
363
+ end
364
+ elsif REDIS_SCRIPTS.key?(name)
365
+ key = 3 if args.size > 2 && js_positive?(args[2])
366
+ elsif REDIS_NUMKEYS.key?(name)
367
+ key = 2 if args.size > 1 && js_positive?(args[1])
368
+ elsif name == "BITOP"
369
+ key = 2
370
+ elsif !REDIS_NO_KEY.key?(name) && !REDIS_PREFIXES.key?(name)
371
+ key = 1
372
+ end
373
+ key && key < args.size ? "#{command} #{redis_key_shape(args[key])}" : command
374
+ end
375
+
376
+ # A statement a package sent: [PIPELINE|MULTI] COMMAND [SUBCOMMAND] [key].
377
+ # Anything else (an argument a hook let through) is (other).
378
+ def redis_statement(text)
379
+ words = trim(text).split(REDIS_SPLIT)
380
+ return "" if words.empty?
381
+
382
+ out = []
383
+ i = 0
384
+ if words.size > 1 && REDIS_PREFIXES.key?(words[0].upcase(:ascii))
385
+ out << words[0].upcase(:ascii)
386
+ i = 1
387
+ end
388
+ name = redis_word(words[i])
389
+ return OTHER_STATEMENT if name.nil? || REDIS_WAITING.key?(name)
390
+
391
+ i += 1
392
+ out << name
393
+ if REDIS_CONTAINERS.key?(name) && i < words.size && (sub = redis_word(words[i]))
394
+ out << sub
395
+ i += 1
396
+ end
397
+ return OTHER_STATEMENT if i < words.size - 1
398
+
399
+ out << redis_key_shape(words[i]) if i < words.size
400
+ out.join(" ")
401
+ end
402
+
193
403
  # "find users {...}": the command, the collection, and the filter's shape.
194
404
  def mongo_statement(text)
195
405
  match = MONGO.match(trim(text))
@@ -202,9 +412,11 @@ module SiteGoose
202
412
  collection = nil
203
413
  end
204
414
  shape = ""
205
- if rest && strict_json?(rest)
415
+ json = rest && strict_json?(rest) ? stand_in_surrogates(rest) : nil
416
+ if json
206
417
  begin
207
- shape = JSON.generate(mongo_shape(JSON.parse(rest, max_nesting: false)))
418
+ shape = JSON.generate(mongo_shape(JSON.parse(json, max_nesting: false)))
419
+ shape = written_surrogates(shape) unless json == rest
208
420
  rescue JSON::ParserError, JSON::GeneratorError, EncodingError, TypeError
209
421
  shape = ""
210
422
  end
@@ -0,0 +1,193 @@
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
+ # The package's own Redis commands: not timed as the app's.
102
+ Array(Queries.own { reader.read }).each do |reading|
103
+ gauges[Queues.key(reading[:system], reading[:broker], reading[:queue])] = reading
104
+ end
105
+ rescue StandardError => e
106
+ # A gap for this minute, never zeros.
107
+ @core.log("queues", "could not read the queues:", e.message)
108
+ end
109
+ minute = Time.at(MinuteRows.minute).utc.iso8601(3)
110
+ rows = @lock.synchronize do
111
+ gauges.each_key { |key| entry_for(*key) }
112
+ @entries.filter_map do |key, entry|
113
+ reading = gauges[key]
114
+ take_row(minute, key, entry, reading) if reading || !entry[:counts].empty?
115
+ end
116
+ end
117
+ send_rows(rows)
118
+ rows
119
+ end
120
+
121
+ # Under @lock: the queue's row, its gauges from reading (nil: unknown),
122
+ # and the counts since the last row, which start again from 0.
123
+ def take_row(minute, key, entry, reading)
124
+ row = { "minute" => minute, "system" => key[0], "broker" => key[1], "queue" => key[2] }
125
+ GAUGES.each { |name| row[name] = Queues.gauge(reading && reading[name.to_sym]) }
126
+ row["added"] = entry[:counts].include?(:added) ? entry[:added] : nil
127
+ row["finished"] = entry[:counts].include?(:finished) ? entry[:finished] : nil
128
+ row["shared"] = false
129
+ entry[:added] = 0
130
+ entry[:finished] = 0
131
+ row
132
+ end
133
+ private :take_row
134
+
135
+ # A whole count, or nil for one the system couldn't give.
136
+ def self.gauge(value)
137
+ return nil unless value.is_a?(Numeric) && value.finite?
138
+
139
+ [value.round, 0].max
140
+ end
141
+
142
+ def send_rows(rows)
143
+ rows.each_slice(MAX_ROWS) do |batch|
144
+ @core.request("queues", "/events/server-queues", auth: :bearer,
145
+ body: { "site_id" => @core.site_id, "server_name" => @server_name, "runtime" => RUNTIME,
146
+ "sender" => @sender, "rows" => batch })
147
+ end
148
+ end
149
+ private :send_rows
150
+
151
+ # What was counted since the last reading (Sidekiq's shutdown, exit):
152
+ # counter rows only, no gauges.
153
+ def flush
154
+ return unless on?
155
+
156
+ minute = Time.at(MinuteRows.minute).utc.iso8601(3)
157
+ rows = @lock.synchronize do
158
+ @entries.filter_map do |key, entry|
159
+ take_row(minute, key, entry, nil) unless entry[:added].zero? && entry[:finished].zero?
160
+ end
161
+ end
162
+ send_rows(rows)
163
+ end
164
+
165
+ def start
166
+ return if @job || !@core.valid?
167
+
168
+ @lock.synchronize do
169
+ @job ||= Periodic.new(SAMPLE_EVERY) do
170
+ sample
171
+ SAMPLE_EVERY
172
+ end
173
+ end
174
+ end
175
+ private :start
176
+
177
+ # A forked worker is another process: its own sender and counts.
178
+ def after_fork_in_child
179
+ @lock = Mutex.new
180
+ @sender = SecureRandom.hex(8)
181
+ @entries.each_value do |entry|
182
+ entry[:added] = 0
183
+ entry[:finished] = 0
184
+ end
185
+ end
186
+
187
+ def close
188
+ @job&.stop
189
+ Forking.unregister(self)
190
+ flush
191
+ end
192
+ end
193
+ end