cosmonats 0.8.0 → 0.10.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 (190) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +73 -22
  3. data/lib/cosmo/active_job/adapter.rb +2 -0
  4. data/lib/cosmo/active_job/executor.rb +7 -0
  5. data/lib/cosmo/active_job/options.rb +6 -0
  6. data/lib/cosmo/api/batch.rb +26 -0
  7. data/lib/cosmo/api/counter.rb +52 -4
  8. data/lib/cosmo/api/cron/entry.rb +34 -20
  9. data/lib/cosmo/api/cron.rb +24 -10
  10. data/lib/cosmo/api/job.rb +15 -1
  11. data/lib/cosmo/api/kv.rb +141 -12
  12. data/lib/cosmo/api/registry.rb +47 -6
  13. data/lib/cosmo/api/stats/jobs.rb +84 -0
  14. data/lib/cosmo/api/stats/metrics.rb +20 -9
  15. data/lib/cosmo/api/stats/processes.rb +27 -11
  16. data/lib/cosmo/api/stats/totals.rb +1 -0
  17. data/lib/cosmo/api/stats.rb +58 -7
  18. data/lib/cosmo/api/stream.rb +73 -24
  19. data/lib/cosmo/batch/callback.rb +5 -0
  20. data/lib/cosmo/batch/dispatcher.rb +4 -4
  21. data/lib/cosmo/batch.rb +34 -11
  22. data/lib/cosmo/cli.rb +6 -0
  23. data/lib/cosmo/client.rb +217 -23
  24. data/lib/cosmo/config/cosmo.yml +1 -0
  25. data/lib/cosmo/config/settings.rb +4 -0
  26. data/lib/cosmo/config.rb +58 -10
  27. data/lib/cosmo/engine.rb +28 -1
  28. data/lib/cosmo/heartbeat.rb +12 -3
  29. data/lib/cosmo/http_server/handler.rb +5 -0
  30. data/lib/cosmo/http_server/health.rb +2 -0
  31. data/lib/cosmo/http_server/ping.rb +2 -0
  32. data/lib/cosmo/http_server.rb +8 -0
  33. data/lib/cosmo/job/data.rb +12 -1
  34. data/lib/cosmo/job/enqueuer.rb +100 -1
  35. data/lib/cosmo/job/limit.rb +5 -1
  36. data/lib/cosmo/job/processor.rb +56 -21
  37. data/lib/cosmo/job/setter.rb +53 -0
  38. data/lib/cosmo/job.rb +71 -2
  39. data/lib/cosmo/logger.rb +37 -0
  40. data/lib/cosmo/middleware/chain.rb +12 -0
  41. data/lib/cosmo/middleware/limit.rb +12 -3
  42. data/lib/cosmo/middleware/metrics.rb +6 -4
  43. data/lib/cosmo/middleware/sentry.rb +6 -4
  44. data/lib/cosmo/middleware/totals.rb +5 -11
  45. data/lib/cosmo/middleware.rb +0 -1
  46. data/lib/cosmo/processor.rb +60 -3
  47. data/lib/cosmo/publisher.rb +8 -0
  48. data/lib/cosmo/services.rb +7 -2
  49. data/lib/cosmo/stream/message.rb +5 -0
  50. data/lib/cosmo/stream/processor.rb +7 -0
  51. data/lib/cosmo/stream/serializer.rb +4 -0
  52. data/lib/cosmo/stream.rb +35 -1
  53. data/lib/cosmo/utils/duration.rb +3 -0
  54. data/lib/cosmo/utils/hash.rb +12 -0
  55. data/lib/cosmo/utils/json.rb +8 -0
  56. data/lib/cosmo/utils/signal.rb +9 -0
  57. data/lib/cosmo/utils/stopwatch.rb +1 -0
  58. data/lib/cosmo/utils/string.rb +4 -0
  59. data/lib/cosmo/utils/thread_pool.rb +8 -0
  60. data/lib/cosmo/utils/ttl_cache.rb +10 -0
  61. data/lib/cosmo/utils.rb +0 -1
  62. data/lib/cosmo/version.rb +1 -1
  63. data/lib/cosmo/web/assets/app.css +273 -629
  64. data/lib/cosmo/web/assets/app.js +158 -0
  65. data/lib/cosmo/web/assets/fonts/OFL.txt +92 -0
  66. data/lib/cosmo/web/assets/fonts/geist-mono.woff2 +0 -0
  67. data/lib/cosmo/web/assets/fonts/geist.woff2 +0 -0
  68. data/lib/cosmo/web/assets/logo.svg +10 -0
  69. data/lib/cosmo/web/cache.rb +77 -0
  70. data/lib/cosmo/web/chart.rb +63 -39
  71. data/lib/cosmo/web/circuit.rb +56 -0
  72. data/lib/cosmo/web/context.rb +6 -4
  73. data/lib/cosmo/web/controllers/application.rb +42 -0
  74. data/lib/cosmo/web/controllers/batches.rb +8 -1
  75. data/lib/cosmo/web/controllers/crons.rb +24 -3
  76. data/lib/cosmo/web/controllers/jobs.rb +88 -68
  77. data/lib/cosmo/web/controllers/metrics.rb +6 -0
  78. data/lib/cosmo/web/controllers/overview.rb +88 -0
  79. data/lib/cosmo/web/controllers/processes.rb +36 -0
  80. data/lib/cosmo/web/controllers/streams.rb +38 -28
  81. data/lib/cosmo/web/helpers/application.rb +101 -0
  82. data/lib/cosmo/web/renderer.rb +36 -6
  83. data/lib/cosmo/web/throughput.rb +104 -0
  84. data/lib/cosmo/web/views/batches/_table.erb +42 -54
  85. data/lib/cosmo/web/views/batches/index.erb +3 -10
  86. data/lib/cosmo/web/views/crons/_table.erb +36 -55
  87. data/lib/cosmo/web/views/crons/index.erb +2 -9
  88. data/lib/cosmo/web/views/jobs/_args.erb +5 -0
  89. data/lib/cosmo/web/views/jobs/_busy.erb +25 -121
  90. data/lib/cosmo/web/views/jobs/_dead.erb +42 -82
  91. data/lib/cosmo/web/views/jobs/_enqueued.erb +33 -113
  92. data/lib/cosmo/web/views/jobs/_panel.erb +34 -0
  93. data/lib/cosmo/web/views/jobs/_queue_row.erb +18 -0
  94. data/lib/cosmo/web/views/jobs/_queues.erb +20 -0
  95. data/lib/cosmo/web/views/jobs/_scheduled.erb +20 -54
  96. data/lib/cosmo/web/views/jobs/index.erb +4 -17
  97. data/lib/cosmo/web/views/layout.erb +73 -22
  98. data/lib/cosmo/web/views/metrics/_chart.erb +37 -32
  99. data/lib/cosmo/web/views/metrics/_panel.erb +3 -3
  100. data/lib/cosmo/web/views/metrics/_table.erb +24 -40
  101. data/lib/cosmo/web/views/metrics/index.erb +8 -16
  102. data/lib/cosmo/web/views/overview/_badges.erb +3 -0
  103. data/lib/cosmo/web/views/overview/_kpis.erb +19 -0
  104. data/lib/cosmo/web/views/overview/_running.erb +18 -0
  105. data/lib/cosmo/web/views/overview/_throughput.erb +50 -0
  106. data/lib/cosmo/web/views/overview/_workers.erb +25 -0
  107. data/lib/cosmo/web/views/overview/index.erb +28 -0
  108. data/lib/cosmo/web/views/processes/_table.erb +67 -0
  109. data/lib/cosmo/web/views/processes/index.erb +1 -0
  110. data/lib/cosmo/web/views/shared/_pager.erb +22 -0
  111. data/lib/cosmo/web/views/shared/unavailable.erb +7 -0
  112. data/lib/cosmo/web/views/streams/_info.erb +29 -86
  113. data/lib/cosmo/web/views/streams/_list.erb +7 -0
  114. data/lib/cosmo/web/views/streams/_pause_banner.erb +8 -16
  115. data/lib/cosmo/web/views/streams/_stream.erb +53 -0
  116. data/lib/cosmo/web/views/streams/index.erb +3 -11
  117. data/lib/cosmo/web/views/streams/info.erb +3 -11
  118. data/lib/cosmo/web.rb +73 -35
  119. data/lib/cosmo.rb +33 -0
  120. data/sig/cosmo/active_job/adapter.rbs +3 -3
  121. data/sig/cosmo/active_job/options.rbs +4 -2
  122. data/sig/cosmo/api/batch.rbs +5 -3
  123. data/sig/cosmo/api/counter.rbs +16 -6
  124. data/sig/cosmo/api/cron/entry.rbs +6 -3
  125. data/sig/cosmo/api/cron.rbs +10 -4
  126. data/sig/cosmo/api/kv.rbs +21 -4
  127. data/sig/cosmo/api/registry.rbs +10 -0
  128. data/sig/cosmo/api/stats/jobs.rbs +34 -0
  129. data/sig/cosmo/api/stats/metrics.rbs +4 -1
  130. data/sig/cosmo/api/stats/processes.rbs +9 -1
  131. data/sig/cosmo/api/stats.rbs +12 -2
  132. data/sig/cosmo/api/stream.rbs +12 -5
  133. data/sig/cosmo/batch/callback.rbs +1 -1
  134. data/sig/cosmo/batch/dispatcher.rbs +1 -1
  135. data/sig/cosmo/batch.rbs +5 -5
  136. data/sig/cosmo/cli.rbs +2 -0
  137. data/sig/cosmo/client.rbs +24 -4
  138. data/sig/cosmo/config/settings.rbs +6 -0
  139. data/sig/cosmo/config.rbs +5 -5
  140. data/sig/cosmo/engine.rbs +5 -0
  141. data/sig/cosmo/heartbeat.rbs +2 -0
  142. data/sig/cosmo/job/data.rbs +3 -1
  143. data/sig/cosmo/job/enqueuer.rbs +12 -0
  144. data/sig/cosmo/job/processor.rbs +18 -3
  145. data/sig/cosmo/job/setter.rbs +20 -0
  146. data/sig/cosmo/job.rbs +10 -4
  147. data/sig/cosmo/logger.rbs +5 -3
  148. data/sig/cosmo/middleware.rbs +0 -8
  149. data/sig/cosmo/processor.rbs +14 -2
  150. data/sig/cosmo/publisher.rbs +1 -0
  151. data/sig/cosmo/stream/processor.rbs +4 -0
  152. data/sig/cosmo/stream.rbs +4 -3
  153. data/sig/cosmo/utils/hash.rbs +2 -1
  154. data/sig/cosmo/utils/signal.rbs +5 -5
  155. data/sig/cosmo/utils/string.rbs +2 -2
  156. data/sig/cosmo/utils/thread_pool.rbs +1 -1
  157. data/sig/cosmo/web/cache.rbs +35 -0
  158. data/sig/cosmo/web/chart.rbs +48 -0
  159. data/sig/cosmo/web/circuit.rbs +29 -0
  160. data/sig/cosmo/web/context.rbs +15 -0
  161. data/sig/cosmo/web/controllers/application.rbs +32 -0
  162. data/sig/cosmo/web/controllers/batches.rbs +11 -0
  163. data/sig/cosmo/web/controllers/crons.rbs +23 -0
  164. data/sig/cosmo/web/controllers/jobs.rbs +47 -0
  165. data/sig/cosmo/web/controllers/metrics.rbs +21 -0
  166. data/sig/cosmo/web/controllers/overview.rbs +31 -0
  167. data/sig/cosmo/web/controllers/processes.rbs +13 -0
  168. data/sig/cosmo/web/controllers/streams.rbs +27 -0
  169. data/sig/cosmo/web/helpers/application.rbs +61 -0
  170. data/sig/cosmo/web/renderer.rbs +33 -0
  171. data/sig/cosmo/web/throughput.rbs +45 -0
  172. data/sig/cosmo/web.rbs +25 -0
  173. data/sig/cosmo.rbs +19 -0
  174. metadata +53 -23
  175. data/lib/cosmo/api/stats/busy.rb +0 -63
  176. data/lib/cosmo/middleware/busy.rb +0 -15
  177. data/lib/cosmo/utils/overrides.rb +0 -206
  178. data/lib/cosmo/utils/warnings.rb +0 -17
  179. data/lib/cosmo/web/controllers/actions.rb +0 -16
  180. data/lib/cosmo/web/views/actions/index.erb +0 -7
  181. data/lib/cosmo/web/views/jobs/_processes.erb +0 -145
  182. data/lib/cosmo/web/views/jobs/_stats.erb +0 -77
  183. data/lib/cosmo/web/views/jobs/_tabs.erb +0 -14
  184. data/lib/cosmo/web/views/jobs/busy.erb +0 -18
  185. data/lib/cosmo/web/views/jobs/dead.erb +0 -18
  186. data/lib/cosmo/web/views/jobs/enqueued.erb +0 -18
  187. data/lib/cosmo/web/views/jobs/scheduled.erb +0 -18
  188. data/lib/cosmo/web/views/streams/_stream_row.erb +0 -42
  189. data/lib/cosmo/web/views/streams/_table.erb +0 -25
  190. data/sig/cosmo/api/stats/busy.rbs +0 -31
