sitegoose 0.3.4 → 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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 641af744b75f89e3ed1818256822c744a2d3ac05dea67d006e92f8aa7ede9be1
4
- data.tar.gz: 111fe2e7d1001be606d33c740243dc816eea337b34941afeb8bd1b75e643c01d
3
+ metadata.gz: ce69bd61fa38892bea9ea285bebd0688fd618deacd1715ae19ec14e3c7f61f02
4
+ data.tar.gz: 83dcc0b5e52dab1c905b45dcb25c20bc242e96cd9c06cde495c5283d2a2812cd
5
5
  SHA512:
6
- metadata.gz: c3521c60c43c997907660337494fb0939a6b16100d762c9dd19e554ebf4e45c1b8cc86f4165d42dfc0ab2e0d6c2d052be5b353d7c3297eb184086584fc508ffc
7
- data.tar.gz: 118029ecf321a5a61733ce79aa29251ef21aca0281d60d95b8ebcbec9b4c4ae69ed5ae69c5f2a34bbaef441d4e9a50f15cf45d19cd7f6139d5423f62831bce15
6
+ metadata.gz: a433baa5a8baa140e54ec32e47778576e8f37a1978216ffd91fe5ec059b2ccab3a187bec96aead0f5d3f54dc12abb1ee33beceb8d0942a99a4804d6ba6593aee
7
+ data.tar.gz: 215d28e1a1ac655eb425c112be445495bbdf14dd03ea454dc32bd7b433054b7a3d40fcc9c835557674c1c75ce307d91be707f552e1d5b336f525f80137824c43
data/README.md CHANGED
@@ -157,6 +157,15 @@ slow. Every value is replaced by `?` before anything is counted
157
157
  SiteGoose.watch_database(CLICKHOUSE)
