@aria-framework/notify 0.1.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 +88 -0
- package/emit.js +80 -0
- package/hub.js +156 -0
- package/index.js +22 -0
- package/package.json +28 -0
- package/store.js +134 -0
package/README.md
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# @aria-framework/notify
|
|
2
|
+
|
|
3
|
+
In-app notifications: durable rows, live delivery to open browsers, and an emitter that a
|
|
4
|
+
scheduler can call.
|
|
5
|
+
|
|
6
|
+
Three pieces, in three places, because that is where they have to run:
|
|
7
|
+
|
|
8
|
+
| | thread | what it is |
|
|
9
|
+
|---|---|---|
|
|
10
|
+
| `createStore` | worker | the SQL, ownership-scoped by `user_id` |
|
|
11
|
+
| `createHub` | main | open SSE responses, in memory |
|
|
12
|
+
| `createEmitter` | main | create then push, fire-and-forget |
|
|
13
|
+
|
|
14
|
+
```js
|
|
15
|
+
// worker
|
|
16
|
+
const store = notify.createStore({ getDb }); // expose as a model the main thread invokes
|
|
17
|
+
|
|
18
|
+
// main
|
|
19
|
+
const hub = notify.createHub();
|
|
20
|
+
const { emit, touch } = notify.createEmitter({ invoke: dbClient.invoke, hub, logger });
|
|
21
|
+
|
|
22
|
+
emit([userId], { type: 'invoice.overdue', title: 'Invoice #412 is overdue',
|
|
23
|
+
link: '/invoices/412', entity_type: 'invoice', entity_id: 412 });
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## No request, no actor
|
|
27
|
+
|
|
28
|
+
Every emitter in the app this came from took a `req` and derived the actor from
|
|
29
|
+
`req.session.user`. That is right for a reply, an assignment, a mention — a person did
|
|
30
|
+
something. It is wrong for a scheduler deciding an invoice is overdue, or a webhook recording a
|
|
31
|
+
payment: no session, no name, nobody to put in front of the title.
|
|
32
|
+
|
|
33
|
+
So the core takes user ids and a payload; an actor is an optional string. A request-shaped
|
|
34
|
+
convenience belongs in the app as a thin wrapper. **A system-raised notification is then the
|
|
35
|
+
ordinary case rather than a special one** — had this required a request, the scheduler would
|
|
36
|
+
have grown a second emitter beside it, which is the duplication the extraction exists to
|
|
37
|
+
prevent.
|
|
38
|
+
|
|
39
|
+
## Fire and forget
|
|
40
|
+
|
|
41
|
+
`emit()` returns a promise for tests and for callers that genuinely want to wait, and it **never
|
|
42
|
+
rejects**. A notification is never more important than the action that caused it: a bell that
|
|
43
|
+
fails must not fail a reply or a payment. Failures are logged and that is all. A synchronously
|
|
44
|
+
throwing `invoke` is caught too, which the obvious `.catch()` version misses.
|
|
45
|
+
|
|
46
|
+
## Ownership scoping IS the authorisation
|
|
47
|
+
|
|
48
|
+
Every read and every write carries `WHERE user_id = ?`. An id you do not own matches zero rows —
|
|
49
|
+
the same answer as an id that does not exist, so it leaks nothing either. There is no separate
|
|
50
|
+
permission check to forget, and **moving that scope to a caller-side `if` would be a silent
|
|
51
|
+
privilege escalation rather than a visible break.** Read it as a constraint on future edits.
|
|
52
|
+
|
|
53
|
+
## Two channels
|
|
54
|
+
|
|
55
|
+
- **users** — "tell these RECIPIENTS something happened". The bell.
|
|
56
|
+
- **entities** — "tell whoever is LOOKING at this record that it changed". `touch(type, id)`.
|
|
57
|
+
|
|
58
|
+
The second is not a nicety. Pushes on the first go to recipients, so someone reading a record
|
|
59
|
+
they do not watch is told nothing — which is the ordinary state of an unassigned ticket or an
|
|
60
|
+
unowned invoice, and exactly the one most likely to be open when it changes.
|
|
61
|
+
|
|
62
|
+
Both events are **contentless**: a type and an id. The client re-fetches through its own
|
|
63
|
+
permission-checked route, so neither channel can leak a title or a body even if a subscription
|
|
64
|
+
were wrong, and the app's own view permission stays the single place access is decided. One
|
|
65
|
+
consumer briefly included an `actorUserId` "so a viewer can ignore its own action"; no client
|
|
66
|
+
ever read it, so its only effect was disclosing a staffer's user id to every other viewer.
|
|
67
|
+
|
|
68
|
+
## THE LIMIT: one process
|
|
69
|
+
|
|
70
|
+
The hub is in memory and per-process. Two app processes behind a load balancer each hold half
|
|
71
|
+
the connections, so a push from one reaches only its own half — **silently, with no error
|
|
72
|
+
anywhere**. Correct for a single process, which is what the current consumers run. A
|
|
73
|
+
multi-process deployment needs a shared bus and this module is not it.
|
|
74
|
+
|
|
75
|
+
Stated here rather than discovered, because nothing about the failure looks like a failure.
|
|
76
|
+
|
|
77
|
+
## What stays the app's
|
|
78
|
+
|
|
79
|
+
Who receives a notification, what the types are called, what the copy says, the migration, the
|
|
80
|
+
routes, and whether any of it needs a permission. "Who cares about this thing" is domain
|
|
81
|
+
knowledge — the answer is "the ticket's watchers" in one app and "whoever owns the invoice" in
|
|
82
|
+
another.
|
|
83
|
+
|
|
84
|
+
`SCHEMA` is exported as the column list this module reads and writes. Your migration owns the
|
|
85
|
+
table and may add to it; nothing here reads a column it was not given.
|
|
86
|
+
|
|
87
|
+
Wire `hub.closeAll()` into graceful shutdown. An SSE response is a request that never finishes,
|
|
88
|
+
so `server.close()` otherwise waits for a drain that never comes.
|
package/emit.js
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Creating a notification, then pushing it to whoever is connected.
|
|
3
|
+
*
|
|
4
|
+
* FIRE AND FORGET. Never awaited into a request, never throws out of one. A notification is
|
|
5
|
+
* never more important than the action that caused it: a bell that fails must not fail a reply,
|
|
6
|
+
* an assignment, or a payment. Failures are logged and that is all.
|
|
7
|
+
*
|
|
8
|
+
* NO REQUEST, NO ACTOR REQUIRED — and this is the part worth reading before changing it.
|
|
9
|
+
*
|
|
10
|
+
* The app this was extracted from raised every notification from a request, and derived the
|
|
11
|
+
* actor from `req.session.user`. That is true of a reply, an assignment, a mention: a person
|
|
12
|
+
* did something. It is NOT true of the cases the second consumer needs — a scheduler deciding
|
|
13
|
+
* at 09:00 that an invoice is overdue, or a webhook recording a payment. Nobody did anything,
|
|
14
|
+
* there is no session, and there is no name to put in front of the title.
|
|
15
|
+
*
|
|
16
|
+
* So the core takes user ids and a payload. An actor is an optional string. A request-shaped
|
|
17
|
+
* convenience belongs in the app, as a thin wrapper that resolves the actor and calls this —
|
|
18
|
+
* which keeps the system-raised notification the ORDINARY case rather than a special one. Had
|
|
19
|
+
* this required a `req`, the scheduler would have grown a second emitter beside it, which is
|
|
20
|
+
* the duplication the extraction exists to prevent.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
'use strict';
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* @param {Function} invoke (model, method, ...args) => Promise — the app's worker bridge
|
|
27
|
+
* @param {object} hub from createHub(); may be omitted where nothing is connected
|
|
28
|
+
* @param {object} logger needs .error; a missing one is not a reason to crash
|
|
29
|
+
* @param {string} model the worker-side model name to call, default 'Notification'
|
|
30
|
+
*/
|
|
31
|
+
function createEmitter({ invoke, hub, logger = console, model = 'Notification' } = {}) {
|
|
32
|
+
if (typeof invoke !== 'function') throw new Error('notify: invoke() is required');
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Create notifications for the given users and push to any open streams.
|
|
36
|
+
*
|
|
37
|
+
* Returns a promise for tests and for callers that genuinely want to wait, but the intended
|
|
38
|
+
* use is to ignore it — see the fire-and-forget note above. It NEVER rejects.
|
|
39
|
+
*
|
|
40
|
+
* @param {number[]} userIds
|
|
41
|
+
* @param {{type, title, body?, link?, actor_name?, entity_type?, entity_id?}} payload
|
|
42
|
+
* @param {{event?: object}} [opts] what to send over SSE; defaults to a contentless nudge
|
|
43
|
+
*/
|
|
44
|
+
function emit(userIds, payload = {}, opts = {}) {
|
|
45
|
+
return Promise.resolve()
|
|
46
|
+
.then(() => invoke(model, 'createMany', userIds, payload))
|
|
47
|
+
.then((r) => {
|
|
48
|
+
const ids = (r && r.userIds) || [];
|
|
49
|
+
if (ids.length && hub) {
|
|
50
|
+
// CONTENTLESS BY DEFAULT. The client re-fetches through its own permission-checked
|
|
51
|
+
// route, so this channel cannot leak a title or a body even if a subscription were
|
|
52
|
+
// wrong — and the app's own view permission stays the single place access is decided.
|
|
53
|
+
hub.pushUsers(ids, opts.event || { type: 'notif' });
|
|
54
|
+
}
|
|
55
|
+
return ids;
|
|
56
|
+
})
|
|
57
|
+
.catch((e) => {
|
|
58
|
+
// Swallowed on purpose. The row is the durable record; if the insert failed there is
|
|
59
|
+
// nothing to deliver, and the action that triggered it has already succeeded.
|
|
60
|
+
try { logger.error(`notify: ${(e && e.message) || e}`); } catch (_) { /* noop */ }
|
|
61
|
+
return [];
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Tell anyone with the record OPEN that it changed, without creating a notification.
|
|
67
|
+
*
|
|
68
|
+
* Separate from emit() because they answer different questions and have different audiences:
|
|
69
|
+
* emit() reaches RECIPIENTS wherever they are, this reaches VIEWERS of one record. A person
|
|
70
|
+
* reading a record they do not watch gets nothing from the first and everything from this.
|
|
71
|
+
*/
|
|
72
|
+
function touch(entityType, entityId, extra = {}) {
|
|
73
|
+
if (!hub) return 0;
|
|
74
|
+
try { return hub.pushEntity(entityType, entityId, extra); } catch (_) { return 0; }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return { emit, touch };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
module.exports = { createEmitter };
|
package/hub.js
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Live delivery of notifications to open browsers.
|
|
3
|
+
*
|
|
4
|
+
* DELIBERATELY IN-MEMORY AND EPHEMERAL. The notifications TABLE is the durable record; this is
|
|
5
|
+
* only about telling a connected tab to re-fetch. A user who is offline sees the badge on their
|
|
6
|
+
* next page load, and nothing here needs to survive a restart.
|
|
7
|
+
*
|
|
8
|
+
* THE LIMIT THAT MUST BE STATED RATHER THAN DISCOVERED: this is per-process. Two app processes
|
|
9
|
+
* behind a load balancer each hold half the connections, so a push from one reaches only its
|
|
10
|
+
* own half — silently, with no error anywhere. Correct for a single process, which is what both
|
|
11
|
+
* current consumers run; a multi-process deployment needs a shared bus and this module is not
|
|
12
|
+
* it.
|
|
13
|
+
*
|
|
14
|
+
* TWO CHANNELS, because they answer different questions:
|
|
15
|
+
*
|
|
16
|
+
* users "tell these RECIPIENTS something happened" — the notification bell
|
|
17
|
+
* entities "tell whoever is LOOKING at this thing that it changed" — the open page
|
|
18
|
+
*
|
|
19
|
+
* The second is not a nicety. Pushes on the first channel go to recipients, so someone reading
|
|
20
|
+
* a record they do not watch is told nothing — which is the ordinary state of an unassigned
|
|
21
|
+
* ticket or an unowned invoice, and exactly the one most likely to be open when it changes.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
'use strict';
|
|
25
|
+
|
|
26
|
+
const HEARTBEAT_MS = 25000; // keep idle connections alive through proxies
|
|
27
|
+
|
|
28
|
+
function createHub({ heartbeatMs = HEARTBEAT_MS } = {}) {
|
|
29
|
+
const users = new Map(); // userId -> Set(res)
|
|
30
|
+
const entities = new Map(); // "type:id" -> Set(res)
|
|
31
|
+
let heartbeat = null;
|
|
32
|
+
|
|
33
|
+
const key = (type, id) => `${type}:${id}`;
|
|
34
|
+
|
|
35
|
+
function ensureHeartbeat() {
|
|
36
|
+
if (heartbeat) return;
|
|
37
|
+
heartbeat = setInterval(() => {
|
|
38
|
+
// Both maps, and each response ONCE: a connection registered on both channels must not
|
|
39
|
+
// be pinged twice, and one registered only for an entity still needs keeping alive.
|
|
40
|
+
const seen = new Set();
|
|
41
|
+
for (const map of [users, entities]) {
|
|
42
|
+
for (const set of map.values()) {
|
|
43
|
+
for (const res of set) {
|
|
44
|
+
if (seen.has(res)) continue;
|
|
45
|
+
seen.add(res);
|
|
46
|
+
try { res.write(': ping\n\n'); } catch (_) { /* dropped */ }
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}, heartbeatMs);
|
|
51
|
+
// Never keep the process alive on account of a keepalive.
|
|
52
|
+
if (heartbeat.unref) heartbeat.unref();
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const add = (map, k, res) => {
|
|
56
|
+
let set = map.get(k);
|
|
57
|
+
if (!set) { set = new Set(); map.set(k, set); }
|
|
58
|
+
set.add(res);
|
|
59
|
+
};
|
|
60
|
+
const remove = (map, k, res) => {
|
|
61
|
+
const set = map.get(k);
|
|
62
|
+
if (!set) return;
|
|
63
|
+
set.delete(res);
|
|
64
|
+
if (!set.size) map.delete(k);
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Register an open SSE response.
|
|
69
|
+
*
|
|
70
|
+
* @param {number} userId
|
|
71
|
+
* @param {object} res
|
|
72
|
+
* @param {{entity?: {type: string, id: number|string}}} [opts] also watch one record
|
|
73
|
+
* @returns {function} unsubscribe — removes from BOTH maps
|
|
74
|
+
*
|
|
75
|
+
* ONE unsubscribe covering both maps, deliberately: two functions is two chances for a
|
|
76
|
+
* caller to wire up only one, and an entry left behind holds a dead response that the
|
|
77
|
+
* heartbeat then writes to forever.
|
|
78
|
+
*/
|
|
79
|
+
function subscribe(userId, res, opts = {}) {
|
|
80
|
+
const uid = Number(userId);
|
|
81
|
+
add(users, uid, res);
|
|
82
|
+
const e = opts.entity;
|
|
83
|
+
const ek = e && e.type != null && e.id != null ? key(e.type, e.id) : null;
|
|
84
|
+
if (ek) add(entities, ek, res);
|
|
85
|
+
ensureHeartbeat();
|
|
86
|
+
return function unsubscribe() {
|
|
87
|
+
remove(users, uid, res);
|
|
88
|
+
if (ek) remove(entities, ek, res);
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const write = (set, payload) => {
|
|
93
|
+
if (!set) return 0;
|
|
94
|
+
let n = 0;
|
|
95
|
+
for (const res of set) {
|
|
96
|
+
try { res.write(payload); n++; } catch (_) { /* dropped */ }
|
|
97
|
+
}
|
|
98
|
+
return n;
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
/** Tell every open stream of each listed user that something arrived for them. */
|
|
102
|
+
function pushUsers(userIds, event) {
|
|
103
|
+
const payload = `data: ${JSON.stringify(event || { type: 'notif' })}\n\n`;
|
|
104
|
+
let n = 0;
|
|
105
|
+
for (const uid of (userIds || [])) n += write(users.get(Number(uid)), payload);
|
|
106
|
+
return n;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Tell everyone VIEWING a record that it changed.
|
|
111
|
+
*
|
|
112
|
+
* The event carries the type and id and NOTHING ELSE by default. The client re-fetches
|
|
113
|
+
* through the normal permission-checked route, so this channel cannot leak content even if a
|
|
114
|
+
* subscription were wrong, and the app's own view permission stays the single place access is
|
|
115
|
+
* decided.
|
|
116
|
+
*
|
|
117
|
+
* One consumer briefly included an `actorUserId` "so a viewer can ignore its own action". No
|
|
118
|
+
* client ever read it, so its only effect was disclosing one staffer's user id to every other
|
|
119
|
+
* viewer on every reply. A field nothing consumes is not a feature waiting to be used.
|
|
120
|
+
*/
|
|
121
|
+
function pushEntity(type, id, extra = {}) {
|
|
122
|
+
const payload = `data: ${JSON.stringify({ type, id, ...extra })}\n\n`;
|
|
123
|
+
return write(entities.get(key(type, id)), payload);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function stats() {
|
|
127
|
+
return { users: users.size, entities: entities.size };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* End every open response and stop the heartbeat.
|
|
132
|
+
*
|
|
133
|
+
* 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 — both maps, because a subscription
|
|
135
|
+
* left open on either one is enough to hold the process.
|
|
136
|
+
*/
|
|
137
|
+
function closeAll() {
|
|
138
|
+
if (heartbeat) { clearInterval(heartbeat); heartbeat = null; }
|
|
139
|
+
const ended = new Set();
|
|
140
|
+
for (const map of [users, entities]) {
|
|
141
|
+
for (const set of map.values()) {
|
|
142
|
+
for (const res of set) {
|
|
143
|
+
if (ended.has(res)) continue; // a connection on both channels ends once
|
|
144
|
+
ended.add(res);
|
|
145
|
+
try { res.end(); } catch (_) { /* ignore */ }
|
|
146
|
+
}
|
|
147
|
+
set.clear();
|
|
148
|
+
}
|
|
149
|
+
map.clear();
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
return { subscribe, pushUsers, pushEntity, stats, closeAll };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
module.exports = { createHub, HEARTBEAT_MS };
|
package/index.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @aria-framework/notify — in-app notifications.
|
|
3
|
+
*
|
|
4
|
+
* Three pieces, in three places, because that is where they have to run:
|
|
5
|
+
*
|
|
6
|
+
* store WORKER thread. The SQL, ownership-scoped by user_id.
|
|
7
|
+
* hub MAIN thread. Open SSE responses, in memory, per process.
|
|
8
|
+
* emit MAIN thread. Create then push, fire-and-forget.
|
|
9
|
+
*
|
|
10
|
+
* What the app keeps: WHO receives a notification, what the types are called, what the copy
|
|
11
|
+
* says, the migration, and the routes. "Who cares about this thing" is domain knowledge — the
|
|
12
|
+
* answer is "the ticket's watchers" in one app and "whoever owns the invoice" in another, and
|
|
13
|
+
* neither belongs here.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
'use strict';
|
|
17
|
+
|
|
18
|
+
module.exports = {
|
|
19
|
+
...require('./store'),
|
|
20
|
+
...require('./hub'),
|
|
21
|
+
...require('./emit')
|
|
22
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@aria-framework/notify",
|
|
3
|
+
"version": "0.1.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
|
+
],
|
|
17
|
+
"peerDependencies": {
|
|
18
|
+
"better-sqlite3": ">=11"
|
|
19
|
+
},
|
|
20
|
+
"peerDependenciesMeta": {
|
|
21
|
+
"better-sqlite3": {
|
|
22
|
+
"optional": true
|
|
23
|
+
}
|
|
24
|
+
},
|
|
25
|
+
"scripts": {
|
|
26
|
+
"test": "node test/store.js && node test/hub.js && node test/emit.js"
|
|
27
|
+
}
|
|
28
|
+
}
|
package/store.js
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The notification rows. WORKER SIDE — this is where the SQL runs.
|
|
3
|
+
*
|
|
4
|
+
* One row per (recipient, event). Nothing here knows what the app's records are: a row carries
|
|
5
|
+
* a `type`, a title, an optional body and link, and an optional `entity_type`/`entity_id`
|
|
6
|
+
* pointing at whatever the app cares about. "Alice replied" and "Invoice #412 is overdue" are
|
|
7
|
+
* the same shape.
|
|
8
|
+
*
|
|
9
|
+
* EVERY QUERY IS OWNERSHIP-SCOPED BY user_id, AND THAT PREDICATE IS THE SECURITY BOUNDARY.
|
|
10
|
+
* An id you do not own simply matches zero rows — there is no separate authorisation check to
|
|
11
|
+
* forget, and moving the scope to a caller-side `if` would be a silent authorisation bug rather
|
|
12
|
+
* than a refactor. Read that as a constraint on future edits, not as a description.
|
|
13
|
+
*
|
|
14
|
+
* The app owns the table. This module documents the columns it uses and reads nothing else, so
|
|
15
|
+
* an app is free to add its own.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
'use strict';
|
|
19
|
+
|
|
20
|
+
/** The columns this module reads and writes. An app's migration must provide at least these. */
|
|
21
|
+
const SCHEMA = `
|
|
22
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
23
|
+
user_id INTEGER NOT NULL, -- recipient; FK to the app's users table
|
|
24
|
+
type TEXT NOT NULL, -- app-defined, e.g. 'assigned' | 'invoice.overdue'
|
|
25
|
+
title TEXT NOT NULL, -- short line
|
|
26
|
+
body TEXT, -- optional snippet
|
|
27
|
+
link TEXT, -- click target
|
|
28
|
+
actor_name TEXT, -- who caused it, SNAPSHOT — survives rename/delete.
|
|
29
|
+
-- NULL for anything a scheduler or webhook raised
|
|
30
|
+
entity_type TEXT, -- app's record type, e.g. 'ticket' | 'invoice'
|
|
31
|
+
entity_id INTEGER,
|
|
32
|
+
is_read INTEGER NOT NULL DEFAULT 0,
|
|
33
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
34
|
+
read_at TEXT
|
|
35
|
+
`;
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* @param {Function} getDb returns the better-sqlite3 handle. A function, not a handle, because
|
|
39
|
+
* the worker opens the database after modules are required.
|
|
40
|
+
* @param {string} table defaults to `notifications`
|
|
41
|
+
*/
|
|
42
|
+
function createStore({ getDb, table = 'notifications' } = {}) {
|
|
43
|
+
if (typeof getDb !== 'function') throw new Error('notify: getDb() is required');
|
|
44
|
+
// Interpolated once, at construction, from a value the APP supplies — never from a request.
|
|
45
|
+
const T = String(table).replace(/[^A-Za-z0-9_]/g, '');
|
|
46
|
+
if (!T) throw new Error('notify: table name must be a plain identifier');
|
|
47
|
+
|
|
48
|
+
const unreadCount = (userId) => getDb()
|
|
49
|
+
.prepare(`SELECT COUNT(*) AS c FROM ${T} WHERE user_id = ? AND is_read = 0`)
|
|
50
|
+
.get(userId).c;
|
|
51
|
+
|
|
52
|
+
return {
|
|
53
|
+
SCHEMA,
|
|
54
|
+
table: T,
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Insert one row per recipient, transactionally.
|
|
58
|
+
*
|
|
59
|
+
* Returns the ids actually written so the caller can hand them to the hub. De-duplicated,
|
|
60
|
+
* because "the assignee" and "a collaborator" are frequently the same person and two bells
|
|
61
|
+
* for one event reads as a bug.
|
|
62
|
+
*
|
|
63
|
+
* @param {number[]} userIds
|
|
64
|
+
* @param {{type, title, body?, link?, actor_name?, entity_type?, entity_id?}} p
|
|
65
|
+
* @returns {{userIds: number[]}}
|
|
66
|
+
*/
|
|
67
|
+
createMany(userIds, p = {}) {
|
|
68
|
+
const ids = [...new Set((userIds || []).filter((v) => v != null).map(Number))]
|
|
69
|
+
.filter((n) => Number.isInteger(n));
|
|
70
|
+
// A notification with no type or no title has nothing to show; refusing quietly is right
|
|
71
|
+
// because the caller is fire-and-forget and must not learn about this through a throw.
|
|
72
|
+
if (!ids.length || !p.type || !p.title) return { userIds: [] };
|
|
73
|
+
|
|
74
|
+
const db = getDb();
|
|
75
|
+
const ins = db.prepare(`
|
|
76
|
+
INSERT INTO ${T} (user_id, type, title, body, link, actor_name, entity_type, entity_id)
|
|
77
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
78
|
+
`);
|
|
79
|
+
db.transaction(() => {
|
|
80
|
+
for (const uid of ids) {
|
|
81
|
+
ins.run(uid, p.type, p.title, p.body || null, p.link || null,
|
|
82
|
+
p.actor_name || null, p.entity_type || null, p.entity_id || null);
|
|
83
|
+
}
|
|
84
|
+
})();
|
|
85
|
+
return { userIds: ids };
|
|
86
|
+
},
|
|
87
|
+
|
|
88
|
+
unreadCount,
|
|
89
|
+
|
|
90
|
+
/** Latest N (read and unread) for the bell, plus the unread count. */
|
|
91
|
+
recent(userId, limit = 15) {
|
|
92
|
+
const lim = Math.min(50, Math.max(1, parseInt(limit, 10) || 15));
|
|
93
|
+
const items = getDb().prepare(
|
|
94
|
+
`SELECT * FROM ${T} WHERE user_id = ? ORDER BY created_at DESC, id DESC LIMIT ?`
|
|
95
|
+
).all(userId, lim);
|
|
96
|
+
return { unread: unreadCount(userId), items };
|
|
97
|
+
},
|
|
98
|
+
|
|
99
|
+
/** Paginated history for a full notifications page. */
|
|
100
|
+
listPage(userId, page = 1, pageSize = 25) {
|
|
101
|
+
const db = getDb();
|
|
102
|
+
const p = Math.max(1, parseInt(page, 10) || 1);
|
|
103
|
+
const size = Math.min(100, Math.max(5, parseInt(pageSize, 10) || 25));
|
|
104
|
+
const total = db.prepare(`SELECT COUNT(*) AS c FROM ${T} WHERE user_id = ?`).get(userId).c;
|
|
105
|
+
const rows = db.prepare(
|
|
106
|
+
`SELECT * FROM ${T} WHERE user_id = ? ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?`
|
|
107
|
+
).all(userId, size, (p - 1) * size);
|
|
108
|
+
return {
|
|
109
|
+
rows, total, page: p, pageSize: size,
|
|
110
|
+
pages: Math.max(1, Math.ceil(total / size)),
|
|
111
|
+
unread: unreadCount(userId)
|
|
112
|
+
};
|
|
113
|
+
},
|
|
114
|
+
|
|
115
|
+
/** Mark one read — ONLY if it belongs to userId. The scope is the authorisation. */
|
|
116
|
+
markRead(id, userId) {
|
|
117
|
+
const r = getDb().prepare(
|
|
118
|
+
`UPDATE ${T} SET is_read = 1, read_at = datetime('now')
|
|
119
|
+
WHERE id = ? AND user_id = ? AND is_read = 0`
|
|
120
|
+
).run(id, userId);
|
|
121
|
+
return { changed: r.changes };
|
|
122
|
+
},
|
|
123
|
+
|
|
124
|
+
markAllRead(userId) {
|
|
125
|
+
const r = getDb().prepare(
|
|
126
|
+
`UPDATE ${T} SET is_read = 1, read_at = datetime('now')
|
|
127
|
+
WHERE user_id = ? AND is_read = 0`
|
|
128
|
+
).run(userId);
|
|
129
|
+
return { changed: r.changes };
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
module.exports = { createStore, SCHEMA };
|