cosmonats 0.8.0 → 0.9.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 (92) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +21 -11
  3. data/lib/cosmo/api/counter.rb +1 -1
  4. data/lib/cosmo/api/cron/entry.rb +10 -11
  5. data/lib/cosmo/api/cron.rb +3 -3
  6. data/lib/cosmo/api/job.rb +1 -1
  7. data/lib/cosmo/api/kv.rb +3 -3
  8. data/lib/cosmo/api/stats/busy.rb +5 -0
  9. data/lib/cosmo/api/stats/metrics.rb +3 -3
  10. data/lib/cosmo/api/stats.rb +15 -0
  11. data/lib/cosmo/api/stream.rb +7 -2
  12. data/lib/cosmo/client.rb +10 -13
  13. data/lib/cosmo/job/data.rb +1 -1
  14. data/lib/cosmo/job/processor.rb +5 -6
  15. data/lib/cosmo/utils.rb +0 -1
  16. data/lib/cosmo/version.rb +1 -1
  17. data/lib/cosmo/web/assets/app.css +271 -629
  18. data/lib/cosmo/web/assets/app.js +158 -0
  19. data/lib/cosmo/web/assets/fonts/OFL.txt +92 -0
  20. data/lib/cosmo/web/assets/fonts/geist-mono.woff2 +0 -0
  21. data/lib/cosmo/web/assets/fonts/geist.woff2 +0 -0
  22. data/lib/cosmo/web/assets/logo.svg +10 -0
  23. data/lib/cosmo/web/cache.rb +75 -0
  24. data/lib/cosmo/web/chart.rb +62 -38
  25. data/lib/cosmo/web/circuit.rb +55 -0
  26. data/lib/cosmo/web/context.rb +0 -4
  27. data/lib/cosmo/web/controllers/application.rb +16 -0
  28. data/lib/cosmo/web/controllers/batches.rb +1 -0
  29. data/lib/cosmo/web/controllers/crons.rb +9 -2
  30. data/lib/cosmo/web/controllers/jobs.rb +50 -59
  31. data/lib/cosmo/web/controllers/metrics.rb +1 -0
  32. data/lib/cosmo/web/controllers/overview.rb +70 -0
  33. data/lib/cosmo/web/controllers/processes.rb +33 -0
  34. data/lib/cosmo/web/controllers/streams.rb +26 -28
  35. data/lib/cosmo/web/helpers/application.rb +57 -0
  36. data/lib/cosmo/web/renderer.rb +19 -6
  37. data/lib/cosmo/web/throughput.rb +104 -0
  38. data/lib/cosmo/web/views/batches/_table.erb +42 -54
  39. data/lib/cosmo/web/views/batches/index.erb +3 -10
  40. data/lib/cosmo/web/views/crons/_table.erb +32 -53
  41. data/lib/cosmo/web/views/crons/index.erb +2 -9
  42. data/lib/cosmo/web/views/jobs/_args.erb +5 -0
  43. data/lib/cosmo/web/views/jobs/_busy.erb +25 -121
  44. data/lib/cosmo/web/views/jobs/_dead.erb +42 -82
  45. data/lib/cosmo/web/views/jobs/_enqueued.erb +33 -113
  46. data/lib/cosmo/web/views/jobs/_panel.erb +29 -0
  47. data/lib/cosmo/web/views/jobs/_queue_row.erb +18 -0
  48. data/lib/cosmo/web/views/jobs/_queues.erb +20 -0
  49. data/lib/cosmo/web/views/jobs/_scheduled.erb +20 -54
  50. data/lib/cosmo/web/views/jobs/index.erb +4 -17
  51. data/lib/cosmo/web/views/layout.erb +73 -22
  52. data/lib/cosmo/web/views/metrics/_chart.erb +37 -32
  53. data/lib/cosmo/web/views/metrics/_panel.erb +3 -3
  54. data/lib/cosmo/web/views/metrics/_table.erb +24 -40
  55. data/lib/cosmo/web/views/metrics/index.erb +8 -16
  56. data/lib/cosmo/web/views/overview/_badges.erb +3 -0
  57. data/lib/cosmo/web/views/overview/_kpis.erb +19 -0
  58. data/lib/cosmo/web/views/overview/_running.erb +18 -0
  59. data/lib/cosmo/web/views/overview/_throughput.erb +50 -0
  60. data/lib/cosmo/web/views/overview/_workers.erb +25 -0
  61. data/lib/cosmo/web/views/overview/index.erb +28 -0
  62. data/lib/cosmo/web/views/processes/_table.erb +67 -0
  63. data/lib/cosmo/web/views/processes/index.erb +1 -0
  64. data/lib/cosmo/web/views/shared/_pager.erb +22 -0
  65. data/lib/cosmo/web/views/shared/unavailable.erb +7 -0
  66. data/lib/cosmo/web/views/streams/_info.erb +28 -86
  67. data/lib/cosmo/web/views/streams/_list.erb +7 -0
  68. data/lib/cosmo/web/views/streams/_pause_banner.erb +8 -16
  69. data/lib/cosmo/web/views/streams/_stream.erb +52 -0
  70. data/lib/cosmo/web/views/streams/index.erb +3 -11
  71. data/lib/cosmo/web/views/streams/info.erb +3 -11
  72. data/lib/cosmo/web.rb +66 -35
  73. data/sig/cosmo/api/cron/entry.rbs +2 -1
  74. data/sig/cosmo/api/stats/busy.rbs +2 -0
  75. data/sig/cosmo/api/stats/metrics.rbs +1 -1
  76. data/sig/cosmo/api/stats.rbs +4 -0
  77. data/sig/cosmo/api/stream.rbs +2 -0
  78. data/sig/cosmo/client.rbs +1 -0
  79. metadata +31 -18
  80. data/lib/cosmo/utils/overrides.rb +0 -206
  81. data/lib/cosmo/utils/warnings.rb +0 -17
  82. data/lib/cosmo/web/controllers/actions.rb +0 -16
  83. data/lib/cosmo/web/views/actions/index.erb +0 -7
  84. data/lib/cosmo/web/views/jobs/_processes.erb +0 -145
  85. data/lib/cosmo/web/views/jobs/_stats.erb +0 -77
  86. data/lib/cosmo/web/views/jobs/_tabs.erb +0 -14
  87. data/lib/cosmo/web/views/jobs/busy.erb +0 -18
  88. data/lib/cosmo/web/views/jobs/dead.erb +0 -18
  89. data/lib/cosmo/web/views/jobs/enqueued.erb +0 -18
  90. data/lib/cosmo/web/views/jobs/scheduled.erb +0 -18
  91. data/lib/cosmo/web/views/streams/_stream_row.erb +0 -42
  92. data/lib/cosmo/web/views/streams/_table.erb +0 -25
