修订 chrome.alarms 相关代码 #843
Draft
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
修订
chrome.alarms相关代码类型:重构 / 行为修正
影响范围:Service Worker 定时任务(周期性 alarm 的创建、触发与补偿)
close #840
背景与目标
chrome.alarms使用相关的若干不一致与边界状况,确保周期任务能够稳定创建、按时触发、异常可补偿。主要改动
周期性 Alarm 的幂等创建
新增/完善
mightCreatePeriodicAlarm:get()产生的runtime.lastError不阻断创建流程;create()的lastError仅记录但不抛错(保持 resolve)。触发回调与补偿机制
新增/完善回调注册与监听:
setPeriodicAlarmCallback、monitorPeriodicAlarm。触发参数包含:
alarm:原始 alarm 对象;triggeredAt:实际执行时间戳;isFlushed:是否补偿执行(当scheduledTime与当前时间相差 ≥ ~65 秒视为补偿)。在回调前后通过
chrome.storage.local维护AlarmPending:<name>记录,以支持 SW 重启后的补偿扫描:同一进程内
monitorPeriodicAlarm()只能启动一次,重复调用将抛错。当触发阶段出现
runtime.lastError(框架层错误)时,本次事件将被忽略:既不调用回调,也不写入/清理 pending。单元测试(Vitest)
为上述关键路径补齐系统性测试,包括:
lastError分支(get()与create());runtime.lastError的忽略策略。测试说明
chromeMock(alarms/storage.local/runtime.lastError)精准注入与断言副作用。兼容性与风险评估
lastError的读取与处理更保守,降低偶发 API 异常带来的连锁失败;monitorPeriodicAlarm()设计为单例监控,若有特殊架构(多入口重复初始化)需留意只初始化一次。关联问题
变更文件(节选)
src/app/service/service_worker/alarm.ts(核心逻辑)src/app/service/service_worker/alarm.test.ts(单测,376+ 行)index.ts、script.ts、subscribe.ts、synchronize.ts与入口src/service_worker.ts。统计