@@ -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,77 @@
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
+ # @return [Cache]
13
+ def self.instance
14
+ @instance ||= new
15
+ end
16
+
17
+ # @param ttl [Numeric] seconds a response is shared
18
+ def initialize(ttl: ENV.fetch("COSMO_WEB_CACHE_TTL", TTL).to_f)
19
+ @ttl = ttl
20
+ @lock = Mutex.new
21
+ @entries = {}
22
+ @gates = {}
23
+ end
24
+
25
+ # @param key [Object]
26
+ # @yieldreturn [Object] the value, computed only when no fresh copy is cached
27
+ # @return [Object]
28
+ def fetch(key)
29
+ return yield unless @ttl.positive?
30
+
31
+ gate(key).synchronize do
32
+ entry = read(key)
33
+ next entry.first if entry
34
+
35
+ yield.tap { |value| write(key, value) }
36
+ end
37
+ end
38
+
39
+ # Forgets every cached value, so the next request reads fresh data.
40
+ #
41
+ # @return [void]
42
+ def clear
43
+ @lock.synchronize { @entries.clear }
44
+ end
45
+
46
+ private
47
+
48
+ def gate(key)
49
+ @lock.synchronize { @gates[key] ||= Mutex.new }
50
+ end
51
+
52
+ def read(key)
53
+ @lock.synchronize do
54
+ entry = @entries[key]
55
+ entry if entry && entry.last > clock
56
+ end
57
+ end
58
+
59
+ def write(key, value)
60
+ @lock.synchronize do
61
+ prune if @entries.size >= LIMIT
62
+ @entries[key] = [value, clock + @ttl]
63
+ end
64
+ end
65
+
66
+ def prune
67
+ now = clock
68
+ @entries.delete_if { |_, (_, expires)| expires <= now }
69
+ @gates.delete_if { |key, _| !@entries.key?(key) }
70
+ end
71
+
72
+ def clock
73
+ ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
74
+ end
75
+ end
76
+ end
77
+ 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: }+
30
- 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
28
+ # @return [String] the path of the run bars, one per day with runs
29
+ def bars
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
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,56 @@
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
+ # @return [Circuit]
14
+ def self.instance
15
+ @instance ||= new
16
+ end
17
+
18
+ def initialize
19
+ @lock = Mutex.new
20
+ @tripped_at = nil
21
+ end
22
+
23
+ # @return [Boolean] whether requests should skip NATS
24
+ def open?
25
+ return true if tripped?
26
+ return false if connected?
27
+
28
+ trip!
29
+ true
30
+ end
31
+
32
+ # Opens the circuit for OPEN_FOR seconds.
33
+ #
34
+ # @return [void]
35
+ def trip!
36
+ @lock.synchronize { @tripped_at = clock }
37
+ end
38
+
39
+ private
40
+
41
+ def tripped?
42
+ @lock.synchronize { @tripped_at && clock - @tripped_at < OPEN_FOR }
43
+ end
44
+
45
+ def connected?
46
+ Client.instance.nc.connected?
47
+ rescue StandardError
48
+ false
49
+ end
50
+
51
+ def clock
52
+ ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
53
+ end
54
+ end
55
+ end
56
+ end
@@ -7,19 +7,21 @@ module Cosmo
7
7
  class Context
