cosmonats 0.7.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 (147) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +219 -113
  3. data/lib/cosmo/active_job/adapter.rb +1 -2
  4. data/lib/cosmo/api/counter.rb +17 -17
  5. data/lib/cosmo/api/cron/entry.rb +10 -11
  6. data/lib/cosmo/api/cron.rb +6 -3
  7. data/lib/cosmo/api/job.rb +1 -1
  8. data/lib/cosmo/api/kv.rb +3 -3
  9. data/lib/cosmo/api/registry.rb +1 -1
  10. data/lib/cosmo/api/stats/busy.rb +6 -1
  11. data/lib/cosmo/api/stats/metrics.rb +109 -0
  12. data/lib/cosmo/api/stats/processes.rb +14 -4
  13. data/lib/cosmo/api/stats/totals.rb +4 -12
  14. data/lib/cosmo/api/stats.rb +18 -2
  15. data/lib/cosmo/api/stream.rb +7 -2
  16. data/lib/cosmo/batch/counters.rb +19 -0
  17. data/lib/cosmo/batch.rb +6 -6
  18. data/lib/cosmo/cli.rb +21 -5
  19. data/lib/cosmo/client.rb +37 -14
  20. data/lib/cosmo/config/cosmo.yml +58 -0
  21. data/lib/cosmo/config/settings.rb +20 -0
  22. data/lib/cosmo/config.rb +144 -19
  23. data/lib/cosmo/heartbeat.rb +11 -0
  24. data/lib/cosmo/job/data.rb +17 -12
  25. data/lib/cosmo/job/enqueuer.rb +53 -0
  26. data/lib/cosmo/job/limit.rb +2 -2
  27. data/lib/cosmo/job/processor.rb +32 -58
  28. data/lib/cosmo/job/requeue.rb +20 -0
  29. data/lib/cosmo/job.rb +8 -22
  30. data/lib/cosmo/logger.rb +15 -2
  31. data/lib/cosmo/middleware/busy.rb +15 -0
  32. data/lib/cosmo/middleware/chain.rb +137 -0
  33. data/lib/cosmo/middleware/limit.rb +50 -0
  34. data/lib/cosmo/middleware/metrics.rb +39 -0
  35. data/lib/cosmo/{sentry/job_processor_middleware.rb → middleware/sentry.rb} +26 -30
  36. data/lib/cosmo/middleware/totals.rb +29 -0
  37. data/lib/cosmo/middleware.rb +7 -0
  38. data/lib/cosmo/processor.rb +11 -5
  39. data/lib/cosmo/publisher.rb +1 -13
  40. data/lib/cosmo/railtie.rb +2 -2
  41. data/lib/cosmo/services.rb +69 -0
  42. data/lib/cosmo/stream/processor.rb +7 -1
  43. data/lib/cosmo/utils/hash.rb +7 -8
  44. data/lib/cosmo/utils.rb +0 -1
  45. data/lib/cosmo/version.rb +1 -1
  46. data/lib/cosmo/web/assets/app.css +271 -571
  47. data/lib/cosmo/web/assets/app.js +158 -0
  48. data/lib/cosmo/web/assets/fonts/OFL.txt +92 -0
  49. data/lib/cosmo/web/assets/fonts/geist-mono.woff2 +0 -0
  50. data/lib/cosmo/web/assets/fonts/geist.woff2 +0 -0
  51. data/lib/cosmo/web/assets/logo.svg +10 -0
  52. data/lib/cosmo/web/cache.rb +75 -0
  53. data/lib/cosmo/web/chart.rb +122 -0
  54. data/lib/cosmo/web/circuit.rb +55 -0
  55. data/lib/cosmo/web/context.rb +0 -4
  56. data/lib/cosmo/web/controllers/application.rb +16 -0
  57. data/lib/cosmo/web/controllers/batches.rb +1 -0
  58. data/lib/cosmo/web/controllers/crons.rb +17 -2
  59. data/lib/cosmo/web/controllers/jobs.rb +59 -54
  60. data/lib/cosmo/web/controllers/metrics.rb +49 -0
  61. data/lib/cosmo/web/controllers/overview.rb +70 -0
  62. data/lib/cosmo/web/controllers/processes.rb +33 -0
  63. data/lib/cosmo/web/controllers/streams.rb +26 -28
  64. data/lib/cosmo/web/helpers/application.rb +67 -0
  65. data/lib/cosmo/web/renderer.rb +19 -6
  66. data/lib/cosmo/web/throughput.rb +104 -0
  67. data/lib/cosmo/web/views/batches/_table.erb +42 -43
  68. data/lib/cosmo/web/views/batches/index.erb +3 -10
  69. data/lib/cosmo/web/views/crons/_table.erb +32 -53
  70. data/lib/cosmo/web/views/crons/index.erb +2 -9
  71. data/lib/cosmo/web/views/jobs/_args.erb +5 -0
  72. data/lib/cosmo/web/views/jobs/_busy.erb +25 -121
  73. data/lib/cosmo/web/views/jobs/_dead.erb +42 -82
  74. data/lib/cosmo/web/views/jobs/_enqueued.erb +33 -113
  75. data/lib/cosmo/web/views/jobs/_panel.erb +29 -0
  76. data/lib/cosmo/web/views/jobs/_queue_row.erb +18 -0
  77. data/lib/cosmo/web/views/jobs/_queues.erb +20 -0
  78. data/lib/cosmo/web/views/jobs/_scheduled.erb +20 -54
  79. data/lib/cosmo/web/views/jobs/index.erb +4 -17
  80. data/lib/cosmo/web/views/layout.erb +73 -22
  81. data/lib/cosmo/web/views/metrics/_chart.erb +41 -0
  82. data/lib/cosmo/web/views/metrics/_panel.erb +13 -0
  83. data/lib/cosmo/web/views/metrics/_table.erb +25 -0
  84. data/lib/cosmo/web/views/metrics/index.erb +9 -0
  85. data/lib/cosmo/web/views/overview/_badges.erb +3 -0
  86. data/lib/cosmo/web/views/overview/_kpis.erb +19 -0
  87. data/lib/cosmo/web/views/overview/_running.erb +18 -0
  88. data/lib/cosmo/web/views/overview/_throughput.erb +50 -0
  89. data/lib/cosmo/web/views/overview/_workers.erb +25 -0
  90. data/lib/cosmo/web/views/overview/index.erb +28 -0
  91. data/lib/cosmo/web/views/processes/_table.erb +67 -0
  92. data/lib/cosmo/web/views/processes/index.erb +1 -0
  93. data/lib/cosmo/web/views/shared/_pager.erb +22 -0
  94. data/lib/cosmo/web/views/shared/unavailable.erb +7 -0
  95. data/lib/cosmo/web/views/streams/_info.erb +28 -86
  96. data/lib/cosmo/web/views/streams/_list.erb +7 -0
  97. data/lib/cosmo/web/views/streams/_pause_banner.erb +8 -16
  98. data/lib/cosmo/web/views/streams/_stream.erb +52 -0
  99. data/lib/cosmo/web/views/streams/index.erb +3 -11
  100. data/lib/cosmo/web/views/streams/info.erb +3 -11
  101. data/lib/cosmo/web.rb +67 -33
  102. data/lib/cosmo.rb +38 -0
  103. data/sig/cosmo/api/counter.rbs +2 -3
  104. data/sig/cosmo/api/cron/entry.rbs +2 -1
  105. data/sig/cosmo/api/stats/busy.rbs +3 -1
  106. data/sig/cosmo/api/stats/metrics.rbs +42 -0
  107. data/sig/cosmo/api/stats/processes.rbs +3 -0
  108. data/sig/cosmo/api/stats/totals.rbs +3 -2
  109. data/sig/cosmo/api/stats.rbs +4 -0
  110. data/sig/cosmo/api/stream.rbs +2 -0
  111. data/sig/cosmo/batch/counters.rbs +10 -0
  112. data/sig/cosmo/batch.rbs +3 -4
  113. data/sig/cosmo/cli.rbs +2 -0
  114. data/sig/cosmo/client.rbs +4 -1
  115. data/sig/cosmo/config/settings.rbs +31 -0
  116. data/sig/cosmo/config.rbs +59 -5
  117. data/sig/cosmo/heartbeat.rbs +2 -0
  118. data/sig/cosmo/job/data.rbs +5 -3
  119. data/sig/cosmo/job/enqueuer.rbs +11 -0
  120. data/sig/cosmo/job/processor.rbs +3 -5
  121. data/sig/cosmo/job/requeue.rbs +9 -0
  122. data/sig/cosmo/job.rbs +0 -2
  123. data/sig/cosmo/logger.rbs +6 -0
  124. data/sig/cosmo/middleware/chain.rbs +51 -0
  125. data/sig/cosmo/middleware/sentry.rbs +14 -0
  126. data/sig/cosmo/middleware.rbs +35 -0
  127. data/sig/cosmo/processor.rbs +2 -0
  128. data/sig/cosmo/publisher.rbs +1 -9
  129. data/sig/cosmo/services.rbs +18 -0
  130. data/sig/cosmo/stream/processor.rbs +2 -0
  131. data/sig/cosmo/utils/hash.rbs +2 -3
  132. data/sig/cosmo.rbs +11 -0
  133. metadata +60 -20
  134. data/lib/cosmo/sentry/auto.rb +0 -6
  135. data/lib/cosmo/utils/overrides.rb +0 -206
  136. data/lib/cosmo/utils/warnings.rb +0 -17
  137. data/lib/cosmo/web/controllers/actions.rb +0 -16
  138. data/lib/cosmo/web/views/actions/index.erb +0 -7
  139. data/lib/cosmo/web/views/jobs/_processes.erb +0 -131
  140. data/lib/cosmo/web/views/jobs/_stats.erb +0 -73
  141. data/lib/cosmo/web/views/jobs/_tabs.erb +0 -8
  142. data/lib/cosmo/web/views/jobs/busy.erb +0 -18
  143. data/lib/cosmo/web/views/jobs/dead.erb +0 -18
  144. data/lib/cosmo/web/views/jobs/enqueued.erb +0 -18
  145. data/lib/cosmo/web/views/jobs/scheduled.erb +0 -18
  146. data/lib/cosmo/web/views/streams/_stream_row.erb +0 -42
  147. 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
