Skip to content

Commit 0384d8c

Browse files
authored
OpenBot Mobile: stop the push token loop, register one at a time, and wait out a 429 (#2881)
* Mobile push: tests that hold registration to once per organization, one at a time, and waiting out a 429 The stand-in for expo-notifications now does what 58.1 does on a phone: asking for the Expo push token without a device token asks the phone for one, and the phone tells every push token listener the token it gave, changed or not. Against the code before the fix these fail: hundreds of registrations in 300ms where there should be two. Also: signing in refused as too many says it couldn't reach OpenBot, and a refresh refused as too many keeps the refresh token. * Mobile push: stop the token listener registering in a loop, one registration at a time, and wait out a 429 Asking expo-notifications for the Expo push token without a device token asks the phone for one, and the phone then tells every push token listener. The listener asked again, so it told itself again: build 7 sent about 10,000 device registrations a minute until the rate limit blocked the phone. The listener now registers with the token it is handed and never asks the phone for one. A token already registered registers nothing. One registration runs at a time, and whatever asks during it makes one more after it, with the newest token. Refused as too many, the phone waits out Retry-After, or a wait that doubles from 30 seconds, before it tries again. Sign-in refused as too many now says it couldn't reach OpenBot, not that OpenBot needs updating, and a refresh refused as too many no longer ends the sign-in.
1 parent 1d3713c commit 0384d8c

7 files changed

Lines changed: 438 additions & 42 deletions

File tree

‎mobile/src/api/request.ts‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,21 +41,35 @@ import {
4141
} from "./generated/organizations/organizations";
4242

4343
/**
44-
* A refusal from the server, with its status and the API's problem code when it gave one, and whether a refusal of
45-
* this app as too old was for a security problem.
44+
* A refusal from the server, with its status and the API's problem code when it gave one, whether a refusal of this
45+
* app as too old was for a security problem, and how long the server asked to be left alone (its Retry-After, in
46+
* milliseconds) when it said.
4647
*/
4748
export class ApiError extends Error {
4849
constructor(
4950
message: string,
5051
readonly status: number,
5152
readonly code?: string,
5253
readonly security = false,
54+
readonly retryAfterMs?: number,
5355
) {
5456
super(message);
5557
this.name = "ApiError";
5658
}
5759
}
5860

61+
/** A Retry-After header in milliseconds from now: seconds, or a date (RFC 9110). Undefined when there is none to read. */
62+
function readRetryAfter(
63+
value: string | null,
64+
now = Date.now(),
65+
): number | undefined {
66+
if (!value) return undefined;
67+
const trimmed = value.trim();
68+
if (/^\d+$/.test(trimmed)) return Number(trimmed) * 1000;
69+
const date = Date.parse(trimmed);
70+
return Number.isNaN(date) ? undefined : Math.max(0, date - now);
71+
}
72+
5973
/**
6074
* The organization every request is in: the one the signed-in person is working in. A generated call is given this in
6175
* place of an id, and the request below fills in the id from the person's own organizations, read once for each sign-in
@@ -416,6 +430,8 @@ export async function apiRequest<T>(
416430
said ?? `Request failed (${response.status}).`,
417431
response.status,
418432
code,
433+
false,
434+
readRetryAfter(response.headers.get("retry-after")),
419435
);
420436
}
421437
return body as T;

‎mobile/src/auth.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,9 @@ function loadMetadata(): Promise<Metadata> {
104104
} catch {
105105
throw new SignInError(UNREACHABLE);
106106
}
107-
if (response.status >= 500) throw new SignInError(UNREACHABLE);
107+
// Refused as too many (the deployment's rate limit) is not a server too old: it is one to try again in a moment.
108+
if (response.status >= 500 || response.status === 429)
109+
throw new SignInError(UNREACHABLE);
108110
if (!response.ok) throw new SignInError(SERVER_TOO_OLD);
109111
return readMetadata(await response.json().catch(() => null), __DEV__);
110112
})();

‎mobile/src/notifications.ts‎

Lines changed: 128 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,26 @@ import {
1414
import { deleteDevice, registerDevice } from "./api/generated/devices/devices";
1515

1616
const 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
*/
92148
export 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
};

‎mobile/src/oauth.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -255,8 +255,9 @@ export function readGrant(body: unknown): Grant {
255255

256256
/**
257257
* Whether a refused token request means the sign-in is over (the refresh token was revoked, used twice, or its owner
258-
* removed), as opposed to the server being unreachable or failing for a while, when the sign-in may still be good.
258+
* removed), as opposed to the server being unreachable, failing for a while, or refusing too many requests (429), when
259+
* the sign-in may still be good.
259260
*/
260261
export function signInEnded(status: number): boolean {
261-
return status >= 400 && status < 500;
262+
return status >= 400 && status < 500 && status !== 429;
262263
}

0 commit comments

Comments
 (0)