8
8
  include Helpers::Application
9
9
 
10
+ # @param locals [Hash{Symbol => Object}] set as instance variables the view reads
11
+ # @param content_for [Hash{Symbol => String}, nil] the blocks the layout yields
10
12
  def initialize(locals, content_for = nil)
11
13
  @content_for = Hash(content_for)
12
14
  locals.each { |k, v| instance_variable_set("@#{k}", v) }
13
15
  end
14
16
 
15
- def binding # rubocop:disable Lint/UselessMethodDefinition
16
- super
17
- end
18
-
17
+ # @param name [Symbol]
18
+ # @return [String, nil] the content captured under +name+
19
19
  def content_for(name)
20
20
  @content_for[name]
21
21
  end
22
22
 
23
+ # @param name [Symbol]
24
+ # @return [Boolean] whether content was captured under +name+
23
25
  def content_for?(name)
24
26
  @content_for.key?(name)
25
27
  end
@@ -6,15 +6,27 @@ module Cosmo
6
6
  class Application
7
7
  include Renderer
8
8
 
9
+ MAX_LIMIT = 100
10
+
11
+ # @param request [Rack::Request]
9
12
  def initialize(request)
10
13
  @request = request
11
14
  end
12
15
 
16
+ # Captures content the layout renders, such as the page title.
17
+ #
18
+ # @param name [Symbol]
19
+ # @param content [String]
20
+ # @return [String] the content
13
21
  def content_for(name, content)
