@aria-framework/notify 0.3.1 → 0.5.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.
- package/README.md +90 -0
- package/assets/bell.css +75 -0
- package/assets/bell.js +68 -6
- package/assets/live.js +304 -0
- package/hub.js +237 -19
- package/index.js +1 -0
- package/package.json +34 -30
- package/views/notify/bell.ejs +5 -1
package/README.md
CHANGED
|
@@ -105,3 +105,93 @@ table and may add to it; nothing here reads a column it was not given.
|
|
|
105
105
|
|
|
106
106
|
Wire `hub.closeAll()` into graceful shutdown. An SSE response is a request that never finishes,
|
|
107
107
|
so `server.close()` otherwise waits for a drain that never comes.
|
|
108
|
+
|
|
109
|
+
## The bell
|
|
110
|
+
|
|
111
|
+
`views/notify/bell.ejs` (markup), `assets/bell.js` (behaviour) and `assets/bell.css` (the unread
|
|
112
|
+
look) ship together. Mount `assetsDir` once (e.g. at `/js/notify`), include the view and load the
|
|
113
|
+
script; the view links the stylesheet itself (local `notifAssets`, default `/js/notify`).
|
|
114
|
+
|
|
115
|
+
Unread rows sit under **New** with a count, read rows under **Earlier**; the labels appear only
|
|
116
|
+
when both groups exist. Unread is a brand-colour tint, a left edge, a dot and full-strength text;
|
|
117
|
+
read rows fade. It is not `bg-light` + bold on purpose: an app that remaps `.bg-light` in dark
|
|
118
|
+
mode made the tint the dropdown's own colour, and the bold never reached the muted title.
|
|
119
|
+
|
|
120
|
+
An app's own notifications page uses the same classes, which every page with the bell already
|
|
121
|
+
has:
|
|
122
|
+
|
|
123
|
+
```html
|
|
124
|
+
<div class="notif-section">New<span class="notif-section-count">3</span></div>
|
|
125
|
+
<a class="list-group-item notif-row is-unread" href="…">
|
|
126
|
+
<span class="notif-who">Warren</span> <span class="notif-what">replied on TBL-4821</span>
|
|
127
|
+
</a>
|
|
128
|
+
<div class="notif-section">Earlier</div>
|
|
129
|
+
<a class="list-group-item notif-row is-read" href="…">…</a>
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
Colours come from @aria-framework/theme's tokens (`--brand-rgb`, `--text`, `--text-faint`), with
|
|
133
|
+
Bootstrap's variables as the fallback.
|
|
134
|
+
|
|
135
|
+
## Live pages (0.5.0)
|
|
136
|
+
|
|
137
|
+
A page that should follow a running job or a list as it changes rides the bell's stream — **no new
|
|
138
|
+
connection, no new channel**. It is the entities channel above, with three additions.
|
|
139
|
+
|
|
140
|
+
**Topics.** A stream may watch up to 8 `type:id` keys, not just one record. A topic is an entity key
|
|
141
|
+
that names something wider than a record: `ask-bench:house` (a running job), `work:p3` (partner 3's
|
|
142
|
+
queue), `work:c12` (one customer's). The frame is still `{type, id}` and nothing else.
|
|
143
|
+
|
|
144
|
+
```js
|
|
145
|
+
// main — the hub with the per-event check (below)
|
|
146
|
+
const hub = notify.createHub({ authorize });
|
|
147
|
+
|
|
148
|
+
// the stream route: topics the app has checked at attach, and the session for the caps
|
|
149
|
+
hub.subscribe(userId, res, { topics: [{ type: 'work', id: 'p3' }], sessionId: req.sessionID, meta: { ctx } });
|
|
150
|
+
|
|
151
|
+
// a write — on the main thread, after db.invoke returned
|
|
152
|
+
hub.publishSoon('work', 'p3'); // coalesced: one frame per topic per 750 ms
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
**Caps.** 6 LIVE streams (streams watching a topic) per session, 12 per user, 1000 streams of any kind per
|
|
156
|
+
process, 8 topics per stream (`LIMITS`; `createHub({ limits })` changes them, none can be switched off). A
|
|
157
|
+
bell-only stream is not under the live caps, so the bell never loses to a seventh tab; bell-only streams have
|
|
158
|
+
their own cap, 20 per USER (`bellPerUser`), so one user cannot fill the process and starve everyone else — over it
|
|
159
|
+
that user's OLDEST bell stream is evicted. Over the session or user cap the OLDEST live stream is evicted (`live-stop evicted`), never the new one — which also clears a
|
|
160
|
+
half-open stream a sleeping laptop left behind. Too many topics or a full process refuse the new stream
|
|
161
|
+
(`too_many_topics`, `busy`). After a `live-stop` bell.js closes the stream and reopens it ONCE without its
|
|
162
|
+
topics, so the bell goes on; a bell-only stream that is stopped is not reopened. A stream lives 60 minutes, then
|
|
163
|
+
is told `live-renew` and ended; bell.js reopens it at once, the page catches up, and the new stream is judged
|
|
164
|
+
afresh, so no scope outlives it. `publishSoon` arms nothing for a topic nobody watches.
|
|
165
|
+
|
|
166
|
+
**The per-event check.** `createHub({ authorize })` — `async ({ userId, sessionId, topic, meta }) =>
|
|
167
|
+
true | false | { stop: reason }`. A frame reaches a subscription only when it answered exactly
|
|
168
|
+
`true`; `false` (or anything else) drops that frame; `{stop}` or a throw ends the stream with that
|
|
169
|
+
reason (`check_failed` for a throw). The answer is reused for at most 5 s (`recheckMs`) per
|
|
170
|
+
subscription and topic, so a burst of fifty events costs one session-store read — and a revoked
|
|
171
|
+
session gets at most 5 s of contentless nudges, each of whose re-fetches its own route refuses. The
|
|
172
|
+
app decides what "may still see" means: re-read the STORED session (signed out, idle, session
|
|
173
|
+
version, act-as switched), and the topic's permission at that scope. That is two locks: the check
|
|
174
|
+
decides who is nudged, and the route's RBAC and RLS still decide what they see.
|
|
175
|
+
|
|
176
|
+
**The client.** Load `assets/live.js` after `bell.js`. A region is an element with an `id` and
|
|
177
|
+
`data-live-topic="type:id …"`; on a frame for one of its topics the page is re-fetched **through its own URL**
|
|
178
|
+
(or that region's own `data-live-src`) and the region replaced by the element with the same id in the answer —
|
|
179
|
+
an answer without it (a sign-in page) changes nothing. The re-fetch carries `X-Live-Fragment: 1`, which
|
|
180
|
+
@aria-framework/auth 0.16.0 lets through WITHOUT counting as activity, so a page left open still idles out. A
|
|
181
|
+
region a person is working in is HELD, not swapped: the focus anywhere inside it, an open modal (`.modal.show`), or
|
|
182
|
+
a control or details/dialog open state that differs from the region's BASELINE — its state when live.js started, at
|
|
183
|
+
DOMContentLoaded and load (for a region nobody is in: a page script setting a value is not work) and after every swap.
|
|
184
|
+
Not the HTML defaults: a `<select>` with no `selected` option, a script-set value and a server-drawn
|
|
185
|
+
`<details open>` are not work. It is re-checked every 2 s, and a held region stays held through a submit that did
|
|
186
|
+
not navigate. Every swap is announced as
|
|
187
|
+
`aria:live-swapped` (`{ id, el }`) so scripts can re-bind (@aria-framework/server 0.17.0's pager and bulk select
|
|
188
|
+
listen on the document and need nothing). `data-live-list` makes it a list of `[data-row-id]` rows (the marker may
|
|
189
|
+
sit on the row or its first cell): with `data-live-insert` (draw it on page 1, default sort, no filter) and nothing
|
|
190
|
+
ticked, new rows are put in and marked New; otherwise a bar says "N new. Show them". Every reconnect catches every
|
|
191
|
+
region up once (there is no replay). When the stream drops or is stopped, a strip says "Live updates paused" with a
|
|
192
|
+
Refresh button. Frames that arrive after this page submitted a form are ignored (the mid-navigation trap above)
|
|
193
|
+
until the page navigates — or, for a submit that does not (a download, `target=_blank`), until it is visible again
|
|
194
|
+
or 8 s pass; a submit a script prevented is not a navigation.
|
|
195
|
+
|
|
196
|
+
Still one process: a write in another process (an ingest server, a node server) reaches no stream
|
|
197
|
+
here. Such a page needs a re-check in the web process, or a shared bus — neither is in this module.
|
package/assets/bell.css
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/* @aria-framework/notify — unread vs read, for the bell AND an app's own notifications page.
|
|
2
|
+
*
|
|
3
|
+
* Linked by views/notify/bell.ejs, so every page with the bell has these classes.
|
|
4
|
+
*
|
|
5
|
+
* Unread used to be Bootstrap's `bg-light fw-semibold`. In dark mode an app that remaps
|
|
6
|
+
* .bg-light to its page colour made the tint the dropdown's own colour (invisible), and on
|
|
7
|
+
* white #F8F9FA was barely there. The bold only reached the actor's name, because the title is
|
|
8
|
+
* muted. So unread now carries three cues: a tint and an edge built from the BRAND colour
|
|
9
|
+
* (visible on light and dark), a dot, and full-strength text. Read rows fade.
|
|
10
|
+
*
|
|
11
|
+
* Colours come from @aria-framework/theme's tokens, falling back to Bootstrap's own variables,
|
|
12
|
+
* so an app without the theme still gets a working look.
|
|
13
|
+
*
|
|
14
|
+
* .notif-row any row (bell item or list-group item)
|
|
15
|
+
* .notif-row.is-unread tint + edge + dot + strong text
|
|
16
|
+
* .notif-row.is-read faded text
|
|
17
|
+
* .notif-section the "New" / "Earlier" label; .notif-section-count is the pill on "New"
|
|
18
|
+
*/
|
|
19
|
+
.notif-row{
|
|
20
|
+
position:relative;
|
|
21
|
+
padding-left:1.75rem !important;
|
|
22
|
+
white-space:normal;
|
|
23
|
+
}
|
|
24
|
+
.notif-row.is-unread{
|
|
25
|
+
background-color:rgba(var(--brand-rgb, var(--bs-primary-rgb)), .12);
|
|
26
|
+
box-shadow:inset 3px 0 0 var(--brand, var(--bs-primary));
|
|
27
|
+
}
|
|
28
|
+
.notif-row.is-unread:hover,
|
|
29
|
+
.notif-row.is-unread:focus{
|
|
30
|
+
background-color:rgba(var(--brand-rgb, var(--bs-primary-rgb)), .2);
|
|
31
|
+
}
|
|
32
|
+
.notif-row.is-unread::before{
|
|
33
|
+
content:"";
|
|
34
|
+
position:absolute;
|
|
35
|
+
left:.7rem;
|
|
36
|
+
top:1.05em;
|
|
37
|
+
width:8px;
|
|
38
|
+
height:8px;
|
|
39
|
+
border-radius:50%;
|
|
40
|
+
background:var(--brand, var(--bs-primary));
|
|
41
|
+
}
|
|
42
|
+
.notif-row.is-unread .notif-who,
|
|
43
|
+
.notif-row.is-unread .notif-what{
|
|
44
|
+
color:var(--text, var(--bs-body-color)) !important;
|
|
45
|
+
font-weight:600;
|
|
46
|
+
}
|
|
47
|
+
.notif-row.is-read .notif-who,
|
|
48
|
+
.notif-row.is-read .notif-what{
|
|
49
|
+
color:var(--text-faint, var(--bs-secondary-color)) !important;
|
|
50
|
+
font-weight:400;
|
|
51
|
+
}
|
|
52
|
+
.notif-section{
|
|
53
|
+
font-family:var(--font-mono, var(--bs-font-monospace));
|
|
54
|
+
font-size:.66rem;
|
|
55
|
+
letter-spacing:.08em;
|
|
56
|
+
text-transform:uppercase;
|
|
57
|
+
color:var(--text-faint, var(--bs-secondary-color));
|
|
58
|
+
padding:.5rem .9rem .25rem;
|
|
59
|
+
}
|
|
60
|
+
.notif-section-count{
|
|
61
|
+
display:inline-block;
|
|
62
|
+
margin-left:.4rem;
|
|
63
|
+
padding:0 .4rem;
|
|
64
|
+
border-radius:99px;
|
|
65
|
+
background:var(--bs-danger);
|
|
66
|
+
color:#fff;
|
|
67
|
+
font-family:var(--bs-body-font-family);
|
|
68
|
+
letter-spacing:0;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/* ── Live page regions (assets/live.js, 0.5.0) ─────────────────────────────────────────────── */
|
|
72
|
+
.live-paused{opacity:.6;transition:opacity .2s;}
|
|
73
|
+
.live-new{background:rgba(var(--brand-rgb, var(--bs-primary-rgb)), .07);transition:background 2s;}
|
|
74
|
+
.live-new-pill{display:inline-block;margin-right:.4em;padding:0 .45em;border-radius:1em;font-size:.72em;font-weight:600;
|
|
75
|
+
background:rgba(var(--brand-rgb, var(--bs-primary-rgb)), .14);color:var(--text, var(--bs-body-color));vertical-align:.1em;}
|
package/assets/bell.js
CHANGED
|
@@ -25,6 +25,20 @@
|
|
|
25
25
|
* somebody is typing. Extra stream query params come from any page element carrying
|
|
26
26
|
* data-notif-stream-param="key=value" (a ticket page watching itself rides the same connection).
|
|
27
27
|
*
|
|
28
|
+
* LIVE PAGES (0.5.0) ride the same connection. Every element carrying data-live-topic="type:id …"
|
|
29
|
+
* adds `topic=type:id` to the stream URL (assets/live.js re-fetches those regions), and frames for
|
|
30
|
+
* a topic the page watches are quiet — they are not the bell's business. Two frames are the server
|
|
31
|
+
* speaking to THIS file:
|
|
32
|
+
* live-stop the stream's LIVE part was refused or stopped (a cap, a check, a signed-out session).
|
|
33
|
+
* A stream that asked for topics is closed and reopened ONCE WITHOUT them, so the bell
|
|
34
|
+
* keeps working (bell-only streams are not capped per session or user); the topics are
|
|
35
|
+
* never asked for again on this page. A bell-only stream that is stopped is closed and
|
|
36
|
+
* NOT reopened — the browser's own retry would otherwise ask every 5 s for a stream the
|
|
37
|
+
* server has just refused. A reload, or the next page, asks afresh.
|
|
38
|
+
* live-renew the stream reached its lifetime: reopened at once (a reconnect, so the page's
|
|
39
|
+
* regions catch up), never left to the 5 s retry.
|
|
40
|
+
* A dropped stream is announced as 'aria:sse-down' (assets/live.js shows "Live updates paused").
|
|
41
|
+
*
|
|
28
42
|
* XSS-safe by construction: rows are createElement/textContent, and only a same-origin PATH may
|
|
29
43
|
* become a row's href — a link that ever carried attacker-influenced text (javascript: or
|
|
30
44
|
* //host) would execute or leave the site on click.
|
|
@@ -43,6 +57,19 @@
|
|
|
43
57
|
var BASE = menu.getAttribute('data-notif-base') || '/notifications';
|
|
44
58
|
var FILL = menu.getAttribute('data-notif-fill') || 'load';
|
|
45
59
|
var QUIET = (menu.getAttribute('data-notif-quiet') || '').split(',').map(function (s) { return s.trim(); }).filter(Boolean);
|
|
60
|
+
QUIET.push('live-stop', 'live-renew');
|
|
61
|
+
|
|
62
|
+
/** The topics this page watches (data-live-topic, space-separated `type:id` keys), de-duplicated. */
|
|
63
|
+
function liveTopics() {
|
|
64
|
+
var out = [];
|
|
65
|
+
document.querySelectorAll('[data-live-topic]').forEach(function (el) {
|
|
66
|
+
(el.getAttribute('data-live-topic') || '').split(/\s+/).forEach(function (t) {
|
|
67
|
+
if (t && out.indexOf(t) === -1) out.push(t);
|
|
68
|
+
});
|
|
69
|
+
});
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
var TOPICS = liveTopics(); // emptied after a live-stop: the bell goes on alone
|
|
46
73
|
var tokenMeta = document.querySelector('meta[name="csrf-token"]');
|
|
47
74
|
var csrf = tokenMeta ? tokenMeta.getAttribute('content') : '';
|
|
48
75
|
|
|
@@ -74,18 +101,20 @@
|
|
|
74
101
|
function row(item) {
|
|
75
102
|
var a = document.createElement('a');
|
|
76
103
|
a.href = safeHref(item.link);
|
|
77
|
-
|
|
78
|
-
|
|
104
|
+
// Unread vs read is bell.css's (.notif-row.is-unread / .is-read), NOT bg-light + bold: an app
|
|
105
|
+
// that remaps .bg-light in dark mode made the tint the dropdown's own colour.
|
|
106
|
+
a.className = 'dropdown-item py-2 border-bottom notif-row ' + (item.is_read ? 'is-read' : 'is-unread');
|
|
79
107
|
|
|
80
108
|
var top = document.createElement('div');
|
|
81
109
|
top.className = 'small';
|
|
82
110
|
if (item.actor_name) {
|
|
83
111
|
var who = document.createElement('span');
|
|
112
|
+
who.className = 'notif-who';
|
|
84
113
|
who.textContent = item.actor_name + ' ';
|
|
85
114
|
top.appendChild(who);
|
|
86
115
|
}
|
|
87
116
|
var what = document.createElement('span');
|
|
88
|
-
what.className = '
|
|
117
|
+
what.className = 'notif-what';
|
|
89
118
|
what.textContent = item.title || '';
|
|
90
119
|
top.appendChild(what);
|
|
91
120
|
a.appendChild(top);
|
|
@@ -112,7 +141,28 @@
|
|
|
112
141
|
list.appendChild(empty);
|
|
113
142
|
return;
|
|
114
143
|
}
|
|
115
|
-
|
|
144
|
+
// Unread under "New (n)", read under "Earlier". Labels only when both groups exist: one label
|
|
145
|
+
// over the whole list says nothing.
|
|
146
|
+
var fresh = data.items.filter(function (it) { return !it.is_read; });
|
|
147
|
+
var seen = data.items.filter(function (it) { return it.is_read; });
|
|
148
|
+
var both = fresh.length && seen.length;
|
|
149
|
+
if (fresh.length && (both || !seen.length)) list.appendChild(section('New', fresh.length));
|
|
150
|
+
fresh.forEach(function (it) { list.appendChild(row(it)); });
|
|
151
|
+
if (both) list.appendChild(section('Earlier'));
|
|
152
|
+
seen.forEach(function (it) { list.appendChild(row(it)); });
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function section(label, count) {
|
|
156
|
+
var h = document.createElement('div');
|
|
157
|
+
h.className = 'notif-section';
|
|
158
|
+
h.textContent = label;
|
|
159
|
+
if (count) {
|
|
160
|
+
var pill = document.createElement('span');
|
|
161
|
+
pill.className = 'notif-section-count';
|
|
162
|
+
pill.textContent = count > 99 ? '99+' : String(count);
|
|
163
|
+
h.appendChild(pill);
|
|
164
|
+
}
|
|
165
|
+
return h;
|
|
116
166
|
}
|
|
117
167
|
|
|
118
168
|
function sync() {
|
|
@@ -137,6 +187,7 @@
|
|
|
137
187
|
// ── The stream ──────────────────────────────────────────────────────────────────────────────
|
|
138
188
|
var es = null;
|
|
139
189
|
var firstOpen = true;
|
|
190
|
+
var stopped = false; // a live-stop: this page does not ask again
|
|
140
191
|
|
|
141
192
|
function streamUrl() {
|
|
142
193
|
var params = [];
|
|
@@ -144,11 +195,12 @@
|
|
|
144
195
|
var p = el.getAttribute('data-notif-stream-param');
|
|
145
196
|
if (p) params.push(p);
|
|
146
197
|
});
|
|
198
|
+
TOPICS.forEach(function (t) { params.push('topic=' + encodeURIComponent(t)); });
|
|
147
199
|
return BASE + '/stream' + (params.length ? '?' + params.join('&') : '');
|
|
148
200
|
}
|
|
149
201
|
|
|
150
202
|
function openStream() {
|
|
151
|
-
if (!window.EventSource || es) return;
|
|
203
|
+
if (!window.EventSource || es || stopped) return;
|
|
152
204
|
try {
|
|
153
205
|
es = new EventSource(streamUrl());
|
|
154
206
|
es.onmessage = function (ev) {
|
|
@@ -158,7 +210,17 @@
|
|
|
158
210
|
// ticket page, a draft indicator, a version-skew banner) ride this connection without
|
|
159
211
|
// knowing it exists, and without burning a second one.
|
|
160
212
|
if (d) document.dispatchEvent(new CustomEvent('aria:sse', { detail: d }));
|
|
161
|
-
if (
|
|
213
|
+
if (d && d.type === 'live-stop') {
|
|
214
|
+
closeStream();
|
|
215
|
+
if (TOPICS.length) { TOPICS = []; openStream(); } else { stopped = true; }
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
if (d && d.type === 'live-renew') { closeStream(); openStream(); return; }
|
|
219
|
+
var forPage = !!d && d.id != null && TOPICS.indexOf(d.type + ':' + d.id) !== -1;
|
|
220
|
+
if (!forPage && (!d || QUIET.indexOf(d.type) === -1)) sync();
|
|
221
|
+
};
|
|
222
|
+
es.onerror = function () {
|
|
223
|
+
document.dispatchEvent(new CustomEvent('aria:sse-down', { detail: {} }));
|
|
162
224
|
};
|
|
163
225
|
es.onopen = function () {
|
|
164
226
|
sync(); // self-heal the badge on every open, reconnects included
|
package/assets/live.js
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @aria-framework/notify — live page regions (0.5.0). Loaded AFTER bell.js, which owns the page's
|
|
3
|
+
* one stream; this file opens nothing. It listens to the DOM events bell.js re-dispatches.
|
|
4
|
+
*
|
|
5
|
+
* MARKUP CONTRACT:
|
|
6
|
+
* <div id="…" data-live-topic="work:p3 work:c12">…</div>
|
|
7
|
+
* A REGION. It must have an id. When a frame for one of its topics arrives (`{type, id}` —
|
|
8
|
+
* contentless), the page is re-fetched THROUGH ITS OWN ROUTE (data-live-src, default the
|
|
9
|
+
* page's own URL) and the region is replaced by the element with the same id in the answer.
|
|
10
|
+
* So the route's RBAC and RLS decide what the region shows, exactly as on a reload. An answer
|
|
11
|
+
* without that element (a sign-in page answers 200 too) changes nothing.
|
|
12
|
+
* data-live-list on a region
|
|
13
|
+
* A LIST: rows are its [data-row-id] elements. Rows the answer has and the page has not are
|
|
14
|
+
* NEW. With data-live-insert on the region (the server draws it on page 1, default sort, no
|
|
15
|
+
* filter) and no checkbox ticked inside it, the region is replaced and the new rows marked
|
|
16
|
+
* `.live-new` with a "New" pill; otherwise the region stays as it is and a bar says
|
|
17
|
+
* "N new. Show them" (a click replaces it). A list a person is working in never moves.
|
|
18
|
+
*
|
|
19
|
+
* WHEN A REGION RE-FETCHES
|
|
20
|
+
* - a frame for one of its topics (coalesced: one fetch however many frames arrive meanwhile);
|
|
21
|
+
* - every RECONNECT (aria:sse-open with firstOpen === false) — all regions, once: a missed event
|
|
22
|
+
* is caught up by reading the state, there is no replay;
|
|
23
|
+
* - never while a field inside it has focus (deferred until it loses it), so a half-typed value
|
|
24
|
+
* is not swapped away.
|
|
25
|
+
*
|
|
26
|
+
* WHAT IT IGNORES: frames that arrive after a form on this page was submitted. A form POST is a
|
|
27
|
+
* navigation, but the browser keeps this page (and its stream) until the answer arrives, so the
|
|
28
|
+
* push written while handling it reaches the very page that caused it (README, "A push reaches the
|
|
29
|
+
* page that CAUSED it"). A submit a script prevented is not a navigation and sets nothing.
|
|
30
|
+
*
|
|
31
|
+
* "LIVE UPDATES PAUSED": a strip above the first region, with a Refresh button, when the stream
|
|
32
|
+
* drops (aria:sse-down) or is stopped (a live-stop frame — "too many open tabs" for too_many); the
|
|
33
|
+
* regions are dimmed. It clears on the next open, which also catches the regions up. A hidden tab
|
|
34
|
+
* closes its stream on purpose (bell.js) and shows no strip.
|
|
35
|
+
*/
|
|
36
|
+
(function () {
|
|
37
|
+
'use strict';
|
|
38
|
+
|
|
39
|
+
var REGIONS = [].slice.call(document.querySelectorAll('[data-live-topic][id]'));
|
|
40
|
+
if (!REGIONS.length) return;
|
|
41
|
+
|
|
42
|
+
var leaving = false; // a form on this page was submitted: its own push is not news
|
|
43
|
+
var leavingTimer = null;
|
|
44
|
+
var busy = false;
|
|
45
|
+
var pending = null; // ids of regions due another fetch once the one in flight lands
|
|
46
|
+
var held = []; // ids of regions skipped because a person is working in them
|
|
47
|
+
var heldTimer = null;
|
|
48
|
+
var stopped = null; // the live-stop reason: the stream has no topics any more (bell.js reopens it bell-only)
|
|
49
|
+
var strip = null;
|
|
50
|
+
var LEAVE_MS = 8000; // a submit that has not navigated by then did not navigate (a download, target=_blank)
|
|
51
|
+
var HELD_MS = 2000;
|
|
52
|
+
|
|
53
|
+
function topicsOf(el) {
|
|
54
|
+
return (el.getAttribute('data-live-topic') || '').split(/\s+/).filter(Boolean);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
document.addEventListener('submit', function (ev) {
|
|
58
|
+
// Read AFTER every handler has run — a document-level confirmation registered after this file (form-ui.js) may
|
|
59
|
+
// still cancel it, and a cancelled submit is not a navigation.
|
|
60
|
+
setTimeout(function () { if (!ev.defaultPrevented) startLeaving(); }, 0);
|
|
61
|
+
});
|
|
62
|
+
function startLeaving() {
|
|
63
|
+
leaving = true;
|
|
64
|
+
// A submit that does not navigate (a download, a form with target=_blank) leaves this page in place:
|
|
65
|
+
// after LEAVE_MS, or when the page is shown again, it is listening again.
|
|
66
|
+
if (leavingTimer) clearTimeout(leavingTimer);
|
|
67
|
+
leavingTimer = setTimeout(function () { leaving = false; leavingTimer = null; }, LEAVE_MS);
|
|
68
|
+
}
|
|
69
|
+
window.addEventListener('pageshow', function (ev) { if (ev.persisted) leaving = false; });
|
|
70
|
+
document.addEventListener('visibilitychange', function () { if (document.visibilityState === 'visible') leaving = false; });
|
|
71
|
+
|
|
72
|
+
// ── The strip ─────────────────────────────────────────────────────────────────────────────
|
|
73
|
+
function showStrip(reason) {
|
|
74
|
+
if (leaving) return;
|
|
75
|
+
if (!strip) {
|
|
76
|
+
strip = document.createElement('div');
|
|
77
|
+
strip.className = 'live-strip alert alert-warning d-flex align-items-center gap-2 py-2 small';
|
|
78
|
+
strip.setAttribute('role', 'status');
|
|
79
|
+
strip.setAttribute('data-live-strip', '');
|
|
80
|
+
var words = document.createElement('span');
|
|
81
|
+
words.className = 'flex-grow-1';
|
|
82
|
+
words.setAttribute('data-live-strip-words', '');
|
|
83
|
+
strip.appendChild(words);
|
|
84
|
+
var btn = document.createElement('button');
|
|
85
|
+
btn.type = 'button';
|
|
86
|
+
btn.className = 'btn btn-sm btn-outline-secondary';
|
|
87
|
+
btn.textContent = 'Refresh';
|
|
88
|
+
btn.addEventListener('click', function () { window.location.reload(); });
|
|
89
|
+
strip.appendChild(btn);
|
|
90
|
+
REGIONS[0].parentNode.insertBefore(strip, REGIONS[0]);
|
|
91
|
+
}
|
|
92
|
+
strip.querySelector('[data-live-strip-words]').textContent = (reason === 'too_many' || reason === 'evicted')
|
|
93
|
+
? 'Live updates paused: too many open tabs. Close one and refresh, or refresh to see changes.'
|
|
94
|
+
: 'Live updates paused. Refresh to see changes.';
|
|
95
|
+
strip.hidden = false;
|
|
96
|
+
REGIONS.forEach(function (r) { r.classList.add('live-paused'); });
|
|
97
|
+
}
|
|
98
|
+
function clearStrip() {
|
|
99
|
+
if (strip) strip.hidden = true;
|
|
100
|
+
REGIONS.forEach(function (r) { r.classList.remove('live-paused'); });
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// ── Re-fetch and swap ─────────────────────────────────────────────────────────────────────
|
|
104
|
+
/**
|
|
105
|
+
* IS A PERSON WORKING IN THIS REGION? Then it is not swapped, and not swapped later behind their back
|
|
106
|
+
* either: it is held until none of these is true, re-checked every HELD_MS.
|
|
107
|
+
* - the focus is anywhere inside it (a field, a button, a link);
|
|
108
|
+
* - a control in it, or a details/dialog's open state, differs from the region's BASELINE (a half-typed
|
|
109
|
+
* value, a changed select or box, a details opened or closed; in a LIST the row boxes are the list's own
|
|
110
|
+
* business: a ticked one shows the "N new" bar instead);
|
|
111
|
+
* - an open modal (.modal.show) is inside it.
|
|
112
|
+
* THE BASELINE is the state as the page had it before anyone could work in it — recorded when this file
|
|
113
|
+
* starts, again at DOMContentLoaded and load for a region nobody is in (a page script that sets a value at
|
|
114
|
+
* load is not a person), and after every swap once aria:live-swapped's listeners have run. Not the HTML
|
|
115
|
+
* defaults: a <select> with no `selected` option has its first one selected but not defaultSelected, a
|
|
116
|
+
* script-set value is not its defaultValue, and a server-drawn <details open> is open — none is work.
|
|
117
|
+
*/
|
|
118
|
+
var baseline = {}; // region id -> stateOf(region) as the page had it
|
|
119
|
+
|
|
120
|
+
function stateOf(el) {
|
|
121
|
+
var list = el.hasAttribute('data-live-list');
|
|
122
|
+
var out = [];
|
|
123
|
+
var fields = el.querySelectorAll('input, textarea, select');
|
|
124
|
+
for (var i = 0; i < fields.length; i++) {
|
|
125
|
+
var f = fields[i];
|
|
126
|
+
if (f.tagName === 'SELECT') {
|
|
127
|
+
var sel = [];
|
|
128
|
+
for (var j = 0; j < f.options.length; j++) if (f.options[j].selected) sel.push(j);
|
|
129
|
+
out.push('s' + sel.join('.'));
|
|
130
|
+
} else if (f.type === 'checkbox' || f.type === 'radio') {
|
|
131
|
+
out.push(list && f.type === 'checkbox' ? '-' : (f.checked ? 'c1' : 'c0'));
|
|
132
|
+
} else if (f.type === 'hidden') {
|
|
133
|
+
out.push('-');
|
|
134
|
+
} else {
|
|
135
|
+
out.push('v' + f.value.length + ':' + f.value);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
var opens = el.querySelectorAll('details, dialog');
|
|
139
|
+
for (var k = 0; k < opens.length; k++) out.push(opens[k].hasAttribute('open') ? 'o1' : 'o0');
|
|
140
|
+
return out.join('|');
|
|
141
|
+
}
|
|
142
|
+
function focusIn(el) {
|
|
143
|
+
var a = document.activeElement;
|
|
144
|
+
return !!(a && a !== document.body && el.contains(a));
|
|
145
|
+
}
|
|
146
|
+
function record(el) { baseline[el.id] = stateOf(el); }
|
|
147
|
+
function recordIdle() { REGIONS.forEach(function (r) { if (!focusIn(r) && !r.querySelector('.modal.show')) record(r); }); }
|
|
148
|
+
REGIONS.forEach(record);
|
|
149
|
+
document.addEventListener('DOMContentLoaded', recordIdle);
|
|
150
|
+
window.addEventListener('load', recordIdle);
|
|
151
|
+
function workedIn(el) {
|
|
152
|
+
if (focusIn(el)) return true;
|
|
153
|
+
if (el.querySelector('.modal.show')) return true;
|
|
154
|
+
return stateOf(el) !== baseline[el.id];
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function hold(ids) {
|
|
158
|
+
ids.forEach(function (id) { if (held.indexOf(id) === -1) held.push(id); });
|
|
159
|
+
if (heldTimer) return;
|
|
160
|
+
heldTimer = setTimeout(function () {
|
|
161
|
+
heldTimer = null;
|
|
162
|
+
var h = held; held = [];
|
|
163
|
+
refresh(h);
|
|
164
|
+
}, HELD_MS);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function rowIds(el) {
|
|
168
|
+
return [].slice.call(el.querySelectorAll('[data-row-id]')).map(function (r) { return r.getAttribute('data-row-id'); });
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function newBar(el, n, fresh) {
|
|
172
|
+
var bar = document.querySelector('[data-live-newbar="' + el.id + '"]');
|
|
173
|
+
if (!bar) {
|
|
174
|
+
bar = document.createElement('div');
|
|
175
|
+
bar.className = 'live-newbar alert alert-info d-flex align-items-center gap-2 py-1 px-2 small';
|
|
176
|
+
bar.setAttribute('data-live-newbar', el.id);
|
|
177
|
+
var words = document.createElement('span');
|
|
178
|
+
words.className = 'flex-grow-1';
|
|
179
|
+
bar.appendChild(words);
|
|
180
|
+
var btn = document.createElement('button');
|
|
181
|
+
btn.type = 'button';
|
|
182
|
+
btn.className = 'btn btn-sm btn-link p-0';
|
|
183
|
+
btn.textContent = 'Show them';
|
|
184
|
+
bar.appendChild(btn);
|
|
185
|
+
el.parentNode.insertBefore(bar, el);
|
|
186
|
+
}
|
|
187
|
+
bar.firstChild.textContent = n + ' new. ';
|
|
188
|
+
bar.lastChild.onclick = function () {
|
|
189
|
+
var cur = document.getElementById(el.id);
|
|
190
|
+
if (cur) swapIn(cur, bar.__fresh, true);
|
|
191
|
+
if (bar.parentNode) bar.parentNode.removeChild(bar);
|
|
192
|
+
};
|
|
193
|
+
bar.__fresh = fresh;
|
|
194
|
+
bar.hidden = false;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Replace `el` by `fresh`, marking rows `fresh` has that `el` had not. */
|
|
198
|
+
function swapIn(el, fresh, markNew) {
|
|
199
|
+
var before = rowIds(el);
|
|
200
|
+
var clone = document.importNode(fresh, true);
|
|
201
|
+
el.parentNode.replaceChild(clone, el);
|
|
202
|
+
REGIONS[REGIONS.indexOf(el)] = clone;
|
|
203
|
+
// Scripts that bound to the old nodes re-bind here (or listen on the document, as pager.js and
|
|
204
|
+
// bulk-select.js do since @aria-framework/server 0.17.0).
|
|
205
|
+
document.dispatchEvent(new CustomEvent('aria:live-swapped', { detail: { id: clone.id, el: clone } }));
|
|
206
|
+
record(clone); // the new baseline: what the server drew, as its listeners have set it up
|
|
207
|
+
if (markNew && before.length) {
|
|
208
|
+
clone.querySelectorAll('[data-row-id]').forEach(function (r) {
|
|
209
|
+
if (before.indexOf(r.getAttribute('data-row-id')) !== -1) return;
|
|
210
|
+
// The marker may sit on the row or on its first cell (an app whose rows must stay a bare <tr>).
|
|
211
|
+
var tr = (r.closest && r.closest('tr')) || r;
|
|
212
|
+
tr.classList.add('live-new');
|
|
213
|
+
var cell = /^T[DH]$/.test(r.tagName) ? r : (r.querySelector('td, th') || r);
|
|
214
|
+
var pill = document.createElement('span');
|
|
215
|
+
pill.className = 'live-new-pill';
|
|
216
|
+
pill.textContent = 'New';
|
|
217
|
+
cell.insertBefore(pill, cell.firstChild);
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
return clone;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function apply(el, fresh) {
|
|
224
|
+
if (!el.hasAttribute('data-live-list')) {
|
|
225
|
+
if (el.innerHTML !== fresh.innerHTML) swapIn(el, fresh, false);
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
var have = rowIds(el);
|
|
229
|
+
var added = rowIds(fresh).filter(function (id) { return have.indexOf(id) === -1; });
|
|
230
|
+
var ticked = !!el.querySelector('input[type="checkbox"]:checked');
|
|
231
|
+
if (el.hasAttribute('data-live-insert') && fresh.hasAttribute('data-live-insert') && !ticked) {
|
|
232
|
+
if (el.innerHTML !== fresh.innerHTML) swapIn(el, fresh, true);
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
if (added.length) newBar(el, added.length, fresh);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function srcOf(el) { return el.getAttribute('data-live-src') || window.location.href; }
|
|
239
|
+
|
|
240
|
+
function refresh(ids) {
|
|
241
|
+
// A submit that may not navigate (a download): a HELD region stays held — it is caught up once listening again.
|
|
242
|
+
if (leaving) { hold(ids); return; }
|
|
243
|
+
if (busy) {
|
|
244
|
+
pending = pending || [];
|
|
245
|
+
ids.forEach(function (id) { if (pending.indexOf(id) === -1) pending.push(id); });
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
var targets = REGIONS.filter(function (r) { return ids.indexOf(r.id) !== -1; });
|
|
249
|
+
var worked = targets.filter(workedIn);
|
|
250
|
+
targets = targets.filter(function (r) { return !workedIn(r); });
|
|
251
|
+
if (worked.length) hold(worked.map(function (r) { return r.id; }));
|
|
252
|
+
if (!targets.length) return;
|
|
253
|
+
// One fetch per source: a region with its own data-live-src is read from there, the rest from this page.
|
|
254
|
+
var bySrc = {};
|
|
255
|
+
targets.forEach(function (r) { (bySrc[srcOf(r)] = bySrc[srcOf(r)] || []).push(r); });
|
|
256
|
+
busy = true;
|
|
257
|
+
Promise.all(Object.keys(bySrc).map(function (src) {
|
|
258
|
+
// X-Live-Fragment marks the page's own re-fetch: @aria-framework/auth 0.16.0 lets it through without
|
|
259
|
+
// counting it as activity, so a page left open still idles out.
|
|
260
|
+
return fetch(src, { credentials: 'same-origin', headers: { 'X-Requested-With': 'fetch', 'X-Live-Fragment': '1' } })
|
|
261
|
+
.then(function (r) { return r.ok ? r.text() : null; })
|
|
262
|
+
.then(function (html) {
|
|
263
|
+
if (html == null) return;
|
|
264
|
+
if (leaving) { hold(bySrc[src].map(function (el) { return el.id; })); return; }
|
|
265
|
+
var doc = new DOMParser().parseFromString(html, 'text/html');
|
|
266
|
+
bySrc[src].forEach(function (el) {
|
|
267
|
+
var cur = document.getElementById(el.id) || el;
|
|
268
|
+
var fresh = doc.getElementById(el.id);
|
|
269
|
+
// No such element in the answer: not this page (a sign-in page is a 200 too). Nothing changes.
|
|
270
|
+
if (!fresh || !fresh.hasAttribute('data-live-topic')) return;
|
|
271
|
+
// Someone started working in it while the answer was on its way: hold it, never swap.
|
|
272
|
+
if (workedIn(cur)) { hold([cur.id]); return; }
|
|
273
|
+
apply(cur, fresh);
|
|
274
|
+
});
|
|
275
|
+
})
|
|
276
|
+
.catch(function () { /* the next frame or reconnect tries again */ });
|
|
277
|
+
})).then(function () {
|
|
278
|
+
busy = false;
|
|
279
|
+
if (pending) { var p = pending; pending = null; refresh(p); }
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
document.addEventListener('aria:sse', function (ev) {
|
|
284
|
+
var d = ev.detail || {};
|
|
285
|
+
if (d.type === 'live-stop') { stopped = d.reason || 'stopped'; showStrip(stopped); return; }
|
|
286
|
+
if (d.id == null || leaving) return;
|
|
287
|
+
var t = d.type + ':' + d.id;
|
|
288
|
+
var ids = REGIONS.filter(function (r) { return topicsOf(r).indexOf(t) !== -1; }).map(function (r) { return r.id; });
|
|
289
|
+
if (ids.length) refresh(ids);
|
|
290
|
+
});
|
|
291
|
+
document.addEventListener('aria:sse-down', function () {
|
|
292
|
+
if (document.visibilityState === 'hidden') return;
|
|
293
|
+
showStrip('down');
|
|
294
|
+
});
|
|
295
|
+
document.addEventListener('aria:sse-open', function (ev) {
|
|
296
|
+
// After a live-stop bell.js keeps the BELL open without topics: this page is still not live.
|
|
297
|
+
if (stopped) return;
|
|
298
|
+
clearStrip();
|
|
299
|
+
// A reconnect: whatever was missed while down is caught up by reading the state once.
|
|
300
|
+
if (ev.detail && ev.detail.firstOpen === false) refresh(REGIONS.map(function (r) { return r.id; }));
|
|
301
|
+
});
|
|
302
|
+
|
|
303
|
+
window.ariaLive = { refresh: function () { refresh(REGIONS.map(function (r) { return r.id; })); } };
|
|
304
|
+
})();
|
package/hub.js
CHANGED
|
@@ -19,15 +19,69 @@
|
|
|
19
19
|
* The second is not a nicety. Pushes on the first channel go to recipients, so someone reading
|
|
20
20
|
* a record they do not watch is told nothing — which is the ordinary state of an unassigned
|
|
21
21
|
* ticket or an unowned invoice, and exactly the one most likely to be open when it changes.
|
|
22
|
+
*
|
|
23
|
+
* 0.5.0 — LIVE PAGES ON THE SAME ENTITY CHANNEL (three additions, nothing new underneath):
|
|
24
|
+
*
|
|
25
|
+
* TOPICS a stream may watch up to `topicsPerStream` `type:id` keys, not just one record —
|
|
26
|
+
* a list ("work:p3"), a running job ("ask-bench:house"). A topic IS an entity key;
|
|
27
|
+
* the frame is still `{type, id}` and nothing else.
|
|
28
|
+
* CAPS per session and per user on LIVE streams (those watching a topic; a bell-only stream is
|
|
29
|
+
* not counted, so the bell never loses to a seventh tab), per process on every stream,
|
|
30
|
+
* topics per stream, and a stream lifetime. Over the session or user cap the OLDEST live
|
|
31
|
+
* stream of that session or user is evicted (`live-stop evicted`), never the new one —
|
|
32
|
+
* which also clears a half-open stream a sleeping laptop left behind. A refused stream
|
|
33
|
+
* (too many topics, the process full) is told `live-stop` and ended.
|
|
34
|
+
* AUTHORISE an optional per-event hook. When it is given, an entity frame reaches a
|
|
35
|
+
* subscription only once the hook said that subscription may still see that topic —
|
|
36
|
+
* and the hook's answer is reused for at most `recheckMs`, so a revoked session gets
|
|
37
|
+
* at most that long of contentless nudges (each of whose re-fetches its own route
|
|
38
|
+
* refuses). Anything but `true` is no frame; a throw is a stop.
|
|
22
39
|
*/
|
|
23
40
|
|
|
24
41
|
'use strict';
|
|
25
42
|
|
|
26
43
|
const HEARTBEAT_MS = 25000; // keep idle connections alive through proxies
|
|
27
44
|
|
|
28
|
-
|
|
45
|
+
/**
|
|
46
|
+
* The default caps (the live-updates plan's D5, approved 30 Oct 2026). Each can be lowered or
|
|
47
|
+
* raised per hub; none can be switched off, because a cap that is not there is the case it exists
|
|
48
|
+
* for — a tab left open forever, or a script opening streams in a loop.
|
|
49
|
+
*/
|
|
50
|
+
const LIMITS = Object.freeze({
|
|
51
|
+
perSession: 6, // LIVE streams (tabs watching a topic) one session may hold
|
|
52
|
+
perUser: 12, // LIVE streams one user may hold, over all their sessions and devices
|
|
53
|
+
bellPerUser: 20, // BELL-ONLY streams one user may hold (counted apart: a bell is never evicted for a live tab)
|
|
54
|
+
perProcess: 1000, // streams this process holds in all
|
|
55
|
+
topicsPerStream: 8, // `type:id` keys one stream may watch
|
|
56
|
+
lifetimeMs: 60 * 60 * 1000 // a stream is renewed after this, so a scope cannot live forever
|
|
57
|
+
});
|
|
58
|
+
const RECHECK_MS = 5000; // an authorise answer is reused for at most this long
|
|
59
|
+
const COALESCE_MS = 750; // publishSoon(): one frame per topic per this window
|
|
60
|
+
|
|
61
|
+
const frame = (obj) => `data: ${JSON.stringify(obj)}\n\n`;
|
|
62
|
+
|
|
63
|
+
function positive(v, name) {
|
|
64
|
+
const n = Number(v);
|
|
65
|
+
if (!Number.isFinite(n) || n < 1) throw new Error(`notify: createHub limit ${name} must be a positive number (got ${JSON.stringify(v)})`);
|
|
66
|
+
return n;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function createHub({
|
|
70
|
+
heartbeatMs = HEARTBEAT_MS, limits = {}, authorize = null, recheckMs = RECHECK_MS,
|
|
71
|
+
coalesceMs = COALESCE_MS, now = () => Date.now(), logger = console
|
|
72
|
+
} = {}) {
|
|
73
|
+
const L = {};
|
|
74
|
+
for (const k of Object.keys(LIMITS)) L[k] = positive(limits[k] === undefined ? LIMITS[k] : limits[k], k);
|
|
75
|
+
if (authorize !== null && typeof authorize !== 'function') throw new Error('notify: authorize must be a function');
|
|
76
|
+
const RECHECK = Math.max(0, Number(recheckMs) || 0);
|
|
77
|
+
|
|
29
78
|
const users = new Map(); // userId -> Set(res)
|
|
30
79
|
const entities = new Map(); // "type:id" -> Set(res)
|
|
80
|
+
const subs = new Map(); // res -> subscription (every open stream; a refused one never)
|
|
81
|
+
const sessions = new Map(); // session id -> Set(res) live streams only, oldest first
|
|
82
|
+
const liveUsers = new Map(); // userId -> Set(res) live streams only, oldest first
|
|
83
|
+
const bellUsers = new Map(); // userId -> Set(res) bell-only streams, oldest first
|
|
84
|
+
const soon = new Map(); // "type:id" -> coalescing timer
|
|
31
85
|
let heartbeat = null;
|
|
32
86
|
|
|
33
87
|
const key = (type, id) => `${type}:${id}`;
|
|
@@ -64,29 +118,111 @@ function createHub({ heartbeatMs = HEARTBEAT_MS } = {}) {
|
|
|
64
118
|
if (!set.size) map.delete(k);
|
|
65
119
|
};
|
|
66
120
|
|
|
121
|
+
/** Tell a stream why it gets no more frames, and end it. bell.js does not reconnect after it. */
|
|
122
|
+
function stopRes(res, reason) {
|
|
123
|
+
try { res.write(frame({ type: 'live-stop', reason })); } catch (_) { /* gone */ }
|
|
124
|
+
try { res.end(); } catch (_) { /* gone */ }
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** The keys a subscription asks for: the one `entity` (0.4.0) and `topics` (0.5.0), de-duplicated. */
|
|
128
|
+
function keysOf(opts) {
|
|
129
|
+
const out = [];
|
|
130
|
+
const take = (e) => {
|
|
131
|
+
if (!e || e.type == null || e.id == null) return;
|
|
132
|
+
const k = key(e.type, e.id);
|
|
133
|
+
if (!out.includes(k)) out.push(k);
|
|
134
|
+
};
|
|
135
|
+
take(opts.entity);
|
|
136
|
+
for (const t of (Array.isArray(opts.topics) ? opts.topics : [])) take(t);
|
|
137
|
+
return out;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Stop an existing stream (the oldest, over a cap): told why, ended, forgotten. */
|
|
141
|
+
function evict(res) {
|
|
142
|
+
const sub = subs.get(res);
|
|
143
|
+
stopRes(res, 'evicted');
|
|
144
|
+
if (sub && sub.unsubscribe) sub.unsubscribe();
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function refused(res, reason) {
|
|
148
|
+
stopRes(res, reason);
|
|
149
|
+
const noop = function unsubscribe() {};
|
|
150
|
+
noop.refused = reason;
|
|
151
|
+
return noop;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
let busyLogged = -Infinity;
|
|
155
|
+
function logBusy() {
|
|
156
|
+
// Once a minute, not once per refusal: a client retrying in a loop must not fill the log.
|
|
157
|
+
if (now() - busyLogged < 60000) return;
|
|
158
|
+
busyLogged = now();
|
|
159
|
+
try { logger.warn(`notify: the stream cap (${L.perProcess} per process) is reached — new streams are refused`); } catch (_) { /* noop */ }
|
|
160
|
+
}
|
|
161
|
+
|
|
67
162
|
/**
|
|
68
163
|
* Register an open SSE response.
|
|
69
164
|
*
|
|
70
165
|
* @param {number} userId
|
|
71
166
|
* @param {object} res
|
|
72
|
-
* @param {{entity?: {type
|
|
73
|
-
*
|
|
167
|
+
* @param {{entity?: {type, id}, topics?: {type, id}[], sessionId?: string, meta?: any}} [opts]
|
|
168
|
+
* `entity` and `topics` are both entity keys; `sessionId` is counted for the per-session
|
|
169
|
+
* cap and handed to `authorize`, as is `meta` (whatever the app needs to re-judge — the
|
|
170
|
+
* scope the page was rendered for, say). Neither is ever sent to the client.
|
|
171
|
+
* @returns {function} unsubscribe — removes from EVERY map. When the stream was refused (a cap)
|
|
172
|
+
* it has been told `live-stop` and ended, and the function is a no-op carrying `.refused`.
|
|
74
173
|
*
|
|
75
|
-
* ONE unsubscribe covering
|
|
76
|
-
*
|
|
77
|
-
*
|
|
174
|
+
* ONE unsubscribe covering every map, deliberately: two functions is two chances for a caller to
|
|
175
|
+
* wire up only one, and an entry left behind holds a dead response that the heartbeat then
|
|
176
|
+
* writes to forever.
|
|
78
177
|
*/
|
|
79
178
|
function subscribe(userId, res, opts = {}) {
|
|
80
179
|
const uid = Number(userId);
|
|
180
|
+
const keys = keysOf(opts);
|
|
181
|
+
const sid = opts.sessionId == null || opts.sessionId === '' ? null : String(opts.sessionId);
|
|
182
|
+
if (keys.length > L.topicsPerStream) return refused(res, 'too_many_topics');
|
|
183
|
+
const isLive = keys.length > 0;
|
|
184
|
+
// A BELL-ONLY stream is capped per USER (never per session: the bell is per person), before the process cap, so one
|
|
185
|
+
// user opening bells in a loop evicts their own oldest instead of filling the process and starving everyone else.
|
|
186
|
+
if (!isLive) while ((bellUsers.get(uid) || new Set()).size >= L.bellPerUser) evict(bellUsers.get(uid).values().next().value);
|
|
187
|
+
if (subs.size >= L.perProcess) {
|
|
188
|
+
logBusy();
|
|
189
|
+
return refused(res, 'busy');
|
|
190
|
+
}
|
|
191
|
+
if (isLive) {
|
|
192
|
+
// EVICT THE OLDEST, never refuse the newest: the tab a person just opened is the one they are looking at.
|
|
193
|
+
if (sid) while ((sessions.get(sid) || new Set()).size >= L.perSession) evict(sessions.get(sid).values().next().value);
|
|
194
|
+
while ((liveUsers.get(uid) || new Set()).size >= L.perUser) evict(liveUsers.get(uid).values().next().value);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const sub = { userId: uid, sessionId: sid, keys, meta: opts.meta, verdicts: new Map(), closed: false, timer: null, unsubscribe: null };
|
|
198
|
+
subs.set(res, sub);
|
|
81
199
|
add(users, uid, res);
|
|
82
|
-
const
|
|
83
|
-
|
|
84
|
-
if (
|
|
200
|
+
for (const k of keys) add(entities, k, res);
|
|
201
|
+
if (isLive && sid) add(sessions, sid, res);
|
|
202
|
+
if (isLive) add(liveUsers, uid, res); else add(bellUsers, uid, res);
|
|
85
203
|
ensureHeartbeat();
|
|
86
|
-
|
|
204
|
+
|
|
205
|
+
function unsubscribe() {
|
|
206
|
+
if (sub.closed) return;
|
|
207
|
+
sub.closed = true;
|
|
208
|
+
if (sub.timer) { clearTimeout(sub.timer); sub.timer = null; }
|
|
209
|
+
subs.delete(res);
|
|
87
210
|
remove(users, uid, res);
|
|
88
|
-
|
|
89
|
-
|
|
211
|
+
for (const k of keys) remove(entities, k, res);
|
|
212
|
+
if (isLive && sid) remove(sessions, sid, res);
|
|
213
|
+
if (isLive) remove(liveUsers, uid, res); else remove(bellUsers, uid, res);
|
|
214
|
+
}
|
|
215
|
+
sub.unsubscribe = unsubscribe;
|
|
216
|
+
|
|
217
|
+
// THE LIFETIME: renewed, not refused. The client reconnects at once and catches up (bell.js
|
|
218
|
+
// on `live-renew`), and the new stream is judged afresh — a scope cannot outlive it.
|
|
219
|
+
sub.timer = setTimeout(() => {
|
|
220
|
+
try { res.write(frame({ type: 'live-renew' })); } catch (_) { /* gone */ }
|
|
221
|
+
try { res.end(); } catch (_) { /* gone */ }
|
|
222
|
+
unsubscribe();
|
|
223
|
+
}, L.lifetimeMs);
|
|
224
|
+
if (sub.timer.unref) sub.timer.unref();
|
|
225
|
+
return unsubscribe;
|
|
90
226
|
}
|
|
91
227
|
|
|
92
228
|
const write = (set, payload) => {
|
|
@@ -107,35 +243,112 @@ function createHub({ heartbeatMs = HEARTBEAT_MS } = {}) {
|
|
|
107
243
|
}
|
|
108
244
|
|
|
109
245
|
/**
|
|
110
|
-
*
|
|
246
|
+
* ONE SUBSCRIPTION, ONE TOPIC: may this frame go out? Resolves true only when `authorize` said
|
|
247
|
+
* exactly `true`. Its answer is reused for `recheckMs` (one call however many events arrive in
|
|
248
|
+
* that window — a burst of fifty touches is one session-store read, not fifty); a `{stop}`
|
|
249
|
+
* answer or a throw ends the stream with that reason.
|
|
250
|
+
*/
|
|
251
|
+
function allowed(res, k, topic) {
|
|
252
|
+
const sub = subs.get(res);
|
|
253
|
+
if (!sub || sub.closed) return Promise.resolve(false);
|
|
254
|
+
const hit = sub.verdicts.get(k);
|
|
255
|
+
if (hit && now() - hit.at < RECHECK) return hit.p;
|
|
256
|
+
const p = Promise.resolve()
|
|
257
|
+
.then(() => authorize({ userId: sub.userId, sessionId: sub.sessionId, topic, meta: sub.meta }))
|
|
258
|
+
.catch((e) => {
|
|
259
|
+
try { logger.error(`notify: authorize failed for ${k} — ${(e && e.message) || e} — the stream is stopped`); } catch (_) { /* noop */ }
|
|
260
|
+
return { stop: 'check_failed' };
|
|
261
|
+
})
|
|
262
|
+
.then((v) => {
|
|
263
|
+
if (v === true) return true;
|
|
264
|
+
if (v && typeof v === 'object' && typeof v.stop === 'string') {
|
|
265
|
+
stopRes(res, v.stop);
|
|
266
|
+
if (sub.unsubscribe) sub.unsubscribe();
|
|
267
|
+
}
|
|
268
|
+
return false;
|
|
269
|
+
});
|
|
270
|
+
sub.verdicts.set(k, { at: now(), p });
|
|
271
|
+
return p;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* Tell everyone VIEWING a record (or watching a topic) that it changed — and, with `authorize`,
|
|
276
|
+
* only those it still allows. Resolves the number of frames written.
|
|
111
277
|
*
|
|
112
278
|
* The event carries the type and id and NOTHING ELSE by default. The client re-fetches
|
|
113
279
|
* through the normal permission-checked route, so this channel cannot leak content even if a
|
|
114
280
|
* subscription were wrong, and the app's own view permission stays the single place access is
|
|
115
281
|
* decided.
|
|
282
|
+
*/
|
|
283
|
+
function publish(type, id, extra = {}) {
|
|
284
|
+
const k = key(type, id);
|
|
285
|
+
const set = entities.get(k);
|
|
286
|
+
if (!set || !set.size) return Promise.resolve(0);
|
|
287
|
+
const payload = frame({ type, id, ...extra });
|
|
288
|
+
if (!authorize) return Promise.resolve(write(set, payload));
|
|
289
|
+
return Promise.all([...set].map((res) => allowed(res, k, { type, id }).then((ok) => {
|
|
290
|
+
if (!ok) return 0;
|
|
291
|
+
const sub = subs.get(res);
|
|
292
|
+
if (!sub || sub.closed) return 0;
|
|
293
|
+
try { res.write(payload); return 1; } catch (_) { return 0; }
|
|
294
|
+
}))).then((ns) => ns.reduce((a, b) => a + b, 0));
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* pushEntity — the 0.4.0 call, unchanged without `authorize` (it writes and returns how many).
|
|
299
|
+
* With `authorize` it goes through publish() and returns how many subscriptions were CANDIDATES;
|
|
300
|
+
* the frames follow once each is allowed.
|
|
116
301
|
*
|
|
117
302
|
* One consumer briefly included an `actorUserId` "so a viewer can ignore its own action". No
|
|
118
303
|
* client ever read it, so its only effect was disclosing one staffer's user id to every other
|
|
119
304
|
* viewer on every reply. A field nothing consumes is not a feature waiting to be used.
|
|
120
305
|
*/
|
|
121
306
|
function pushEntity(type, id, extra = {}) {
|
|
122
|
-
const
|
|
123
|
-
return write(
|
|
307
|
+
const set = entities.get(key(type, id));
|
|
308
|
+
if (!authorize) return write(set, frame({ type, id, ...extra }));
|
|
309
|
+
publish(type, id, extra).catch(() => {});
|
|
310
|
+
return set ? set.size : 0;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* publish(), coalesced: every call for one topic within `coalesceMs` becomes ONE frame, sent at
|
|
315
|
+
* the end of the window. For a writer that touches a topic in a loop (a job's progress, a batch
|
|
316
|
+
* of events) — one re-fetch per open page per window, however many writes. Fire and forget.
|
|
317
|
+
*/
|
|
318
|
+
function publishSoon(type, id) {
|
|
319
|
+
const k = key(type, id);
|
|
320
|
+
if (soon.has(k) || !entities.has(k)) return; // nobody watching: no timer, no work
|
|
321
|
+
const t = setTimeout(() => {
|
|
322
|
+
soon.delete(k);
|
|
323
|
+
publish(type, id).catch(() => {});
|
|
324
|
+
}, coalesceMs);
|
|
325
|
+
if (t.unref) t.unref();
|
|
326
|
+
soon.set(k, t);
|
|
124
327
|
}
|
|
125
328
|
|
|
329
|
+
/** Is anybody watching this topic? (A writer may skip the work of finding out what changed.) */
|
|
330
|
+
const watched = (type, id) => entities.has(key(type, id));
|
|
331
|
+
|
|
126
332
|
function stats() {
|
|
127
333
|
return { users: users.size, entities: entities.size };
|
|
128
334
|
}
|
|
129
335
|
|
|
336
|
+
/** The live layer's counts (0.5.0), beside stats(): open streams, sessions holding one, and the caps. */
|
|
337
|
+
function streamStats() {
|
|
338
|
+
return { streams: subs.size, sessions: sessions.size, topics: entities.size, limits: { ...L, recheckMs: RECHECK } };
|
|
339
|
+
}
|
|
340
|
+
|
|
130
341
|
/**
|
|
131
342
|
* End every open response and stop the heartbeat.
|
|
132
343
|
*
|
|
133
344
|
* Wire this into graceful shutdown. An SSE response is a request that never finishes, so
|
|
134
|
-
* server.close() waits for a drain that will never come —
|
|
135
|
-
* left open on
|
|
345
|
+
* server.close() waits for a drain that will never come — every map, because a subscription
|
|
346
|
+
* left open on any one is enough to hold the process.
|
|
136
347
|
*/
|
|
137
348
|
function closeAll() {
|
|
138
349
|
if (heartbeat) { clearInterval(heartbeat); heartbeat = null; }
|
|
350
|
+
for (const t of soon.values()) clearTimeout(t);
|
|
351
|
+
soon.clear();
|
|
139
352
|
const ended = new Set();
|
|
140
353
|
for (const map of [users, entities]) {
|
|
141
354
|
for (const set of map.values()) {
|
|
@@ -148,9 +361,14 @@ function createHub({ heartbeatMs = HEARTBEAT_MS } = {}) {
|
|
|
148
361
|
}
|
|
149
362
|
map.clear();
|
|
150
363
|
}
|
|
364
|
+
for (const sub of subs.values()) { sub.closed = true; if (sub.timer) clearTimeout(sub.timer); }
|
|
365
|
+
subs.clear();
|
|
366
|
+
sessions.clear();
|
|
367
|
+
liveUsers.clear();
|
|
368
|
+
bellUsers.clear();
|
|
151
369
|
}
|
|
152
370
|
|
|
153
|
-
return { subscribe, pushUsers, pushEntity, stats, closeAll };
|
|
371
|
+
return { subscribe, pushUsers, pushEntity, publish, publishSoon, watched, stats, streamStats, closeAll };
|
|
154
372
|
}
|
|
155
373
|
|
|
156
|
-
module.exports = { createHub, HEARTBEAT_MS };
|
|
374
|
+
module.exports = { createHub, HEARTBEAT_MS, LIMITS, RECHECK_MS, COALESCE_MS };
|
package/index.js
CHANGED
|
@@ -27,6 +27,7 @@ module.exports = {
|
|
|
27
27
|
// views/notify/bell.ejs is the markup half, shipped together so the hook names cannot drift.
|
|
28
28
|
// staticDirs.push({ mount: '/js/notify', dir: notify.assetsDir })
|
|
29
29
|
// viewDirs.push(notify.viewsDir)
|
|
30
|
+
// 0.5.0 — assets/live.js (live page regions) ships in the same assets dir; load it after bell.js.
|
|
30
31
|
assetsDir: path.join(__dirname, 'assets'),
|
|
31
32
|
viewsDir: path.join(__dirname, 'views')
|
|
32
33
|
};
|
package/package.json
CHANGED
|
@@ -1,30 +1,34 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@aria-framework/notify",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Aria App Framework — notify module. In-app notifications: ownership-scoped rows, a per-process SSE hub for live delivery, and a fire-and-forget emitter that needs no request and no actor, so a scheduler can raise one.",
|
|
5
|
-
"license": "UNLICENSED",
|
|
6
|
-
"private": false,
|
|
7
|
-
"publishConfig": {
|
|
8
|
-
"access": "public"
|
|
9
|
-
},
|
|
10
|
-
"main": "index.js",
|
|
11
|
-
"files": [
|
|
12
|
-
"index.js",
|
|
13
|
-
"store.js",
|
|
14
|
-
"hub.js",
|
|
15
|
-
"emit.js",
|
|
16
|
-
"assets/",
|
|
17
|
-
"views/"
|
|
18
|
-
],
|
|
19
|
-
"peerDependencies": {
|
|
20
|
-
"better-sqlite3": ">=11"
|
|
21
|
-
},
|
|
22
|
-
"peerDependenciesMeta": {
|
|
23
|
-
"better-sqlite3": {
|
|
24
|
-
"optional": true
|
|
25
|
-
}
|
|
26
|
-
},
|
|
27
|
-
"
|
|
28
|
-
"
|
|
29
|
-
}
|
|
30
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "@aria-framework/notify",
|
|
3
|
+
"version": "0.5.0",
|
|
4
|
+
"description": "Aria App Framework — notify module. In-app notifications: ownership-scoped rows, a per-process SSE hub for live delivery (with topics, caps and a per-event authorise hook for live pages), and a fire-and-forget emitter that needs no request and no actor, so a scheduler can raise one.",
|
|
5
|
+
"license": "UNLICENSED",
|
|
6
|
+
"private": false,
|
|
7
|
+
"publishConfig": {
|
|
8
|
+
"access": "public"
|
|
9
|
+
},
|
|
10
|
+
"main": "index.js",
|
|
11
|
+
"files": [
|
|
12
|
+
"index.js",
|
|
13
|
+
"store.js",
|
|
14
|
+
"hub.js",
|
|
15
|
+
"emit.js",
|
|
16
|
+
"assets/",
|
|
17
|
+
"views/"
|
|
18
|
+
],
|
|
19
|
+
"peerDependencies": {
|
|
20
|
+
"better-sqlite3": ">=11"
|
|
21
|
+
},
|
|
22
|
+
"peerDependenciesMeta": {
|
|
23
|
+
"better-sqlite3": {
|
|
24
|
+
"optional": true
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"jsdom": "^30.0.1"
|
|
29
|
+
},
|
|
30
|
+
"scripts": {
|
|
31
|
+
"test": "node test/store.js && node test/schema-parity.js && node test/hub.js && node test/live-hub.js && node test/emit.js && node test/bell.js && node test/live-client.js",
|
|
32
|
+
"prepublishOnly": "node ../../test/packaging.js notify"
|
|
33
|
+
}
|
|
34
|
+
}
|
package/views/notify/bell.ejs
CHANGED
|
@@ -9,14 +9,18 @@
|
|
|
9
9
|
notifQuiet comma list of SSE frame types that must NOT re-sync the bell (e.g. 'ticket,draft')
|
|
10
10
|
notifUnread server-rendered initial unread count (keeps the badge honest before JS runs,
|
|
11
11
|
and with JS off the bell stays a working link to the notifications page)
|
|
12
|
-
notifWidth dropdown width (default '340px')
|
|
12
|
+
notifWidth dropdown width (default '340px')
|
|
13
|
+
notifAssets where assets/ is mounted (default '/js/notify'; bell.css is linked from it,
|
|
14
|
+
so the unread look ships with the markup and an app cannot forget it) %>
|
|
13
15
|
<%
|
|
14
16
|
var __base = (typeof notifBase === 'undefined') ? '/notifications' : notifBase;
|
|
15
17
|
var __fill = (typeof notifFill === 'undefined') ? 'load' : notifFill;
|
|
16
18
|
var __quiet = (typeof notifQuiet === 'undefined') ? '' : notifQuiet;
|
|
17
19
|
var __unread = (typeof notifUnread === 'undefined') ? 0 : Number(notifUnread) || 0;
|
|
18
20
|
var __width = (typeof notifWidth === 'undefined') ? '340px' : notifWidth;
|
|
21
|
+
var __assets = (typeof notifAssets === 'undefined') ? '/js/notify' : notifAssets;
|
|
19
22
|
%>
|
|
23
|
+
<link rel="stylesheet" href="<%= __assets %>/bell.css">
|
|
20
24
|
<div class="dropdown" id="notif-menu" data-notif-base="<%= __base %>" data-notif-fill="<%= __fill %>"<% if (__quiet) { %> data-notif-quiet="<%= __quiet %>"<% } %>>
|
|
21
25
|
<a href="<%= __base %>" class="bell-btn" role="button"
|
|
22
26
|
data-bs-toggle="dropdown" data-bs-auto-close="outside" aria-expanded="false" title="Notifications">
|