158
158
  ```
159
159
 
160
+ - **Redis**: automatic with `redis-client` (so the `redis` gem 5 and Sidekiq 7
161
+ too), through its own `RedisClient.register` middleware. Each command is its
162
+ command and first key's shape only (`GET user:?:cart`), never an argument or
163
+ value; a pipeline is one `PIPELINE GET user:?` call and a `multi` one
164
+ `MULTI INCR hits:?`. Blocking commands (`BRPOP`, Sidekiq's fetch) and the
165
+ package's own queue readings aren't timed; Sidekiq's other commands are. An
166
+ error reply or no answer is a failure; a nil or a `MOVED` isn't. The `redis`
167
+ gem 4 has its own connection code, which isn't seen.
168
+
160
169
  A query counts under the request (or Sidekiq or `platform.job` run) it ran
161
170
  in, with the same method and route Server speed shows; one outside them,
162
171
  like a console or a thread of your own, counts as `JOB (background)`. A
@@ -15,6 +15,10 @@
15
15
  # ClickHouse: the click_house gem's ClickHouse::Connection through
16
16
  # SiteGoose.watch_database(connection), one line; an Active Record
17
17
  # ClickHouse adapter (clickhouse-activerecord) through sql.active_record.
18
+ # Redis: redis-client's global middleware (RedisClient.register),
19
+ # automatic; the redis gem 5 and Sidekiq 7 run on it. Each command is
20
+ # "GET user:?:cart" (QueryText.redis_command): the command and its first
21
+ # key's shape, never an argument or value.
18
22
  #
19
23
  # A query is added to the request (or job) it ran in, and the request's
20
24
  # queries go into the minute's rows when it finishes, under the method and
@@ -190,6 +194,9 @@ module SiteGoose
190
194
  REQUEST = Context::QUERIES
191
195
  # Set while an outer layer times a query, so an inner one leaves it.
192
196
  TIMING = :sitegoose_query_timing
197
+ # Set while the package makes Redis commands of its own (the queue
198
+ # readings), which aren't timed.
199
+ OWN = :sitegoose_own_redis
193
200
  CACHE_MAX = 2000
194
201
  CACHE_TEXT = 4000
195
202
 
@@ -230,6 +237,29 @@ module SiteGoose
230
237
  Thread.current[TIMING] = saved
231
238
  end
232
239
 
240
+ def own?
241
+ Thread.current[OWN] ? true : false
242
+ end
243
+
244
+ # Whether a Redis command now goes untimed: the package's own, no
245
+ # platform timing queries, or no answer to that (a signal handler
246
+ # can't take the lock), which never reaches the app's command.
247
+ def redis_untimed?
248
+ own? || active.nil?
249
+ rescue StandardError
250
+ true
251
+ end
252
+
253
+ # Runs the block with this thread's Redis commands left out: the
254
+ # package's own.
255
+ def own
256
+ saved = Thread.current[OWN]
257
+ Thread.current[OWN] = true
258
+ yield
259
+ ensure
260
+ Thread.current[OWN] = saved
261
+ end
262
+
233
263
  # One finished query, from any hook. db: one of QueryText::DATABASES.
234
264
  def record(db, text, ms, failed: false)
235
265
  active&.record(db, text, ms, failed: failed)
@@ -242,6 +272,97 @@ module SiteGoose
242
272
  def install
243
273
  hook_active_record
244
274
  hook_mongo
275
+ hook_redis
276
+ end
277
+
278
+ # redis-client's global middleware, registered once per process. The
279
+ # redis gem 4 has its own connection code, which this doesn't see.
280
+ def hook_redis
281
+ return if @hooked[:redis] || !defined?(::RedisClient) || !::RedisClient.respond_to?(:register)
282
+
283
+ @hooked[:redis] = true
284
+ return if defined?(::RedisClient::Middlewares) && ::RedisClient::Middlewares.include?(RedisHook)
285
+
286
+ ::RedisClient.register(RedisHook)
287
+ rescue StandardError
288
+ nil
289
+ end
290
+
291
+ # The connection's own set-up, which redis-client sends as a pipeline
292
+ # when it connects.
293
+ PRELUDE = %w[HELLO AUTH SELECT CLIENT ROLE READONLY].to_h { |name| [name, true] }.freeze
294
+
295
+ # A pipeline as one call: "PIPELINE <first command timed>", or "MULTI
296
+ # <first command>" for a transaction (MULTI ... EXEC); nil when none
297
+ # of its commands is timed, or it is the connection's set-up.
298
+ def redis_pipeline(commands)
299
+ return nil if !commands.is_a?(Array) || commands.empty?
300
+
301
+ if redis_name(commands[0]) == "MULTI"
302
+ prefix = "MULTI"
303
+ ends = redis_name(commands[-1])
304
+ last = ends == "EXEC" || ends == "DISCARD" ? -2 : -1
305
+ inside = commands[1..last]
306
+ else
307
+ # Stops at the first command that isn't set-up: an app's pipeline
308
+ # of thousands isn't read twice.
309
+ return nil if commands.all? { |command| PRELUDE.key?(redis_name(command)) }
310
+
311
+ prefix = "PIPELINE"
312
+ inside = commands
313
+ end
314
+ inside.each do |command|
315
+ first = QueryText.redis_command(command)
316
+ return "#{prefix} #{first}" if first
317
+ end
318
+ nil
319
+ end
320
+
321
+ def redis_name(command)
322
+ command.is_a?(Array) ? QueryText.redis_word(command[0]) : nil
323
+ end
324
+
325
+ # Runs a Redis command (or pipeline) and records it: failed when it
326
+ # raised (an error reply, no answer) or, for a pipeline, answered an
327
+ # error (sent with exception: false, or inside a transaction's EXEC,
328
+ # which redis-client raises only after the middleware). A single
329
+ # command's error reply always raises, so its answer isn't looked at.
330
+ # MOVED and ASK are redirections: the cluster client sends the command
331
+ # again (through this middleware too), so the redirected try isn't
332
+ # recorded, only the one that answers.
333
+ def time_redis(statement, pipelined: false)
334
+ started = SiteGoose.clock
335
+ failed = true
336
+ redirected = false
337
+ begin
338
+ result = yield
339
+ failed = pipelined ? redis_errors?(result, statement.start_with?("MULTI ")) : false
340
+ result
341
+ rescue StandardError => e
342
+ failed = redis_error?(e)
343
+ redirected = !failed
344
+ raise
345
+ ensure
346
+ record("redis", statement, (SiteGoose.clock - started) * 1000, failed: failed) unless redirected
347
+ end
348
+ end
349
+
350
+ # A pipeline's answers: an error among them, or in a transaction's
351
+ # EXEC answer (its last).
352
+ def redis_errors?(results, multi)
353
+ return false unless results.is_a?(Array)
354
+ return true if results.any? { |item| redis_error?(item) }
355
+
356
+ multi && results.last.is_a?(Array) && results.last.any? { |item| redis_error?(item) }
357
+ end
358
+
359
+ def redis_error?(value)
360
+ return false unless value.is_a?(StandardError)
361
+
362
+ message = value.message.to_s
363
+ !(message.start_with?("MOVED ") || message.start_with?("ASK "))
364
+ rescue StandardError
365
+ true
245
366
  end
246
367
 
247
368
  # Active Record's sql.active_record notification (Rails, or Active
@@ -375,6 +496,38 @@ module SiteGoose
375
496
  end
376
497
  end
377
498
 
499
+ # redis-client's middleware (RedisClient.register): every client's
500
+ # commands, the redis gem 5's and Sidekiq's too. Blocking commands
501
+ # (BLPOP, BRPOP: Sidekiq's fetch) aren't timed, nor the package's own
502
+ # (Queries.own). With no platform timing queries it only passes on.
503
+ module RedisHook
504
+ def call(command, redis_config)
505
+ return super if Queries.redis_untimed?
506
+
507
+ statement = begin
508
+ QueryText.redis_command(command)
509
+ rescue StandardError
510
+ nil
511
+ end
512
+ return super if statement.nil?
513
+
514
+ Queries.time_redis(statement) { super }
515
+ end
516
+
517
+ def call_pipelined(commands, redis_config)
518
+ return super if Queries.redis_untimed?
519
+
520
+ statement = begin
521
+ Queries.redis_pipeline(commands)
522
+ rescue StandardError
523
+ nil
524
+ end
525
+ return super if statement.nil?
526
+
527
+ Queries.time_redis(statement, pipelined: true) { super }
528
+ end
529
+ end
530
+
378
531
  # Extends one Sequel::Database (Sequel's own extensions wrap the same
379
532
  # public method); nothing else of Sequel is changed.
380
533
  module SequelHook
@@ -18,7 +18,7 @@ module SiteGoose
18
18
  MAX_STATEMENT = 1000
19
19
  OTHER_STATEMENT = "(other)"
20
20
  # The databases a row may name; anything else is "other".
21
- DATABASES = %w[postgresql mysql mariadb sqlite mssql oracle clickhouse mongodb other].freeze
21
+ DATABASES = %w[postgresql mysql mariadb sqlite mssql oracle clickhouse mongodb redis other].freeze
22
22
 
23
23
  # JavaScript's \s (and what its trim() removes).
24
24
  SPACE = "\\t\\n\\v\\f\\r \\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff"
@@ -53,6 +53,8 @@ module SiteGoose
53
53
  db = database_of(db)
54
54
  shaped = if db == "mongodb"
55
55
  mongo_statement(text)
56
+ elsif db == "redis"
57
+ redis_statement(text)
56
58
  elsif db == "other" && text.include?("\\")
57
59
  # A database we don't know may or may not take a backslash as an
58
60
  # escape, and each reading leaks what the other hides. When they
@@ -265,6 +267,139 @@ module SiteGoose
265
267
  json.gsub(STAND_INS) { |c| format("\\u%04x", c.ord - STAND_IN) }
266
268
  end
267
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
+
268
403
  # "find users {...}": the command, the collection, and the filter's shape.
269
404
  def mongo_statement(text)
270
405
  match = MONGO.match(trim(text))
@@ -98,7 +98,8 @@ module SiteGoose
98
98
  readers = @lock.synchronize { @readers.dup }
99
99
  gauges = {}
100
100
  readers.each do |reader|
101
- Array(reader.read).each do |reading|
101
+ # The package's own Redis commands: not timed as the app's.
102
+ Array(Queries.own { reader.read }).each do |reading|
102
103
  gauges[Queues.key(reading[:system], reading[:broker], reading[:queue])] = reading
103
104
  end
104
105
  rescue StandardError => e
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module SiteGoose
4
- VERSION = "0.3.4"
4
+ VERSION = "0.3.5"
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: sitegoose
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.3.4
4
+ version: 0.3.5
5
5
  platform: ruby
6
6
  authors:
7
7
  - steviec87