diff --git a/apps/ai/src/mcp/tools/get-incident-timeline.ts b/apps/ai/src/mcp/tools/get-incident-timeline.ts index 42d4164136..b2ead0b912 100644 --- a/apps/ai/src/mcp/tools/get-incident-timeline.ts +++ b/apps/ai/src/mcp/tools/get-incident-timeline.ts @@ -27,7 +27,7 @@ function formatTimestamp(iso: string | null): string | undefined { } const channelLabel = (channel: string): string => - channel === "email" ? "email" : `${Str.capitalize(channel)} DM` + channel === "email" ? "email" : channel === "push" ? "phone" : `${Str.capitalize(channel)} DM` interface PageRow { readonly userId: string diff --git a/apps/api/src/routes/v2/alchemy-provider.integration.test.ts b/apps/api/src/routes/v2/alchemy-provider.integration.test.ts index 2e063d8ef6..d69f6567cd 100644 --- a/apps/api/src/routes/v2/alchemy-provider.integration.test.ts +++ b/apps/api/src/routes/v2/alchemy-provider.integration.test.ts @@ -170,17 +170,17 @@ const makeHarness = () => { const alertRulesLive = AlertRulesService.layer.pipe( Layer.provide(Layer.mergeAll(testDb.layer, runtimeLive)), ) + // Incident pushes and the pages a chain step sends to a person's phone. + const mobilePushLive = Layer.effect(MobilePushService, MobilePushService.make).pipe( + Layer.provide( + Layer.mergeAll(ApnsClient.layer, MobileDevicesService.layer, LiveActivitiesService.layer), + ), + ) const alertsLive = Layer.effect(AlertsService, AlertsService.make).pipe( Layer.provide(InvestigationStarter.layer), Layer.provide(FetchHttpClient.layer), Layer.provide(ChatAlertPoster.layer), - Layer.provide( - Layer.effect(MobilePushService, MobilePushService.make).pipe( - Layer.provide( - Layer.mergeAll(ApnsClient.layer, MobileDevicesService.layer, LiveActivitiesService.layer), - ), - ), - ), + Layer.provide(mobilePushLive), Layer.provide( Layer.mergeAll( envLive, @@ -199,6 +199,7 @@ const makeHarness = () => { alertRulesLive, Layer.effect(AlertMemberNotifier, AlertMemberNotifier.make).pipe( Layer.provide(ChatAlertPoster.layer), + Layer.provide(mobilePushLive), Layer.provide( Layer.mergeAll(envLive, testDb.layer, runtimeLive, emailLive, orgMembersLive), ), diff --git a/apps/api/src/routes/v2/alerts.http.test.ts b/apps/api/src/routes/v2/alerts.http.test.ts index bea7185b09..f225e8eedf 100644 --- a/apps/api/src/routes/v2/alerts.http.test.ts +++ b/apps/api/src/routes/v2/alerts.http.test.ts @@ -183,17 +183,17 @@ const makeHarness = ( const alertRulesLive = AlertRulesService.layer.pipe( Layer.provide(Layer.mergeAll(testDb.layer, runtimeLive)), ) + // Incident pushes and the pages a chain step sends to a person's phone. + const mobilePushLive = Layer.effect(MobilePushService, MobilePushService.make).pipe( + Layer.provide( + Layer.mergeAll(ApnsClient.layer, MobileDevicesService.layer, LiveActivitiesService.layer), + ), + ) const alertsLive = Layer.effect(AlertsService, AlertsService.make).pipe( Layer.provide(InvestigationStarter.layer), Layer.provide(FetchHttpClient.layer), Layer.provide(ChatAlertPoster.layer), - Layer.provide( - Layer.effect(MobilePushService, MobilePushService.make).pipe( - Layer.provide( - Layer.mergeAll(ApnsClient.layer, MobileDevicesService.layer, LiveActivitiesService.layer), - ), - ), - ), + Layer.provide(mobilePushLive), Layer.provide( Layer.mergeAll( envLive, @@ -212,6 +212,7 @@ const makeHarness = ( alertRulesLive, Layer.effect(AlertMemberNotifier, AlertMemberNotifier.make).pipe( Layer.provide(ChatAlertPoster.layer), + Layer.provide(mobilePushLive), Layer.provide( Layer.mergeAll(envLive, testDb.layer, runtimeLive, emailLive, orgMembersLive), ), diff --git a/apps/landing/src/content/docs/alerting/escalation-chains.md b/apps/landing/src/content/docs/alerting/escalation-chains.md index a91836ec50..1edc6a2da1 100644 --- a/apps/landing/src/content/docs/alerting/escalation-chains.md +++ b/apps/landing/src/content/docs/alerting/escalation-chains.md @@ -24,7 +24,7 @@ A chain can have up to 10 steps, each with up to 10 targets and a wait of up to | Target | Who is paged | | ----------- | ------------------------------------------------------------------------------------------------------------- | | Destination | A [notification destination](/docs/alerting/notification-destinations): a channel, PagerDuty, a webhook. | -| Person | One member, by email, and by direct message in a chat workspace they have linked their account in. | +| Person | One member: by email, by a push to their phones if they use the Maple app, and by direct message in a chat workspace they have linked their account in. | | Schedule | Whoever an [on-call schedule](/docs/alerting/on-call-schedules) says is on call when the step comes up. | Who is on call is read when the step fires, not when the chain was saved or the incident opened. diff --git a/packages/backend/src/services/alerts/AlertMemberNotifier.ts b/packages/backend/src/services/alerts/AlertMemberNotifier.ts index e1da445ac5..868a07d1c0 100644 --- a/packages/backend/src/services/alerts/AlertMemberNotifier.ts +++ b/packages/backend/src/services/alerts/AlertMemberNotifier.ts @@ -30,9 +30,11 @@ import { Database } from "@maple/backend/platform/DatabaseLive" import { summarizeCause } from "@maple/backend/platform/describe-cause" import { makeDbExecute } from "@maple/backend/platform/db-execute" import { EmailService } from "@maple/backend/platform/EmailService" +import { MobilePushService } from "@maple/backend/services/push/MobilePushService" import { Env } from "@maple/backend/platform/Env" import { OrgMembersService, type OrgMember } from "@maple/backend/services/org/OrgMembersService" import { buildAlertEmailContent } from "./alert-email" +import { PUSH_CHANNEL } from "./alert-escalation-runs" import { makePersistenceError } from "./alert-persistence" import { AlertRuntime } from "./AlertRuntime" import { ChatAlertPoster } from "./ChatAlertPoster" @@ -56,6 +58,10 @@ const FailureMessages = { noEmail: "No email address is known for this member", emailFailed: "The email could not be sent", unreadable: "The stored page could not be read", + pushFailed: "The push could not be sent", + noPhone: "No phone is registered for this member", + pushNotConfigured: "Push is not set up on this deployment", + phoneGone: "The member's phone no longer accepts pushes", noChatAccount: "The page names no chat account", noWorkspaceKnowsUser: "No linked chat workspace could reach this member", chatAuth: "The chat workspace refused Maple's credentials", @@ -178,6 +184,7 @@ export class AlertMemberNotifier extends Context.Service + Effect.gen(function* () { + const context = input.context + const summary = yield* mobilePush.pageMember({ + orgId: row.orgId, + userId: row.userId, + incidentId: row.incidentId, + ruleId: context.ruleId, + title: `You are paged · ${context.ruleName}`, + body: `${context.severity === "critical" ? "Critical" : "Warning"} incident, unacknowledged. Open it to acknowledge.`, + linkUrl: input.linkUrl, + collapseId: `page:${row.incidentId}`, + }) + // Without push credentials nothing was tried: say that, not that the member has no phone. + const attempt: Attempt = !summary.configured + ? { status: "skipped", message: FailureMessages.pushNotConfigured } + : summary.sent > 0 + ? { status: "sent" } + : summary.failed > 0 + ? failure(FailureMessages.pushFailed, true) + : { + status: "skipped", + // A token Apple called dead was just switched off: that is not "no phone". + message: + summary.unregistered > 0 + ? FailureMessages.phoneGone + : FailureMessages.noPhone, + } + return attempt + }) + const sendDirectMessage = ( row: AlertMemberNotificationRow, payload: MemberPayload, @@ -439,7 +478,9 @@ export class AlertMemberNotifier extends Context.Service cleanupTestDbs(trackedDbs)) @@ -206,6 +207,11 @@ const layerFor = ( readonly directory?: Array readonly email?: (typeof EmailService)["Service"] readonly deliveryTimeoutMs?: number + /** Records the pages pushed to members' phones; `memberPagesFail` lets none of them land. */ + readonly memberPages?: Array + readonly memberPagesFail?: boolean + readonly memberPagesUnconfigured?: boolean + readonly memberPagesApple?: { down: boolean } } = {}, ) => { const directory = options.directory ?? [...MEMBERS] @@ -218,6 +224,16 @@ const layerFor = ( { fetch: okFetch, ...(timeoutMs === undefined ? undefined : { deliveryTimeoutMs: () => timeoutMs }), + ...(options.memberPages === undefined ? undefined : { memberPages: options.memberPages }), + ...(options.memberPagesFail === undefined + ? undefined + : { memberPagesFail: options.memberPagesFail }), + ...(options.memberPagesUnconfigured === undefined + ? undefined + : { memberPagesUnconfigured: options.memberPagesUnconfigured }), + ...(options.memberPagesApple === undefined + ? undefined + : { memberPagesApple: options.memberPagesApple }), }, options.email ?? stubEmailService(emails), ChatAlertPoster.layer.pipe( @@ -747,6 +763,147 @@ describe("escalation pages the on-call", () => { }) }) + /** A phone `userId` registered the Maple app on; `disabled` marks its token dead. */ + const registerPhone = (testDb: TestDb, orgId: OrgId, userId: string, disabled = false) => + Effect.promise(() => + executeSql( + testDb, + `insert into mobile_devices + (id, org_id, user_id, platform, token, environment, bundle_id, preferences, + disabled_at, last_seen_at, created_at, updated_at) + values (gen_random_uuid()::text, $1, $2, 'ios', md5(random()::text), 'production', + 'dev.maple.app', '{}'::jsonb, $3, now(), now(), now())`, + [orgId, userId, disabled ? new Date(NOW).toISOString() : null], + ), + ) + + it.effect("pages the on-call person's phone as well, and only a phone that can still be pushed", () => { + const testDb = createTestDb(trackedDbs) + const state = { tracesAggregateRows: errorRate(10) } + const emails: Array = [] + const memberPages: Array = [] + return Effect.gen(function* () { + const chat = yield* makeChat + yield* TestClock.setTime(NOW) + return yield* Effect.gen(function* () { + // Step 2 pages Ben (on call today) and Chen; Ben has the app, Chen's token is dead. + const { alerts, orgId } = yield* setup("org_page_phone", testDb, { + secondStep: [ + { type: "user", userId: ben }, + { type: "user", userId: chen }, + ], + }) + yield* registerPhone(testDb, orgId, ben) + yield* registerPhone(testDb, orgId, chen, true) + yield* ticks(alerts, 10) + + assert.deepStrictEqual( + Arr.map(memberPages, (page) => [page.userId, page.title]), + [[ben, "You are paged · Checkout error rate"]], + ) + const pushRows = Arr.filter(yield* pageRows(testDb, orgId), (row) => row.channel === "push") + assert.deepStrictEqual( + Arr.map(pushRows, (row) => [row.user_id, row.status]), + [[ben, "sent"]], + ) + // The email still goes to both: the phone is one more way in, not a replacement. + assert.sameMembers( + Arr.map(emails, (email) => email.to), + ["ben@acme.test", "chen@acme.test"], + ) + }).pipe(Effect.provide(layerFor(testDb, state, emails, chat, { memberPages }))) + }) + }) + + it.effect("settles a phone page nobody's phone took as skipped, with why", () => { + const testDb = createTestDb(trackedDbs) + const state = { tracesAggregateRows: errorRate(10) } + const emails: Array = [] + const memberPages: Array = [] + return Effect.gen(function* () { + const chat = yield* makeChat + yield* TestClock.setTime(NOW) + return yield* Effect.gen(function* () { + const { alerts, orgId } = yield* setup("org_page_phone_gone", testDb, { + secondStep: [{ type: "user", userId: ben }], + }) + yield* registerPhone(testDb, orgId, ben) + yield* ticks(alerts, 10) + const pushRows = Arr.filter(yield* pageRows(testDb, orgId), (row) => row.channel === "push") + assert.deepStrictEqual( + Arr.map(pushRows, (row) => [row.status, row.error_message]), + [["skipped", "The member's phone no longer accepts pushes"]], + ) + }).pipe( + Effect.provide(layerFor(testDb, state, emails, chat, { memberPages, memberPagesFail: true })), + ) + }) + }) + + it.effect("retries a phone page Apple could not take, and sends it", () => { + const testDb = createTestDb(trackedDbs) + const state = { tracesAggregateRows: errorRate(10) } + const emails: Array = [] + const memberPages: Array = [] + const apple = { down: true } + return Effect.gen(function* () { + const chat = yield* makeChat + yield* TestClock.setTime(NOW) + return yield* Effect.gen(function* () { + const { alerts, orgId } = yield* setup("org_page_phone_retry", testDb, { + secondStep: [{ type: "user", userId: ben }], + }) + yield* registerPhone(testDb, orgId, ben) + yield* ticks(alerts, 10) + const push = Effect.map(pageRows(testDb, orgId), (rows) => + Arr.map( + Arr.filter(rows, (row) => row.channel === "push"), + (row) => [row.status, row.attempt_number, row.error_message], + ), + ) + assert.deepStrictEqual(yield* push, [["queued", 1, "The push could not be sent"]]) + apple.down = false + yield* ticks(alerts, 2) + assert.deepStrictEqual(yield* push, [["sent", 2, null]]) + }).pipe( + Effect.provide( + layerFor(testDb, state, emails, chat, { memberPages, memberPagesApple: apple }), + ), + ) + }) + }) + + it.effect("a phone page on a deployment without push says so, not that the member has no phone", () => { + const testDb = createTestDb(trackedDbs) + const state = { tracesAggregateRows: errorRate(10) } + const emails: Array = [] + const memberPages: Array = [] + return Effect.gen(function* () { + const chat = yield* makeChat + yield* TestClock.setTime(NOW) + return yield* Effect.gen(function* () { + const { alerts, orgId } = yield* setup("org_page_phone_unconfigured", testDb, { + secondStep: [{ type: "user", userId: ben }], + }) + yield* registerPhone(testDb, orgId, ben) + yield* ticks(alerts, 10) + const pushRows = Arr.filter(yield* pageRows(testDb, orgId), (row) => row.channel === "push") + assert.deepStrictEqual( + Arr.map(pushRows, (row) => [row.status, row.error_message]), + [["skipped", "Push is not set up on this deployment"]], + ) + }).pipe( + Effect.provide( + layerFor(testDb, state, emails, chat, { + memberPages, + memberPagesFail: true, + memberPagesUnconfigured: true, + }), + ), + ) + }) + }) + it.effect("refuses to delete a schedule a running escalation still pages", () => { const testDb = createTestDb(trackedDbs) const state = { tracesAggregateRows: errorRate(10) } diff --git a/packages/backend/src/services/alerts/alert-escalation-runs.ts b/packages/backend/src/services/alerts/alert-escalation-runs.ts index 1bae9d44ef..12627ad755 100644 --- a/packages/backend/src/services/alerts/alert-escalation-runs.ts +++ b/packages/backend/src/services/alerts/alert-escalation-runs.ts @@ -35,6 +35,7 @@ import { ChatIdentities, ChatWorkspaces, EscalationChains, + MobileDevices, OnCallOverrides, OnCallSchedules, } from "@maple/db/tables" @@ -288,9 +289,15 @@ export const enabledDestinationIds = (db: MapleDb, orgId: OrgId, ids: ReadonlyAr ) .pipe(Effect.map((rows) => new Set(Arr.map(rows, (row) => row.id)))) -/** One channel a person is paged on: email, or a direct message to a linked chat account. */ +/** The channel of a page to a member's own phones. */ +export const PUSH_CHANNEL = "push" + +const pushRecipient = (userId: UserId): MemberRecipient => ({ userId, channel: PUSH_CHANNEL }) + +/** One channel a person is paged on: email, their phones, or a direct message to a linked chat account. */ export type MemberRecipient = | { readonly userId: UserId; readonly channel: "email" } + | { readonly userId: UserId; readonly channel: typeof PUSH_CHANNEL } | { readonly userId: UserId readonly channel: ChatConnectorId @@ -391,7 +398,7 @@ export const loadStepRecipients = ( missingUserIds: [], } if (userIds.length === 0) return { ...base, recipients: [] } satisfies StepRecipients - const [identities, workspaces] = yield* Effect.all( + const [identities, workspaces, phones] = yield* Effect.all( [ db.run( PG.from(ChatIdentities) @@ -404,6 +411,12 @@ export const loadStepRecipients = ( .select("connector") .where(($) => [$.orgId.eq(orgId), $.directMessagesEnabled.eq(true)]), ), + // Who has a phone that can still be pushed: a page there is queued only for them. + db.run( + PG.from(MobileDevices) + .select("userId") + .where(($) => [$.orgId.eq(orgId), $.userId.in_(...userIds), $.disabledAt.isNull()]), + ), ], { concurrency: "unbounded" }, ) @@ -421,8 +434,10 @@ export const loadStepRecipients = ( ] : [], ) + const withPhone = new Set(Arr.map(phones, (row) => row.userId)) const recipients = Arr.flatMap(userIds, (userId): ReadonlyArray => [ { userId, channel: "email" }, + ...(withPhone.has(userId) ? [pushRecipient(userId)] : []), ...Arr.filter(chatRecipients, (recipient) => recipient.userId === userId), ]) return { ...base, recipients } satisfies StepRecipients @@ -464,7 +479,7 @@ export const memberNotificationDedupeKey = ( ) => "identityId" in recipient ? `${runId}:${pass}:${step}:${recipient.userId}:${recipient.channel}:${recipient.identityId}` - : `${runId}:${pass}:${step}:${recipient.userId}:email` + : `${runId}:${pass}:${step}:${recipient.userId}:${recipient.channel}` export type EscalationApplyOutcome = | "sent" diff --git a/packages/backend/src/services/alerts/alerts-service-test-support.ts b/packages/backend/src/services/alerts/alerts-service-test-support.ts index b87ec71052..beda9c6695 100644 --- a/packages/backend/src/services/alerts/alerts-service-test-support.ts +++ b/packages/backend/src/services/alerts/alerts-service-test-support.ts @@ -3,7 +3,11 @@ import { LiveActivitiesService } from "@maple/backend/services/push/LiveActivitiesService" import { MobileDevicesService } from "@maple/backend/services/push/MobileDevicesService" import { ApnsClient } from "@maple/backend/platform/Apns" -import { MobilePushService, type IncidentPushEvent } from "@maple/backend/services/push/MobilePushService" +import { + MobilePushService, + type IncidentPushEvent, + type MemberPagePush, +} from "@maple/backend/services/push/MobilePushService" import { ChatAlertPoster } from "./ChatAlertPoster" import { Cause, @@ -205,6 +209,13 @@ export interface TestOverrides extends Partial { readonly chatSessions?: ChatSessionsApi /** Records every incident push instead of sending it through the real push service. */ readonly pushes?: Array + /** Records every page pushed to a member's phones; `memberPagesFail`: Apple calls their token dead. */ + readonly memberPages?: Array + readonly memberPagesFail?: boolean + /** The deployment has no push credentials: a page reports that nothing was tried. */ + readonly memberPagesUnconfigured?: boolean + /** Read on every page: while `down`, Apple cannot be reached and the send fails. */ + readonly memberPagesApple?: { down: boolean } } export const DEFAULT_CLOCK_EPOCH_MS = 1_700_000_000_000 @@ -260,10 +271,19 @@ export const makeLayer = ( chatAlertPoster: Layer.Layer = ChatAlertPoster.layer, members: ReadonlyArray = TEST_ORG_MEMBERS, ) => { - const { fetch: fetchImpl = globalThis.fetch, chatSessions, pushes, ...runtimeOverrides } = overrides + const { + fetch: fetchImpl = globalThis.fetch, + chatSessions, + pushes, + memberPages, + memberPagesFail, + memberPagesUnconfigured, + memberPagesApple, + ...runtimeOverrides + } = overrides const noPushes = { sent: 0, failed: 0, unregistered: 0, skipped: 0 } const mobilePushLive = - pushes === undefined + pushes === undefined && memberPages === undefined ? Layer.effect(MobilePushService, MobilePushService.make).pipe( Layer.provide( Layer.mergeAll( @@ -275,8 +295,19 @@ export const makeLayer = ( ) : Layer.succeed(MobilePushService, { notifyIncident: (event) => - Effect.sync(() => pushes.push(event)).pipe(Effect.as(noPushes)), + Effect.sync(() => pushes?.push(event)).pipe(Effect.as(noPushes)), notifyIncidentDigest: () => Effect.succeed(noPushes), + pageMember: (page) => + Effect.sync(() => memberPages?.push(page)).pipe( + Effect.as({ + ...noPushes, + ...(memberPagesApple?.down === true ? { failed: 1 } : undefined), + sent: memberPagesFail === true || memberPagesApple?.down === true ? 0 : 1, + unregistered: + memberPagesFail === true && memberPagesUnconfigured !== true ? 1 : 0, + configured: memberPagesUnconfigured !== true, + }), + ), refreshWidgets: () => Effect.succeed(noPushes), }) const configLive = makeConfig() @@ -334,6 +365,7 @@ export const makeLayer = ( const memberNotifierLive = Layer.effect(AlertMemberNotifier, AlertMemberNotifier.make).pipe( Layer.provide(chatAlertPoster), + Layer.provide(mobilePushLive), Layer.provide(Layer.mergeAll(envLive, databaseLive, runtimeLive, emailLive, orgMembersLive)), ) const alertsLive = Layer.effect(AlertsService, AlertsService.make).pipe( diff --git a/packages/backend/src/services/push/MobilePushService.test.ts b/packages/backend/src/services/push/MobilePushService.test.ts index 5f06271046..1a4c359b16 100644 --- a/packages/backend/src/services/push/MobilePushService.test.ts +++ b/packages/backend/src/services/push/MobilePushService.test.ts @@ -1,5 +1,6 @@ import { assert, describe, expect, it } from "@effect/vitest" import { encodePublicId } from "@maple/domain/http/v2" +import { MobileDevicePersistenceError } from "@maple/domain/http" import { MobileDeviceId, OrgId, UserId } from "@maple/primitives" import { Effect, Layer, Schema, Array as Arr } from "effect" import { @@ -92,7 +93,8 @@ interface LiveActivityRecorder { const background: Array = [] const makeLayer = ( - devices: ReadonlyArray, + // `null`: the device read fails, as when the database is down. + devices: ReadonlyArray | null, sendImpl: (push: ApnsPush) => ApnsSendResult, sent: Array, // Device writes as `disable:::` and `pushed::`, so the org each write is scoped to is asserted. @@ -127,8 +129,14 @@ const makeLayer = ( register: () => Effect.die("unused"), unregister: () => Effect.die("unused"), find: () => Effect.die("unused"), - listForUser: () => Effect.die("unused"), - listForOrg: () => Effect.succeed(devices), + listForUser: (_orgId, userId) => + devices === null + ? Effect.fail(new MobileDevicePersistenceError({ message: "database is down" })) + : Effect.succeed(Arr.filter(devices, (one) => one.userId === userId)), + listForOrg: () => + devices === null + ? Effect.fail(new MobileDevicePersistenceError({ message: "database is down" })) + : Effect.succeed(devices), disable: (orgId, id, reason) => { deviceWrites.push(`disable:${orgId}:${id}:${reason}`) return Effect.void @@ -486,6 +494,140 @@ describe("MobilePushService.notifyIncident", () => { }) }) +describe("MobilePushService.pageMember", () => { + const OTHER = Schema.decodeSync(UserId)("user_push_other") + const page = { + orgId: ORG, + userId: USER, + incidentId: "00000000-0000-4000-8000-0000000000a1", + ruleId: "00000000-0000-4000-8000-0000000000b1", + title: "You are paged · Checkout error rate", + body: "Critical incident, unacknowledged. Open it to acknowledge.", + linkUrl: "https://app.maple.test/alerts/incidents/x", + collapseId: "page:x", + } + // Everything off: what the org's incidents tell this person is their choice, a page is not. + const muted = { + criticalIncidents: false, + warningIncidents: false, + resolvedIncidents: false, + newErrorIssues: false, + anomalies: false, + } + + it.effect("reaches the member's own phones whatever their preferences, and nobody else's", () => { + const sent: Array = [] + const deviceWrites: Array = [] + return Effect.gen(function* () { + const push = yield* MobilePushService + const summary = yield* push.pageMember(page) + assert.deepStrictEqual(summary, { + sent: 1, + failed: 0, + unregistered: 0, + skipped: 0, + configured: true, + }) + assert.deepStrictEqual( + Arr.map(sent, (one) => [one.deviceToken, one.interruptionLevel, one.alert?.title]), + [["token-1", "time-sensitive", page.title]], + ) + // Opens the incident by its public id, as an incident push does. + assert.match(String(sent[0]?.data?.maple_incident_id), /^inc_/) + assert.deepStrictEqual(deviceWrites, [`pushed:${ORG}:${deviceId(1)}`]) + }).pipe( + Effect.provide( + makeLayer( + [ + device(1, { preferences: muted }), + device(2, { userId: OTHER }), + device(3, { enabled: false }), + ], + () => ({ outcome: "sent", apnsId: null }), + sent, + deviceWrites, + ), + ), + ) + }) + + it.effect("switches off a phone Apple says is gone, and reports that nothing landed", () => { + const deviceWrites: Array = [] + return Effect.gen(function* () { + const push = yield* MobilePushService + const summary = yield* push.pageMember(page) + assert.deepStrictEqual(summary, { + sent: 0, + failed: 0, + unregistered: 1, + skipped: 0, + configured: true, + }) + assert.deepStrictEqual(deviceWrites, [ + `disable:${ORG}:${deviceId(1)}:Unregistered`, + `pushed:${ORG}:`, + ]) + }).pipe( + Effect.provide( + makeLayer( + [device(1)], + () => ({ outcome: "unregistered", reason: "Unregistered" }), + [], + deviceWrites, + ), + ), + ) + }) + + it.effect("counts a device read that failed as a failed page, not as no phone", () => { + const sent: Array = [] + return Effect.gen(function* () { + const push = yield* MobilePushService + // Failed, so the page is tried again once the read works; "no phone" would settle it. + assert.deepStrictEqual(yield* push.pageMember(page), { + sent: 0, + failed: 1, + unregistered: 0, + skipped: 0, + configured: true, + }) + assert.lengthOf(sent, 0) + }).pipe(Effect.provide(makeLayer(null, () => ({ outcome: "sent", apnsId: null }), sent, []))) + }) + + it.effect("sends nothing for a member without a phone, or without APNs credentials", () => { + const sent: Array = [] + const none = { sent: 0, failed: 0, unregistered: 0, skipped: 0 } + const withoutPhone = Effect.gen(function* () { + const push = yield* MobilePushService + assert.deepStrictEqual(yield* push.pageMember(page), { ...none, configured: true }) + }).pipe( + Effect.provide( + makeLayer( + [device(2, { userId: OTHER })], + () => ({ outcome: "sent", apnsId: null }), + sent, + [], + ), + ), + ) + const unconfigured = Effect.gen(function* () { + const push = yield* MobilePushService + // Told apart from a member without a phone: this one has one, the deployment cannot push. + assert.deepStrictEqual(yield* push.pageMember(page), { ...none, configured: false }) + }).pipe( + Effect.provide( + makeLayer([device(1)], () => ({ outcome: "sent", apnsId: null }), sent, [], false), + ), + ) + return Effect.gen(function* () { + yield* withoutPhone + yield* unconfigured + assert.lengthOf(sent, 0) + }) + }) +}) + describe("buildLiveActivitySeries", () => { it("puts the checks oldest-first and appends the value that fired this push", () => { // `listRuleChecks` returns newest first, and the check that just fired is diff --git a/packages/backend/src/services/push/MobilePushService.ts b/packages/backend/src/services/push/MobilePushService.ts index 2231ae3b41..d9b2c64719 100644 --- a/packages/backend/src/services/push/MobilePushService.ts +++ b/packages/backend/src/services/push/MobilePushService.ts @@ -5,6 +5,7 @@ import type { AlertSeverity, AlertSignalType, OrgId, + UserId, } from "@maple/domain/http" import { PublicIdPrefixes, encodePublicId } from "@maple/domain/http/v2" import { Cause, Clock, Context, Duration, Effect, Layer, Array as Arr, String as Str } from "effect" @@ -144,6 +145,11 @@ export interface IncidentDigestPushEvent { export interface MobilePushServiceApi { readonly notifyIncident: (event: IncidentPushEvent) => Effect.Effect readonly notifyIncidentDigest: (event: IncidentDigestPushEvent) => Effect.Effect + /** + * A page to one person's own phones, from an escalation step. It is not filtered by their + * notification preferences: those tune what the org's incidents tell them, a page is for them. + */ + readonly pageMember: (page: MemberPagePush) => Effect.Effect /** * Wake the organization's phones so their Home Screen widgets can refresh. * @@ -154,6 +160,25 @@ export interface MobilePushServiceApi { readonly refreshWidgets: (orgId: OrgId, reason: string) => Effect.Effect } +/** What a page to one member's phones came to. */ +export interface MemberPageSummary extends MobilePushSummary { + /** False on a deployment without push credentials: nothing was tried, whatever phones exist. */ + readonly configured: boolean +} + +/** An escalation step's page to one member. */ +export interface MemberPagePush { + readonly orgId: OrgId + readonly userId: UserId + readonly incidentId: string + readonly ruleId: string + readonly title: string + readonly body: string + readonly linkUrl: string + /** One notification per incident on the phone: a later step's page replaces this one. */ + readonly collapseId: string +} + const SEND_CONCURRENCY = 8 const SEND_TIMEOUT = Duration.seconds(8) @@ -544,6 +569,116 @@ export class MobilePushService extends Context.Service | null => listed), + Effect.catch((error) => + Effect.logWarning("Mobile push: could not list devices for a page").pipe( + Effect.annotateLogs({ orgId: page.orgId, error: error.message }), + Effect.as(null), + ), + ), + ) + if (registered === null) { + yield* Effect.annotateCurrentSpan({ "maple.push.devices_unreadable": true }) + return { ...empty, failed: 1 } + } + const targets = Arr.filter(registered, (device) => device.enabled) + yield* Effect.annotateCurrentSpan({ "maple.push.devices": targets.length }) + if (targets.length === 0) return empty + const results = yield* Effect.forEach( + targets, + (device) => + apns + .send({ + deviceToken: device.token, + environment: device.environment, + bundleId: device.bundleId, + alert: { title: page.title, body: page.body }, + interruptionLevel: "time-sensitive", + priority: 10, + collapseId: page.collapseId, + data: { + maple_kind: "alert_incident", + maple_event: "page", + maple_incident_id: encodePublicId( + PublicIdPrefixes.alertIncident, + page.incidentId, + ), + maple_rule_id: encodePublicId(PublicIdPrefixes.alertRule, page.ruleId), + maple_org_id: page.orgId, + maple_url: page.linkUrl, + }, + }) + .pipe( + Effect.timeout(SEND_TIMEOUT), + Effect.map((result) => ({ + device, + outcome: result.outcome, + reason: result.outcome === "sent" ? "" : result.reason, + })), + Effect.catch((error) => + Effect.logWarning("Mobile push: a page could not be sent").pipe( + Effect.annotateLogs({ + orgId: page.orgId, + deviceId: device.id, + error: error.message, + }), + Effect.as({ + device, + outcome: "failed" as const, + reason: error.message, + }), + ), + ), + ), + { concurrency: SEND_CONCURRENCY }, + ) + const withOutcome = (outcome: (typeof results)[number]["outcome"]) => + Arr.filter(results, (result) => result.outcome === outcome) + // A token Apple calls dead is switched off, as an incident push does. + yield* Effect.forEach( + withOutcome("unregistered"), + ({ device, reason }) => + devices.disable(page.orgId, device.id, reason).pipe( + ignoreLogged("Mobile push: could not disable a dead device", { + orgId: page.orgId, + deviceId: device.id, + }), + ), + { discard: true }, + ) + const pushed = Arr.map(withOutcome("sent"), ({ device }) => device.id) + yield* devices.markPushed(page.orgId, pushed).pipe( + ignoreLogged("Mobile push: could not record which devices were pushed", { + orgId: page.orgId, + deviceCount: pushed.length, + }), + ) + return { + sent: pushed.length, + failed: withOutcome("failed").length, + unregistered: withOutcome("unregistered").length, + skipped: 0, + configured: true, + } + }) + const notifyIncident = Effect.fn("MobilePushService.notifyIncident")(function* ( event: IncidentPushEvent, ) { @@ -1083,7 +1218,12 @@ export class MobilePushService extends Context.Service