sitegoose 0.3.4 → 0.3.6

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: 309be56528382651cd8349212625ff2fd18a0d8eaa8ccf89feb37cc2dcf0b4c9
4
+ data.tar.gz: 8ae02d206bb48807ee2dd1f897ed6df9626d66d6d778b7a8ecb5add053c64d59
5
5
  SHA512:
6
- metadata.gz: c3521c60c43c997907660337494fb0939a6b16100d762c9dd19e554ebf4e45c1b8cc86f4165d42dfc0ab2e0d6c2d052be5b353d7c3297eb184086584fc508ffc
7
- data.tar.gz: 118029ecf321a5a61733ce79aa29251ef21aca0281d60d95b8ebcbec9b4c4ae69ed5ae69c5f2a34bbaef441d4e9a50f15cf45d19cd7f6139d5423f62831bce15
6
+ metadata.gz: 4b2813f31c8dd0e34d7fb96c34385d1a8dd3b516b33158672674b843cd9018dca539c8657c2e0af13a551d5825d346f343d92ff2f51d4e39eab38baf947d28ee
7
+ data.tar.gz: cab8dad76633bfbfdfd68646f653ada807c7ffe6e6e09705a52a3f685a05060cb32c7473b0769a22db4e2a497b940df89f09c0141cae18e43b673c132507d46d
data/README.md CHANGED
@@ -12,25 +12,30 @@ gem "sitegoose"
12
12
 
13
13
  ## Rails
14
14
 
15
- Nothing to add to the middleware stack: the gem's Railtie puts it first.
15
+ Add the gem and put your keys in the environment (site settings has all
16
+ three, ready to copy). That's all: the gem's Railtie puts its middleware
17
+ first.
16
18
 
17
- ```ruby
18
- # config/initializers/sitegoose.rb
19
- SiteGoose.configure(
20
- site_id: "YOUR_SITE_ID",
21
- secret: ENV["ANALYTICS_SITE_SECRET"], # site settings; keep it on the server
22
- endpoint: "https://YOUR_COLLECTOR_URL",
23
- # trust_proxy: 1, # behind Nginx or a load balancer
24
- # trust_proxy: "cloudflare", # every request through Cloudflare
25
- )
19
+ ```bash
20
+ ANALYTICS_SITE_ID=YOUR_SITE_ID
21
+ ANALYTICS_SITE_SECRET=YOUR_SITE_SECRET
22
+ ANALYTICS_ENDPOINT=https://YOUR_COLLECTOR_URL
23
+ # ANALYTICS_TRUST_PROXY=1 # behind Nginx or a load balancer
24
+ # ANALYTICS_TRUST_PROXY=cloudflare # every request through Cloudflare
25
+ # ANALYTICS_SERVER_NAME=api # several services on one site
26
26
  ```
27
27
 
28
- Or keep it in the credentials (`bin/rails credentials:edit`), under
29
- `sitegoose:` with the same keys, or in `config.sitegoose`.
30
- The environment works too: `ANALYTICS_SITE_ID`, `ANALYTICS_SITE_SECRET`,
31
- `ANALYTICS_ENDPOINT`, `ANALYTICS_SERVER_NAME`, `ANALYTICS_TRUST_PROXY`.
32
- Lowest first: the environment, credentials, `config.sitegoose`,
33
- `configure`.
28
+ With `dotenv-rails`, `.env` works as usual: the platform is made on first
29
+ use, after it has loaded.
30
+
31
+ Options in code go in an initializer, or the credentials
32
+ (`bin/rails credentials:edit`, under `sitegoose:`), or `config.sitegoose`.
33
+ Lowest first: the environment, credentials, `config.sitegoose`, `configure`.
34
+
35
+ ```ruby
36
+ # config/initializers/sitegoose.rb (optional)
37
+ SiteGoose.configure(trust_proxy: 1, errors: { capture_logging: true })
38
+ ```
34
39
 
35
40
  Then, on their own:
36
41
 
@@ -47,10 +52,11 @@ In your code: `SiteGoose.track(...)`, or `SiteGoose.platform`.
47
52
  ## Sinatra and other Rack apps
48
53
 
49
54
  ```ruby
