useOfflineBookingCachePolling.js 8.99 KB
import Taro from '@tarojs/taro'
import { refresh_offline_booking_cache } from '@/composables/useOfflineBookingCache'
import { get_network_type, is_usable_network } from '@/utils/network'

/**
 * @description: 轮询状态
 * @property {Number} timer_id 轮询定时器id
 * @property {Boolean} running 是否正在轮询
 * @property {Boolean} in_flight 是否正在刷新
 * @property {Number} ref_count 引用计数
 * @property {Boolean} app_enabled 是否启用应用
 * @property {Object} last_options 最后一次选项
 * @property {Boolean} network_usable 网络可用性
 * @property {Boolean} has_network_listener 是否已注册网络监听器
 * @property {Function} network_listener 网络监听器
 * @property {Promise} network_listener_promise 网络监听器Promise
 */

const polling_state = {
    timer_id: null, // 轮询定时器id
    running: false, // 是否正在轮询
    in_flight: false, // 是否正在刷新
    ref_count: 0, // 引用计数
    app_enabled: false, // 是否启用应用
    last_options: null, // 最后一次选项
    network_usable: null, // 网络可用性
    has_network_listener: false, // 是否已注册网络监听器
    network_listener: null, // 网络监听器
    network_listener_promise: null, // 网络监听器Promise
}

/**
 * @description: 缓存最后一次 options(用于网络恢复时重启轮询)
 * @param {Object} options 选项
 * @return {Object} 最后一次选项
 */

const normalize_options = (options) => {
    polling_state.last_options = options || polling_state.last_options || {}
    return polling_state.last_options
}

/**
 * @description: 刷新离线预约缓存一次
 * @param {Object} options 选项
 * @param {Boolean} options.force 是否强制刷新
 */

const run_refresh_once = async (options) => {
    if (polling_state.in_flight) return // 核心防重复——如果正在刷新,直接返回
    // 标记为“正在刷新”
    polling_state.in_flight = true
    try {
        await refresh_offline_booking_cache({ force: !!options?.force })
    } finally {
        // 刷新完成后,标记为“刷新完成”
        polling_state.in_flight = false
    }
}

/**
 * @description: 更新网络可用性
 */

const update_network_usable = async () => {
    const type = await get_network_type()
    polling_state.network_usable = is_usable_network(type)
}

/**
 * @description: 判断是否需要运行轮询
 * @return {Boolean} 是否需要运行轮询
 */

const should_run_polling = () => {
    if (polling_state.ref_count <= 0) return false
    if (polling_state.network_usable === false) return false
    if (polling_state.network_usable === null) return false
    return true
}

/**
 * @description: 确保网络监听器已注册
 * @return {Promise} 网络监听器Promise
 */

const ensure_network_listener = async () => {
    /**
     * 代码优先通过两个条件判断避免重复执行监听器逻辑
     * 1. 有已注册的监听器直接返回
     * 2. 有未完成的注册 Promise 则直接返回
     */

    if (polling_state.has_network_listener) {
        await update_network_usable()
        return
    }

    if (polling_state.network_listener_promise) {
        await polling_state.network_listener_promise
        return
    }

    // 立即执行异步的监听器注册流程(标记状态→更新网络可用性→定义回调→注册监听)
    polling_state.network_listener_promise = (async () => {
        // 标记已注册网络监听器
        polling_state.has_network_listener = true
        // 初始化时更新网络可用性
        await update_network_usable()

        // 网络状态变化监听器, 网络状态变化时的处理逻辑,此时只是定义,不会立即执行
        polling_state.network_listener = (res) => {
            const is_connected = res?.isConnected !== false
            const type = res?.networkType || 'unknown'
            polling_state.network_usable = is_connected && is_usable_network(type)

            // 网络不可用时,停止轮询
            if (!polling_state.network_usable) {
                stop_offline_booking_cache_polling()
                return
            }

            if (should_run_polling()) {
                start_offline_booking_cache_polling(polling_state.last_options || {})
            }
        }

        try {
            // 注册网络状态变化监听器
            Taro.onNetworkStatusChange(polling_state.network_listener)
        } catch (e) {
            polling_state.has_network_listener = false
            polling_state.network_listener = null
            polling_state.network_usable = null
            console.error('注册网络监听失败:', e)
        }
    })()

    try {
        // 等待网络监听器初始化完成, Taro.onNetworkStatusChange
        await polling_state.network_listener_promise
    } finally {
        // 等待注册流程完成后,强制清空 Promise 缓存(finally 块),保证下次执行逻辑时状态干净。
        polling_state.network_listener_promise = null
    }
}

