@jskit-ai/push-core 0.1.4 → 0.1.6

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/CHANGELOG.md CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - `push.sendEach(notifications)` sends several notifications, each to its own people with its own fields, in the same statements as one `push.send`, and answers their outcomes summed. A notification's `hiddenBody` is shown in place of `body` to a person who hides text (it was empty). `GET /api/push`'s devices carry their `tokenHash`, so a client can tell which is this one.
5
6
  - Its migrations declare `"after": ["@jskit-ai/users-core"]`: they create a key to `users` with their tables, and ran before users-core created it on a new database (path order), which MySQL and PostgreSQL refuse.
6
7
  - Quiet hours with one end are refused with the empty end in `details.fieldErrors` (`quietFrom` or `quietTo`, codes `push.settings.quietFromRequired` and `push.settings.quietToRequired`), so the field shows it. The refusals of a browser subscription, an unknown push service and an unknown time zone now say what the person can do.
7
8
  - The manifest's `jskit.capabilities.requires` lists `runtime.env` and `runtime.logger`, which `PushFeature` requires; without them an app's server stopped at start-up.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/push-core",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "jskit test"
@@ -89,15 +89,15 @@
89
89
  }
90
90
  },
91
91
  "dependencies": {
92
- "@jskit-ai/resource-core": "0.1.235",
92
+ "@jskit-ai/resource-core": "0.1.236",
93
93
  "json-rest-schema": "^1.0.20",
94
94
  "web-push": "4.0.0"
95
95
  },
96
96
  "peerDependencies": {
97
- "@jskit-ai/database-runtime": "0.1.302",
98
- "@jskit-ai/http-runtime": "0.2.46",
99
- "@jskit-ai/kernel": "0.2.44",
100
- "@jskit-ai/resource-runtime": "0.2.69",
101
- "@jskit-ai/users-core": "0.2.88"
97
+ "@jskit-ai/database-runtime": "0.1.303",
98
+ "@jskit-ai/http-runtime": "0.2.47",
99
+ "@jskit-ai/kernel": "0.2.45",
100
+ "@jskit-ai/resource-runtime": "0.2.70",
101
+ "@jskit-ai/users-core": "0.2.89"
102
102
  }
103
103
  }
@@ -38,6 +38,9 @@ function createPush({ devices, settings, senders, vapidPublicKey, environment, l
38
38
  kind: device.kind,
39
39
  label: device.label || "",
40
40
  environment: device.environment || "",
41
+ // The same hash push_devices keys a device by, so a page can tell which listed device is its own
42
+ // (push-web's isCurrent); the token itself never leaves the server.
43
+ tokenHash: device.tokenHash,
41
44
  createdAt: device.createdAt,
42
45
  lastSeenAt: device.lastSeenAt || null
43
46
  }))),
