feat(mobile): add ota policy client and debug controls

This commit is contained in:
DIYgod
2026-04-10 20:55:48 +08:00
parent 56b23b55ee
commit d87c91c1d9
4 changed files with 300 additions and 45 deletions
+47
View File
@@ -14,6 +14,8 @@ import { BugCuteReIcon } from "@/src/icons/bug_cute_re"
import { JotaiPersistSyncStorage } from "@/src/lib/jotai"
import { Navigation } from "@/src/lib/navigation/Navigation"
import { setEnvProfile, useEnvProfile } from "@/src/lib/proxy-env"
import { toast } from "@/src/lib/toast"
import { useOtaActions, useOtaState } from "@/src/modules/ota/provider"
import { DebugScreen } from "@/src/screens/(headless)/DebugScreen"
export const DebugButton = () => {
@@ -91,7 +93,32 @@ export const DebugButton = () => {
}
export const EnvProfileIndicator = () => {
const envProfile = useEnvProfile()
const otaState = useOtaState()
const { checkForUpdates, reloadUpdate } = useOtaActions()
if (!__DEV__ && envProfile === "prod") return null
const handleCheckOtaUpdate = async () => {
try {
const result = await checkForUpdates()
if (result.kind === "available") {
toast.success(`OTA update ${result.version} is ready`)
return
}
toast.info("No OTA update available")
} catch (error) {
toast.error(error instanceof Error ? error.message : "Failed to check OTA update")
}
}
const handleReloadOtaUpdate = async () => {
try {
await reloadUpdate()
} catch (error) {
toast.error(error instanceof Error ? error.message : "Failed to reload OTA update")
}
}
return (
<View
className="absolute bottom-0 left-16 items-center justify-center"
@@ -116,6 +143,26 @@ export const EnvProfileIndicator = () => {
</DropdownMenu.Item>
)
})}
<DropdownMenu.Item
key="check-ota-update"
onSelect={() => {
void handleCheckOtaUpdate()
}}
>
<DropdownMenu.ItemTitle>Check OTA Update</DropdownMenu.ItemTitle>
</DropdownMenu.Item>
<DropdownMenu.Item
key="reload-ota-update"
onSelect={() => {
void handleReloadOtaUpdate()
}}
>
<DropdownMenu.ItemTitle>
{otaState.pendingVersion
? `Reload OTA Update (${otaState.pendingVersion})`
: "Reload OTA Update"}
</DropdownMenu.ItemTitle>
</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Root>
</View>
@@ -0,0 +1,53 @@
import { beforeEach, describe, expect, it, vi } from "vitest"
import { fetchStorePolicy } from "../client"
describe("fetchStorePolicy", () => {
beforeEach(() => {
vi.stubGlobal(
"fetch",
vi.fn().mockResolvedValue(
new Response(
JSON.stringify({ action: "block", targetVersion: "0.4.3", message: "Update required" }),
{
status: 200,
headers: { "content-type": "application/json" },
},
),
),
)
})
it("returns the parsed policy response", async () => {
const result = await fetchStorePolicy({
baseUrl: "https://ota.folo.is",
product: "mobile",
channel: "production",
installedBinaryVersion: "0.4.1",
})
expect(result.action).toBe("block")
expect(result.targetVersion).toBe("0.4.3")
})
it("throws when the policy request fails", async () => {
vi.stubGlobal(
"fetch",
vi.fn().mockResolvedValue(
new Response(JSON.stringify({ message: "Internal Server Error" }), {
status: 500,
headers: { "content-type": "application/json" },
}),
),
)
await expect(
fetchStorePolicy({
baseUrl: "https://ota.folo.is",
product: "mobile",
channel: "production",
installedBinaryVersion: "0.4.1",
}),
).rejects.toThrow("Failed to fetch OTA policy")
})
})
+31
View File
@@ -0,0 +1,31 @@
export interface FetchStorePolicyInput {
baseUrl: string
product: string
channel: string
installedBinaryVersion: string
}
export interface StorePolicyResponse {
action: string
targetVersion?: string | null
message?: string | null
}
export const fetchStorePolicy = async ({
baseUrl,
product,
channel,
installedBinaryVersion,
}: FetchStorePolicyInput): Promise<StorePolicyResponse> => {
const requestUrl = new URL("/policy", baseUrl)
requestUrl.searchParams.set("product", product)
requestUrl.searchParams.set("channel", channel)
requestUrl.searchParams.set("installedBinaryVersion", installedBinaryVersion)
const response = await fetch(requestUrl.toString())
if (!response.ok) {
throw new Error(`Failed to fetch OTA policy (${response.status})`)
}
return (await response.json()) as StorePolicyResponse
}
+169 -45
View File
@@ -1,13 +1,29 @@
import { nativeApplicationVersion } from "expo-application"
import type { Manifest } from "expo-updates"
import * as Updates from "expo-updates"
import type { PropsWithChildren } from "react"
import type { ActionDispatch, PropsWithChildren } from "react"
import { createContext, use, useEffect, useMemo, useReducer } from "react"
import { InteractionManager } from "react-native"
import { fetchStorePolicy } from "./client"
import { initialOtaState, reduceOtaState } from "./store"
import type { OtaState } from "./types"
import type { OtaAction, OtaState } from "./types"
const OtaContext = createContext<OtaState>(initialOtaState)
const OtaBaseUrl = "https://ota.folo.is"
const OtaProduct = "mobile"
export type OtaCheckForUpdatesResult = { kind: "available"; version: string } | { kind: "idle" }
interface OtaActions {
checkForUpdates: () => Promise<OtaCheckForUpdatesResult>
reloadUpdate: () => Promise<void>
}
const OtaActionsContext = createContext<OtaActions>({
checkForUpdates: async () => ({ kind: "idle" }),
reloadUpdate: async () => {},
})
const resolvePendingVersion = (manifest: Manifest | undefined): string => {
if (!manifest) {
@@ -30,6 +46,112 @@ const resolvePendingVersion = (manifest: Manifest | undefined): string => {
return Updates.runtimeVersion ?? "unknown"
}
const getOtaChannel = () => Updates.channel ?? "default"
const getInstalledBinaryVersion = () =>
nativeApplicationVersion ?? Updates.runtimeVersion ?? "unknown"
const getErrorMessage = (error: unknown, fallback: string) => {
return error instanceof Error ? error.message : fallback
}
const refreshStorePolicy = async () => {
try {
return await fetchStorePolicy({
baseUrl: OtaBaseUrl,
product: OtaProduct,
channel: getOtaChannel(),
installedBinaryVersion: getInstalledBinaryVersion(),
})
} catch (error) {
console.warn("[ota] Failed to fetch store policy", error)
return null
}
}
const runOtaCheck = async ({
dispatch,
currentPendingVersion,
isUpdatePending,
shouldCancel = () => false,
}: {
dispatch: ActionDispatch<[action: OtaAction]>
currentPendingVersion: string | null
isUpdatePending: boolean
shouldCancel?: () => boolean
}): Promise<OtaCheckForUpdatesResult> => {
const dispatchIfActive = (action: OtaAction) => {
if (!shouldCancel()) {
dispatch(action)
}
}
const policyPromise = refreshStorePolicy()
try {
if (currentPendingVersion) {
await policyPromise
if (shouldCancel()) {
return { kind: "idle" }
}
dispatchIfActive({
type: "downloaded",
version: currentPendingVersion,
})
return { kind: "available", version: currentPendingVersion }
}
dispatchIfActive({ type: "checking" })
const checkResult = await Updates.checkForUpdateAsync()
if (shouldCancel()) {
return { kind: "idle" }
}
if (!checkResult.isAvailable) {
await policyPromise
if (!isUpdatePending) {
dispatchIfActive({ type: "reset" })
}
return { kind: "idle" }
}
dispatchIfActive({ type: "downloading" })
const fetchResult = await Updates.fetchUpdateAsync()
if (shouldCancel()) {
return { kind: "idle" }
}
await policyPromise
if (fetchResult.isNew && fetchResult.manifest) {
const version = resolvePendingVersion(fetchResult.manifest)
dispatchIfActive({
type: "downloaded",
version,
})
return { kind: "available", version }
}
if (!isUpdatePending) {
dispatchIfActive({ type: "reset" })
}
return { kind: "idle" }
} catch (error) {
await policyPromise
dispatchIfActive({
type: "failed",
message: getErrorMessage(error, "Failed to check for updates."),
})
throw error instanceof Error ? error : new Error("Failed to check for updates.")
}
}
export const OtaProvider = ({ children }: PropsWithChildren) => {
const { checkError, downloadError, downloadedUpdate, isUpdatePending } = Updates.useUpdates()
const [state, dispatch] = useReducer(reduceOtaState, initialOtaState)
@@ -42,6 +164,8 @@ export const OtaProvider = ({ children }: PropsWithChildren) => {
return resolvePendingVersion(downloadedUpdate.manifest)
}, [downloadedUpdate, isUpdatePending])
const currentPendingVersion = nativePendingVersion ?? state.pendingVersion
useEffect(() => {
if (!nativePendingVersion) {
return
@@ -74,46 +198,14 @@ export const OtaProvider = ({ children }: PropsWithChildren) => {
const runBackgroundCheck = async () => {
try {
dispatch({ type: "checking" })
const checkResult = await Updates.checkForUpdateAsync()
if (isCancelled) {
return
}
if (!checkResult.isAvailable) {
if (!isUpdatePending) {
dispatch({ type: "reset" })
}
return
}
dispatch({ type: "downloading" })
const fetchResult = await Updates.fetchUpdateAsync()
if (isCancelled) {
return
}
if (fetchResult.isNew && fetchResult.manifest) {
dispatch({
type: "downloaded",
version: resolvePendingVersion(fetchResult.manifest),
})
return
}
if (!isUpdatePending) {
dispatch({ type: "reset" })
}
} catch (error) {
if (isCancelled) {
return
}
dispatch({
type: "failed",
message: error instanceof Error ? error.message : "Failed to check for updates.",
await runOtaCheck({
dispatch,
currentPendingVersion: nativePendingVersion,
isUpdatePending,
shouldCancel: () => isCancelled,
})
} catch {
// runOtaCheck already syncs OTA failures into state.
}
}
@@ -127,19 +219,51 @@ export const OtaProvider = ({ children }: PropsWithChildren) => {
}
}, [isUpdatePending, nativePendingVersion])
const actions = useMemo<OtaActions>(() => {
return {
checkForUpdates: async () => {
if (!Updates.isEnabled) {
throw new Error("OTA updates are not enabled.")
}
return runOtaCheck({
dispatch,
currentPendingVersion,
isUpdatePending,
})
},
reloadUpdate: async () => {
if (!Updates.isEnabled) {
throw new Error("OTA updates are not enabled.")
}
if (!currentPendingVersion) {
throw new Error("No OTA update is ready to reload.")
}
await Updates.reloadAsync()
},
}
}, [currentPendingVersion, isUpdatePending])
const value = useMemo(() => {
if (!nativePendingVersion) {
if (!currentPendingVersion) {
return state
}
return {
status: "ready" as const,
pendingVersion: nativePendingVersion,
pendingVersion: currentPendingVersion,
errorMessage: null,
}
}, [nativePendingVersion, state])
}, [currentPendingVersion, state])
return <OtaContext value={value}>{children}</OtaContext>
return (
<OtaActionsContext value={actions}>
<OtaContext value={value}>{children}</OtaContext>
</OtaActionsContext>
)
}
export const useOtaState = () => use(OtaContext)
export const useOtaActions = () => use(OtaActionsContext)