@aria-framework/notify 0.5.0 → 0.6.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 CHANGED
@@ -158,7 +158,7 @@ bell-only stream is not under the live caps, so the bell never loses to a sevent
158
158
  their own cap, 20 per USER (`bellPerUser`), so one user cannot fill the process and starve everyone else — over it
159
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
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
161
+ (`too_many_topics`, `busy`; 0.6.0: a named audience over its own cap is `busy` too, see Audiences). After a `live-stop` bell.js closes the stream and reopens it ONCE without its
162
162
  topics, so the bell goes on; a bell-only stream that is stopped is not reopened. A stream lives 60 minutes, then
163
163
  is told `live-renew` and ended; bell.js reopens it at once, the page catches up, and the new stream is judged
164
164
  afresh, so no scope outlives it. `publishSoon` arms nothing for a topic nobody watches.
@@ -189,9 +189,72 @@ listen on the document and need nothing). `data-live-list` makes it a list of `[
189
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
190
  ticked, new rows are put in and marked New; otherwise a bar says "N new. Show them". Every reconnect catches every
191
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)
192
+ Refresh button — or, when the app refused the topics with the reason `off` (0.5.1: its installation-wide switch),
193
+ "Live updates are off". Frames that arrive after this page submitted a form are ignored (the mid-navigation trap above)
193
194
  until the page navigates — or, for a submit that does not (a download, `target=_blank`), until it is visible again
194
195
  or 8 s pass; a submit a script prevented is not a navigation.
195
196
 
196
197
  Still one process: a write in another process (an ingest server, a node server) reaches no stream
197
198
  here. Such a page needs a re-check in the web process, or a shared bus — neither is in this module.
199
+
200
+ ## Audiences (0.6.0)
201
+
202
+ A stream carries an **audience**. `staff` is the default — a `subscribe` that passes none is exactly what it was in
203
+ 0.5.1 — and any other audience must be named in `limits.perAudience`, which gives it a cap of its own **inside**
204
+ `perProcess`. The one named by default is `contact`, for a customer portal's contacts:
205
+
206
+ ```js
207
+ // a portal contact's stream: counted under the contact cap, never against staff's reserve
208
+ hub.subscribe(contactKey, res, { topics, sessionId, meta, audience: 'contact' });
209
+ ```
210
+
211
+ **Why.** One process cap shared by everyone lets one audience starve another: at 12 live streams each, about 84
212
+ contacts with tabs open fill 1000 streams, and every staff bell and live page after that is told `busy`. With
213
+ `perAudience: { contact: N }`, contacts can never hold more than N, so staff always keep `perProcess` − N.
214
+
215
+ **The default: 400 of 1000 (40 %).** Staff keep 600 — every staff member's bell plus a handful of live tabs, for well
216
+ over a hundred staff at once, far beyond any team these apps serve — while contacts get 400 streams: at the two or
217
+ three tabs a portal visit actually opens, more than a hundred contacts on the portal at the same moment, and about
218
+ five times the 84 that fill the process today. A hub that sets `perProcess` and not `perAudience` gets the same 40 %
219
+ of its own total (floored: at `perProcess: 2000` contacts get 800; at `perProcess: 2` they get 0). An explicit
220
+ `perAudience` value is merged over the default per audience, and an explicit `0` means that audience is off: every
221
+ stream of it is refused `busy`, exactly as a derived 0 is.
222
+
223
+ **The rules.**
224
+
225
+ - A named audience at its cap is **refused** (`live-stop busy`), like the process cap. It never evicts: the
226
+ per-session and per-user caps evict the OLDEST stream of the SAME session or person, but the streams under an
227
+ audience cap belong to other people — two contacts of two partners — and one's new tab must not end another's.
228
+ - **A person at their own limit is never refused for it.** The per-session and per-user evictions run BEFORE the
229
+ audience and process caps (0.6.0; in 0.5.x they ran after, so a person holding six tabs while the process was
230
+ full was told `busy` instead of losing their oldest). Their own oldest goes, which frees the place the new tab
231
+ takes in the same audience, so a contact at the contact cap or a staff member at a full process keeps working.
232
+ That holds while a user id and a session id each belong to one audience; the hub's contact keys are negative and
233
+ never a staff id.
234
+ - Staff are never refused because of contacts. Staff are refused only when the whole process is full, and that
235
+ needs staff themselves to hold at least `perProcess` − the named caps. Staff may use room a named audience leaves
236
+ idle; a named audience under its own cap is still refused when the process is full.
237
+ - The warn names the audience: `notify: the contact stream cap (400 of 1000 per process) is reached — …` or
238
+ `notify: the stream cap (1000 per process) is reached — … (this one: audience staff; held: staff 600, contact
239
+ 400)`. Each line is logged once a minute per cap and audience, so contacts being refused never hides the line
240
+ that says staff are.
241
+ - Any audience string may be named (`perAudience: { contact: 300, kiosk: 50 }`). `subscribe` **throws** on an
242
+ audience that is neither `staff` nor named — a misspelt `'contacts'` would otherwise be an uncapped stream.
243
+ `createHub` throws when the named caps together are not below `perProcess` (staff would keep no reserve), on a cap
244
+ that is neither 0 nor a positive number, and on `perAudience.staff` (staff is the reserve; `perProcess` caps it).
245
+ - `streamStats()` adds `audiences: { staff, contact, … }` (open streams of each) and `limits.perAudience`.
246
+
247
+ ### Upgrading to 0.6.0
248
+
249
+ - **Nothing changes for a caller that passes no audience**: every stream is `staff`, and staff can still use the
250
+ whole `perProcess` while no contact holds a stream. 0.6.0 also carries 0.5.1's strip wording (`off`), which was
251
+ never published on its own.
252
+ - **An app that serves non-staff streams should pass `audience`** — until it does, those streams are counted as
253
+ staff and the reserve protects no one. The hub's customer portal stream is the one known case
254
+ (`routes/portal.js`, `GET /portal/live/stream`: `audience: 'contact'`).
255
+ - **A live stream at its own per-session or per-user limit now evicts its own oldest even when the process is
256
+ full** (0.5.x refused it `busy`). Callers need do nothing; it only ever ends a stream of the same session or user.
257
+ - **A hub that set `limits: { perProcess }` below 3** now has a contact cap of 0 (40 % floored), so contact streams
258
+ are all refused there; give it an explicit `perAudience` or a larger `perProcess` before passing `'contact'`.
259
+ - **A hub that names its own audiences** must keep their caps (with the default contact one) below `perProcess`, or
260
+ `createHub` throws at boot.
package/assets/live.js CHANGED
@@ -29,7 +29,8 @@
29
29
  * page that CAUSED it"). A submit a script prevented is not a navigation and sets nothing.
30
30
  *
31
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
32
+ * drops (aria:sse-down) or is stopped (a live-stop frame — "too many open tabs" for too_many, and
33
+ * "Live updates are off" for `off`, the reason an app gives when it has switched live pages off); the
33
34
  * regions are dimmed. It clears on the next open, which also catches the regions up. A hidden tab
34
35
  * closes its stream on purpose (bell.js) and shows no strip.
35
36
  */
@@ -89,9 +90,13 @@
89
90
  strip.appendChild(btn);
90
91
  REGIONS[0].parentNode.insertBefore(strip, REGIONS[0]);
91
92
  }
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.';
93
+ // 'off' (0.5.1): the APP switched live updates off (an installation-wide switch, the live-updates plan's D8) and
94
+ // refused the page's topics for that reason — nothing is paused that will resume, so the strip says so.
95
+ strip.querySelector('[data-live-strip-words]').textContent = reason === 'off'
96
+ ? 'Live updates are off. Refresh to see changes.'
97
+ : (reason === 'too_many' || reason === 'evicted')
98
+ ? 'Live updates paused: too many open tabs. Close one and refresh, or refresh to see changes.'
99
+ : 'Live updates paused. Refresh to see changes.';
95
100
  strip.hidden = false;
96
101
  REGIONS.forEach(function (r) { r.classList.add('live-paused'); });
97
102
  }
package/hub.js CHANGED
@@ -36,6 +36,13 @@
36
36
  * and the hook's answer is reused for at most `recheckMs`, so a revoked session gets
37
37
  * at most that long of contentless nudges (each of whose re-fetches its own route
38
38
  * refuses). Anything but `true` is no frame; a throw is a stop.
39
+ *
40
+ * 0.6.0 — AUDIENCES. A stream carries an audience: `staff` (the default — every caller from before
41
+ * 0.6.0) or one named in `limits.perAudience` (`contact`, a customer portal's contacts). A named
42
+ * audience has a cap of its own INSIDE `perProcess` (default `contact`: 40 % of it, 400 of 1000), so
43
+ * however many contacts open tabs, staff keep `perProcess` − the named caps in reserve. Over its cap a
44
+ * new stream of that audience is refused `busy`, like the process cap — never another audience's
45
+ * stream evicted (two contacts of two partners are strangers; one's tab must not end the other's).
39
46
  */
40
47
 
41
48
  'use strict';
@@ -53,8 +60,12 @@ const LIMITS = Object.freeze({
53
60
  bellPerUser: 20, // BELL-ONLY streams one user may hold (counted apart: a bell is never evicted for a live tab)
54
61
  perProcess: 1000, // streams this process holds in all
55
62
  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
63
+ lifetimeMs: 60 * 60 * 1000, // a stream is renewed after this, so a scope cannot live forever
64
+ // Caps for the named audiences (0.6.0), each INSIDE perProcess. A hub that does not set one gets it as the same
65
+ // SHARE of its own perProcess (contact: 40 % — so a hub that raises perProcess raises both halves).
66
+ perAudience: Object.freeze({ contact: 400 })
57
67
  });
68
+ const DEFAULT_AUDIENCE = 'staff';
58
69
  const RECHECK_MS = 5000; // an authorise answer is reused for at most this long
59
70
  const COALESCE_MS = 750; // publishSoon(): one frame per topic per this window
60
71
 
@@ -66,12 +77,34 @@ function positive(v, name) {
66
77
  return n;
67
78
  }
68
79
 
80
+ /**
81
+ * The named audiences' caps. Each given value must be positive, or 0 for "this audience off"; a default not given is the default's share of this hub's
82
+ * perProcess (floored — at a perProcess of 2 the contact cap is 0, i.e. no contact stream at all). The named caps
83
+ * together must leave the default audience at least one stream, or the reserve this exists for is not there.
84
+ */
85
+ function audienceCaps(given, perProcess) {
86
+ if (given !== undefined && (given === null || typeof given !== 'object' || Array.isArray(given))) {
87
+ throw new Error(`notify: createHub limit perAudience must be an object of audience: cap (got ${JSON.stringify(given)})`);
88
+ }
89
+ const out = {};
90
+ for (const [a, n] of Object.entries(LIMITS.perAudience)) out[a] = Math.floor(perProcess * n / LIMITS.perProcess);
91
+ for (const [a, n] of Object.entries(given || {})) {
92
+ if (a === DEFAULT_AUDIENCE) throw new Error(`notify: createHub limit perAudience.${a} — ${DEFAULT_AUDIENCE} is the reserve the other caps protect, and is capped only by perProcess`);
93
+ if (n === undefined) continue;
94
+ out[a] = n === 0 ? 0 : positive(n, `perAudience.${a}`); // 0: that audience off (no stream), as a derived 0 is
95
+ }
96
+ const named = Object.values(out).reduce((x, y) => x + y, 0);
97
+ if (named >= perProcess) throw new Error(`notify: createHub limits perAudience (${named} in all) must be below perProcess (${perProcess}), so ${DEFAULT_AUDIENCE} keep a reserve`);
98
+ return Object.freeze(out);
99
+ }
100
+
69
101
  function createHub({
70
102
  heartbeatMs = HEARTBEAT_MS, limits = {}, authorize = null, recheckMs = RECHECK_MS,
71
103
  coalesceMs = COALESCE_MS, now = () => Date.now(), logger = console
72
104
  } = {}) {
73
105
  const L = {};
74
- for (const k of Object.keys(LIMITS)) L[k] = positive(limits[k] === undefined ? LIMITS[k] : limits[k], k);
106
+ for (const k of Object.keys(LIMITS)) if (k !== 'perAudience') L[k] = positive(limits[k] === undefined ? LIMITS[k] : limits[k], k);
107
+ L.perAudience = audienceCaps(limits.perAudience, L.perProcess);
75
108
  if (authorize !== null && typeof authorize !== 'function') throw new Error('notify: authorize must be a function');
76
109
  const RECHECK = Math.max(0, Number(recheckMs) || 0);
77
110
 
@@ -81,6 +114,7 @@ function createHub({
81
114
  const sessions = new Map(); // session id -> Set(res) live streams only, oldest first
82
115
  const liveUsers = new Map(); // userId -> Set(res) live streams only, oldest first
83
116
  const bellUsers = new Map(); // userId -> Set(res) bell-only streams, oldest first
117
+ const audiences = new Map(); // audience -> Set(res) every open stream, by audience
84
118
  const soon = new Map(); // "type:id" -> coalescing timer
85
119
  let heartbeat = null;
86
120
 
@@ -151,12 +185,20 @@ function createHub({
151
185
  return noop;
152
186
  }
153
187
 
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 */ }
188
+ const held = (a) => (audiences.get(a) || new Set()).size;
189
+ const heldAll = () => [DEFAULT_AUDIENCE, ...Object.keys(L.perAudience)].map((a) => `${a} ${held(a)}`).join(', ');
190
+
191
+ // Once a minute PER CAP AND AUDIENCE, not once per refusal: a client retrying in a loop must not fill the log — and
192
+ // contacts refused at their own cap must not hide the line that says staff are being refused too.
193
+ const busyLogged = new Map();
194
+ function logBusy(which, audience) {
195
+ const k = `${which}:${audience}`;
196
+ if (now() - (busyLogged.has(k) ? busyLogged.get(k) : -Infinity) < 60000) return;
197
+ busyLogged.set(k, now());
198
+ const msg = which === 'audience'
199
+ ? `notify: the ${audience} stream cap (${L.perAudience[audience]} of ${L.perProcess} per process) is reached — new ${audience} streams are refused; other audiences are unaffected (held: ${heldAll()})`
200
+ : `notify: the stream cap (${L.perProcess} per process) is reached — new streams are refused (this one: audience ${audience}; held: ${heldAll()})`;
201
+ try { logger.warn(msg); } catch (_) { /* noop */ }
160
202
  }
161
203
 
162
204
  /**
@@ -164,10 +206,13 @@ function createHub({
164
206
  *
165
207
  * @param {number} userId
166
208
  * @param {object} res
167
- * @param {{entity?: {type, id}, topics?: {type, id}[], sessionId?: string, meta?: any}} [opts]
209
+ * @param {{entity?: {type, id}, topics?: {type, id}[], sessionId?: string, meta?: any, audience?: string}} [opts]
168
210
  * `entity` and `topics` are both entity keys; `sessionId` is counted for the per-session
169
211
  * 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.
212
+ * scope the page was rendered for, say). Neither is ever sent to the client. `audience`
213
+ * (0.6.0) is `staff` when absent, else must name a `limits.perAudience` cap — an unknown one
214
+ * THROWS, because a misspelt `'contacts'` counted as nobody's would be the uncapped stream
215
+ * the cap exists to stop.
171
216
  * @returns {function} unsubscribe — removes from EVERY map. When the stream was refused (a cap)
172
217
  * it has been told `live-stop` and ended, and the function is a no-op carrying `.refused`.
173
218
  *
@@ -179,24 +224,39 @@ function createHub({
179
224
  const uid = Number(userId);
180
225
  const keys = keysOf(opts);
181
226
  const sid = opts.sessionId == null || opts.sessionId === '' ? null : String(opts.sessionId);
227
+ const audience = opts.audience == null ? DEFAULT_AUDIENCE : opts.audience;
228
+ if (audience !== DEFAULT_AUDIENCE && !Object.prototype.hasOwnProperty.call(L.perAudience, audience)) {
229
+ throw new Error(`notify: subscribe audience ${JSON.stringify(audience)} is neither ${DEFAULT_AUDIENCE} nor one of limits.perAudience (${Object.keys(L.perAudience).join(', ')})`);
230
+ }
182
231
  if (keys.length > L.topicsPerStream) return refused(res, 'too_many_topics');
183
232
  const isLive = keys.length > 0;
184
233
  // A BELL-ONLY stream is capped per USER (never per session: the bell is per person), before the process cap, so one
185
234
  // user opening bells in a loop evicts their own oldest instead of filling the process and starving everyone else.
186
235
  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
- }
236
+ // A LIVE stream likewise evicts the OLDEST of its own session and user BEFORE the caps below (0.6.0; in 0.5.x it came
237
+ // after them): never refuse the newest — the tab a person just opened is the one they are looking at — and a person
238
+ // at their own limit frees the place their new tab takes, so a full audience or process does not refuse them busy.
239
+ // Each evicted stream is the same person's, so it frees a place in the same audience — which holds as long as a user
240
+ // id and a session id each belong to ONE audience (the hub's contact keys are negative; staff ids are not).
191
241
  if (isLive) {
192
- // EVICT THE OLDEST, never refuse the newest: the tab a person just opened is the one they are looking at.
193
242
  if (sid) while ((sessions.get(sid) || new Set()).size >= L.perSession) evict(sessions.get(sid).values().next().value);
194
243
  while ((liveUsers.get(uid) || new Set()).size >= L.perUser) evict(liveUsers.get(uid).values().next().value);
195
244
  }
245
+ // A NAMED AUDIENCE AT ITS CAP is refused, never served by evicting a stream of someone else in it. Checked before the
246
+ // process cap so the log names the cap that actually refused it. The default audience has no cap of its own here.
247
+ if (audience !== DEFAULT_AUDIENCE && held(audience) >= L.perAudience[audience]) {
248
+ logBusy('audience', audience);
249
+ return refused(res, 'busy');
250
+ }
251
+ if (subs.size >= L.perProcess) {
252
+ logBusy('process', audience);
253
+ return refused(res, 'busy');
254
+ }
196
255
 
197
- const sub = { userId: uid, sessionId: sid, keys, meta: opts.meta, verdicts: new Map(), closed: false, timer: null, unsubscribe: null };
256
+ const sub = { userId: uid, sessionId: sid, audience, keys, meta: opts.meta, verdicts: new Map(), closed: false, timer: null, unsubscribe: null };
198
257
  subs.set(res, sub);
199
258
  add(users, uid, res);
259
+ add(audiences, audience, res);
200
260
  for (const k of keys) add(entities, k, res);
201
261
  if (isLive && sid) add(sessions, sid, res);
202
262
  if (isLive) add(liveUsers, uid, res); else add(bellUsers, uid, res);
@@ -208,6 +268,7 @@ function createHub({
208
268
  if (sub.timer) { clearTimeout(sub.timer); sub.timer = null; }
209
269
  subs.delete(res);
210
270
  remove(users, uid, res);
271
+ remove(audiences, audience, res);
211
272
  for (const k of keys) remove(entities, k, res);
212
273
  if (isLive && sid) remove(sessions, sid, res);
213
274
  if (isLive) remove(liveUsers, uid, res); else remove(bellUsers, uid, res);
@@ -333,9 +394,12 @@ function createHub({
333
394
  return { users: users.size, entities: entities.size };
334
395
  }
335
396
 
336
- /** The live layer's counts (0.5.0), beside stats(): open streams, sessions holding one, and the caps. */
397
+ /** The live layer's counts (0.5.0), beside stats(): open streams, sessions holding one, streams by audience (0.6.0), and the caps. */
337
398
  function streamStats() {
338
- return { streams: subs.size, sessions: sessions.size, topics: entities.size, limits: { ...L, recheckMs: RECHECK } };
399
+ const byAudience = {};
400
+ for (const a of [DEFAULT_AUDIENCE, ...Object.keys(L.perAudience)]) byAudience[a] = held(a);
401
+ return { streams: subs.size, sessions: sessions.size, topics: entities.size, audiences: byAudience,
402
+ limits: { ...L, perAudience: { ...L.perAudience }, recheckMs: RECHECK } };
339
403
  }
340
404
 
341
405
  /**
@@ -366,9 +430,10 @@ function createHub({
366
430
  sessions.clear();
367
431
  liveUsers.clear();
368
432
  bellUsers.clear();
433
+ audiences.clear();
369
434
  }
370
435
 
371
436
  return { subscribe, pushUsers, pushEntity, publish, publishSoon, watched, stats, streamStats, closeAll };
372
437
  }
373
438
 
374
- module.exports = { createHub, HEARTBEAT_MS, LIMITS, RECHECK_MS, COALESCE_MS };
439
+ module.exports = { createHub, HEARTBEAT_MS, LIMITS, DEFAULT_AUDIENCE, RECHECK_MS, COALESCE_MS };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
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.",
3
+ "version": "0.6.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 per session, user, audience and process, 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
5
  "license": "UNLICENSED",
6
6
  "private": false,
7
7
  "publishConfig": {