@@ -0,0 +1,158 @@
1
+ (function () {
2
+ 'use strict';
3
+
4
+ var root = document.documentElement;
5
+ var systemDark = window.matchMedia('(prefers-color-scheme: dark)');
6
+ var flashTimer;
7
+ var BACKOFF_LIMIT = 60000;
8
+
9
+ if (window.htmx) htmx.config.timeout = 20000;
10
+
11
+ function isPoller(el) {
12
+ return !!(el && el.dataset && el.dataset.poll !== undefined);
13
+ }
14
+
15
+ function pollDelay(el) {
16
+ var base = (parseFloat(el.dataset.poll) || 5) * 1000;
17
+ return Math.min(base * Math.pow(2, el.cosmoFailures || 0), Math.max(base, BACKOFF_LIMIT));
18
+ }
19
+
20
+ function poll(el) {
21
+ if (!el.isConnected) return;
22
+ if (document.hidden) {
23
+ el.cosmoHeld = true;
24
+ return;
25
+ }
26
+ htmx.trigger(el, 'cosmo:poll');
27
+ }
28
+
29
+ function schedule(el) {
30
+ clearTimeout(el.cosmoTimer);
31
+ if (el.isConnected) el.cosmoTimer = setTimeout(function () { poll(el); }, pollDelay(el));
32
+ }
33
+
34
+ function markOnline(online) {
35
+ document.body.classList.toggle('offline', !online);
36
+ var label = document.querySelector('.live-label');
37
+ if (label) label.textContent = online ? 'live' : 'offline';
38
+ }
39
+
40
+ function settled(el, failed) {
41
+ if (!el.cosmoPolling) return;
42
+ el.cosmoPolling = false;
43
+ el.cosmoFailures = failed ? (el.cosmoFailures || 0) + 1 : 0;
44
+ markOnline(!failed);
45
+ schedule(el);
46
+ }
47
+
48
+ document.addEventListener('htmx:beforeRequest', function (event) {
49
+ if (isPoller(event.detail.elt)) event.detail.elt.cosmoPolling = true;
50
+ });
51
+
52
+ document.addEventListener('htmx:afterRequest', function (event) {
53
+ if (isPoller(event.detail.elt)) settled(event.detail.elt, !event.detail.successful);
54
+ });
55
+
56
+ ['htmx:sendError', 'htmx:timeout'].forEach(function (name) {
57
+ document.addEventListener(name, function (event) {
58
+ if (isPoller(event.detail.elt)) settled(event.detail.elt, true);
59
+ });
60
+ });
61
+
62
+ document.addEventListener('visibilitychange', function () {
63
+ if (document.hidden) return;
64
+ document.querySelectorAll('[data-poll]').forEach(function (el) {
65
+ if (!el.cosmoHeld) return;
66
+ el.cosmoHeld = false;
67
+ poll(el);
68
+ });
69
+ });
70
+
71
+ if (window.htmx) {
72
+ htmx.onLoad(function (content) {
73
+ var pollers = Array.prototype.slice.call(content.querySelectorAll('[data-poll]'));
74
+ if (isPoller(content)) pollers.push(content);
75
+ pollers.forEach(function (el) {
76
+ if (!/\bload\b/.test(el.getAttribute('hx-trigger') || '')) schedule(el);
77
+ });
78
+ });
79
+ }
80
+
81
+ function store(key, value) {
82
+ try { localStorage.setItem(key, value); } catch (e) {}
83
+ }
84
+
85
+ function applyTheme(mode) {
86
+ root.dataset.themeMode = mode;
87
+ root.dataset.theme = mode === 'auto' ? (systemDark.matches ? 'dark' : 'light') : mode;
88
+ document.querySelectorAll('[data-theme-set]').forEach(function (button) {
89
+ var on = button.dataset.themeSet === mode;
90
+ button.classList.toggle('on', on);
91
+ button.setAttribute('aria-pressed', on);
92
+ });
93
+ }
94
+
95
+ systemDark.addEventListener('change', function () {
96
+ if (root.dataset.themeMode === 'auto') applyTheme('auto');
97
+ });
98
+
99
+ var actions = {
100
+ theme: function (el) {
101
+ store('cosmo-theme', el.dataset.themeSet);
102
+ applyTheme(el.dataset.themeSet);
103
+ },
104
+ 'open-menu': function () { document.body.classList.add('menu-open'); },
105
+ 'close-menu': function () { document.body.classList.remove('menu-open'); }
106
+ };
107
+
108
+ function tick() {
109
+ var clock = document.getElementById('clock');
110
+ if (clock) clock.textContent = ' · ' + new Date().toLocaleTimeString('en-GB');
111
+ }
112
+
113
+ function hideFlash() {
114
+ var flash = document.getElementById('flash');
115
+ if (!flash || !flash.textContent.trim()) return;
116
+ clearTimeout(flashTimer);
117
+ flashTimer = setTimeout(function () { flash.textContent = ''; }, 2400);
118
+ }
119
+
120
+ document.addEventListener('click', function (event) {
121
+ var el = event.target.closest('[data-action]');
122
+ if (el && actions[el.dataset.action]) actions[el.dataset.action](el);
123
+ });
124
+
125
+ document.addEventListener('keydown', function (event) {
126
+ if (event.key === 'Escape') document.body.classList.remove('menu-open');
127
+ });
128
+
129
+ window.addEventListener('resize', function () {
130
+ if (window.innerWidth > 900) document.body.classList.remove('menu-open');
131
+ });
132
+
133
+ document.addEventListener('htmx:beforeSwap', function (event) {
134
+ event.detail.target.cosmoScroll = Array.prototype.map.call(
135
+ event.detail.target.querySelectorAll('.scroll'), function (el) { return el.scrollLeft; }
136
+ );
137
+ });
138
+
139
+ document.addEventListener('htmx:afterSettle', function (event) {
140
+ var saved = event.detail.target.cosmoScroll;
141
+ if (saved) {
142
+ event.detail.target.querySelectorAll('.scroll').forEach(function (el, i) { el.scrollLeft = saved[i] || 0; });
143
+ }
144
+ hideFlash();
145
+ });
146
+
147
+ document.addEventListener('DOMContentLoaded', function () {
148
+ var reload = document.querySelector('[data-reload]');
149
+ if (reload) {
150
+ markOnline(false);
151
+ setTimeout(function () { location.reload(); }, (parseFloat(reload.dataset.reload) || 10) * 1000);
152
+ }
153
+
154
+ applyTheme(root.dataset.themeMode || 'auto');
155
+ tick();
156
+ setInterval(tick, 1000);
157
+ });
158
+ })();
@@ -0,0 +1,92 @@
1
+ Copyright (c) 2023 Vercel, in collaboration with basement.studio
2
+
3
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+ This license is copied below, and is also available with a FAQ at:
5
+ http://scripts.sil.org/OFL
6
+
7
+ -----------------------------------------------------------
8
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
9
+ -----------------------------------------------------------
10
+
11
+ PREAMBLE
12
+ The goals of the Open Font License (OFL) are to stimulate worldwide
13
+ development of collaborative font projects, to support the font creation
14
+ efforts of academic and linguistic communities, and to provide a free and
15
+ open framework in which fonts may be shared and improved in partnership
16
+ with others.
17
+
18
+ The OFL allows the licensed fonts to be used, studied, modified and
19
+ redistributed freely as long as they are not sold by themselves. The
20
+ fonts, including any derivative works, can be bundled, embedded,
21
+ redistributed and/or sold with any software provided that any reserved
22
+ names are not used by derivative works. The fonts and derivatives,
23
+ however, cannot be released under any other type of license. The
24
+ requirement for fonts to remain under this license does not apply
25
+ to any document created using the fonts or their derivatives.
26
+
27
+ DEFINITIONS
28
+ "Font Software" refers to the set of files released by the Copyright
29
+ Holder(s) under this license and clearly marked as such. This may
30
+ include source files, build scripts and documentation.
31
+
32
+ "Reserved Font Name" refers to any names specified as such after the
33
+ copyright statement(s).
34
+
35
+ "Original Version" refers to the collection of Font Software components as
36
+ distributed by the Copyright Holder(s).
37
+
38
+ "Modified Version" refers to any derivative made by adding to, deleting,
39
+ or substituting -- in part or in whole -- any of the components of the
40
+ Original Version, by changing formats or by porting the Font Software to a
41
+ new environment.
42
+
43
+ "Author" refers to any designer, engineer, programmer, technical
44
+ writer or other person who contributed to the Font Software.
45
+
46
+ PERMISSION AND CONDITIONS
47
+ Permission is hereby granted, free of charge, to any person obtaining
48
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
49
+ redistribute, and sell modified and unmodified copies of the Font
50
+ Software, subject to the following conditions:
51
+
52
+ 1) Neither the Font Software nor any of its individual components,
53
+ in Original or Modified Versions, may be sold by itself.
54
+
55
+ 2) Original or Modified Versions of the Font Software may be bundled,
56
+ redistributed and/or sold with any software, provided that each copy
57
+ contains the above copyright notice and this license. These can be
58
+ included either as stand-alone text files, human-readable headers or
59
+ in the appropriate machine-readable metadata fields within text or
60
+ binary files as long as those fields can be easily viewed by the user.
61
+
62
+ 3) No Modified Version of the Font Software may use the Reserved Font
63
+ Name(s) unless explicit written permission is granted by the corresponding
64
+ Copyright Holder. This restriction only applies to the primary font name as
65
+ presented to the users.
66
+
67
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
68
+ Software shall not be used to promote, endorse or advertise any
69
+ Modified Version, except to acknowledge the contribution(s) of the
70
+ Copyright Holder(s) and the Author(s) or with their explicit written
71
+ permission.
72
+
73
+ 5) The Font Software, modified or unmodified, in part or in whole,
74
+ must be distributed entirely under this license, and must not be
75
+ distributed under any other license. The requirement for fonts to
76
+ remain under this license does not apply to any document created
77
+ using the Font Software.
78
+
79
+ TERMINATION
80
+ This license becomes null and void if any of the above conditions are
81
+ not met.
82
+
83
+ DISCLAIMER
84
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
85
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
86
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
87
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
88
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
89
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
90
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
91
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
92
+ OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -0,0 +1,10 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
2
+ <line x1="66" y1="20" x2="76" y2="6" stroke="#0b0f1e" stroke-width="7" stroke-linecap="round"/>
3
+ <line x1="66" y1="20" x2="76" y2="6" stroke="#ECEAE2" stroke-width="3" stroke-linecap="round"/>
4
+ <circle cx="77" cy="6" r="5.5" fill="#ff8a3d" stroke="#0b0f1e" stroke-width="3"/>
5
+ <rect x="24" y="76" width="52" height="18" rx="7" fill="#e2524a" stroke="#0b0f1e" stroke-width="4"/>
6
+ <circle cx="50" cy="48" r="36" fill="#f4f1e8" stroke="#0b0f1e" stroke-width="4.5"/>
7
+ <rect x="25" y="32" width="50" height="34" rx="16" fill="#7fe3ff" stroke="#0b0f1e" stroke-width="4.5"/>
8
+ <path d="M33 47 Q34 39 43 38" stroke="#ffffff" stroke-width="4.5" fill="none" stroke-linecap="round"/>
9
+ <circle cx="64" cy="57" r="2.6" fill="#ffffff"/>
10
+ </svg>
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Cosmo
4
+ class Web
5
+ # A short-lived, process-wide cache of the web UI's refresh responses: requests for the same data, from several
6
+ # open tabs, wait for a single fetch and share its result for TTL seconds, so viewers don't multiply NATS reads.
7
+ class Cache
8
+ # Seconds a response is shared. Override with COSMO_WEB_CACHE_TTL; 0 turns the cache off.
9
+ TTL = 2
10
+ LIMIT = 256
11
+
12
+ def self.instance
13
+ @instance ||= new
14
+ end
15
+
16
+ def initialize(ttl: ENV.fetch("COSMO_WEB_CACHE_TTL", TTL).to_f)
17
+ @ttl = ttl
18
+ @lock = Mutex.new
19
+ @entries = {}
20
+ @gates = {}
21
+ end
22
+
23
+ # @param key [Object]
24
+ # @yieldreturn [Object] the value, computed only when no fresh copy is cached
25
+ # @return [Object]
26
+ def fetch(key)
27
+ return yield unless @ttl.positive?
28
+
29
+ gate(key).synchronize do
30
+ entry = read(key)
31
+ next entry.first if entry
32
+
33
+ yield.tap { |value| write(key, value) }
34
+ end
35
+ end
36
+
37
+ # Forgets every cached value, so the next request reads fresh data.
38
+ #
39
+ # @return [void]
40
+ def clear
41
+ @lock.synchronize { @entries.clear }
42
+ end
43
+
44
+ private
45
+
46
+ def gate(key)
47
+ @lock.synchronize { @gates[key] ||= Mutex.new }
48
+ end
49
+
50
+ def read(key)
51
+ @lock.synchronize do
52
+ entry = @entries[key]
53
+ entry if entry && entry.last > clock
54
+ end
55
+ end
56
+
57
+ def write(key, value)
58
+ @lock.synchronize do
59
+ prune if @entries.size >= LIMIT
60
+ @entries[key] = [value, clock + @ttl]
61
+ end
62
+ end
63
+
64
+ def prune
65
+ now = clock
66
+ @entries.delete_if { |_, (_, expires)| expires <= now }
67
+ @gates.delete_if { |key, _| !@entries.key?(key) }
68
+ end
69
+
70
+ def clock
71
+ ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
72
+ end
73
+ end
74
+ end
75
+ end
@@ -2,19 +2,18 @@
2
2
 