14
22
  @content_for ||= {}
15
23
  @content_for[name] = content
16
24
  end
17
25
 
26
+ # @param template [String] the view, relative to Renderer::VIEWS_ROOT and without +.erb+
27
+ # @param locals [Hash{Symbol => Object}, nil] the view's instance variables
28
+ # @param layout [Boolean] whether to wrap the view in the page layout
29
+ # @return [String] the rendered HTML
18
30
  def render(template, locals = nil, layout: false)
19
31
  defaults = { request: @request }
20
32
  locals = Hash(locals).merge(defaults)
@@ -26,17 +38,47 @@ module Cosmo
26
38
  erb("layout", defaults, @content_for)
27
39
  end
28
40
 
41
+ # @return [Hash{String => Object}] the query and form parameters
29
42
  def params
30
43
  @request.params
31
44
  end
32
45
 
46
+ # @param default [Integer] the page size when the request names none
47
+ # @return [Integer] the requested page size, kept between 1 and MAX_LIMIT
48
+ def limit(default)
49
+ (params["limit"] || default).to_i.clamp(1, MAX_LIMIT)
50
+ end
51
+
52
+ # @return [String] the request path
33
53
  def path
34
54
  @request.path
35
55
  end
36
56
 
57
+ # @return [Boolean] whether htmx sent the request
37
58
  def hx_request?
