about summary refs log tree commit diff
path: root/src/state/geolocation/config.ts
blob: 1f7f2daf221c84ded3d16dc34c87acf1f42904ce (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
import {networkRetry} from '#/lib/async/retry'
import {
  DEFAULT_GEOLOCATION_CONFIG,
  GEOLOCATION_CONFIG_URL,
} from '#/state/geolocation/const'
import {emitGeolocationConfigUpdate} from '#/state/geolocation/events'
import {logger} from '#/state/geolocation/logger'
import {BAPP_CONFIG_DEV_BYPASS_SECRET, IS_DEV} from '#/env'
import {type Device, device} from '#/storage'

async function getGeolocationConfig(
  url: string,
): Promise<Device['geolocation']> {
  const res = await fetch(url, {
    headers: IS_DEV
      ? {
          'x-dev-bypass-secret': BAPP_CONFIG_DEV_BYPASS_SECRET,
        }
      : undefined,
  })

  if (!res.ok) {
    throw new Error(`geolocation config: fetch failed ${res.status}`)
  }

  const json = await res.json()

  if (json.countryCode) {
    /**
     * Only construct known values here, ignore any extras.
     */
    const config: Device['geolocation'] = {
      countryCode: json.countryCode,
      regionCode: json.regionCode ?? undefined,
      ageRestrictedGeos: json.ageRestrictedGeos ?? [],
      ageBlockedGeos: json.ageBlockedGeos ?? [],
    }
    logger.debug(`geolocation config: success`)
    return config
  } else {
    return undefined
  }
}

/**
 * Local promise used within this file only.
 */
let geolocationConfigResolution: Promise<{success: boolean}> | undefined

/**
 * Begin the process of resolving geolocation config. This should be called
 * once at app start.
 *
 * THIS METHOD SHOULD NEVER THROW.
 *
 * This method is otherwise not used for any purpose. To ensure geolocation
 * config is resolved, use {@link ensureGeolocationConfigIsResolved}
 */
export function beginResolveGeolocationConfig() {
  /**
   * Here for debug purposes. Uncomment to prevent hitting the remote geo service, and apply whatever data you require for testing.
   */
  // if (__DEV__) {
  //   geolocationConfigResolution = new Promise(y => y({success: true}))
  //   device.set(['deviceGeolocation'], undefined) // clears GPS data
  //   device.set(['geolocation'], DEFAULT_GEOLOCATION_CONFIG) // clears bapp-config data
  //   return
  // }

  geolocationConfigResolution = new Promise(async resolve => {
    let success = true

    try {
      // Try once, fail fast
      const config = await getGeolocationConfig(GEOLOCATION_CONFIG_URL)
      if (config) {
        device.set(['geolocation'], config)
        emitGeolocationConfigUpdate(config)
      } else {
        // endpoint should throw on all failures, this is insurance
        throw new Error(
          `geolocation config: nothing returned from initial request`,
        )
      }
    } catch (e: any) {
      success = false

      logger.debug(`geolocation config: failed initial request`, {
        safeMessage: e.message,
      })

      // set to default
      device.set(['geolocation'], DEFAULT_GEOLOCATION_CONFIG)

      // retry 3 times, but don't await, proceed with default
      networkRetry(3, () => getGeolocationConfig(GEOLOCATION_CONFIG_URL))
        .then(config => {
          if (config) {
            device.set(['geolocation'], config)
            emitGeolocationConfigUpdate(config)
            success = true
          } else {
            // endpoint should throw on all failures, this is insurance
            throw new Error(`geolocation config: nothing returned from retries`)
          }
        })
        .catch((e: any) => {
          // complete fail closed
          logger.debug(`geolocation config: failed retries`, {
            safeMessage: e.message,
          })
        })
    } finally {
      resolve({success})
    }
  })
}

/**
 * Ensure that geolocation config has been resolved, or at the very least attempted
 * once. Subsequent retries will not be captured by this `await`. Those will be
 * reported via {@link emitGeolocationConfigUpdate}.
 */
export async function ensureGeolocationConfigIsResolved() {
  if (!geolocationConfigResolution) {
    throw new Error(
      `geolocation config: beginResolveGeolocationConfig not called yet`,
    )
  }

  const cached = device.get(['geolocation'])
  if (cached) {
    logger.debug(`geolocation config: using cache`)
  } else {
    logger.debug(`geolocation config: no cache`)
    const {success} = await geolocationConfigResolution
    if (success) {
      logger.debug(`geolocation config: resolved`)
    } else {
      logger.info(`geolocation config: failed to resolve`)
    }
  }
}