3
3
  module Cosmo
4
4
  class Web
5
- # Geometry for the Metrics tab's SVG chart: a bar per day for the number of runs on the left axis, and a line for
6
- # the average execution time on the right one.
5
+ # Geometry for the Metrics tab's chart: a bar per day for the number of runs on the left axis and a line for the
6
+ # average execution time on the right one, drawn into a viewBox the page stretches to its width, axes and hover
7
+ # targets laid out in percent.
7
8
  class Chart
8
- WIDTH = 760
9
- HEIGHT = 240
10
- TOP = 16
11
- BOTTOM = 212
12
- LEFT = 52
13
- RIGHT = 700
14
- TICKS = 4
15
- LABELS = 10
16
-
17
- # @param series [Array<Hash>] +{ date:, count:, exec_ms: }+ per day, oldest first
9
+ WIDTH = 1000
10
+ HEIGHT = 220
11
+ PLOT = 214
12
+ TICKS = 3
13
+ LABELS = 6
14
+ BAR = 28
15
+
16
+ # @param series [Array<Hash>] +{ date:, count:, failed:, exec_ms:, wait_ms: }+ per day, oldest first
18
17
  def initialize(series)
19
18
  @series = series
20
19
  @count_top = top(series.map { _1[:count] }.max.to_i)
