boto-rb-management-ui 0.31.0

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.
Files changed (106) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE +21 -0
  3. data/README.md +22 -0
  4. data/db/migrations/20261201000001_create_boto_monitor_instances.rb +14 -0
  5. data/db/migrations/20261201000002_create_boto_monitor_series.rb +20 -0
  6. data/db/migrations/20261201000003_create_boto_monitor_errors.rb +19 -0
  7. data/db/migrations/20261201000004_create_boto_monitor_traces.rb +19 -0
  8. data/db/migrations/20261201000005_create_boto_monitor_runtime.rb +23 -0
  9. data/db/migrations/20261201000006_create_boto_monitor_n_plus_ones.rb +17 -0
  10. data/db/migrations/20261201000007_add_browser_data_to_boto_monitor.rb +31 -0
  11. data/db/migrations/20261203000001_create_boto_monitor_streams.rb +24 -0
  12. data/db/migrations/20261203000002_add_streams_open_to_boto_monitor_instances.rb +12 -0
  13. data/lib/boto/companions/management_ui.rb +8 -0
  14. data/lib/boto/management_ui/app.rb +84 -0
  15. data/lib/boto/management_ui/app_traits.rb +34 -0
  16. data/lib/boto/management_ui/assets/monitor/api.js +36 -0
  17. data/lib/boto/management_ui/assets/monitor/charts.js +212 -0
  18. data/lib/boto/management_ui/assets/monitor/constants.js +70 -0
  19. data/lib/boto/management_ui/assets/monitor/dom.js +70 -0
  20. data/lib/boto/management_ui/assets/monitor/format.js +76 -0
  21. data/lib/boto/management_ui/assets/monitor/header.js +2 -0
  22. data/lib/boto/management_ui/assets/monitor/main.js +33 -0
  23. data/lib/boto/management_ui/assets/monitor/panes.js +109 -0
  24. data/lib/boto/management_ui/assets/monitor/runtime.js +26 -0
  25. data/lib/boto/management_ui/assets/monitor/services.js +174 -0
  26. data/lib/boto/management_ui/assets/monitor/spa.js +203 -0
  27. data/lib/boto/management_ui/assets/monitor/traces.js +88 -0
  28. data/lib/boto/management_ui/assets/panel/base.css +87 -0
  29. data/lib/boto/management_ui/assets/panel/errors.css +36 -0
  30. data/lib/boto/management_ui/assets/panel/gateway.css +3 -0
  31. data/lib/boto/management_ui/assets/panel/layout.css +63 -0
  32. data/lib/boto/management_ui/assets/panel/monitor_layout.css +77 -0
  33. data/lib/boto/management_ui/assets/panel/monitor_tables.css +97 -0
  34. data/lib/boto/management_ui/assets/panel/service_view.css +102 -0
  35. data/lib/boto/management_ui/assets/panel/services.css +55 -0
  36. data/lib/boto/management_ui/assets/panel/spa.css +41 -0
  37. data/lib/boto/management_ui/assets/panel/tables.css +67 -0
  38. data/lib/boto/management_ui/assets/panel/tabs.css +71 -0
  39. data/lib/boto/management_ui/assets/panel/traces.css +45 -0
  40. data/lib/boto/management_ui/browser_telemetry.rb +87 -0
  41. data/lib/boto/management_ui/gateway_view.rb +57 -0
  42. data/lib/boto/management_ui/health_probe.rb +70 -0
  43. data/lib/boto/management_ui/in_process_receiver.rb +17 -0
  44. data/lib/boto/management_ui/monitor/api.rb +87 -0
  45. data/lib/boto/management_ui/monitor/batch_schema/browser_call_entry.rb +26 -0
  46. data/lib/boto/management_ui/monitor/batch_schema/browser_error_entry.rb +41 -0
  47. data/lib/boto/management_ui/monitor/batch_schema/checks.rb +90 -0
  48. data/lib/boto/management_ui/monitor/batch_schema/error_entry.rb +37 -0
  49. data/lib/boto/management_ui/monitor/batch_schema/n_plus_one_entry.rb +30 -0
  50. data/lib/boto/management_ui/monitor/batch_schema/page_entry.rb +25 -0
  51. data/lib/boto/management_ui/monitor/batch_schema/runtime.rb +33 -0
  52. data/lib/boto/management_ui/monitor/batch_schema/series.rb +41 -0
  53. data/lib/boto/management_ui/monitor/batch_schema/streams.rb +46 -0
  54. data/lib/boto/management_ui/monitor/batch_schema/trace_entry.rb +45 -0
  55. data/lib/boto/management_ui/monitor/batch_schema.rb +138 -0
  56. data/lib/boto/management_ui/monitor/ingest.rb +126 -0
  57. data/lib/boto/management_ui/monitor/memory_store/error_table.rb +53 -0
  58. data/lib/boto/management_ui/monitor/memory_store/instance_table.rb +45 -0
  59. data/lib/boto/management_ui/monitor/memory_store/n_plus_one_table.rb +44 -0
  60. data/lib/boto/management_ui/monitor/memory_store/runtime_table.rb +55 -0
  61. data/lib/boto/management_ui/monitor/memory_store/series_table.rb +49 -0
  62. data/lib/boto/management_ui/monitor/memory_store/staleness.rb +20 -0
  63. data/lib/boto/management_ui/monitor/memory_store/stream_table.rb +36 -0
  64. data/lib/boto/management_ui/monitor/memory_store/trace_table.rb +41 -0
  65. data/lib/boto/management_ui/monitor/memory_store.rb +118 -0
  66. data/lib/boto/management_ui/monitor/percentile.rb +38 -0
  67. data/lib/boto/management_ui/monitor/period.rb +48 -0
  68. data/lib/boto/management_ui/monitor/queries/browser_calls.rb +56 -0
  69. data/lib/boto/management_ui/monitor/queries/browser_view.rb +91 -0
  70. data/lib/boto/management_ui/monitor/queries/charts.rb +66 -0
  71. data/lib/boto/management_ui/monitor/queries/live_instances.rb +44 -0
  72. data/lib/boto/management_ui/monitor/queries/points.rb +61 -0
  73. data/lib/boto/management_ui/monitor/queries/route_view.rb +46 -0
  74. data/lib/boto/management_ui/monitor/queries/runtime_view.rb +80 -0
  75. data/lib/boto/management_ui/monitor/queries/service_cards.rb +65 -0
  76. data/lib/boto/management_ui/monitor/queries/streams.rb +39 -0
  77. data/lib/boto/management_ui/monitor/queries/trace_tree.rb +47 -0
  78. data/lib/boto/management_ui/monitor/queries/vitals.rb +50 -0
  79. data/lib/boto/management_ui/monitor/queries.rb +171 -0
  80. data/lib/boto/management_ui/monitor/retention.rb +62 -0
  81. data/lib/boto/management_ui/monitor/schema.rb +64 -0
  82. data/lib/boto/management_ui/monitor/sql_store/error_writer.rb +62 -0
  83. data/lib/boto/management_ui/monitor/sql_store/instance_writer.rb +63 -0
  84. data/lib/boto/management_ui/monitor/sql_store/n_plus_one_writer.rb +50 -0
  85. data/lib/boto/management_ui/monitor/sql_store/rows.rb +99 -0
  86. data/lib/boto/management_ui/monitor/sql_store/series_writer.rb +52 -0
  87. data/lib/boto/management_ui/monitor/sql_store/streams_writer.rb +34 -0
  88. data/lib/boto/management_ui/monitor/sql_store.rb +139 -0
  89. data/lib/boto/management_ui/monitor/store.rb +78 -0
  90. data/lib/boto/management_ui/monitor/stream_point.rb +45 -0
  91. data/lib/boto/management_ui/panel/env_rows.rb +54 -0
  92. data/lib/boto/management_ui/panel/html_view.rb +43 -0
  93. data/lib/boto/management_ui/panel/json_view.rb +43 -0
  94. data/lib/boto/management_ui/panel/masking.rb +43 -0
  95. data/lib/boto/management_ui/panel/page.rb +41 -0
  96. data/lib/boto/management_ui/panel/service_info.rb +62 -0
  97. data/lib/boto/management_ui/panel.html.erb +207 -0
  98. data/lib/boto/management_ui/panel.rb +115 -0
  99. data/lib/boto/management_ui/password_auth.rb +26 -0
  100. data/lib/boto/management_ui/service_list.rb +59 -0
  101. data/lib/boto/management_ui/setup.rb +103 -0
  102. data/lib/boto/management_ui/spas.rb +73 -0
  103. data/lib/boto/management_ui/tabs.rb +40 -0
  104. data/lib/boto/management_ui/version.rb +7 -0
  105. data/lib/boto/management_ui.rb +15 -0
  106. metadata +203 -0