/**
 * @description: 注销网络监听器
 */

const teardown_network_listener = () => {
    if (!polling_state.has_network_listener) return
    if (polling_state.ref_count > 0) return
    polling_state.has_network_listener = false
    if (polling_state.network_listener && typeof Taro.offNetworkStatusChange === 'function') {
        try {
            Taro.offNetworkStatusChange(polling_state.network_listener)
        } catch (e) {
            polling_state.network_listener = null
        }
    }
    polling_state.network_listener = null
    polling_state.network_usable = null
}

/**
 * @description: 启动离线预约缓存轮询
 * @param {Object} options 选项
 * @param {Number} options.interval_ms 轮询间隔,单位毫秒
 * @param {Boolean} options.immediate 是否立即刷新一次
 * @param {Boolean} options.force 是否强制刷新(透传给 refresh_offline_booking_cache)
 */

const start_offline_booking_cache_polling = (options) => {
    normalize_options(options)
    if (!should_run_polling()) return // 不满足轮询条件直接返回
    const interval_ms = Number(options?.interval_ms || 60000)
    if (polling_state.running) return // 核心防重复——如果已经在轮询,直接返回

    polling_state.running = true // 标记为“正在轮询”

    // 立即刷新一次,确保轮询开始时数据是最新的
    if (options?.immediate !== false) {
        run_refresh_once(options)
    }

    // 启动轮询定时器,按照指定间隔执行刷新操作
    polling_state.timer_id = setInterval(() => {
        run_refresh_once(options)
    }, interval_ms)
}

/**
 * @description: 停止离线预约缓存轮询
 */

const stop_offline_booking_cache_polling = () => {
    if (polling_state.timer_id) {
        clearInterval(polling_state.timer_id)
        polling_state.timer_id = null
    }
    polling_state.running = false
}

/**
 * 引用计数的核心作用
 * 这两个函数实现了轮询功能的 “引用计数式资源管理”,本质是追踪有多少 “使用者 / 场景” 依赖这个轮询功能,从而决定是否启动 / 维持 / 停止轮询、注册 / 注销网络监听器,
 * 核心目的是:
 * - 避免轮询被重复启动、错误停止
 * - 防止无使用者时仍占用资源(定时器、网络监听器)
 * - 保证多场景共用轮询时的逻辑一致性
 */

/**
 * @description: 增加轮询引用计数
 * 核心动作:将全局的 ref_count 加 1,代表 “又多了一个场景需要使用轮询功能”。
 * @param {Object} options 选项
 */

const acquire_polling_ref = (options) => {
    normalize_options(options)
    polling_state.ref_count += 1
    // 增加引用计数后,确保网络监听器已注册并初始化完成,然后启动轮询
    ensure_network_listener().then(() => start_offline_booking_cache_polling(polling_state.last_options || {}))
}

/**
 * @description: 减少轮询引用计数
 * 核心动作:将 ref_count 减 1(且保证不会为负数),代表 “有一个场景不再需要轮询功能”。
 */

const release_polling_ref = () => {
    polling_state.ref_count = Math.max(0, polling_state.ref_count - 1)
    if (polling_state.ref_count === 0) {
        // 引用计数降为0时,停止轮询并注销网络监听器
        stop_offline_booking_cache_polling()
        teardown_network_listener()
    }
}

/**
 * @description: 启用离线预约缓存轮询
 * @param {Object} options 选项
 */

export const enable_offline_booking_cache_polling = (options) => {
    normalize_options(options)
    // 核心防重复——如果已经启用,直接返回
    if (polling_state.app_enabled) {
        ensure_network_listener().then(() => start_offline_booking_cache_polling(polling_state.last_options || {}))
        return
    }
    polling_state.app_enabled = true
    acquire_polling_ref(polling_state.last_options || {})
}

/**
 * @description: 禁用离线预约缓存轮询
 */

export const disable_offline_booking_cache_polling = () => {
    if (!polling_state.app_enabled) return
    polling_state.app_enabled = false
    release_polling_ref()
}