@@ -26,58 +25,83 @@ module Cosmo
26
25
  @series.all? { _1[:count].zero? }
27
26
  end
28
27
 
29
- # @return [Array<Hash>] +{ x:, y:, width:, height:, title: }+
28
+ # @return [String] the path of the run bars, one per day with runs
30
29
  def bars # rubocop:disable Metrics/AbcSize
31
- @series.each_with_index.map do |day, index|
32
- height = scale(day[:count], @count_top)
33
- { x: (slot_x(index) + (slot * 0.15)).round(1), y: (BOTTOM - height).round(1), width: (slot * 0.7).round(1),
34
- height: height.round(1), title: "#{label(day[:date])}: #{day[:count]} run(s)" }
35
- end
36
- end
37
-
38
- # @return [Array<Hash>] +{ x:, y:, title: }+ for the days with an average
39
- def points
30
+ width = (slot * 0.6).clamp(2, BAR).round(1)
40
31
  @series.each_with_index.filter_map do |day, index|
41
- next unless day[:exec_ms]
32
+ next if day[:count].zero?
42
33
 
43
- { x: (slot_x(index) + (slot / 2)).round(1), y: (BOTTOM - scale(day[:exec_ms], @exec_top)).round(1),
44
- title: "#{label(day[:date])}: #{day[:exec_ms]} ms on average" }
45
- end
34
+ height = scale(day[:count], @count_top).round(1)
35
+ "M#{(center(index) - (width / 2)).round(1)} #{HEIGHT} v#{-height} h#{width} v#{height} Z"
36
+ end.join(" ")
46
37
  end
