@@ -14,7 +14,26 @@ import {
1414import { deleteDevice , registerDevice } from "./api/generated/devices/devices" ;
1515
1616const key = "openbot-device-id" ;
17- export async function registerPush ( ) {
17+
18+ /** A device push token as one string, to tell whether Expo handed over a token the phone has already registered. */
19+ const tokenKey = ( device : Notifications . DevicePushToken ) =>
20+ typeof device . data === "string" ? device . data : JSON . stringify ( device . data ) ;
21+
22+ /** The device push token this phone last registered with, while the app runs. */
23+ let registeredDevice : Notifications . DevicePushToken | undefined ;
24+
25+ /**
26+ * Register the phone for push, in every organization the person is in. With the device push token Expo handed to a
27+ * push token listener (`devicePushToken`), that token is registered; without one, the phone is asked for its token.
28+ *
29+ * Asking the phone for its token tells every push token listener the token it gave, changed or not (expo-notifications'
30+ * native PushTokenModule sends `onDevicePushToken` after each fetch, on iOS and Android). So a listener passes the token
31+ * it was handed, and is never the one that asks: build 7 asked from inside its listener, which told the listener again,
32+ * and registered some 10,000 times a minute until the deployment's rate limit shut the phone out.
33+ */
34+ export async function registerPush (
35+ devicePushToken ?: Notifications . DevicePushToken ,
36+ ) {
1837 if ( ! Device . isDevice )
1938 throw new Error (
2039 "Register push notifications on a physical device using a signed development build." ,
@@ -38,8 +57,11 @@ export async function registerPush() {
3857 permission = await Notifications . requestPermissionsAsync ( ) ;
3958 if ( permission . status !== "granted" )
4059 throw new Error ( "Notification permission was not granted." ) ;
60+ const device =
61+ devicePushToken ?? ( await Notifications . getDevicePushTokenAsync ( ) ) ;
4162 const { data : token } = await Notifications . getExpoPushTokenAsync ( {
4263 projectId,
64+ devicePushToken : device ,
4365 } ) ;
4466 let id = await SecureStore . getItemAsync ( key ) ;
4567 if ( ! id ) {
@@ -49,22 +71,28 @@ export async function registerPush() {
4971 // Registered under the id this install made, in every organization the person is in, so a Bot in any of them can
5072 // reach the phone, and sign-out takes it off each (unregisterPush). Sent again, a token Expo has changed replaces
5173 // the old one rather than adding a second phone.
52- const device = { token, projectId, platform : Platform . OS } ;
74+ const registration = { token, projectId, platform : Platform . OS } ;
5375 const held = await organizationsHeld ( ) ;
5476 const where =
5577 held . length > 0 ? held . map ( ( each ) => each . id ) : [ ORGANIZATION_ID ] ;
5678 const failures : unknown [ ] = [ ] ;
5779 for ( const organization of where ) {
5880 try {
59- await registerDevice ( organization , ME , id , device ) ;
81+ await registerDevice ( organization , ME , id , registration ) ;
6082 } catch ( error ) {
83+ // Refused as too many: the limit is on the phone, so the other organizations would be refused too.
84+ if ( tooMany ( error ) ) throw error ;
6185 failures . push ( error ) ;
6286 }
6387 }
6488 // Registered nowhere: say why. Refused by some organizations only (one that turned push off), the rest still reach it.
6589 if ( failures . length === where . length ) throw failures [ 0 ] ;
90+ registeredDevice = device ;
6691 return id ;
6792}
93+
94+ const tooMany = ( error : unknown ) : error is ApiError =>
95+ error instanceof ApiError && error . status === 429 ;
6896/**
6997 * Whether this phone gets push notifications: the person allowed them, and the app registered the
7098 * phone (it keeps the id it registered under until sign-out takes it off).
@@ -80,21 +108,112 @@ export async function pushTurnedOn(): Promise<boolean> {
80108 * notifications on for: a push token Expo changed since replaces the old one, and a phone the server
81109 * dropped (Expo said it stopped taking them) is registered again. Never asks for permission.
82110 */
83- export async function renewPush ( ) : Promise < void > {
84- if ( await pushTurnedOn ( ) ) await registerPush ( ) ;
111+ export async function renewPush (
112+ devicePushToken ?: Notifications . DevicePushToken ,
113+ ) : Promise < void > {
114+ if ( await pushTurnedOn ( ) ) await registerPush ( devicePushToken ) ;
85115}
86116
117+ /**
118+ * A registration asked for: with the newest token Expo handed over, if one asked; whether anything but a token asked
119+ * (`always`: a start or a move registers even with the token already registered); and whether to ask the phone for its
120+ * token rather than use the one last registered (`fresh`: a start, so a token changed while the app was closed is sent).
121+ */
122+ type Wanted = {
123+ device ?: Notifications . DevicePushToken ;
124+ always : boolean ;
125+ fresh : boolean ;
126+ } ;
127+ /** Two asks as one: the newer token, and every reason either had. */
128+ const together = ( older : Wanted , newer : Wanted ) : Wanted => ( {
129+ device : newer . device ?? older . device ,
130+ always : older . always || newer . always ,
131+ fresh : older . fresh || newer . fresh ,
132+ } ) ;
133+
134+ /** Refused as too many with no Retry-After, the first wait; it doubles with each refusal in a row, up to the longest. */
135+ const FIRST_WAIT_MS = 30_000 ;
136+ const LONGEST_WAIT_MS = 30 * 60_000 ;
137+
87138/**
88139 * Keep the phone registered while somebody is signed in: now, each time they come to work in another organization
89140 * (one they just joined is registered in too), and each time the phone's push token changes. Never asks for
90141 * permission: a phone the person didn't turn notifications on for is left alone. Returns how to stop.
142+ *
143+ * One registration runs at a time. Whatever asks for one while it runs (a move, a token) makes one more after it, with
144+ * the newest token, however many asked. Told a token the phone has already registered (Expo tells the listener the
145+ * token each time the phone is asked for it), it registers nothing. Refused as too many, it waits out the server's
146+ * Retry-After, or a wait that doubles with each refusal, then tries once more.
91147 */
92148export function keepPushRegistered ( ) : ( ) => void {
93- const renew = ( ) => void renewPush ( ) . catch ( ( ) => { } ) ;
94- renew ( ) ;
95- const leaveMoves = onOrganizationMoved ( renew ) ;
96- const tokens = Notifications . addPushTokenListener ( renew ) ;
149+ let stopped = false ;
150+ let running = false ;
151+ /** The registration asked for next, everything that asked for it since the last one started taken together. */
152+ let next : Wanted | undefined ;
153+ let waitUntil = 0 ;
154+ let refusals = 0 ;
155+ let timer : ReturnType < typeof setTimeout > | undefined ;
156+
157+ const ask = ( wanted : Wanted ) => {
158+ if ( stopped ) return ;
159+ next = next ? together ( next , wanted ) : wanted ;
160+ void run ( ) ;
161+ } ;
162+
163+ async function run ( ) : Promise < void > {
164+ if ( running || stopped || ! next ) return ;
165+ const wait = waitUntil - Date . now ( ) ;
166+ if ( wait > 0 ) {
167+ timer ??= setTimeout ( ( ) => {
168+ timer = undefined ;
169+ void run ( ) ;
170+ } , wait ) ;
171+ return ;
172+ }
173+ const now = next ;
174+ next = undefined ;
175+ // Only told the token it already has: nothing to register.
176+ if (
177+ ! now . always &&
178+ now . device &&
179+ registeredDevice &&
180+ tokenKey ( now . device ) === tokenKey ( registeredDevice )
181+ )
182+ return ;
183+ running = true ;
184+ try {
185+ // A move registers with the token already known, so the phone isn't asked for it (and the listener told) again.
186+ await renewPush ( now . device ?? ( now . fresh ? undefined : registeredDevice ) ) ;
187+ refusals = 0 ;
188+ } catch ( error ) {
189+ if ( tooMany ( error ) ) {
190+ refusals += 1 ;
191+ const backOff = Math . min (
192+ FIRST_WAIT_MS * 2 ** ( refusals - 1 ) ,
193+ LONGEST_WAIT_MS ,
194+ ) ;
195+ waitUntil =
196+ Date . now ( ) + Math . min ( error . retryAfterMs ?? backOff , LONGEST_WAIT_MS ) ;
197+ // Tried again once the wait is over, with whatever asked in the meantime.
198+ next = next ? together ( now , next ) : now ;
199+ }
200+ // Any other failure is left until something asks again, as before.
201+ } finally {
202+ running = false ;
203+ }
204+ void run ( ) ;
205+ }
206+
207+ ask ( { always : true , fresh : true } ) ;
208+ const leaveMoves = onOrganizationMoved ( ( ) =>
209+ ask ( { always : true , fresh : false } ) ,
210+ ) ;
211+ const tokens = Notifications . addPushTokenListener ( ( device ) =>
212+ ask ( { device, always : false , fresh : false } ) ,
213+ ) ;
97214 return ( ) => {
215+ stopped = true ;
216+ if ( timer ) clearTimeout ( timer ) ;
98217 leaveMoves ( ) ;
99218 tokens . remove ( ) ;
100219 } ;
0 commit comments