Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions apps/link-service/chaos/run.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ async function bringUp() {
*/
function createProbe(world) {
const pings = [], gaps = [];
let live = null, lastEventAt = 0, stopped = false, timer = null, inFlight = 0, liveReq = null;
let live = null, lastEventAt = 0, openedAt = 0, stopped = false, timer = null, inFlight = 0, liveReq = null;
const port = () => Number(new URL(world.app.origin()).port);
const host = () => world.app.host();
function call(path, { method = "GET", body = null, timeoutMs = 8000, port: at = port(), host: name = host() } = {}) {
Expand Down Expand Up @@ -180,6 +180,7 @@ function createProbe(world) {
res.on("close", () => closed("closed"));
});
liveReq = req;
openedAt = Date.now();
let done = false;
function closed() {
if (done) return;
Expand All @@ -198,7 +199,10 @@ function createProbe(world) {
const up = now - lastEventAt < 5000;
if (!up && downSince === null) downSince = Math.max(lastEventAt, now - 5000);
if (up && downSince !== null) { gaps.push({ from: downSince, to: now }); downSince = null; }
if (liveReq && now - lastEventAt > 20_000 && live) { liveReq.destroy(); }
// as the app does (src/lib/live-events.ts): a dial that sends nothing in LIVE_EVENTS_OPEN_MS (8 s) is dialled again,
// and a stream that went quiet after it sent something is dialled again after 20 s
const quietFor = now - Math.max(lastEventAt, openedAt);
if (liveReq && quietFor > (live ? 20_000 : 8_000)) { liveReq.destroy(); }
}, 250);
return {
start() { timer = setInterval(tick, 500); openLive(); },
Expand Down Expand Up @@ -336,5 +340,6 @@ if (!process.env.DUSK_CHAOS_DIR) {
} else {
process.env.DUSK_CHAOS_PARENT = String(process.pid);
for (const signal of ["SIGINT", "SIGTERM"]) process.on(signal, () => process.exit(130));
main().catch((error) => { console.error(error); process.exit(2); });
// the results are written by then; a socket or timer some scenario left open would otherwise hold the run until CI's job limit
main().then(() => process.exit(process.exitCode ?? 0), (error) => { console.error(error); process.exit(2); });
}
35 changes: 31 additions & 4 deletions apps/link-service/chaos/scenarios.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// things route around it) and answers { clearedAt, pass, note, sees }. run.mjs measures the rest.
import { createHash } from "node:crypto";
import { chmodSync } from "node:fs";
import { Agent as HttpsAgent, request as httpsRequest } from "node:https";
import { join } from "node:path";

import { createTunnelAgent } from "../agent.mjs";
Expand All @@ -27,17 +28,43 @@ async function failover(world, { kill = true } = {}) {
return { pass: moved !== home && moved !== null, note: `moved ${home} -> ${moved} in ${Math.round((workedAt - started) / 1000)} s`, clearedAt: started };
}

/** `count` more servers and apps on the default node, in this process: the agent's and the app's relay code each */
/** a fetch that keeps to one connection of its own. Node's built-in fetch shares one pool for the whole process, and the
* chaos workflow runs without installing packages, so this uses node:https. `close()` ends the connection. */
function fetchOverOwnConnection() {
const agent = new HttpsAgent({ keepAlive: true, maxSockets: 1 });
const ownFetch = (url, { method = "GET", headers = {}, body, signal } = {}) => new Promise((resolve, reject) => {
const request = httpsRequest(url, { method, headers, agent, signal }, (answer) => {
const chunks = [];
answer.on("data", (chunk) => chunks.push(chunk));
answer.on("error", reject);
answer.on("end", () => {
const noBody = [204, 205, 304].includes(answer.statusCode);
const answerHeaders = Object.entries(answer.headers).flatMap(([name, value]) => (Array.isArray(value) ? value.map((one) => [name, one]) : [[name, value]]));
resolve(new Response(noBody ? null : Buffer.concat(chunks), { status: answer.statusCode, headers: answerHeaders }));
});
});
request.on("error", reject);
request.end(body);
});
return { fetch: ownFetch, close: () => agent.destroy() };
}

/** `count` more servers and apps on the default node, in this process: the agent's and the app's relay code each. Each
* sets up its link over its own connection, so the node's front gives it its own address, as `count` machines would have:
* on one connection they would be one address, over the node's limit on new links an address may make in a minute. */
async function crowd(world, count) {
const base = world.url("contabo"), relay = createRelayClient({ base }), out = [];
const base = world.url("contabo"), out = [];
for (let i = 0; i < count; i += 1) {
const own = fetchOverOwnConnection();
const ownFetch = own.fetch;
const keys = newLinkKeys();
const made = await relay.create({ verifier: keys.verifier, appPub: keys.pub });
const made = await createRelayClient({ base, fetch: ownFetch }).create({ verifier: keys.verifier, appPub: keys.pub });
const vps = vpsTokenOf(keys.secret);
const post = (path, body) => fetch(`${base}/v1/sessions/${made.id}/${path}`, { method: "POST", headers: { authorization: `Bearer ${vps}`, "content-type": "application/json" }, body: JSON.stringify(body) });
const post = (path, body) => ownFetch(`${base}/v1/sessions/${made.id}/${path}`, { method: "POST", headers: { authorization: `Bearer ${vps}`, "content-type": "application/json" }, body: JSON.stringify(body) });
await post("claim", {});
const tunnel = { key: randomBytes(32).toString("base64url"), vps: randomBytes(32).toString("base64url"), app: randomBytes(32).toString("base64url") };
const done = await post("result", { sealed: seal(Buffer.alloc(32), made.id, Buffer.from("{}")), vpsPub: keys.pub, tunnel: { vps: sha256hex(tunnel.vps), app: sha256hex(tunnel.app) } });
await own.close();
if (!done.ok) throw new Error(`crowd link ${i} answered ${done.status}`);
const agent = createTunnelAgent({ base, id: made.id, key: tunnel.key, token: tunnel.vps, server: { host: "127.0.0.1", port: world.bot.port }, log: () => {} });
const running = agent.run();
Expand Down
1 change: 1 addition & 0 deletions apps/link-service/src/push-relay.d.mts
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,5 @@ export function activityBody(push: RelayActivityPush): object;
export function alertBody(message: RelayPushMessage): object;
export function fcmBody(token: string, message: RelayPushMessage, draws: boolean): object;
export const SERVICE_TIMEOUT_MS: number;
export const BADGE_KIND: "badge";
export function createPushRelay(options?: Record<string, unknown>): { services: string[]; route(...args: unknown[]): Promise<unknown> };
14 changes: 10 additions & 4 deletions apps/link-service/src/push-relay.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,12 @@ export function pushMessage(value) {

const idsOf = ({ botName: _name, badge: _badge, ...ids }) => ids;

/** an iPhone's app icon count and nothing else, sent when a read elsewhere changes it; its ids are placeholders */
export const BADGE_KIND = "badge";

/** the APNs alert: stacked under its conversation, opened by the app's extension (mutable-content) to show the preview */
export function alertBody(message) {
if (message.kind === BADGE_KIND) return { aps: { badge: message.badge } };
const category = pushCategory(message);
return {
aps: {
Expand Down Expand Up @@ -211,7 +215,7 @@ export function createPushRelay({ env = process.env, now = Date.now, fetch: fetc
}

function sendAlert(token, environment, message) {
return sendApns(token, environment, { "apns-topic": apns.topic, "apns-push-type": "alert", "apns-priority": "10" }, alertBody(message));
return sendApns(token, environment, { "apns-topic": apns.topic, "apns-push-type": "alert", "apns-priority": message.kind === BADGE_KIND ? "5" : "10" }, alertBody(message));
}

function sendActivity(token, environment, activity) {
Expand Down Expand Up @@ -264,10 +268,11 @@ export function createPushRelay({ env = process.env, now = Date.now, fetch: fetc

return {
services,
/** GET /v1/push says which services it delivers; POST /v1/push {service, token, environment?, draws?, message | activity}
* sends one (an activity is APNs only; `draws`: FCM to an app that draws its own notification) */
/** GET /v1/push says which services it delivers, and `badges`: it sends a badge-only push; POST /v1/push {service,
* token, environment?, draws?, message | activity} sends one (an activity and a badge are APNs only; `draws`: FCM to
* an app that draws its own notification) */
async route(req, res, { method, readJson, send, fail, ip }) {
if (method === "GET") return send(res, 200, { services });
if (method === "GET") return send(res, 200, { services, badges: true });
if (method !== "POST") return fail(res, 405, "method not allowed");
const body = await readJson(req, 16_384);
const service = SERVICES.has(body?.service) ? body.service : null;
Expand All @@ -277,6 +282,7 @@ export function createPushRelay({ env = process.env, now = Date.now, fetch: fetc
const activity = body?.activity !== undefined && service === "apns" ? activityMessage(body.activity) : null;
const message = activity ? null : pushMessage(body?.message);
if (!service || !token || (!message && !activity)) return fail(res, 400, "service, token and message are required", "invalid");
if (message?.kind === BADGE_KIND && (service !== "apns" || message.badge === undefined)) return fail(res, 400, "a badge push is APNs only and carries its count", "invalid");
if (!services.includes(service)) return fail(res, 503, `this relay has no ${service === "apns" ? "APNs" : "FCM"} keys`, "not_configured");
if (!allowed(`ip:${ip}`, PER_IP_PER_MINUTE) || !allowed(`token:${token}`, PER_TOKEN_PER_MINUTE)) return fail(res, 429, "too many pushes", "rate_limited");
let outcome;
Expand Down
25 changes: 24 additions & 1 deletion apps/link-service/test/push-relay.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ afterEach(async () => { if (server) await new Promise((resolve) => server.close(
describe("push relay", () => {
it("says which services it delivers and refuses one it has no keys for", async () => {
await start(createPushRelay({ env: {}, fetch: fakeFetch(), readFile }));
expect(await (await fetch(`${base}/v1/push`)).json()).toEqual({ services: [] });
expect(await (await fetch(`${base}/v1/push`)).json()).toEqual({ services: [], badges: true });
const answer = await post({ service: "fcm", token: "fixture-token", message });
expect(answer.status).toBe(503);
expect((await answer.json()).code).toBe("not_configured");
Expand Down Expand Up @@ -102,6 +102,29 @@ describe("push relay", () => {
});
});

it("sends an iPhone its icon's count alone, with no alert, at the low priority, and refuses one for FCM or with no count", async () => {
const requests = [];
const http2Connect = (origin) => {
const session = Object.assign(new EventEmitter(), { closed: false, destroyed: false, unref() {}, close() {}, destroy() {} });
session.request = (headers) => {
const stream = Object.assign(new EventEmitter(), { setEncoding() {}, close() {} });
stream.end = (body) => { requests.push({ origin, headers, body: JSON.parse(body) }); queueMicrotask(() => { stream.emit("response", { ":status": 200 }); stream.emit("end"); }); };
return stream;
};
return session;
};
await start(createPushRelay({ env: { DUSK_APNS_KEY_FILE: "/keys/apns.p8", DUSK_APNS_KEY_ID: "key", DUSK_APNS_TEAM_ID: "team", DUSK_APNS_TOPIC: "com.example.omb" }, http2Connect, readFile }));
const badge = { id: "badge", kind: "badge", botId: "badge", botName: "dusk bot", threadId: "badge", badge: 0 };
expect(await (await post({ service: "apns", token: "abcdef0123456789", message: badge })).json()).toEqual({ outcome: "sent" });
expect(requests[0].headers["apns-push-type"]).toBe("alert");
expect(requests[0].headers["apns-priority"]).toBe("5");
expect(requests[0].body).toEqual({ aps: { badge: 0 } });
expect((await post({ service: "fcm", token: "fixture-token", message: badge })).status).toBe(400);
const { badge: _count, ...noCount } = badge;
expect((await post({ service: "apns", token: "abcdef0123456789", message: noCount })).status).toBe(400);
expect(requests).toHaveLength(1);
});

it("drops an APNs connection that stopped answering and sends on a new one, so later pushes do not wait on it", async () => {
const sessions = [];
const http2Connect = () => {
Expand Down
7 changes: 5 additions & 2 deletions docs/phone-push.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,10 @@ stack together, one notification per conversation on Android with its lines in i
Activity line's seal with the salt in `PUSH_PREVIEW_SEAL`), so only that phone can read it. Without a key (Android
before 12, an older app) the line is "New message".
- iPhone: an APNs alert with `mutable-content`, `thread-id` the conversation, `badge` the unread count and no collapse
id; the app's Notification Service Extension opens the preview and attaches the bot's picture.
id; the app's Notification Service Extension opens the preview and attaches the bot's picture. When notifications
are read on any device and the count changes, each iPhone gets a push with only its new count (no alert, no sound,
priority 5), within a second of the read. Through the push relay this goes only when the relay's `GET /v1/push`
answers `badges: true`, since an older relay would show it as a "New message" alert.
- Android: a phone that registered with `draws: true` gets data-only high priority FCM messages, which Android hands to
the app even when it is closed; the app draws the notification itself (MessagingStyle, the bot as the person). An
older app gets the system-drawn notification on the `messages` channel.
Expand All @@ -41,7 +44,7 @@ stack together, one notification per conversation on Android with its lines in i
On the iPhone, a push that lands while the app is open shows as the system's own banner, unless it is about the
conversation on screen, which shows nothing. Pushes already in Notification Center are removed once read: when that
conversation opens, when a read arrives from another device while the app is open, and each time the app comes back.
An iPhone that stays locked keeps a push read elsewhere until the app next opens.
An iPhone that stays locked keeps a push read elsewhere until the app next opens; its icon's count follows the read.

On Android, a conversation read anywhere (the desktop, another phone, "mark all read") also clears its notification on
every other Android phone that was shown it, with the app closed too: once every line a phone got there is read, the
Expand Down
Loading
Loading