47
38
 
48
- # @return [String] the +points+ attribute of the execution time polyline
39
+ # @return [String] the path of the execution time line, broken over days without a successful run
49
40
  def line
50
- points.map { "#{_1[:x]},#{_1[:y]}" }.join(" ")
41
+ drawing = false
42
+ @series.each_with_index.filter_map do |day, index|
43
+ unless day[:exec_ms]
44
+ drawing = false
45
+ next
46
+ end
47
+
48
+ command = drawing ? "L" : "M"
49
+ drawing = true
50
+ "#{command}#{center(index).round(1)} #{exec_y(day[:exec_ms])}"
51
+ end.join(" ")
52
+ end
53
+
54
+ # @return [String] the path of the horizontal grid lines
55
+ def grid
56
+ (0..TICKS).map { "M0 #{(HEIGHT - (PLOT * _1 / TICKS.to_f)).round(1)} H#{WIDTH}" }.join(" ")
51
57
  end
52
58
 
53
- # @return [Array<Hash>] +{ y:, count:, exec_ms: }+ per horizontal grid line, bottom up
59
+ # @return [Array<Hash>] +{ count:, exec_ms: }+ per grid line, top down
54
60
  def ticks
55
- (0..TICKS).map do |step|
56
- { y: (BOTTOM - ((BOTTOM - TOP) * step / TICKS.to_f)).round(1),
57
- count: (@count_top * step / TICKS.to_f).round, exec_ms: (@exec_top * step / TICKS.to_f).round }
61
+ TICKS.downto(0).map do |step|
62
+ { count: (@count_top * step / TICKS.to_f).round, exec_ms: (@exec_top * step / TICKS.to_f).round }
58
63
  end
