@astratra/native 0.1.0 → 0.3.0
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/README.md +251 -2
- package/package.json +9 -3
- package/src/connectivity.js +359 -0
- package/src/index.d.ts +307 -0
- package/src/index.js +5 -1
- package/src/mediaCache.js +262 -0
- package/src/pictureSource.js +696 -0
- package/src/updates.js +196 -0
package/README.md
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
# @astratra/native
|
|
2
2
|
|
|
3
3
|
La plomberie mobile, sans le moteur mobile : **session sécurisée, verrou
|
|
4
|
-
biométrique, notifications natives, retour de paiement
|
|
4
|
+
biométrique, notifications natives, retour de paiement, état du réseau, mises à
|
|
5
|
+
jour à distance, cache de médias, sources d'images**.
|
|
5
6
|
|
|
6
7
|
Le package ne charge ni `expo-secure-store`, ni `expo-local-authentication`,
|
|
7
|
-
ni `expo-web-browser`. Il les **reçoit**. Même règle que `@astratra/notify`
|
|
8
|
+
ni `expo-web-browser`, ni NetInfo, ni `expo-updates`, ni `expo-file-system`. Il les **reçoit**. Même règle que `@astratra/notify`
|
|
8
9
|
avec son transport, et même bénéfice : tout ce qui suit se teste en Node, sans
|
|
9
10
|
simulateur ni build natif.
|
|
10
11
|
|
|
@@ -202,3 +203,251 @@ resolveGlassMode({ platform, apiAvailable, effectAvailable }); // 'native' | 'fa
|
|
|
202
203
|
|
|
203
204
|
Décidé une fois, pour que toutes les surfaces répondent pareil : un en-tête qui
|
|
204
205
|
floute au-dessus d'une carte qui ne floute pas est pire que ni l'un ni l'autre.
|
|
206
|
+
|
|
207
|
+
# Réseau
|
|
208
|
+
|
|
209
|
+
```js
|
|
210
|
+
import NetInfo from '@react-native-community/netinfo';
|
|
211
|
+
import { createConnectivityMonitor } from '@astratra/native';
|
|
212
|
+
|
|
213
|
+
export const network = createConnectivityMonitor({ netInfo: NetInfo });
|
|
214
|
+
network.start(); // une fois, au lancement
|
|
215
|
+
network.setRecoveryProbe(() => api.request('/health'));
|
|
216
|
+
|
|
217
|
+
// dans le client HTTP
|
|
218
|
+
if (!network.shouldAttemptRequest()) return fromCache();
|
|
219
|
+
try { const r = await fetch(url); network.noteTransportSuccess(); return r; }
|
|
220
|
+
catch (e) { network.noteTransportFailure(isAbort(e) ? 'timeout' : 'unreachable'); throw e; }
|
|
221
|
+
|
|
222
|
+
// dans un écran
|
|
223
|
+
const offline = useSyncExternalStore(network.subscribe, network.isOffline);
|
|
224
|
+
useEffect(() => network.onComeback(reload), []);
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
**Hors ligne veut dire : aucune interface.** `isConnected === false`, rien
|
|
228
|
+
d'autre. Un `isInternetReachable` à `null` — le système n'a pas encore tranché,
|
|
229
|
+
les premières secondes de chaque lancement — n'est pas une panne : le traiter
|
|
230
|
+
comme tel fait clignoter « hors ligne » à chaque ouverture.
|
|
231
|
+
|
|
232
|
+
**Le « sans Internet » du système n'est pas une panne non plus.** Ce verdict ne
|
|
233
|
+
vient pas de votre serveur : sur Android c'est le drapeau « validé » du Wi-Fi,
|
|
234
|
+
posé seulement après avoir joint un serveur de Google ; ailleurs NetInfo sonde
|
|
235
|
+
lui-même une adresse Google. Sur un Wi-Fi où ce test échoue (DNS du
|
|
236
|
+
fournisseur, filtrage, lenteur), le réseau est déclaré mort alors que les
|
|
237
|
+
requêtes de l'application passent. Constaté en production : l'application se
|
|
238
|
+
disait hors ligne sur le Wi-Fi seul, et ne se croyait en ligne qu'avec les
|
|
239
|
+
données mobiles allumées en même temps. L'état reste donc « inconnu », les
|
|
240
|
+
requêtes partent, et **ce sont elles qui tranchent**.
|
|
241
|
+
|
|
242
|
+
**Un échec de transport se retient trente secondes** (`blackoutMs`). Le cas le
|
|
243
|
+
plus pénible — le Wi-Fi d'hôtel qui accepte la connexion et ne laisse rien
|
|
244
|
+
passer — n'est jamais évident pour le système. Sans cette mémoire, chaque écran
|
|
245
|
+
repayait tout le délai d'expiration avant de montrer son cache ; avec, le
|
|
246
|
+
premier paie, les suivants affichent tout de suite. N'importe quel appel qui
|
|
247
|
+
aboutit l'efface.
|
|
248
|
+
|
|
249
|
+
**Une expiration n'accuse pas toujours le réseau.** Si le système affirme
|
|
250
|
+
qu'Internet est joignable, un serveur lent expire comme un portail captif :
|
|
251
|
+
c'est le serveur qui est en cause, et basculer tout le monde hors ligne
|
|
252
|
+
servirait du cache périmé à tous les écrans. Un refus de transport, lui, est
|
|
253
|
+
formel.
|
|
254
|
+
|
|
255
|
+
**À l'échéance, on repose la question.** Sans cela, rien ne prévenait les
|
|
256
|
+
écrans quand les trente secondes tombaient, et le seul signal de reprise était
|
|
257
|
+
le retour de la radio — qui n'était jamais partie. La sonde part une fois ; si
|
|
258
|
+
elle réussit, la reprise est annoncée, sinon le constat repart. Rien ne part
|
|
259
|
+
quand le système affirme l'absence de réseau.
|
|
260
|
+
|
|
261
|
+
**Le retour du réseau est un événement, pas un état** (`onComeback`) : c'est
|
|
262
|
+
lui qui relance ce qui avait échoué, une seule fois. `refresh()`, pour une
|
|
263
|
+
tâche d'arrière-plan qui se réveille, relit le système sans l'émettre — la
|
|
264
|
+
tâche va vider la file elle-même.
|
|
265
|
+
|
|
266
|
+
**Le lien compte à part** (`getConnectionLink()` : `wifi`, `cellular`, `none`,
|
|
267
|
+
`unknown`). Passer du Wi-Fi aux données mobiles ne change pas « en ligne », et
|
|
268
|
+
change tout pour ce qui se paie au mégaoctet. Traitez `unknown` comme facturé.
|
|
269
|
+
|
|
270
|
+
Les règles sont aussi exportées seules, pures : `readReachability`,
|
|
271
|
+
`readConnectionLink`, `worthAttempting`, `hasComeBack`,
|
|
272
|
+
`shouldDeclareTransportDown`.
|
|
273
|
+
|
|
274
|
+
# Mises à jour à distance
|
|
275
|
+
|
|
276
|
+
```js
|
|
277
|
+
import * as Updates from 'expo-updates';
|
|
278
|
+
import { AppState } from 'react-native';
|
|
279
|
+
import { createUpdateWatcher } from '@astratra/native';
|
|
280
|
+
|
|
281
|
+
const watcher = createUpdateWatcher({
|
|
282
|
+
updates: Updates,
|
|
283
|
+
appState: AppState,
|
|
284
|
+
isOnline: network.shouldAttemptRequest,
|
|
285
|
+
pendingWrites: () => outbox.pending,
|
|
286
|
+
onError: (error, { where }) => report(error, where)
|
|
287
|
+
});
|
|
288
|
+
watcher.start();
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
**Vérifier au lancement, puis au plus une fois par heure** (`checkIntervalMs`),
|
|
292
|
+
au retour au premier plan, et jamais hors ligne. Une mise à jour que
|
|
293
|
+
l'application ne demande jamais ne sert à rien — c'était le cas.
|
|
294
|
+
|
|
295
|
+
**Appliquer seulement quand personne ne regarde.** Au passage en arrière-plan,
|
|
296
|
+
un délai de grâce de 45 secondes (`graceMs`) : répondre à un SMS et revenir
|
|
297
|
+
prend quelques secondes, et recharger pendant cet aller-retour renvoyait la
|
|
298
|
+
personne à l'écran de démarrage, sa page perdue. Revenir annule le délai ; un
|
|
299
|
+
nouveau départ le recommence en entier.
|
|
300
|
+
|
|
301
|
+
**À l'échéance, on revérifie.** Sur iOS, un minuteur gelé en arrière-plan part
|
|
302
|
+
au retour au premier plan, avant l'événement de changement d'état : sans cette
|
|
303
|
+
garde, le rechargement tombait sous les yeux de la personne.
|
|
304
|
+
|
|
305
|
+
**Jamais avec des écritures en attente.** Recharger en pleine reprise de la
|
|
306
|
+
file hors ligne peut rejouer une entrée avant qu'elle soit marquée partie.
|
|
307
|
+
L'occasion suivante la posera.
|
|
308
|
+
|
|
309
|
+
`describeBuild(version)` donne ce que tourne vraiment le téléphone ; son
|
|
310
|
+
`release` (`1.2.0+3f2a9c1d`, ou `1.2.0+embedded`) distingue deux mises à jour du
|
|
311
|
+
même binaire dans les rapports de plantage.
|
|
312
|
+
|
|
313
|
+
# Cache de médias
|
|
314
|
+
|
|
315
|
+
```js
|
|
316
|
+
import * as FileSystem from 'expo-file-system/legacy';
|
|
317
|
+
import { createMediaCache, contentKey, extensionFor } from '@astratra/native';
|
|
318
|
+
|
|
319
|
+
const cache = createMediaCache({
|
|
320
|
+
fs: FileSystem,
|
|
321
|
+
directory: `${FileSystem.cacheDirectory}audio/`,
|
|
322
|
+
extensions: ['m4a', 'wav']
|
|
323
|
+
});
|
|
324
|
+
|
|
325
|
+
const uri = await cache.resolve(contentKey('v2', lang, text), async () => {
|
|
326
|
+
const response = await api.raw('/speak', { method: 'POST', body });
|
|
327
|
+
const bytes = await response.arrayBuffer();
|
|
328
|
+
return {
|
|
329
|
+
extension: extensionFor(response.headers.get('content-type'), { 'audio/mp4': 'm4a' }, 'wav'),
|
|
330
|
+
write: (tempUri) => FileSystem.writeAsStringAsync(tempUri, toBase64(bytes), { encoding: 'base64' })
|
|
331
|
+
};
|
|
332
|
+
});
|
|
333
|
+
```
|
|
334
|
+
|
|
335
|
+
La première version de ce cache retéléchargeait tout le fichier à chaque
|
|
336
|
+
lecture, et laissait chaque copie sous un nom horodaté que plus rien ne
|
|
337
|
+
relisait : le dossier grossissait sans fin.
|
|
338
|
+
|
|
339
|
+
**Une clé stable par contenu.** `contentKey(...parties)` : tout ce qui change
|
|
340
|
+
les octets, **version comprise** — quand le serveur change son rendu, la
|
|
341
|
+
nouvelle version retire les anciens fichiers. Les parties sont encodées, pas
|
|
342
|
+
collées : `('a:b', 'c')` et `('a', 'b:c')` ne partagent pas de clé. 106 bits,
|
|
343
|
+
en JS pur (une empreinte native serait asynchrone et ne tournerait pas en Node).
|
|
344
|
+
|
|
345
|
+
**Écrire à côté, puis déplacer.** Une coupure au milieu de l'écriture laisse un
|
|
346
|
+
`.tmp`, jamais un fichier tronqué pris pour valide à la lecture suivante. Deux
|
|
347
|
+
appuis sur le même contenu : le déplacement perdant cède au fichier déjà posé.
|
|
348
|
+
|
|
349
|
+
**Un dossier borné** : 40 fichiers et 60 Mo par défaut (`maxFiles`,
|
|
350
|
+
`maxBytes`), les plus anciens partent d'abord. Le plus récent **ne part
|
|
351
|
+
jamais**, même trop lourd à lui seul : c'est celui qu'on lit. Un temporaire de
|
|
352
|
+
plus de cinq minutes (`abandonedAfterMs`) est le reste d'un téléchargement
|
|
353
|
+
coupé ; plus jeune, il est peut-être en cours d'écriture, on n'y touche pas.
|
|
354
|
+
Le rangement suit chaque écriture, sans retenir la lecture, un seul à la fois.
|
|
355
|
+
|
|
356
|
+
Le dossier doit être **à lui seul** : tout ce qui n'y porte pas l'une des
|
|
357
|
+
extensions déclarées est traité comme un temporaire abandonné.
|
|
358
|
+
|
|
359
|
+
L'API historique d'Expo ne sait pas toucher la date d'un fichier sans le
|
|
360
|
+
réécrire : l'éviction suit donc l'ordre de téléchargement, pas celui de
|
|
361
|
+
lecture. Un fichier très relu finit par partir, puis revient au prochain appui.
|
|
362
|
+
|
|
363
|
+
# Images
|
|
364
|
+
|
|
365
|
+
```js
|
|
366
|
+
import * as FileSystem from 'expo-file-system/legacy';
|
|
367
|
+
import * as Sharing from 'expo-sharing';
|
|
368
|
+
import { createPictureSources, createPictureFiles, pictureUti } from '@astratra/native';
|
|
369
|
+
|
|
370
|
+
const pictures = createPictureSources({
|
|
371
|
+
appUrl: API_BASE_URL, // 'https://api.example.com' ou '…/api'
|
|
372
|
+
getToken: () => session.getAccessToken()
|
|
373
|
+
});
|
|
374
|
+
|
|
375
|
+
// Pour <Image> (React Native ou expo-image) : le jeton seulement chez soi.
|
|
376
|
+
const source = await pictures.resolve('/images/abc');
|
|
377
|
+
// { uri: 'https://api.example.com/images/abc', headers: { Authorization: 'Bearer …' } }
|
|
378
|
+
await pictures.resolve('https://cdn.example.org/fig.jpg'); // { uri } — jamais d'en-tête
|
|
379
|
+
await pictures.resolve('https://api.example.com@evil.com/x'); // null — refusée
|
|
380
|
+
|
|
381
|
+
// L'original en fichier, pour Photos ou la feuille de partage.
|
|
382
|
+
const files = createPictureFiles({
|
|
383
|
+
sources: pictures,
|
|
384
|
+
fs: FileSystem,
|
|
385
|
+
directory: `${FileSystem.cacheDirectory}pictures/`
|
|
386
|
+
});
|
|
387
|
+
const uri = await files.named('/images/abc', title, { fallback: t('picture'), query: { original: 1 } });
|
|
388
|
+
await Sharing.shareAsync(uri, { dialogTitle: title, UTI: pictureUti(uri) ?? undefined });
|
|
389
|
+
```
|
|
390
|
+
|
|
391
|
+
Une application montre trois sortes d'images : **les siennes**, servies par son
|
|
392
|
+
API derrière le jeton de la personne (`/images/abc`, ou la même adresse écrite
|
|
393
|
+
en entier) ; celles **du dehors** (une publication, un CDN), chargées telles
|
|
394
|
+
quelles ; celles **intégrées** (`data:image/…`) dans un document.
|
|
395
|
+
|
|
396
|
+
**Le jeton ne part que vers l'origine de l'application.** La première version
|
|
397
|
+
de cette règle était un test de préfixe (`https://` = dehors) et collait le
|
|
398
|
+
chemin après l'URL de base de l'API. Deux adresses qu'on n'a pas écrites
|
|
399
|
+
soi-même suffisaient à envoyer le jeton ailleurs :
|
|
400
|
+
|
|
401
|
+
| Adresse reçue | Collée après `https://api.example.com` | Part vers |
|
|
402
|
+
| --- | --- | --- |
|
|
403
|
+
| `.evil.com/x` | `https://api.example.com.evil.com/x` | evil.com, **avec le jeton** |
|
|
404
|
+
| `@evil.com/x` | `https://api.example.com@evil.com/x` | evil.com, **avec le jeton** |
|
|
405
|
+
|
|
406
|
+
Ici l'adresse est **analysée**, son origine comparée **en entier** (schéma, hôte,
|
|
407
|
+
port — jamais une sous-chaîne ni un préfixe), et ce qui ne s'analyse pas
|
|
408
|
+
proprement est **refusé** au lieu d'être deviné : identifiants dans l'autorité
|
|
409
|
+
(`app.example.com@evil.com`), barre oblique inverse, caractère de contrôle ou
|
|
410
|
+
espace (l'analyseur WHATWG supprime tabulations et retours à la ligne en
|
|
411
|
+
silence), hôte encodé en `%` ou non ASCII, port hors plage, `//hôte` relatif au
|
|
412
|
+
schéma, chemin sans `/` initial. `app.example.com.evil.com`,
|
|
413
|
+
`evil.com/?u=app.example.com`, `cdn.app.example.com`, un autre port ou `http`
|
|
414
|
+
au lieu de `https` sont **d'autres origines** : chargées sans jeton. L'en-tête
|
|
415
|
+
est décidé au dernier moment, sur l'adresse finale (`headersFor`).
|
|
416
|
+
|
|
417
|
+
Pourquoi pas `new URL()` : le polyfill de React Native n'implémente pas
|
|
418
|
+
`hostname` sur toutes les versions, et l'analyseur WHATWG est tolérant
|
|
419
|
+
exactement là où un attaquant s'en sert. Un analyseur strict qui refuse vaut
|
|
420
|
+
mieux qu'un analyseur tolérant qui répare.
|
|
421
|
+
|
|
422
|
+
**Le dehors en `https` seulement** (`allowHttpOutside` pour l'autoriser) : iOS
|
|
423
|
+
bloque `http` de toute façon, et une page qui en charge trahit ce qu'on lit.
|
|
424
|
+
L'origine de l'application elle-même peut être en `http` (développement local).
|
|
425
|
+
|
|
426
|
+
**Les images intégrées** sont jugées sur leur **longueur** avant tout balayage
|
|
427
|
+
(10 Mo décodés par défaut, `maxDataBytes`) : une adresse de 200 Mo est refusée en
|
|
428
|
+
temps constant. Seul l'en-tête est examiné pour sa forme (256 premiers
|
|
429
|
+
caractères). SVG n'est pas accepté par défaut (c'est un document, pas une
|
|
430
|
+
image) ; `dataTypes` pour l'ajouter.
|
|
431
|
+
|
|
432
|
+
**La clé de cache** (`cacheKey`) : l'adresse normalisée — un chemin et la même
|
|
433
|
+
adresse écrite en entier la partagent — **jamais le jeton** ; 106 bits
|
|
434
|
+
(`contentKey`), là où l'ancienne empreinte de 32 bits pouvait faire partager un
|
|
435
|
+
fichier à deux images. `variant` et `version` séparent deux rendus et retirent
|
|
436
|
+
une ancienne règle.
|
|
437
|
+
|
|
438
|
+
**Les fichiers** (`createPictureFiles`) : l'original est téléchargé sous un nom
|
|
439
|
+
temporaire puis déplacé **une fois complet et reconnu**. L'ancienne version
|
|
440
|
+
servait n'importe quel fichier trouvé dans le dossier — un téléchargement coupé
|
|
441
|
+
à mi-chemin devenait l'image, pour toujours. Le type vient des **octets**
|
|
442
|
+
(`sniffPictureType` : PNG, JPEG, GIF, WebP, HEIC, AVIF, BMP), jamais du nom : une
|
|
443
|
+
page d'erreur HTML servie en 200 est refusée (`not_a_picture`) au lieu d'être
|
|
444
|
+
enregistrée dans Photos comme JPEG. Un statut hors 2xx est une erreur `http`.
|
|
445
|
+
Deux appels simultanés partagent un seul téléchargement. Le dossier est borné
|
|
446
|
+
par `createMediaCache`. `named()` en fait une copie au titre de l'image
|
|
447
|
+
(`pictureFileName` : caractères réservés retirés, pas de fichier caché, coupé en
|
|
448
|
+
caractères et non en octets) ; seule la dernière copie nommée est gardée.
|
|
449
|
+
|
|
450
|
+
Les erreurs sont des **codes** (`PictureSourceError`: `refused` + raison,
|
|
451
|
+
`http` + statut, `not_a_picture`), jamais des phrases. La permission de Photos
|
|
452
|
+
(`expo-media-library`) reste à l'application.
|
|
453
|
+
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@astratra/native",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Mobile plumbing without the mobile runtime: secure token session with an injected keystore, a biometric gate, native push registration and foreground watching,
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "Mobile plumbing without the mobile runtime: secure token session with an injected keystore, a biometric gate, native push registration and foreground watching, a checkout round-trip that survives a missing native module, network state that only calls a missing interface offline, over-the-air updates applied when nobody is looking, a bounded on-disk media cache, and picture sources that send the token to the app's own origin only, with originals kept as files. Adapters injected, so it tests in plain Node.",
|
|
5
5
|
"engines": {
|
|
6
6
|
"node": ">=20"
|
|
7
7
|
},
|
|
@@ -26,7 +26,13 @@
|
|
|
26
26
|
"expo",
|
|
27
27
|
"session",
|
|
28
28
|
"biometric",
|
|
29
|
-
"push"
|
|
29
|
+
"push",
|
|
30
|
+
"netinfo",
|
|
31
|
+
"offline",
|
|
32
|
+
"expo-updates",
|
|
33
|
+
"cache",
|
|
34
|
+
"image",
|
|
35
|
+
"pictures"
|
|
30
36
|
],
|
|
31
37
|
"license": "MIT",
|
|
32
38
|
"publishConfig": {
|
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What "online" means, exactly — and who gets to say it.
|
|
3
|
+
*
|
|
4
|
+
* An app with no network signal ends up inferring one from the last request:
|
|
5
|
+
* a status pill that says "offline" when the SERVER fell over, blaming the
|
|
6
|
+
* person's network, and stays green while a request hangs.
|
|
7
|
+
*
|
|
8
|
+
* The OS knows three distinct things, and conflating them is the classic trap:
|
|
9
|
+
*
|
|
10
|
+
* - `isConnected`: an interface is up. A hotel wifi that wants a login page
|
|
11
|
+
* says YES, and nothing gets through.
|
|
12
|
+
* - `isInternetReachable`: the OS's own verdict on the outside world. It is
|
|
13
|
+
* `null` for the first seconds after launch, and — see below — its "no"
|
|
14
|
+
* is about Google, not about us.
|
|
15
|
+
* - the link type (wifi, cellular, none).
|
|
16
|
+
*
|
|
17
|
+
* The rule: offline only when the OS has NO interface at all. Everything else
|
|
18
|
+
* is either proven online or unknown, and unknown lets requests go out. OUR
|
|
19
|
+
* requests are what settle it: a transport failure is remembered for a short
|
|
20
|
+
* while (the blackout below), and a success clears it.
|
|
21
|
+
*
|
|
22
|
+
* NetInfo is INJECTED, like the keystore: importing it here would drag a native
|
|
23
|
+
* module into every test and into every place it is absent.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
/** Thirty seconds: long enough to spare the next screens the wait, short
|
|
27
|
+
* enough that a passing outage does not condemn the app. */
|
|
28
|
+
const TRANSPORT_BLACKOUT_MS = 30_000;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* @param {{isConnected?: boolean|null, isInternetReachable?: boolean|null}|null|undefined} snapshot
|
|
32
|
+
* @returns {'online'|'offline'|'unknown'} `unknown` is a state of its own, not
|
|
33
|
+
* a default: it lets the UI stay silent instead of announcing an outage it
|
|
34
|
+
* has not observed.
|
|
35
|
+
*/
|
|
36
|
+
function readReachability(snapshot) {
|
|
37
|
+
if (!snapshot) return 'unknown';
|
|
38
|
+
|
|
39
|
+
/* No interface at all: the only case where the OS is certain without having
|
|
40
|
+
to reach anything. */
|
|
41
|
+
if (snapshot.isConnected === false) return 'offline';
|
|
42
|
+
|
|
43
|
+
/* An interface the OS calls "no Internet" is NOT proof of an outage. Seen in
|
|
44
|
+
production: that verdict does not come from our server. On Android it is
|
|
45
|
+
the wifi's "validated" flag, set only after reaching a Google endpoint;
|
|
46
|
+
elsewhere NetInfo probes a Google URL itself. On a wifi where that test
|
|
47
|
+
fails (provider DNS, filtering, slowness) the network is declared dead
|
|
48
|
+
while the app's own requests go through: the app showed "offline" on
|
|
49
|
+
wifi alone, and believed itself online only with mobile data switched on
|
|
50
|
+
too (the OS then validated through 4G).
|
|
51
|
+
|
|
52
|
+
So it stays unknown, requests go out, and a real failure is caught by the
|
|
53
|
+
transport blackout. Captive portals and exhausted data plans are still
|
|
54
|
+
detected — by the failure itself, not by Google's probe. */
|
|
55
|
+
if (snapshot.isInternetReachable === false) return 'unknown';
|
|
56
|
+
|
|
57
|
+
if (snapshot.isConnected === true && snapshot.isInternetReachable === true) return 'online';
|
|
58
|
+
|
|
59
|
+
/* Interface up, verdict not rendered yet. Treating that as an outage would
|
|
60
|
+
flash "offline" on every launch and teach people to ignore the pill. */
|
|
61
|
+
return 'unknown';
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* The current link, from the point of view of what it COSTS.
|
|
66
|
+
*
|
|
67
|
+
* Not the same question as "are we online": a download on home wifi is free,
|
|
68
|
+
* the same one on mobile data is paid by the megabyte. Ethernet and a docked
|
|
69
|
+
* tablet's wifi sit on the same side; whatever cannot be named is `unknown`,
|
|
70
|
+
* and callers should treat unknown as metered.
|
|
71
|
+
*
|
|
72
|
+
* @returns {'wifi'|'cellular'|'none'|'unknown'}
|
|
73
|
+
*/
|
|
74
|
+
function readConnectionLink(snapshot) {
|
|
75
|
+
if (!snapshot) return 'unknown';
|
|
76
|
+
if (readReachability(snapshot) === 'offline') return 'none';
|
|
77
|
+
const type = String(snapshot.type ?? '').toLowerCase();
|
|
78
|
+
if (type === 'wifi' || type === 'ethernet' || type === 'wimax') return 'wifi';
|
|
79
|
+
if (type === 'cellular') return 'cellular';
|
|
80
|
+
if (type === 'none') return 'none';
|
|
81
|
+
return 'unknown';
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Should an outage be announced? Only an established one. */
|
|
85
|
+
function isDefinitelyOffline(snapshot) {
|
|
86
|
+
return readReachability(snapshot) === 'offline';
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Is a request worth attempting? Yes, unless certain otherwise. Blocking on
|
|
91
|
+
* `unknown` would stop the app from starting during the seconds the OS has not
|
|
92
|
+
* decided yet — that is, on every launch.
|
|
93
|
+
*/
|
|
94
|
+
function worthAttempting(snapshot) {
|
|
95
|
+
return readReachability(snapshot) !== 'offline';
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Did the network just come back? That transition, and only it, should trigger
|
|
100
|
+
* a reload. Reacting to "we are online" would refire every request on each OS
|
|
101
|
+
* notification, including when nothing changed.
|
|
102
|
+
*/
|
|
103
|
+
function hasComeBack(previous, next) {
|
|
104
|
+
return previous === 'offline' && next === 'online';
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Does a failed request prove the NETWORK is down?
|
|
109
|
+
*
|
|
110
|
+
* The blackout stops EVERY request: it must only be raised when the network is
|
|
111
|
+
* to blame. A server taking longer than the timeout — peak hour, a heavy
|
|
112
|
+
* endpoint — expires exactly like a captive wifi. The OS knows the difference:
|
|
113
|
+
* when it AFFIRMS the Internet is reachable, a timeout blames the server, and
|
|
114
|
+
* flipping the app offline on a healthy connection would serve stale cache to
|
|
115
|
+
* every screen.
|
|
116
|
+
*
|
|
117
|
+
* A transport refusal ("Network request failed") is conclusive whatever the OS
|
|
118
|
+
* says: the request never left.
|
|
119
|
+
*
|
|
120
|
+
* @param {{reason: 'timeout'|'unreachable', reachability: 'online'|'offline'|'unknown'}} input
|
|
121
|
+
*/
|
|
122
|
+
function shouldDeclareTransportDown({ reason, reachability } = {}) {
|
|
123
|
+
if (reason === 'unreachable') return true;
|
|
124
|
+
return reachability !== 'online';
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** NetInfo's state, narrowed to what the rules read. */
|
|
128
|
+
function toSnapshot(state) {
|
|
129
|
+
const source = state || {};
|
|
130
|
+
return {
|
|
131
|
+
isConnected: source.isConnected ?? null,
|
|
132
|
+
isInternetReachable: source.isInternetReachable ?? null,
|
|
133
|
+
type: source.type ?? null
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* One subscription to the OS for the whole app.
|
|
139
|
+
*
|
|
140
|
+
* Every screen with its own NetInfo listener keeps the radio busy for nothing,
|
|
141
|
+
* and on an entry-level phone that is paid in battery. Screens subscribe to
|
|
142
|
+
* this monitor, not to the OS.
|
|
143
|
+
*
|
|
144
|
+
* @param {object} [options]
|
|
145
|
+
* @param {{addEventListener: Function, fetch: Function}} [options.netInfo]
|
|
146
|
+
* @react-native-community/netinfo's default export, or anything shaped like
|
|
147
|
+
* it. Only needed for start() and refresh().
|
|
148
|
+
* @param {number} [options.blackoutMs] How long a transport failure is
|
|
149
|
+
* remembered.
|
|
150
|
+
* @param {() => number} [options.now]
|
|
151
|
+
*/
|
|
152
|
+
function createConnectivityMonitor(options = {}) {
|
|
153
|
+
const netInfo = options.netInfo || null;
|
|
154
|
+
const blackoutMs = Number.isFinite(options.blackoutMs) ? options.blackoutMs : TRANSPORT_BLACKOUT_MS;
|
|
155
|
+
const now = typeof options.now === 'function' ? options.now : () => Date.now();
|
|
156
|
+
|
|
157
|
+
let snapshot = null;
|
|
158
|
+
let reachability = 'unknown';
|
|
159
|
+
let unsubscribeNetInfo = null;
|
|
160
|
+
|
|
161
|
+
const listeners = new Set();
|
|
162
|
+
const comebackListeners = new Set();
|
|
163
|
+
|
|
164
|
+
let transportDownUntil = 0;
|
|
165
|
+
let blackoutTimer = null;
|
|
166
|
+
let recoveryProbe = null;
|
|
167
|
+
|
|
168
|
+
function notifyAll() {
|
|
169
|
+
for (const notify of [...listeners]) notify();
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function notifyComeback() {
|
|
173
|
+
for (const notify of [...comebackListeners]) notify();
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function clearTransportDown() {
|
|
177
|
+
transportDownUntil = 0;
|
|
178
|
+
if (blackoutTimer) clearTimeout(blackoutTimer);
|
|
179
|
+
blackoutTimer = null;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function publish(next, emitComeback = true) {
|
|
183
|
+
const previous = reachability;
|
|
184
|
+
/* The link TYPE counts separately: moving from wifi to mobile data leaves
|
|
185
|
+
"online" unchanged, and changes everything for what is paid by the
|
|
186
|
+
megabyte. Without this second witness, a settings screen kept announcing
|
|
187
|
+
wifi after the person left the house. */
|
|
188
|
+
const previousLink = readConnectionLink(snapshot);
|
|
189
|
+
snapshot = next;
|
|
190
|
+
reachability = readReachability(next);
|
|
191
|
+
if (previous === reachability && previousLink === readConnectionLink(next)) return;
|
|
192
|
+
|
|
193
|
+
notifyAll();
|
|
194
|
+
/* The return of the network is an EVENT, not a state: it restarts what had
|
|
195
|
+
failed, once. What we had observed no longer holds. */
|
|
196
|
+
if (hasComeBack(previous, reachability)) {
|
|
197
|
+
clearTransportDown();
|
|
198
|
+
if (emitComeback) notifyComeback();
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* The end of the blackout, and the question put back to the server.
|
|
204
|
+
*
|
|
205
|
+
* The blackout used to be read off the clock, and nobody was told when it
|
|
206
|
+
* lapsed: a status bell sat on "offline" until something else repainted it,
|
|
207
|
+
* and screens that had fallen back to cache stayed there, since the only
|
|
208
|
+
* recovery signal was the RADIO coming back — and it had never left. Seen
|
|
209
|
+
* against a dev server restarted by a file watcher several times a minute:
|
|
210
|
+
* each restart refused one connection, and the app believed itself offline
|
|
211
|
+
* long after the server answered again.
|
|
212
|
+
*
|
|
213
|
+
* So at expiry the screens are told, and ONE light request goes to the
|
|
214
|
+
* server. If it succeeds, noteTransportSuccess() announces the recovery; if
|
|
215
|
+
* it fails, the blackout restarts. Nothing is sent while the OS affirms
|
|
216
|
+
* there is no network: its own return will take care of it.
|
|
217
|
+
*/
|
|
218
|
+
function armBlackoutTimer() {
|
|
219
|
+
if (blackoutTimer) clearTimeout(blackoutTimer);
|
|
220
|
+
blackoutTimer = setTimeout(() => {
|
|
221
|
+
blackoutTimer = null;
|
|
222
|
+
notifyAll();
|
|
223
|
+
if (reachability !== 'offline' && recoveryProbe) {
|
|
224
|
+
Promise.resolve()
|
|
225
|
+
.then(() => recoveryProbe())
|
|
226
|
+
.catch(() => undefined);
|
|
227
|
+
}
|
|
228
|
+
}, blackoutMs);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function isTransportDown() {
|
|
232
|
+
return now() < transportDownUntil;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* A request failed in transport. Remember it: the case that hurts most is
|
|
237
|
+
* never obvious to the OS — the wifi that accepts the connection and lets
|
|
238
|
+
* nothing through. `isInternetReachable` stays null there, and every screen
|
|
239
|
+
* paid the full request timeout before showing its cache. With the
|
|
240
|
+
* blackout, the first screen pays the wait, the next ones show cache at once.
|
|
241
|
+
*
|
|
242
|
+
* @param {'timeout'|'unreachable'} [reason]
|
|
243
|
+
*/
|
|
244
|
+
function noteTransportFailure(reason = 'unreachable') {
|
|
245
|
+
/* A timeout on a network the OS calls healthy blames the server, not the
|
|
246
|
+
connection: it does not cut everyone's requests for thirty seconds. */
|
|
247
|
+
if (!shouldDeclareTransportDown({ reason, reachability })) return;
|
|
248
|
+
/* Compared to the clock, not to zero: an expired blackout leaves its date
|
|
249
|
+
behind, and a `!transportDownUntil` test silenced the next outage. */
|
|
250
|
+
const wasDown = isTransportDown();
|
|
251
|
+
transportDownUntil = now() + blackoutMs;
|
|
252
|
+
armBlackoutTimer();
|
|
253
|
+
/* The blackout is news: a screen open for an hour must learn it without
|
|
254
|
+
having asked anything itself. */
|
|
255
|
+
if (!wasDown) notifyAll();
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** Any request that got an answer. Clears the blackout and, if there was one,
|
|
259
|
+
* announces the recovery like the radio's own return would. */
|
|
260
|
+
function noteTransportSuccess() {
|
|
261
|
+
if (!transportDownUntil) return;
|
|
262
|
+
clearTransportDown();
|
|
263
|
+
notifyAll();
|
|
264
|
+
if (reachability !== 'offline') notifyComeback();
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function onNetInfoState(state) {
|
|
268
|
+
publish(toSnapshot(state));
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
return {
|
|
272
|
+
/** Start listening to the OS. Idempotent: a second call does nothing. */
|
|
273
|
+
start() {
|
|
274
|
+
if (unsubscribeNetInfo) return;
|
|
275
|
+
if (!netInfo) throw new Error('createConnectivityMonitor: start() needs a netInfo adapter.');
|
|
276
|
+
const subscription = netInfo.addEventListener(onNetInfoState);
|
|
277
|
+
unsubscribeNetInfo = typeof subscription === 'function'
|
|
278
|
+
? subscription
|
|
279
|
+
: () => subscription && typeof subscription.remove === 'function' && subscription.remove();
|
|
280
|
+
Promise.resolve()
|
|
281
|
+
.then(() => netInfo.fetch())
|
|
282
|
+
.then(onNetInfoState)
|
|
283
|
+
.catch(() => undefined);
|
|
284
|
+
},
|
|
285
|
+
|
|
286
|
+
stop() {
|
|
287
|
+
if (unsubscribeNetInfo) unsubscribeNetInfo();
|
|
288
|
+
unsubscribeNetInfo = null;
|
|
289
|
+
clearTransportDown();
|
|
290
|
+
},
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Re-read the OS, for a background task waking from suspension: the last
|
|
294
|
+
* known state may be frozen. The comeback event is NOT emitted — it would
|
|
295
|
+
* start a second flush alongside the one the background task is about to
|
|
296
|
+
* run itself.
|
|
297
|
+
* @returns {Promise<boolean>} Whether a request is worth attempting.
|
|
298
|
+
*/
|
|
299
|
+
async refresh() {
|
|
300
|
+
if (!netInfo) throw new Error('createConnectivityMonitor: refresh() needs a netInfo adapter.');
|
|
301
|
+
publish(toSnapshot(await netInfo.fetch()), false);
|
|
302
|
+
return worthAttempting(snapshot);
|
|
303
|
+
},
|
|
304
|
+
|
|
305
|
+
/** Feed a state by hand — tests, or a platform with its own source. */
|
|
306
|
+
setSnapshot(next) {
|
|
307
|
+
publish(toSnapshot(next));
|
|
308
|
+
},
|
|
309
|
+
|
|
310
|
+
getReachability: () => reachability,
|
|
311
|
+
getConnectionLink: () => readConnectionLink(snapshot),
|
|
312
|
+
isTransportDown,
|
|
313
|
+
|
|
314
|
+
/** One answer for the whole app: the OS affirms no network, or the app has
|
|
315
|
+
* just observed that nothing gets through. */
|
|
316
|
+
isOffline: () => reachability === 'offline' || isTransportDown(),
|
|
317
|
+
|
|
318
|
+
/** A blackout just observed is a certainty, even before the OS decides. */
|
|
319
|
+
shouldAttemptRequest: () => !isTransportDown() && worthAttempting(snapshot),
|
|
320
|
+
|
|
321
|
+
noteTransportFailure,
|
|
322
|
+
noteTransportSuccess,
|
|
323
|
+
|
|
324
|
+
/** The light request fired when a blackout lapses. Null disables it. */
|
|
325
|
+
setRecoveryProbe(probe) {
|
|
326
|
+
recoveryProbe = typeof probe === 'function' ? probe : null;
|
|
327
|
+
},
|
|
328
|
+
|
|
329
|
+
/** Any change of state or link. Shaped for useSyncExternalStore. */
|
|
330
|
+
subscribe(listener) {
|
|
331
|
+
listeners.add(listener);
|
|
332
|
+
return () => {
|
|
333
|
+
listeners.delete(listener);
|
|
334
|
+
};
|
|
335
|
+
},
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* The network came BACK. Separate from subscribe(): a screen that reloads
|
|
339
|
+
* on recovery has no reason to re-render on every OS heartbeat.
|
|
340
|
+
*/
|
|
341
|
+
onComeback(listener) {
|
|
342
|
+
comebackListeners.add(listener);
|
|
343
|
+
return () => {
|
|
344
|
+
comebackListeners.delete(listener);
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
module.exports = {
|
|
351
|
+
TRANSPORT_BLACKOUT_MS,
|
|
352
|
+
readReachability,
|
|
353
|
+
readConnectionLink,
|
|
354
|
+
isDefinitelyOffline,
|
|
355
|
+
worthAttempting,
|
|
356
|
+
hasComeBack,
|
|
357
|
+
shouldDeclareTransportDown,
|
|
358
|
+
createConnectivityMonitor
|
|
359
|
+
};
|