@@ -0,0 +1,171 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "time"
4
+
5
+ module Boto
6
+ module ManagementUi
7
+ module Monitor
8
+ # What the panel asks for, as hashes ready for JSON.
9
+ #
10
+ # Every series query SUMS the rows of the same minute and labels (count, sum and each bucket position); it
11
+ # never reads "the" row. With several gateway replicas on Postgres there can be more than one row for the
12
+ # same service, minute and labels, and the sum is what keeps the numbers right.
13
+ class Queries
14
+ DEFAULT_STALE_AFTER = 120
15
+ DEFAULT_TRACE_LIMIT = 50
16
+ BROWSER_ERROR_SOURCE = "browser"
17
+
18
+ def self.iso(time)
19
+ time&.getutc&.iso8601
20
+ end
21
+
22
+ def initialize(store:, clock: Time, stale_after: DEFAULT_STALE_AFTER)
23
+ @store = store
24
+ @clock = clock
25
+ @live = LiveInstances.new(store:, clock:, stale_after:)
26
+ @cards = ServiceCards.new(store:, clock:, live: @live)
27
+ end
28
+
29
+ def solution(period:)
30
+ period = Period.parse(period)
31
+ all = @cards.names.to_h { |name| [name, @store.instances(name)] }
32
+ live = all.transform_values { |infos| @live.only(infos) }
33
+ live_infos = live.values.flatten
34
+ Points.summary(@cards.total(period), period.seconds).merge(
35
+ "period" => period.name, "services" => live.count { |_name, infos| infos.any? },
36
+ "instances" => live_infos.size, "in_flight" => live_infos.sum { |info| info["in_flight"].to_i },
37
+ "last_batch_at" => self.class.iso(all.values.flatten.map { |info| info["last_seen"] }.max)
38
+ )
39
+ end
40
+
41
+ def services(period:)
42
+ period = Period.parse(period)
43
+ { "services" => @cards.cards(period) }
44
+ end
45
+
46
+ def routes(service:, period:)
47
+ period = Period.parse(period)
48
+ view = RouteView.new(period:, now: @clock.now, flagged: n_plus_one_keys(service, period),
49
+ streamed: stream_routes(service, period))
50
+ { "routes" => view.call(route_rows(service, period)) }
51
+ end
52
+
53
+ def streams(service:, period:)
54
+ period = Period.parse(period)
55
+ { "open" => @live.of(service).sum { |info| info["streams_open"].to_i },
56
+ "routes" => Streams.new(stream_rows(service, period)).call }
57
+ end
58
+
59
+ def charts(service:, period:)
60
+ period = Period.parse(period)
61
+ from, to = period.window(@clock.now)
62
+ Charts.new(step: period.step, from: from, to: to)
63
+ .build(route_rows(service, period), runtime_rows(service, from, to))
64
+ end
65
+
66
+ def errors(service:, period:)
67
+ period = Period.parse(period)
68
+ { "errors" => recent_errors(service, period, Store::DEFAULT_ERROR_SOURCE) }
69
+ end
70
+
71
+ def browser_errors(service:, period:)
72
+ period = Period.parse(period)
73
+ errors = recent_errors(service, period, BROWSER_ERROR_SOURCE).map do |error|
74
+ error.merge("browsers" => by_count(error["browsers"]))
75
+ end
76
+ { "errors" => errors }
77
+ end
78
+
79
+ def pages(service:, period:)
80
+ period = Period.parse(period)
81
+ from, to = period.window(@clock.now)
82
+ BrowserView.new(period: period, from: from, to: to, rows: browser_series(service, period, "page"),
83
+ errors: recent_errors(service, period, BROWSER_ERROR_SOURCE)).call
84
+ end
85
+
86
+ def browser_calls(service:, period:)
87
+ period = Period.parse(period)
88
+ rows = browser_series(service, period, "browser_call")
89
+ routes_by_ref = rows.map { |row| row["ref"] }.uniq.to_h { |ref| [ref, route_rows(ref, period)] }
90
+ { "browser_calls" => BrowserCalls.new(rows, routes_by_ref:).call }
91
+ end
92
+
93
+ def n_plus_ones(service:, period:)
94
+ period = Period.parse(period)
95
+ groups = recent_n_plus_ones(service, period)
96
+ { "n_plus_ones" => groups.sort_by { |entry| -Time.iso8601(entry["last_at"]).to_i } }
97
+ end
98
+
99
+ def traces(service:, limit: DEFAULT_TRACE_LIMIT)
100
+ { "traces" => @store.traces(service, limit: limit).map { |trace| trace.except("spans") } }
101
+ end
102
+
103
+ def trace(service:, trace_id:)
104
+ found = @store.trace(service, trace_id)
105
+ return unless found
106
+
107
+ TraceTree.new(store: @store).call(found.merge("service" => service))
108
+ end
109
+
110
+ def runtime(service:)
111
+ live = @live.of(service)
112
+ rows = @live.runtime(service, live)
113
+ { "instances" => live.map { |info| RuntimeView.instance_view(rows_of(rows, info), info, current_minute) } }
114
+ end
115
+
116
+ private
117
+
118
+ # Route keys with an N+1 group seen in the period, so the route list can flag them.
119
+ def n_plus_one_keys(service, period)
120
+ recent_n_plus_ones(service, period).map { |entry| RouteView.key(entry) }
121
+ end
122
+
123
+ # Routes with a stream in the period, by route only: the stream series have no verb.
124
+ def stream_routes(service, period)
125
+ stream_rows(service, period).map { |row| row["route"] }.uniq
126
+ end
127
+
128
+ def stream_rows(service, period)
129
+ from, to = period.window(@clock.now)
130
+ @store.streams(service: service, from: from, to: to)
131
+ end
132
+
133
+ def recent_n_plus_ones(service, period)
134
+ since = @clock.now - period.seconds
135
+ @store.n_plus_ones(service).select { |entry| Time.iso8601(entry["last_at"]) >= since }
136
+ end
137
+
138
+ def recent_errors(service, period, source)
139
+ since = @clock.now - period.seconds
140
+ kept = @store.errors(service, source: source).select { |error| Time.iso8601(error["last_at"]) >= since }
141
+ kept.sort_by { |error| -Time.iso8601(error["last_at"]).to_i }
142
+ end
143
+
144
+ def by_count(browsers)
145
+ browsers.sort_by { |browser, count| [-count, browser] }.to_h
146
+ end
147
+
148
+ def route_rows(service, period)
149
+ browser_series(service, period, "routes")
150
+ end
151
+
152
+ def browser_series(service, period, kind)
153
+ from, to = period.window(@clock.now)
154
+ @store.series(service: service, from: from, to: to).select { |row| row["kind"] == kind }
155
+ end
156
+
157
+ def runtime_rows(service, from, to)
158
+ @store.runtime_series(service: service, from: from, to: to)
159
+ end
160
+
161
+ def current_minute
162
+ Period.minute_floor(@clock.now)
163
+ end
164
+
165
+ def rows_of(rows, info)
166
+ rows.select { |row| row["instance"] == info["instance"] }
167
+ end
168
+ end
169
+ end
170
+ end
171
+ end
@@ -0,0 +1,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Boto
4
+ module ManagementUi
5
+ module Monitor
6
+ # Purges what is past the retention windows, every hour, from a thread. Only stores with #purge are purged;
7
+ # MemoryStore keeps its own window.
8
+ class Retention
9
+ SECONDS_PER_DAY = 86_400
10
+ DEFAULT_INTERVAL = 3600
11
+ DEFAULT_METRICS_DAYS = 7
12
+ DEFAULT_TRACES_DAYS = 3
13
+
14
+ def initialize(store:, metrics_days: DEFAULT_METRICS_DAYS, traces_days: DEFAULT_TRACES_DAYS,
15
+ clock: Time, interval: DEFAULT_INTERVAL, log: $stderr)
16
+ @store = store
17
+ @metrics_window = metrics_days * SECONDS_PER_DAY
18
+ @traces_window = traces_days * SECONDS_PER_DAY
19
+ @clock = clock
20
+ @interval = interval
21
+ @log = log
22
+ @wakeup = Thread::Queue.new
23
+ end
24
+
25
+ def run_once
26
+ return unless @store.respond_to?(:purge)
27
+
28
+ now = @clock.now
29
+ @store.purge(before_metrics: now - @metrics_window, before_traces: now - @traces_window)
30
+ end
31
+
32
+ def start
33
+ @thread = Thread.new { loop_until_stopped }
34
+ self
35
+ end
36
+
37
+ # Pushing wakes the thread at once, so stop does not wait for the interval.
38
+ def stop
39
+ return unless @thread
40
+
41
+ @wakeup.push(:stop)
42
+ @thread.join
43
+ @thread = nil
44
+ end
45
+
46
+ private
47
+
48
+ def loop_until_stopped
49
+ until @wakeup.pop(timeout: @interval)
50
+ run_once_logging
51
+ end
52
+ end
53
+
54
+ def run_once_logging
55
+ run_once
56
+ rescue StandardError => error
57
+ @log.puts("boto monitor retention failed: #{error.class}: #{error.message}")
58
+ end
59
+ end
60
+ end
61
+ end
62
+ end
@@ -0,0 +1,64 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "boto/database"
4
+
5
+ module Boto
6
+ module ManagementUi
7
+ module Monitor
8
+ # Applies this gem's db/migrations to the monitor database, in a control table of its own, so they never mix
9
+ # with the migrations of a project that shares the database.
10
+ class Schema
11
+ MIGRATIONS_DIR = File.expand_path("../../../../db/migrations", __dir__)
12
+ CONTROL_TABLE = :boto_monitor_schema_migrations
13
+ IDS = :integer
14
+ # "boto" in ASCII: a fixed key for the Postgres advisory lock, unlikely to clash with an app's own lock.
15
+ ADVISORY_LOCK_KEY = 1_651_996_272
16
+
17
+ def self.apply(database, migrations_dir: MIGRATIONS_DIR)
18
+ new(database, migrations_dir: migrations_dir).apply
19
+ end
20
+
21
+ def initialize(database, migrations_dir: MIGRATIONS_DIR)
22
+ @database = database
23
+ @migrations_dir = migrations_dir
24
+ end
25
+
26
+ def apply
27
+ with_lock do
28
+ pending = pending_names
29
+ Migration::Plan.new(@database, @migrations_dir, ids: IDS).check_migrate!(pending)
30
+ Migration::TimestampMigrator.new(@database, @migrations_dir, { table: CONTROL_TABLE }, ids: IDS).run
31
+ end
32
+ nil
33
+ end
34
+
35
+ private
36
+
37
+ # Gateway workers (--processes) and replicas start together. SQLite: the first worker holds the write lock
38
+ # while it migrates and the others wait for it; Postgres: an advisory lock.
39
+ def with_lock(&block)
40
+ return @database.transaction(mode: :immediate, &block) if @database.database_type == :sqlite
41
+ return yield unless @database.database_type == :postgres
42
+
43
+ @database.synchronize do
44
+ @database.run("SELECT pg_advisory_lock(#{ADVISORY_LOCK_KEY})")
45
+ begin
46
+ yield
47
+ ensure
48
+ @database.run("SELECT pg_advisory_unlock(#{ADVISORY_LOCK_KEY})")
49
+ end
50
+ end
51
+ end
52
+
53
+ def pending_names
54
+ applied = @database.table_exists?(CONTROL_TABLE) ? @database[CONTROL_TABLE].select_map(:filename) : []
55
+ file_names - applied
56
+ end
57
+
58
+ def file_names
59
+ Dir.glob("*.rb", base: @migrations_dir).sort
60
+ end
61
+ end
62
+ end
63
+ end
64
+ end
@@ -0,0 +1,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "time"
5
+
6
+ module Boto
7
+ module ManagementUi
8
+ module Monitor
9
+ class SqlStore
10
+ # One row per fingerprint: the count adds up and first_at stays, as in MemoryStore.
11
+ class ErrorWriter
12
+ def initialize(database)
13
+ @database = database
14
+ end
15
+
16
+ def write(service, errors, source)
17
+ errors.each { |error| remember(service, source, error) }
18
+ end
19
+
20
+ private
21
+
22
+ # Another gateway worker may insert the same fingerprint at the same time: the insert then does nothing
23
+ # (Postgres answers nil), and the count goes into the row that worker created.
24
+ def remember(service, source, error)
25
+ key = { service: service, source: source, fingerprint: error["fingerprint"] }
26
+ dataset = @database[:boto_monitor_errors].where(key)
27
+ previous = dataset.for_update.first
28
+ return add(dataset, previous, error) if previous
29
+ return if @database[:boto_monitor_errors].insert_conflict.insert(error_row(error).merge(key))
30
+
31
+ add(dataset, dataset.for_update.first, error)
32
+ end
33
+
34
+ def add(dataset, previous, error)
35
+ dataset.update(error_row(error).merge(
36
+ count: previous[:count] + error["count"], first_at: previous[:first_at],
37
+ browsers: merge_browsers(previous[:browsers], error["browsers"])
38
+ ))
39
+ end
40
+
41
+ def error_row(error)
42
+ {
43
+ fingerprint: error["fingerprint"], class_name: error["class"], message: error["message"],
44
+ location: error["location"], verb: error["verb"], route: error["route"], count: error["count"],
45
+ first_at: Time.iso8601(error["first_at"]), last_at: Time.iso8601(error["last_at"]),
46
+ backtrace: JSON.generate(error["backtrace"]), trace_id: error["trace_id"],
47
+ browsers: merge_browsers(nil, error["browsers"])
48
+ }
49
+ end
50
+
51
+ # Server errors have no browsers (nil); browser errors add up the count of each browser.
52
+ def merge_browsers(stored, incoming)
53
+ return nil unless incoming
54
+
55
+ totals = stored ? JSON.parse(stored) : {}
56
+ JSON.generate(totals.merge(incoming) { |_browser, old, new| old + new })
57
+ end
58
+ end
59
+ end
60
+ end
61
+ end
62
+ end
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "time"
4
+
5
+ module Boto
6
+ module ManagementUi
7
+ module Monitor
8
+ class SqlStore
9
+ # Keeps one row per process of an instance, and one runtime row per instance and minute (the last batch wins).
10
+ class InstanceWriter
11
+ def initialize(database)
12
+ @database = database
13
+ end
14
+
15
+ def write(batch, minute, received_at)
16
+ service = batch["service"]
17
+ process_key = { service: service, instance: batch["instance"], process: batch["process"] }
18
+ upsert(:boto_monitor_instances, process_key, instance_values(batch, received_at),
19
+ started_at: Time.iso8601(batch["started_at"]))
20
+ upsert_runtime(process_key.merge(minute: minute), runtime_values(batch))
21
+ end
22
+
23
+ private
24
+
25
+ # Updates the row when it exists, so on_insert (started_at) is only set once.
26
+ def upsert(table, key, values, on_insert = {})
27
+ dataset = @database[table].where(key)
28
+ dataset.insert(key.merge(on_insert, values)) if dataset.update(values).zero?
29
+ end
30
+
31
+ # Summed fields add to the stored value (a NULL counts as 0); the others take the new batch's value.
32
+ def upsert_runtime(key, values)
33
+ dataset = @database[:boto_monitor_runtime].where(key)
34
+ dataset.insert(key.merge(values)) if dataset.update(accumulate(values)).zero?
35
+ end
36
+
37
+ def accumulate(values)
38
+ values.each_with_object({}) do |(column, value), changes|
39
+ if !BatchSchema::SUMMED_RUNTIME.include?(column.to_s)
40
+ changes[column] = value
41
+ elsif !value.nil?
42
+ changes[column] = Sequel.function(:coalesce, column, 0) + value
43
+ end
44
+ end
45
+ end
46
+
47
+ def instance_values(batch, received_at)
48
+ { boto_version: batch["boto"], last_seen_at: received_at, in_flight: batch["in_flight"],
49
+ streams_open: batch.dig("streams", "open") }
50
+ end
51
+
52
+ def runtime_values(batch)
53
+ runtime = batch["runtime"]
54
+ pool = runtime["pool"] || {}
55
+ Rows::RUNTIME_COLUMNS.to_h { |column| [column.to_sym, runtime[column]] }.merge(
56
+ pool_size: pool["size"], pool_in_use: pool["in_use"], in_flight: batch["in_flight"]
57
+ )
58
+ end
59
+ end
60
+ end
61
+ end
62
+ end
63
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "time"
4
+
5
+ module Boto
6
+ module ManagementUi
7
+ module Monitor
8
+ class SqlStore
9
+ # One row per fingerprint: counts add up, the biggest max_repeats wins and first_at stays, as in MemoryStore.
10
+ class NPlusOneWriter
11
+ def initialize(database)
12
+ @database = database
13
+ end
14
+
15
+ def write(service, n_plus_ones)
16
+ n_plus_ones.each { |entry| remember(service, entry) }
17
+ end
18
+
19
+ private
20
+
21
+ # Same race as the ErrorWriter: another gateway worker may insert the fingerprint first, so the count goes
22
+ # into the row that worker created.
23
+ def remember(service, entry)
24
+ dataset = @database[:boto_monitor_n_plus_ones].where(service: service, fingerprint: entry["fingerprint"])
25
+ previous = dataset.for_update.first
26
+ return add(dataset, previous, entry) if previous
27
+ return if @database[:boto_monitor_n_plus_ones].insert_conflict.insert(row(entry).merge(service: service))
28
+
29
+ add(dataset, dataset.for_update.first, entry)
30
+ end
31
+
32
+ def add(dataset, previous, entry)
33
+ dataset.update(row(entry).merge(
34
+ count: previous[:count] + entry["count"], max_repeats: [previous[:max_repeats], entry["max_repeats"]].max,
35
+ first_at: previous[:first_at]
36
+ ))
37
+ end
38
+
39
+ def row(entry)
40
+ {
41
+ fingerprint: entry["fingerprint"], verb: entry["verb"], route: entry["route"], sql: entry["sql"],
42
+ count: entry["count"], max_repeats: entry["max_repeats"], first_at: Time.iso8601(entry["first_at"]),
43
+ last_at: Time.iso8601(entry["last_at"]), trace_id: entry["trace_id"]
44
+ }
45
+ end
46
+ end
47
+ end
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,99 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Boto
6
+ module ManagementUi
7
+ module Monitor
8
+ class SqlStore
9
+ # Turns database rows into the hashes the Store interface returns, the same shape MemoryStore gives.
10
+ module Rows
11
+ RUNTIME_COLUMNS = %w[cpu memory memory_limit cpu_limit memory_source gc_count dropped].freeze
12
+ TRACE_COLUMNS = %i[trace_id parent_id verb route path status duration reason].freeze
13
+ N_PLUS_ONE_COLUMNS = %i[fingerprint verb route sql count max_repeats trace_id].freeze
14
+
15
+ module_function
16
+
17
+ def iso(time)
18
+ time.getutc.iso8601
19
+ end
20
+
21
+ def series(row)
22
+ labels = BatchSchema::SERIES_LABELS.fetch(row[:kind]).to_h { |label| [label, row[label.to_sym]] }
23
+ { "minute" => row[:minute], "kind" => row[:kind] }.merge(
24
+ labels, "count" => row[:count], "sum" => row[:sum], "buckets" => JSON.parse(row[:buckets])
25
+ )
26
+ end
27
+
28
+ # Only browser errors have "browsers", as in MemoryStore.
29
+ def error(row)
30
+ entry = {
31
+ "fingerprint" => row[:fingerprint], "class" => row[:class_name], "message" => row[:message],
32
+ "location" => row[:location], "verb" => row[:verb], "route" => row[:route], "count" => row[:count],
33
+ "first_at" => iso(row[:first_at]), "last_at" => iso(row[:last_at]),
34
+ "backtrace" => JSON.parse(row[:backtrace]), "trace_id" => row[:trace_id], "source" => row[:source]
35
+ }
36
+ row[:browsers] ? entry.merge("browsers" => JSON.parse(row[:browsers])) : entry
37
+ end
38
+
39
+ def n_plus_one(row)
40
+ row.slice(*N_PLUS_ONE_COLUMNS).transform_keys(&:to_s).merge(
41
+ "first_at" => iso(row[:first_at]), "last_at" => iso(row[:last_at])
42
+ )
43
+ end
44
+
45
+ def trace(row)
46
+ row.slice(*TRACE_COLUMNS).transform_keys(&:to_s).merge(
47
+ "started_at" => iso(row[:started_at]), "spans" => JSON.parse(row[:spans])
48
+ )
49
+ end
50
+
51
+ def instance(row, runtime)
52
+ { "instance" => row[:instance], "started_at" => row[:started_at], "last_seen" => row[:last_seen_at],
53
+ "process" => row[:process],
54
+ "in_flight" => row[:in_flight], "streams_open" => row[:streams_open], "runtime" => runtime }
55
+ end
56
+
57
+ # The rows of a minute and route are summed here: the same key can have one row per gateway worker.
58
+ def streams(rows)
59
+ rows.group_by { |row| [row[:minute], row[:route]] }.map do |(minute, route), group|
60
+ { "minute" => minute, "route" => route }.merge(StreamPoint.total(group.map { |row| stream_point(row) }))
61
+ end
62
+ end
63
+
64
+ def stream_point(row)
65
+ BatchSchema::STREAM_COUNTERS.to_h { |key| [key, row[key.to_sym]] }.merge(
66
+ "rejected" => JSON.parse(row[:rejected]), "closed" => JSON.parse(row[:closed]),
67
+ "duration" => { "count" => row[:duration_count], "sum" => row[:duration_sum],
68
+ "buckets" => JSON.parse(row[:duration_buckets]) }
69
+ )
70
+ end
71
+
72
+ def stream_columns(point)
73
+ BatchSchema::STREAM_COUNTERS.to_h { |key| [key.to_sym, point[key]] }.merge(
74
+ rejected: JSON.generate(point["rejected"]), closed: JSON.generate(point["closed"]),
75
+ duration_count: point["duration"]["count"], duration_sum: point["duration"]["sum"],
76
+ duration_buckets: JSON.generate(point["duration"]["buckets"])
77
+ )
78
+ end
79
+
80
+ def runtime_series(row)
81
+ { "minute" => row[:minute], "instance" => row[:instance], "process" => row[:process],
82
+ "in_flight" => row[:in_flight] }.merge(runtime(row))
83
+ end
84
+
85
+ def runtime(row)
86
+ pool = pool_of(row)
87
+ RUNTIME_COLUMNS.to_h { |column| [column, row[column.to_sym]] }.merge("pool" => pool)
88
+ end
89
+
90
+ def pool_of(row)
91
+ return nil if row[:pool_size].nil? && row[:pool_in_use].nil?
92
+
93
+ { "size" => row[:pool_size], "in_use" => row[:pool_in_use] }
94
+ end
95
+ end
96
+ end
97
+ end
98
+ end
99
+ end
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Boto
4
+ module ManagementUi
5
+ module Monitor
6
+ class SqlStore
7
+ # Adds the routes and operations of a batch to the per-minute series, summing with what is already there.
8
+ class SeriesWriter
9
+ EMPTY_POINT = { count: 0, sum: 0.0, buckets: Array.new(BatchSchema::BUCKET_COUNT, 0) }.freeze
10
+
11
+ def initialize(database)
12
+ @database = database
13
+ end
14
+
15
+ def write(service, minute, batch)
16
+ BatchSchema::SERIES_KINDS.each do |key, kind|
17
+ labels = BatchSchema::SERIES_LABELS.fetch(kind)
18
+ batch[key].each { |entry| add(service, minute, kind, labels, entry) }
19
+ end
20
+ end
21
+
22
+ private
23
+
24
+ # Labels that do not apply to the kind are null; `where` with nil matches IS NULL, so the row is found.
25
+ # Two gateway workers on Postgres can insert the same key at once (no unique index takes nulls), so only
26
+ # the row read is updated; the queries sum the rows of a key.
27
+ def add(service, minute, kind, labels, entry)
28
+ key = { service: service, minute: minute, kind: kind }.merge(entry.slice(*labels).transform_keys(&:to_sym))
29
+ previous = @database[:boto_monitor_series].where(key).for_update.first
30
+ if previous
31
+ @database[:boto_monitor_series].where(id: previous[:id]).update(total(point_of(previous), entry))
32
+ else
33
+ @database[:boto_monitor_series].insert(key.merge(total(EMPTY_POINT, entry)))
34
+ end
35
+ end
36
+
37
+ def point_of(row)
38
+ { count: row[:count], sum: row[:sum], buckets: JSON.parse(row[:buckets]) }
39
+ end
40
+
41
+ def total(point, entry)
42
+ {
43
+ count: point[:count] + entry["count"],
44
+ sum: point[:sum] + entry["sum"],
45
+ buckets: JSON.generate(point[:buckets].zip(entry["buckets"]).map { |old, new| old + new })
46
+ }
47
+ end
48
+ end
49
+ end
50
+ end
51
+ end
52
+ end
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Boto
4
+ module ManagementUi
5
+ module Monitor
6
+ class SqlStore
7
+ # Adds the stream routes of a batch to the per-minute sums, as SeriesWriter does for the series.
8
+ class StreamsWriter
9
+ def initialize(database)
10
+ @database = database
11
+ end
12
+
13
+ def write(service, minute, streams)
14
+ streams["routes"].each { |entry| add(service, minute, entry) }
15
+ end
16
+
17
+ private
18
+
19
+ # Only the row read is updated (see SeriesWriter): two gateway workers on Postgres can insert the same key.
20
+ def add(service, minute, entry)
21
+ key = { service: service, minute: minute, route: entry["route"] }
22
+ previous = @database[:boto_monitor_streams].where(key).for_update.first
23
+ point = StreamPoint.add(previous ? Rows.stream_point(previous) : StreamPoint.empty, entry)
24
+ if previous
25
+ @database[:boto_monitor_streams].where(id: previous[:id]).update(Rows.stream_columns(point))
26
+ else
27
+ @database[:boto_monitor_streams].insert(key.merge(Rows.stream_columns(point)))
28
+ end
29
+ end
30
+ end
31
+ end
32
+ end
33
+ end
34
+ end