59
64
  end
60
65
 
61
- # @return [Array<Hash>] +{ x:, text: }+, thinned out to at most LABELS
66
+ # @return [Array<Hash>] +{ left:, text: }+ x axis labels in percent, thinned out to at most LABELS
62
67
  def labels
63
68
  every = (@series.size / LABELS.to_f).ceil.clamp(1, nil)
64
69
  @series.each_with_index.filter_map do |day, index|
65
- { x: (slot_x(index) + (slot / 2)).round(1), text: label(day[:date]) } if (index % every).zero?
70
+ { left: percent(center(index)), text: label(day[:date]) } if (index % every).zero?
71
+ end
72
+ end
73
+
74
+ # @return [Array<Hash>] per day the hover column +left+/+width+, its +center+, the execution time dot +dot+
75
+ # (nil without one) and the bar top +top+, in percent, with the day's numbers
76
+ def points # rubocop:disable Metrics/AbcSize
77
+ @series.each_with_index.map do |day, index|
78
+ bar_top = HEIGHT - scale(day[:count], @count_top)
79
+ day.merge(left: percent(slot * index), width: percent(slot), center: percent(center(index)),
80
+ dot: day[:exec_ms] && percent(exec_y(day[:exec_ms]), HEIGHT), top: percent(bar_top, HEIGHT),
81
+ label: label(day[:date]))
66
82
  end