@@ -0,0 +1,122 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Cosmo
4
+ class Web
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.
8
+ class Chart
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
17
+ def initialize(series)
18
+ @series = series
19
+ @count_top = top(series.map { _1[:count] }.max.to_i)
20
+ @exec_top = top(series.filter_map { _1[:exec_ms] }.max.to_f)
21
+ end
22
+
23
+ # @return [Boolean]
24
+ def empty?
25
+ @series.all? { _1[:count].zero? }
26
+ end
27
+
28
+ # @return [String] the path of the run bars, one per day with runs
29
+ def bars # rubocop:disable Metrics/AbcSize
30
+ width = (slot * 0.6).clamp(2, BAR).round(1)
31
+ @series.each_with_index.filter_map do |day, index|
32
+ next if day[:count].zero?
33
+
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(" ")
37
+ end
38
+
39
+ # @return [String] the path of the execution time line, broken over days without a successful run
40
+ def line
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(" ")
57
+ end
58
+
59
+ # @return [Array<Hash>] +{ count:, exec_ms: }+ per grid line, top down
60
+ def ticks
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 }
63
+ end
64
+ end
65
+
66
+ # @return [Array<Hash>] +{ left:, text: }+ x axis labels in percent, thinned out to at most LABELS
67
+ def labels
68
+ every = (@series.size / LABELS.to_f).ceil.clamp(1, nil)
69
+ @series.each_with_index.filter_map do |day, index|
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]))
82
+ end
83
+ end
84
+
85
+ private
86
+
87
+ def slot
88
+ WIDTH / [@series.size, 1].max.to_f
89
+ end
90
+
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)
97
+ end
98
+
99
+ def scale(value, top)
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)
105
+ end
106
+
107
+ # The smallest "nice" axis maximum (1, 2 or 5 times a power of ten per tick) at or above +max+.
108
+ def top(max)
109
+ return TICKS if max.zero?
110
+
111
+ raw = max / TICKS.to_f
112
+ magnitude = 10**Math.log10(raw).floor
113
+ step = [1, 2, 5, 10].map { _1 * magnitude }.find { _1 >= raw }
114
+ step * TICKS
115
+ end
116
+
117
+ def label(date)
118
+ "#{date[4, 2]}/#{date[6, 2]}"
119
+ end
120
+ end
121
+ end
122
+ end
@@ -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
 