50
- use SiteGoose::Middleware,
51
- site_id: "YOUR_SITE_ID", secret: ENV["ANALYTICS_SITE_SECRET"], endpoint: "https://YOUR_COLLECTOR_URL"
55
+ use SiteGoose::Middleware # the keys from ANALYTICS_* in the environment, as for Rails
52
56
  ```
53
57
 
58
+ Or pass them: `use SiteGoose::Middleware, site_id: "...", secret: ENV["ANALYTICS_SITE_SECRET"], endpoint: "https://..."`.
59
+
54
60
  Put it first; added twice (by hand next to the Railtie, or by an engine),
55
61
  the second copy passes requests straight on. Sinatra's route patterns (`/users/:id`) and its error pages are
56
62
  read on their own; set `set :raise_errors, false` (production's default) or
@@ -157,6 +163,15 @@ slow. Every value is replaced by `?` before anything is counted
157
163
  SiteGoose.watch_database(CLICKHOUSE)
158
164
  ```
159
165
 
166
+ - **Redis**: automatic with `redis-client` (so the `redis` gem 5 and Sidekiq 7
167
+ too), through its own `RedisClient.register` middleware. Each command is its
168
+ command and first key's shape only (`GET user:?:cart`), never an argument or
169
+ value; a pipeline is one `PIPELINE GET user:?` call and a `multi` one
170
+ `MULTI INCR hits:?`. Blocking commands (`BRPOP`, Sidekiq's fetch) and the
171
+ package's own queue readings aren't timed; Sidekiq's other commands are. An
172
+ error reply or no answer is a failure; a nil or a `MOVED` isn't. The `redis`
173
+ gem 4 has its own connection code, which isn't seen.
174
+
160
175
  A query counts under the request (or Sidekiq or `platform.job` run) it ran
161
176
  in, with the same method and route Server speed shows; one outside them,
162
177
  like a console or a thread of your own, counts as `JOB (background)`. A
@@ -391,13 +406,20 @@ platform = SiteGoose.platform
391
406
  session = platform.session_id(request) # the visit, from the X-Analytics-Session header
392
407
 
393
408
  platform.track("purchase", { "numeric_value" => "49.90", "currency" => "EUR", "event_uid" => "order-#{order.id}" }, session_id: session)
394
- platform.identify(user.id, session_id: session)
409
+ platform.identify(user.id, session_id: session, traits: { plan: "pro", seats: 5, trial: false }) # traits are optional
395
410
  platform.lead({ "email" => "ana@example.com", "name" => "Ana", "status" => "qualified" })
396
411
  ```
397
412
 
398
413
  `track` sends in the background; `identify` and `lead` wait for the answer
399
414
  (up to 5 seconds).
400
415
 
416
+ **User traits:** `identify` takes optional `traits:`, a hash of name to text,
417
+ number or `true`/`false` (a symbol value is sent as its name). Arrays, hashes
418
+ and other values are left out (and `traits` is left off when nothing is left).
419
+ The collector does the rest: names are lowercased with spaces and dashes as
420
+ `_` (up to 40 letters, digits and `_`), text is cut at 200 characters, values
421
+ that look like an email address are dropped, and at most 20 are kept.
422
+
401
423
  **Link to the visit:** send the tracker's session ID with your site's requests:
402
424
 
403
425
  ```js
@@ -6,7 +6,8 @@
6
6
  #
7
7
  # - track(): events, batched to POST /events/server-events in the background.
8
8
  # Each gets an event_uid, so a retried batch can be told apart from new events.
9
- # - identify(): links the browser's visit to your user ID (/events/identify).
9
+ # - identify(): links the browser's visit to your user ID (/events/identify),
10
+ # with optional traits about the user (plan, seats...).
10
11
  # - lead(): adds or updates a lead (/events/lead).
11
12
  # identify() and lead() wait for the answer (up to 5 seconds).
12
13
 
@@ -79,14 +80,34 @@ module SiteGoose
79
80
  ok
80
81
  end
81
82
 
82
- # Links the visit to your user ID. true when stored.
83
- def identify(user_id, session_id = "")
83
+ # Links the visit to your user ID. true when stored. traits: what you know
84
+ # about the user, name => text, number or true/false
85
+ # ({ plan: "pro", seats: 5 }); anything else is left out, and the
86
+ # collector cleans the names and values.
87
+ def identify(user_id, session_id = "", traits = nil)
84
88
  return false if user_id.to_s.empty? || session_id.to_s.empty? || !@core.on?("analytics")
85
89
 
86
- res = @core.request("analytics", "/events/identify", body: { "user_id" => user_id.to_s, "session_id" => session_id.to_s })
90
+ body = { "user_id" => user_id.to_s, "session_id" => session_id.to_s }
91
+ kept = self.class.scalar_traits(traits)
92
+ body["traits"] = kept unless kept.empty?
93
+ res = @core.request("analytics", "/events/identify", body: body)
87
94
  res ? res.ok? : false
88
95
  end
89
96
 
97
+ # The traits that are text (a symbol as its name), a finite number or
98
+ # true/false, with their names as strings.
99
+ def self.scalar_traits(traits)
100
+ return {} unless traits.is_a?(Hash)
101
+
102
+ traits.each_with_object({}) do |(name, value), kept|
103
+ case value
104
+ when String, Integer, true, false then kept[name.to_s] = value
105
+ when Symbol then kept[name.to_s] = value.to_s
106
+ when Float then kept[name.to_s] = value if value.finite?
107
+ end
108
+ end
109
+ end
110
+
90
111
  # fields: email or phone, and name, status, tags, note, deal fields...
91
112
  # Returns {"status", "lead_id"}, or nil.
92
113
  def lead(fields, session_id = "")
@@ -438,7 +438,24 @@ module SiteGoose
438
438
  nil
439
439
  end
440
440
 
441
- HEADER_NAME = /\A[A-Za-z][A-Za-z0-9-]{0,63}\z/.freeze
441
+ # The nine headers the dashboard can produce (expresscollect/Analytics/
442
+ # platform.js, headersOf), lower case. A list of what's allowed, not of
443
+ # what isn't: whoever got into our servers still couldn't make this app
444
+ # grant another site its users' data (Access-Control-Allow-*), send every
445
+ # page elsewhere (Refresh), log everyone out (Clear-Site-Data) or change
446
+ # what a response is. Shared cases: sdk/protocols/header-cases.json.
447
+ SECURITY_HEADERS = %w[strict-transport-security x-content-type-options x-frame-options referrer-policy
448
+ permissions-policy cross-origin-opener-policy content-security-policy
449
+ content-security-policy-report-only reporting-endpoints].freeze
450
+ HEADER_VALUE = /\A[\x20-\x7e\t]*\z/.freeze
451
+
452
+ # One of SECURITY_HEADERS, in any case, with a value of visible ASCII,
453
+ # spaces and tabs (no line breaks, nothing a server rejects), at most
454
+ # 4,000 characters.
455
+ def self.safe_header?(pair)
456
+ pair.is_a?(Array) && pair.size == 2 && pair[0].is_a?(String) && SECURITY_HEADERS.include?(pair[0].downcase) &&
457
+ pair[1].is_a?(String) && pair[1].size <= 4000 && pair[1].match?(HEADER_VALUE)
458
+ end
442
459
 
443
460
  def sync_switches
444
461
  headers = { "X-Platform-Modules" => @loaded.join(",") }
@@ -454,11 +471,7 @@ module SiteGoose
454
471
  @switches = data["modules"]
455
472
  @flags = data["flags"].is_a?(Hash) ? data["flags"] : {}
456
473
  @maintenance = data["maintenance"].is_a?(Hash) ? data["maintenance"] : { "on" => false }
457
- # Only well-formed headers (no line breaks can get through).
458
- @headers = (data["headers"].is_a?(Array) ? data["headers"] : []).select do |pair|
459
- pair.is_a?(Array) && pair.size == 2 && pair[0].is_a?(String) && pair[0].match?(HEADER_NAME) &&
460
- pair[1].is_a?(String) && !pair[1].include?("\r") && !pair[1].include?("\n") && pair[1].size <= 4000
461
- end
474
+ @headers = (data["headers"].is_a?(Array) ? data["headers"] : []).select { |pair| Core.safe_header?(pair) }
462
475
  @etag = res.headers["etag"].to_s
463
476
  end
464
477
  [MIN_SYNC, (data["sync"].is_a?(Numeric) && data["sync"].positive? ? data["sync"].to_i : RETRY)].max
@@ -264,9 +264,10 @@ module SiteGoose
264
264
  analytics ? analytics.track(name, fields, session_id) : ""
265
265
  end
266
266
 
267
- def identify(user_id, session_id: "")
267
+ # traits: optional user properties, name => text, number or true/false.
268
+ def identify(user_id, session_id: "", traits: nil)
268
269
  analytics = @modules["analytics"]
269
- analytics ? analytics.identify(user_id, session_id) : false
270
+ analytics ? analytics.identify(user_id, session_id, traits) : false
270
271
  end
271
272
 
272
273
  def lead(fields, session_id: "")
@@ -33,6 +33,19 @@ module SiteGoose
33
33
  # The collector reads these; everything else, cookies above all, stays here.
34
34
  PASS_HEADERS = %w[content-type user-agent accept-language referer origin sec-fetch-site sec-ch-ua
35
35
  sec-ch-ua-mobile sec-ch-ua-platform].freeze
36
+ # What a collector answer may be served as from the site's own domain. Its
37
+ # type comes from the collector, so anything else becomes plain text, and
38
+ # nosniff stops a browser guessing: a server that is no longer ours still
39
+ # can't answer <prefix>/api/... with a page that runs as the customer's own
40
+ # site. Shared cases: sdk/protocols/proxy-answer-cases.json.
41
+ ANSWER_TYPES = %w[application/json text/plain image/webp].freeze
42
+
43
+ def self.answer_type(value)
44
+ given = value.is_a?(String) ? value : ""
45
+ kind = given.split(";", 2).first.to_s.strip.downcase
46
+ ANSWER_TYPES.include?(kind) && given.match?(/\A[\x20-\x7e]*\z/) ? given : "text/plain; charset=utf-8"
47
+ end
48
+
36
49
  SAFE_PATH = %r{\A[A-Za-z0-9/_.-]{1,120}\z}.freeze
37
50
  FILE_PATH = %r{\Av(\d+(?:\.\d+\.\d+)?)/([a-z]+\.js)\z}.freeze
38
51
  # These run on the app's own request threads, so they are short, and a
@@ -238,8 +251,8 @@ module SiteGoose
238
251
  begin
239
252
  answer = fetch(url, method: method, headers: out, body: method == "POST" ? body.to_s : nil)
240
253
  answer.code.to_i >= 500 ? failed : worked
241
- passed = {}
242
- %w[content-type cache-control retry-after].each do |name|
254
+ passed = { "content-type" => Proxy.answer_type(answer["content-type"]), "x-content-type-options" => "nosniff" }
255
+ %w[cache-control retry-after].each do |name|
243
256
  value = answer[name]
244
257
  passed[name] = value if value && !value.empty?
245
258
  end
@@ -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.6"
5
5
  end
data/lib/sitegoose.rb CHANGED
@@ -207,8 +207,8 @@ module SiteGoose
207
207
  platform&.track(name, fields, session_id: session_id) || ""
208
208
  end
209
209
 
210
- def identify(user_id, session_id: "")
211
- platform ? platform.identify(user_id, session_id: session_id) : false
210
+ def identify(user_id, session_id: "", traits: nil)
211
+ platform ? platform.identify(user_id, session_id: session_id, traits: traits) : false
212
212
  end
213
213
 
214
214
  def lead(fields, session_id: "")
metadata CHANGED
@@ -1,14 +1,14 @@
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.6
5
5
  platform: ruby
6
6
  authors:
7
7
  - steviec87
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-11-07 00:00:00.000000000 Z
11
+ date: 2026-11-13 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: rack