67
83
  end
68
84
 
69
85
  private
70
86
 
71
87
  def slot
72
- (RIGHT - LEFT) / [@series.size, 1].max.to_f
88
+ WIDTH / [@series.size, 1].max.to_f
73
89
  end
74
90
 
75
- def slot_x(index)
76
- LEFT + (slot * index)
91
+ def center(index)
92
+ slot * (index + 0.5)
93
+ end
94
+
95
+ def exec_y(value)
96
+ (HEIGHT - scale(value, @exec_top)).round(1)
77
97
  end
78
98
 
79
99
  def scale(value, top)
80
- top.zero? ? 0 : (BOTTOM - TOP) * value / top.to_f
100
+ top.zero? ? 0 : PLOT * value / top.to_f
101
+ end
102
+
103
+ def percent(value, total = WIDTH)
104
+ (value / total.to_f * 100).round(2)
81
105
  end
82
106
 
83
107
  # The smallest "nice" axis maximum (1, 2 or 5 times a power of ten per tick) at or above +max+.
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Cosmo
4
+ class Web
5
+ # Keeps the web UI from tying up server threads on an unreachable NATS: it is open, and requests answer at once
6
+ # without touching NATS, while the client is disconnected or for OPEN_FOR seconds after a request failed on a
7
+ # NATS timeout or connection error. The first request after that tries NATS again.
8
+ class Circuit
9
+ OPEN_FOR = 10
10
+ ERRORS = [NATS::IO::Timeout, NATS::IO::ConnectError, NATS::IO::ConnectionClosedError,
11
+ NATS::IO::StaleConnectionError].freeze
12
+
13
+ def self.instance
14
+ @instance ||= new
15
+ end
16
+
17
+ def initialize
18
+ @lock = Mutex.new
19
+ @tripped_at = nil
20
+ end
21
+
22
+ # @return [Boolean] whether requests should skip NATS
23
+ def open?
24
+ return true if tripped?
25
+ return false if connected?
26
+
27
+ trip!
28
+ true
29
+ end
30
+
31
+ # Opens the circuit for OPEN_FOR seconds.
32
+ #
33
+ # @return [void]
34
+ def trip!
35
+ @lock.synchronize { @tripped_at = clock }
36
+ end
37
+
38
+ private
39
+
40
+ def tripped?
41
+ @lock.synchronize { @tripped_at && clock - @tripped_at < OPEN_FOR }
42
+ end
43
+
44
+ def connected?
45
+ Client.instance.nc.connected?
46
+ rescue StandardError
47
+ false
48
+ end
49
+
50
+ def clock
51
+ ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
52
+ end
53
+ end
54
+ end
55
+ end
@@ -12,10 +12,6 @@ module Cosmo
12
12
  locals.each { |k, v| instance_variable_set("@#{k}", v) }