38
59
  @request.get_header("HTTP_HX_REQUEST") == "true"
39
60
  end
61
+
62
+ # 503 while NATS is unreachable: a bare body for an htmx request, which leaves the page as it is and backs
63
+ # off, or a page that reloads itself.
64
+ #
65
+ # @return [Array] the Rack response
66
+ def unavailable
67
+ headers = { "content-type" => "text/html; charset=utf-8", "retry-after" => Circuit::OPEN_FOR.to_s }
68
+ return respond_with(503, headers:, body: "NATS is unreachable") if hx_request?
69
+
70
+ content_for :title, "Unavailable"
71
+ content_for :subtitle, "The web UI can't reach NATS."
72
+ respond_with 503, headers:, body: render("shared/unavailable", { retry: Circuit::OPEN_FOR }, layout: true)
73
+ end
74
+
75
+ # An out-of-band swap of the page header's flash message, appended to an htmx response.
76
+ #
77
+ # @param message [String] escaped before rendering
78
+ # @return [String] the HTML
79
+ def flash(message)
80
+ %(<div id="flash" class="flash" hx-swap-oob="true">#{Rack::Utils.escape_html(message)}</div>)
81
+ end
40
82
  end
41
83
  end
42
84
  end
@@ -6,13 +6,20 @@ module Cosmo
6
6
  class Web
7
7
  module Controllers
8
8
  class Batches < Application
9
+ # Renders the batches page.
10
+ #
11
+ # @return [Array] the Rack response
9
12
  def index
10
13
  content_for :title, "Batches"
14
+ content_for :subtitle, "Grouped jobs with a callback when the last one lands."
11
15
  ok render("batches/index", layout: true)
12
16
  end
13
17
 
18
+ # Renders the batches table.
19
+ #
20
+ # @return [Array] the Rack response
14
21
  def _table
15
- limit = (params["limit"] || API::Batch::LIMIT).to_i
22
+ limit = limit(API::Batch::LIMIT)
16
23
  ok render("batches/_table", { batches: API::Batch.all(limit:) })
17
24
  end
18
25
  end