@@ -118,42 +121,73 @@ function createPush({ devices, settings, senders, vapidPublicKey, environment, l
118
121
 
119
122
  /**
120
123
  * Sends one notification to every device of these people, except where they turned its kind off or are in quiet
121
- * hours; a person who hides text gets the title alone. Statements stay a few whatever the number of devices.
124
+ * hours; a person who hides text gets the title alone, or its `hiddenBody`. Statements stay a few whatever the number
125
+ * of devices.
122
126
  * @param {import("./types.js").PushNotification} notification
123
127
  */
124
128
  async function send(notification) {
125
- const { userIds, kind, title } = notification;
126
- if (!Array.isArray(userIds) || !KIND.test(String(kind)) || !String(title || "").trim()) {
127
- throw new TypeError("push.send needs userIds (an array), a kind such as \"message\" and a title.");
129
+ return sendNotifications([notification], "push.send");
130
+ }
131
+
132
+ /**
133
+ * Sends several notifications at once, each to its own people with its own title, url, group and badge, as `send`
134
+ * does each: every person's devices and settings are read in one statement each, whatever the number of
135
+ * notifications. It answers the summed outcome. A device several of them reach keeps one state: gone if any was
136
+ * gone, else sent if any was sent, else one more failure.
137
+ * @param {readonly import("./types.js").PushNotification[]} notifications
138
+ */
139
+ async function sendEach(notifications) {
140
+ if (!Array.isArray(notifications)) throw new TypeError("push.sendEach needs an array of notifications, each as push.send takes one.");
141
+ return sendNotifications(notifications, "push.sendEach");
142
+ }
143
+
144
+ async function sendNotifications(notifications, call) {
145
+ for (const { userIds, kind, title } of notifications) {
146
+ if (!Array.isArray(userIds) || !KIND.test(String(kind)) || !String(title || "").trim()) {
147
+ throw new TypeError(`${call} needs userIds (an array), a kind such as "message" and a title.`);
148
+ }
128
149
  }
129
- const ids = [...new Set(userIds.map(String))];
150
+ const people = notifications.map((notification) => [...new Set(notification.userIds.map(String))]);
151
+ const ids = [...new Set(people.flat())];
130
152
  const [all, settingsFor] = await Promise.all([
131
- devices.listForUsers(ids, systemOptions),
153
+ ids.length ? devices.listForUsers(ids, systemOptions) : [],
132
154
  settings.readForUsers(ids, systemOptions)
133
155
  ]);
156
+ const devicesOf = Map.groupBy(all, (device) => String(device.userId));
134
157
  const at = new Date(now());
135
- const targets = all.filter((device) => {
136
- const own = settingsFor(device.userId);
137
- return !own.kindsOff.includes(kind) && !inQuietHours(own, at);
158
+ const deliveries = [];
159
+ let reached = 0;
160
+ let skipped = 0;
161
+ notifications.forEach((notification, index) => {
162
+ for (const device of people[index].flatMap((userId) => devicesOf.get(userId) || [])) {
163
+ reached += 1;
164
+ const own = settingsFor(device.userId);
165
+ if (own.kindsOff.includes(notification.kind) || inQuietHours(own, at)) skipped += 1;
166
+ else deliveries.push({ device, message: messageFor(notification, own) });
167
+ }
138
168
  });
139
- const skipped = all.length - targets.length;
140
169
  if (environment !== "production") {
170
+ const [first] = notifications;
141
171
  logSideEffect(logger, environment, {
142
172
  kind: "push notification",
143
- summary: `the "${kind}" notification "${title}" to ${targets.length} device(s)`,
144
- details: { notificationKind: kind, title, userIds: ids, devices: targets.length }
173
+ summary: notifications.length === 1
174
+ ? `the "${first.kind}" notification "${first.title}" to ${deliveries.length} device(s)`
175
+ : `${notifications.length} notifications to ${deliveries.length} device(s)`,
176
+ details: notifications.length === 1
177
+ ? { notificationKind: first.kind, title: first.title, userIds: people[0], devices: deliveries.length }
178
+ : { notifications: notifications.length, userIds: ids, devices: deliveries.length }
145
179
  });
146
- return Object.freeze({ devices: all.length, sent: 0, gone: 0, failed: 0, skipped, logged: targets.length });
180
+ return Object.freeze({ devices: reached, sent: 0, gone: 0, failed: 0, skipped, logged: deliveries.length });
147
181
  }
148
- const outcomes = await sendAll(targets, (device) => messageFor(notification, settingsFor(device.userId)));
149
- return recordOutcomes(targets, outcomes, all.length, skipped);
182
+ const outcomes = await sendAll(deliveries);
183
+ return recordOutcomes(deliveries, outcomes, reached, skipped);
150
184
  }
151
185
 
152
- async function sendAll(targets, messageOf) {
153
- const outcomes = new Array(targets.length);
154
- for (let start = 0; start < targets.length; start += SEND_CONCURRENCY) {
155
- const batch = targets.slice(start, start + SEND_CONCURRENCY);
156
- const answered = await Promise.all(batch.map((device) => sendOne(device, messageOf(device))));
186
+ async function sendAll(deliveries) {
187
+ const outcomes = new Array(deliveries.length);
188
+ for (let start = 0; start < deliveries.length; start += SEND_CONCURRENCY) {
189
+ const batch = deliveries.slice(start, start + SEND_CONCURRENCY);
190
+ const answered = await Promise.all(batch.map(({ device, message }) => sendOne(device, message)));
157
191
  answered.forEach((outcome, index) => {
158
192
  outcomes[start + index] = outcome;
159
193
  });
@@ -175,15 +209,26 @@ function createPush({ devices, settings, senders, vapidPublicKey, environment, l
175
209
  }
176
210
  }
177
211
 
178
- // Writes only to the devices whose state changed: gone, failing, or answering again after failing.
179
- async function recordOutcomes(targets, outcomes, total, skipped) {
180
- const sent = [];
212
+ // The state a device keeps after its deliveries: gone if any was gone, else sent if any was sent, else failed if any
213
+ // failed; other outcomes (unconfigured, throttled) change nothing.
214
+ const STATE_ORDER = Object.freeze(["gone", "sent", "failed"]);
215
+
216
+ // Writes only to the devices whose state changed: gone, failing, or answering again after failing. `sent` counts
217
+ // deliveries; `gone` and `failed` count devices, each once.
218
+ async function recordOutcomes(deliveries, outcomes, total, skipped) {
219
+ const stateOf = new Map();
220
+ let sent = 0;
221
+ deliveries.forEach(({ device }, index) => {
222
+ const { status } = outcomes[index];
223
+ if (status === "sent") sent += 1;
224
+ const rank = STATE_ORDER.indexOf(status);
225
+ const kept = stateOf.get(device.id);
226
+ if (rank >= 0 && (!kept || rank < STATE_ORDER.indexOf(kept.status))) stateOf.set(device.id, { device, status });
227
+ });
181
228
  const recovered = [];
182
229
  const gone = [];
183
230
  const failuresByCount = new Map();
184
- targets.forEach((device, index) => {
185
- const { status } = outcomes[index];
186
- if (status === "sent") sent.push(device.id);
231
+ for (const { device, status } of stateOf.values()) {
187
232
  if (status === "sent" && Number(device.failures || 0) > 0) recovered.push(device.id);
188
233
  if (status === "gone") gone.push(device.id);
189
234
  if (status === "failed") {
@@ -191,12 +236,12 @@ function createPush({ devices, settings, senders, vapidPublicKey, environment, l
191
236
  if (failures >= MAX_FAILURES) gone.push(device.id);
192
237
  else failuresByCount.set(failures, [...(failuresByCount.get(failures) || []), device.id]);
193
238
  }
194
- });
239
+ }
195
240
  await devices.clearFailures(recovered, systemOptions);
196
241
  await devices.removeIds(gone, systemOptions);
197
242
  await devices.setFailures(failuresByCount, systemOptions);
198
- const failed = [...failuresByCount.values()].reduce((count, ids) => count + ids.length, 0);
199
- return Object.freeze({ devices: total, sent: sent.length, gone: gone.length, failed, skipped, logged: 0 });
243
+ const failed = [...failuresByCount.values()].reduce((count, idsFailing) => count + idsFailing.length, 0);
244
+ return Object.freeze({ devices: total, sent, gone: gone.length, failed, skipped, logged: 0 });
200
245
  }
201
246
 
202
247
  /**
@@ -226,7 +271,18 @@ function createPush({ devices, settings, senders, vapidPublicKey, environment, l
226
271
  await settings.removeForUser(userId, systemOptions);
227
272
  }
228
273
 
229
- return Object.freeze({ readOverview, registerDevice, forgetDevice, removeDevice, updateSettings, send, updateLiveActivity, forgetAccount, close });
274
+ return Object.freeze({
275
+ readOverview,
276
+ registerDevice,
277
+ forgetDevice,
278
+ removeDevice,
279
+ updateSettings,
280
+ send,
281
+ sendEach,
282
+ updateLiveActivity,
283
+ forgetAccount,
284
+ close
285
+ });
230
286
  }
231
287
 
232
288
  /** @param {Record<string, any>} device */
@@ -235,12 +291,13 @@ function deviceOf(device) {
235
291
  }
236
292
 
237
293
  /**
238
- * The message a device gets: the notification's fields, its text left out for a person who hides it.
294
+ * The message a device gets: the notification's fields, its text left out for a person who hides it, or its
295
+ * `hiddenBody` (such as "New message") in its place.
239
296
  * @param {import("./types.js").PushNotification} notification
240
297
  * @param {{ showText: boolean }} own
241
298
  */
242
- function messageFor({ kind, title, body, url, data, actions, badge, group, category, channel }, own) {
243
- const message = { kind, title, body: own.showText ? body || "" : "", url, data, actions, badge, group, category, channel };
299
+ function messageFor({ kind, title, body, hiddenBody, url, data, actions, badge, group, category, channel }, own) {
300
+ const message = { kind, title, body: own.showText ? body || "" : hiddenBody || "", url, data, actions, badge, group, category, channel };
244
301
  return Object.fromEntries(Object.entries(message).filter(([, value]) => value !== undefined && value !== ""));
245
302
  }
246
303
 
@@ -3,16 +3,18 @@
3
3
  /** @typedef {ReturnType<typeof import("./pushService.js").createPush>} Push */
4
4
 
5
5
  /**
6
- * One notification for `push.send`: the people it is for and what it says. `kind` is one the application declares
6
+ * One notification for `push.send` (or one of `push.sendEach`'s): the people it is for and what it says. `kind` is one the application declares
7
7
  * (`config.push.kinds`), which people turn on or off; `url` is the app's own page a tap opens; `actions` are the
8
8
  * buttons a browser shows; `category` names an action set the app's iOS and Android projects declare; `group` threads
9
9
  * notifications together (iOS thread id, Android tag, web push topic); `channel` is the Android channel; `badge` is the
10
- * count the app's icon shows.
10
+ * count the app's icon shows; `hiddenBody` is sent in place of `body` to a person who hides message text ("New
11
+ * message"), who otherwise gets the title alone.
11
12
  * @typedef {object} PushNotification
12
13
  * @property {ReadonlyArray<string>} userIds
13
14
  * @property {string} kind
14
15
  * @property {string} title
15
16
  * @property {string} [body]
17
+ * @property {string} [hiddenBody]
16
18
  * @property {string} [url]
17
19
  * @property {Record<string, unknown>} [data]
18
20
  * @property {ReadonlyArray<{ action: string, title: string }>} [actions]
@@ -22,7 +24,7 @@
22
24
  * @property {string} [channel]
23
25
  */
24
26
 
25
- /** @typedef {Omit<PushNotification, "userIds">} PushMessage What one device is sent. */
27
+ /** @typedef {Omit<PushNotification, "userIds" | "hiddenBody">} PushMessage What one device is sent. */
26
28
 
27
29
  /**
28
30
  * @typedef {object} PushSender
@@ -1,5 +1,6 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
+ import { deviceTokenHash } from "../src/server/deviceRegistry.js";
3
4
  import { expectFlatQueries } from "@jskit-ai/resource-runtime/test";
4
5
  import { as, startPush } from "./support/pushHarness.js";
5
6
 
@@ -21,6 +22,14 @@ test("a person registers each device once, again by the same token, and sees onl
21
22
  assert.deepEqual(ada.configured, { webpush: false, apns: false, fcm: false });
22
23
  });
23
24
 
25
+ test("the overview lists each device with the hash push_devices keys it by, never its token", async (t) => {
26
+ const { push } = await startPush(t, { people: 1 });
27
+ await push.registerDevice({ kind: "fcm", token: "ada-phone" }, as(1));
28
+ const [listed] = (await push.readOverview(as(1))).devices;
29
+ assert.equal(listed.tokenHash, deviceTokenHash("fcm", "ada-phone"));
30
+ assert.equal(listed.token, undefined);
31
+ });
32
+
24
33
  test("a phone token another person registered moves to the person now signed in on it", async (t) => {
25
34
  const { push } = await startPush(t);
26
35
  await push.registerDevice({ kind: "fcm", token: "shared-phone" }, as(1));
package/test/send.test.js CHANGED
@@ -82,3 +82,49 @@ test("a send's statements stay the same from 10 devices to 1,000", async (t) =>
82
82
  run: (userIds) => push.send({ userIds, kind: "message", title: "Hello" })
83
83
  });
84
84
  });
85
+
86
+ test("sendEach sends each notification to its own people with its own fields, and sums their outcomes", async (t) => {
87
+ const delivered = fakeFcm(t);
88
+ const { push } = await startPush(t, { env: PRODUCTION, people: 3 });
89
+ await push.registerDevice({ kind: "fcm", token: "ada-phone" }, as(1));
90
+ await push.registerDevice({ kind: "fcm", token: "gone-ada-tablet" }, as(1));
91
+ await push.registerDevice({ kind: "fcm", token: "grace-phone" }, as(2));
92
+ await push.updateSettings({ kindsOff: [], showText: false }, as(2));
93
+ await push.updateSettings({ kindsOff: ["message"], showText: true }, as(3));
94
+ await push.registerDevice({ kind: "fcm", token: "linus-phone" }, as(3));
95
+
96
+ const result = await push.sendEach([
97
+ { userIds: ["1", "2"], kind: "message", title: "Chat 7", body: "Lunch?", hiddenBody: "New message", url: "/chats/7", badge: 2 },
98
+ { userIds: ["1"], kind: "message", title: "Chat 8", body: "Done", url: "/chats/8", badge: 3 },
99
+ { userIds: ["3"], kind: "message", title: "Chat 9" }
100
+ ]);
101
+ // Ada's tablet is reached twice and gone once; Linus turned messages off.
102
+ assert.deepEqual(result, { devices: 6, sent: 3, gone: 1, failed: 0, skipped: 1, logged: 0 });
103
+ assert.deepEqual(delivered.map((message) => [message.token, message.notification]), [
104
+ ["ada-phone", { title: "Chat 7", body: "Lunch?" }],
105
+ ["grace-phone", { title: "Chat 7", body: "New message" }],
106
+ ["ada-phone", { title: "Chat 8", body: "Done" }]
107
+ ]);
108
+ assert.deepEqual((await push.readOverview(as(1))).devices.map((device) => device.kind), ["fcm"], "the gone tablet is forgotten once");
109
+ await assert.rejects(push.sendEach({ userIds: ["1"], kind: "message", title: "x" }), /push\.sendEach needs an array/u);
110
+ await assert.rejects(push.sendEach([{ userIds: ["1"], kind: "Bad Kind", title: "x" }]), /push\.sendEach needs userIds/u);
111
+ });
112
+
113
+ test("sendEach's statements stay the same from 3 notifications to 100", async (t) => {
114
+ fakeFcm(t);
115
+ const { knex, push } = await startPush(t, { env: PRODUCTION, people: 210 });
116
+ let nextUser = 1;
117
+ await expectFlatQueries({
118
+ sizes: [3, 100],
119
+ environment: process.env,
120
+ knex,
121
+ async seed(size) {
122
+ const userIds = Array.from({ length: size }, () => String(nextUser++));
123
+ await knex("push_devices").insert(userIds.map((userId) => ({
124
+ user_id: Number(userId), kind: "fcm", token: `device-${userId}`, token_hash: deviceTokenHash("fcm", `device-${userId}`)
125
+ })));
126
+ return userIds.map((userId) => ({ userIds: [userId], kind: "message", title: `Chat ${userId}`, badge: 1 }));
127
+ },
128
+ run: (notifications) => push.sendEach(notifications)
129
+ });
130
+ });