13
13
  end
14
14
 
15
- def binding # rubocop:disable Lint/UselessMethodDefinition
16
- super
17
- end
18
-
19
15
  def content_for(name)
20
16
  @content_for[name]
21
17
  end
@@ -37,6 +37,22 @@ module Cosmo
37
37
  def hx_request?
38
38
  @request.get_header("HTTP_HX_REQUEST") == "true"
39
39
  end
40
+
41
+ # 503 while NATS is unreachable: a bare body for an htmx request, which leaves the page as it is and backs
42
+ # off, or a page that reloads itself.
43
+ def unavailable
44
+ headers = { "content-type" => "text/html; charset=utf-8", "retry-after" => Circuit::OPEN_FOR.to_s }
45
+ return respond_with(503, headers:, body: "NATS is unreachable") if hx_request?
46
+
47
+ content_for :title, "Unavailable"
48
+ content_for :subtitle, "The web UI can't reach NATS."
49
+ respond_with 503, headers:, body: render("shared/unavailable", { retry: Circuit::OPEN_FOR }, layout: true)
50
+ end
51
+
52
+ # An out-of-band swap of the page header's flash message, appended to an htmx response.
53
+ def flash(message)
54
+ %(<div id="flash" class="flash" hx-swap-oob="true">#{Rack::Utils.escape_html(message)}</div>)
55
+ end
40
56
  end
41
57
  end
42
58
  end
@@ -8,6 +8,7 @@ module Cosmo
8
8
  class Batches < Application
9
9
  def index
10
10
  content_for :title, "Batches"
11
+ content_for :subtitle, "Grouped jobs with a callback when the last one lands."
11
12
  ok render("batches/index", layout: true)
12
13
  end
13
14
 
@@ -10,6 +10,7 @@ module Cosmo
10
10
  return not_found unless Config.scheduled.enabled
11
11
 
12
12
  content_for :title, "Crons"
13
+ content_for :subtitle, "Schedules parked in NATS. NATS keeps the time."
13
14
  ok render("crons/index", layout: true)
14
15
  end
15
16
 
@@ -26,7 +27,7 @@ module Cosmo
26
27
 
27
28
  subject = Rack::Utils.unescape(params["subject"].to_s)
28
29
  cron.run_now!(subject)
29
- ok
30
+ ok flash("#{label(subject)} enqueued now")
30
31
  end
31
32
 
32
33
  # Purge the schedule from NATS so it stops firing.
@@ -35,7 +36,7 @@ module Cosmo
35
36
 
36
37
  subject = Rack::Utils.unescape(params["subject"].to_s)
37
38
  cron.delete!(subject)
38
- _table
39
+ ok render("crons/_table", { schedules: cron.all }) + flash("#{label(subject)} deleted")
39
40
  end
40
41
 
41
42
  private
@@ -43,6 +44,12 @@ module Cosmo
43
44
  def cron
44
45
  @cron ||= API::Cron.instance
45
46
  end
47
+
48
+ # "cosmo.cron.default.report_job.monthly" → "monthly", "cosmo.cron.default.report_job" → "report_job"
49
+ def label(subject)
50
+ parts = subject.split(".")
51
+ parts.size > 4 ? parts.drop(4).join(".") : parts.last
52
+ end
46
53
  end
47
54
  end
48
55
  end