@@ -7,27 +7,36 @@ module Cosmo
7
7
  module Controllers
8
8
  class Crons < Application
9
9
  def index
10
+ return not_found unless Config.scheduled.enabled
11
+
10
12
  content_for :title, "Crons"
13
+ content_for :subtitle, "Schedules parked in NATS. NATS keeps the time."
11
14
  ok render("crons/index", layout: true)
12
15
  end
13
16
 
14
17
  def _table
18
+ return not_found unless Config.scheduled.enabled
19
+
15
20
  ok render("crons/_table", { schedules: cron.all })
16
21
  end
17
22
 
18
23
  # Dispatch the job immediately, bypassing the schedule timer.
19
24
  # Expects params["subject"] = the schedule subject stored in NATS.
20
25
  def run_now
26
+ return not_found unless Config.scheduled.enabled
27
+
21
28
  subject = Rack::Utils.unescape(params["subject"].to_s)
22
29
  cron.run_now!(subject)
23
- ok
30
+ ok flash("#{label(subject)} enqueued now")
24
31
  end
25
32
 
26
33
  # Purge the schedule from NATS so it stops firing.
27
34
  def delete
35
+ return not_found unless Config.scheduled.enabled
36
+
28
37
  subject = Rack::Utils.unescape(params["subject"].to_s)
29
38
  cron.delete!(subject)
30
- _table
39
+ ok render("crons/_table", { schedules: cron.all }) + flash("#{label(subject)} deleted")
31
40
  end
32
41
 
33
42
  private
@@ -35,6 +44,12 @@ module Cosmo
35
44
  def cron
36
45
  @cron ||= API::Cron.instance
37
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
38
53
  end
39
54
  end
40
55
  end