diff --git a/packages/message/errors.ts b/packages/message/errors.ts new file mode 100644 index 000000000..fde2f7975 --- /dev/null +++ b/packages/message/errors.ts @@ -0,0 +1,7 @@ +/** Transport failure: a request may have executed although its response was lost. */ +export class MessageResponseLostError extends Error { + constructor(message: string) { + super(message); + this.name = "MessageResponseLostError"; + } +} diff --git a/packages/message/extension_message.ts b/packages/message/extension_message.ts index e0702c98f..660134ce5 100644 --- a/packages/message/extension_message.ts +++ b/packages/message/extension_message.ts @@ -1,6 +1,7 @@ import EventEmitter from "eventemitter3"; import type { Message, MessageConnect, MessageSend, RuntimeMessageSender, TMessage, TMessageCommAction } from "./types"; import { uuidv4 } from "@App/pkg/utils/uuid"; +import { MessageResponseLostError } from "./errors"; const listenerMgr = new EventEmitter(); // 单一管理器 @@ -17,15 +18,14 @@ export class ExtensionMessage implements Message { // 发送消息 注意不进行回调的内存泄漏 sendMessage(data: TMessage): Promise { - return new Promise((resolve: ((value: T) => void) | null) => { + return new Promise((resolve, reject) => { chrome.runtime.sendMessage(data, (resp: T) => { const lastError = chrome.runtime.lastError; if (lastError) { - console.error("chrome.runtime.lastError in chrome.runtime.sendMessage:", lastError); - // 通信API出错不回继续对话 + reject(new MessageResponseLostError(lastError.message || "Extension message delivery failed")); + return; } - resolve!(resp); - resolve = null; + resolve(resp); }); }); } diff --git a/packages/message/extension_message_receipt.test.ts b/packages/message/extension_message_receipt.test.ts new file mode 100644 index 000000000..771399ec8 --- /dev/null +++ b/packages/message/extension_message_receipt.test.ts @@ -0,0 +1,31 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { ExtensionMessage } from "./extension_message"; + +describe("ExtensionMessage RPC response", () => { + afterEach(() => vi.unstubAllGlobals()); + + it("lastError rejects instead of resolving an absent response", async () => { + const runtime = { + lastError: { message: "Extension context invalidated" }, + sendMessage: vi.fn((_request: unknown, callback: (response: unknown) => void) => callback(undefined)), + }; + vi.stubGlobal("chrome", { runtime }); + await expect(new ExtensionMessage().sendMessage({ action: "test" })).rejects.toThrow( + "Extension context invalidated" + ); + }); + + it("successful void payload remains a valid transport response", async () => { + const runtime = { + lastError: undefined, + sendMessage: vi.fn((_request: unknown, callback: (response: unknown) => void) => + callback({ code: 0, data: undefined }) + ), + }; + vi.stubGlobal("chrome", { runtime }); + await expect(new ExtensionMessage().sendMessage({ action: "test" })).resolves.toEqual({ + code: 0, + data: undefined, + }); + }); +}); diff --git a/src/app/logger/message_writer.test.ts b/src/app/logger/message_writer.test.ts index 507ad165f..bcd6c038e 100644 --- a/src/app/logger/message_writer.test.ts +++ b/src/app/logger/message_writer.test.ts @@ -5,6 +5,14 @@ import { SenderRuntime, Server } from "@Packages/message/server"; import MessageWriter from "./message_writer"; describe("MessageWriter 页面日志路由", () => { + it("已失效 context 导致日志发送失败时不能产生未处理 rejection", async () => { + const sender = { sendMessage: vi.fn().mockRejectedValue(new Error("Extension context invalidated")) }; + const writer = MessageWriter.serviceWorker(sender as unknown as import("@Packages/message/types").MessageSend); + expect(() => writer.write("error", "closed", { env: "test" })).not.toThrow(); + await Promise.resolve(); + expect(sender.sendMessage).toHaveBeenCalledOnce(); + }); + it("页面调用方应将日志发送到 service worker 的 logger 处理器", () => { const message = new MockMessage(new EventEmitter()); const handler = vi.fn(); diff --git a/src/app/logger/message_writer.ts b/src/app/logger/message_writer.ts index e39bcf289..ae1e2af00 100644 --- a/src/app/logger/message_writer.ts +++ b/src/app/logger/message_writer.ts @@ -15,7 +15,8 @@ export default class MessageWriter implements Writer { } write(level: LogLevel, message: string, label: LogLabel): void { - this.msgSender.sendMessage({ + // Logging is best-effort. Never recurse into the logger on transport failure. + void this.msgSender.sendMessage({ action: this.action, data: { id: 0, @@ -24,6 +25,6 @@ export default class MessageWriter implements Writer { label, createtime: Date.now(), }, - }); + }).catch(() => undefined); } } diff --git a/src/app/repo/scripts.ts b/src/app/repo/scripts.ts index 301ba7304..d477e71cb 100644 --- a/src/app/repo/scripts.ts +++ b/src/app/repo/scripts.ts @@ -105,6 +105,8 @@ export type PageScriptResource = Record { diff --git a/src/app/service/content/exec_script.ts b/src/app/service/content/exec_script.ts index ae8ee47c7..887f7ae70 100644 --- a/src/app/service/content/exec_script.ts +++ b/src/app/service/content/exec_script.ts @@ -4,7 +4,7 @@ import { createContext, createProxyContext } from "./create_context"; import type { GMInfoEnv, ScriptFunc } from "./types"; import { compileScript, isContextMenuScript } from "./utils"; import type { Message } from "@Packages/message/types"; -import type { ValueUpdateDataEncoded } from "./types"; +import type { ValueSnapshot, ValueUpdateDataEncoded } from "./types"; import { evaluateGMInfo } from "./gm_api/gm_info"; import type { IGM_Base } from "./gm_api/gm_api"; import type { TScriptInfo } from "@App/app/repo/scripts"; @@ -74,8 +74,12 @@ export default class ExecScript { this.sandboxContext?.emitEvent(event, eventId, data); } - valueUpdate(data: ValueUpdateDataEncoded) { - this.sandboxContext?.valueUpdate(data); + valueUpdate(data: ValueUpdateDataEncoded): void | Promise { + return this.sandboxContext?.valueUpdate(data); + } + + valueSnapshot(snapshot: ValueSnapshot) { + this.sandboxContext?.valueSnapshot(snapshot); } execContext: any; diff --git a/src/app/service/content/gm_api/gm_api.test.ts b/src/app/service/content/gm_api/gm_api.test.ts index d09336d0a..889af65b9 100644 --- a/src/app/service/content/gm_api/gm_api.test.ts +++ b/src/app/service/content/gm_api/gm_api.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from "vitest"; import ExecScript from "../exec_script"; import type { ScriptLoadInfo } from "@App/app/service/service_worker/types"; -import type { GMInfoEnv, ScriptFunc } from "../types"; +import type { GMInfoEnv, ScriptFunc, ValueUpdateDataEncoded } from "../types"; import { compileScript, compileScriptCode } from "../utils"; import type { Message } from "@Packages/message/types"; import { encodeRValue } from "@App/pkg/utils/message_value"; @@ -58,7 +58,7 @@ describe("GM Resource API", () => { resource: { [name]: makeResource("https://example.com/data.txt", "declared resource", "resource") }, }, } as unknown as ScriptRunResource; - const api = new GMApi("test", {} as Message, {} as Message, script); + const api = new GMApi("test", {} as Message, {} as Message, script as unknown as ScriptRunResource); expect(api.GM_getResourceText(name)).toBe("declared resource"); expect(api.GM_getResourceURL(name)).toContain("ZGVjbGFyZWQgcmVzb3VyY2U="); @@ -591,6 +591,29 @@ describe.concurrent("GM_menu", () => { }); }); +// A value write has a committed RPC receipt, even when its Port notification is absent. +// Use realistic acknowledgements so the tests observe only the intended GM operations. +const createCommittedValueSender = () => + vi.fn().mockImplementation(async (message: { data: { + api: string; + params: unknown[]; + uuid: string; + runFlag: string; + } }) => ({ + code: 0, + data: { + committed: true, + update: { + id: message.data.params[0], + uuid: message.data.uuid, + storageName: message.data.uuid, + entries: [], + sender: { runFlag: message.data.runFlag }, + valueUpdated: false, + }, + }, + })); + describe.concurrent("GM_value", () => { it.concurrent("GM_setValue", async () => { const script = Object.assign({}, scriptRes) as ScriptLoadInfo; @@ -608,7 +631,7 @@ describe.concurrent("GM_value", () => { let ret4 = GM_getValue("window"); return {ret1, ret2, ret3, ret4}; `; - const mockSendMessage = vi.fn().mockResolvedValue({ code: 0 }); + const mockSendMessage = createCommittedValueSender(); const mockMessage = { sendMessage: mockSendMessage, } as unknown as Message; @@ -743,7 +766,7 @@ const value6 = GM_getValue("abc"); return { value1, value2, value3, values1,values2, allValues1, allValues2, value4, value5, value6 }; `; - const mockSendMessage = vi.fn().mockResolvedValue({ code: 0 }); + const mockSendMessage = createCommittedValueSender(); const mockMessage = { sendMessage: mockSendMessage, } as unknown as Message; @@ -863,7 +886,7 @@ return { value1, value2, value3, values1,values2, allValues1, allValues2, value4 let ret4 = GM_getValues(["window"]); return {ret1, ret2, ret3, ret4}; `; - const mockSendMessage = vi.fn().mockResolvedValue({ code: 0 }); + const mockSendMessage = createCommittedValueSender(); const mockMessage = { sendMessage: mockSendMessage, } as unknown as Message; @@ -991,7 +1014,7 @@ return { value1, value2, value3, values1,values2, allValues1, allValues2, value4 let ret2 = GM_getValues(["a","b","c"]); return {ret1, ret2}; `; - const mockSendMessage = vi.fn().mockResolvedValue({ code: 0 }); + const mockSendMessage = createCommittedValueSender(); const mockMessage = { sendMessage: mockSendMessage, } as unknown as Message; @@ -1065,7 +1088,7 @@ return { value1, value2, value3, values1,values2, allValues1, allValues2, value4 let ret2 = GM_getValues(["a","b","c"]); return {ret1, ret2}; `; - const mockSendMessage = vi.fn().mockResolvedValue({ code: 0 }); + const mockSendMessage = createCommittedValueSender(); const mockMessage = { sendMessage: mockSendMessage, } as unknown as Message; @@ -1146,7 +1169,7 @@ return { value1, value2, value3, values1,values2, allValues1, allValues2, value4 GM_setValue("param1", 123); }); `; - const mockSendMessage = vi.fn().mockResolvedValue({ code: 0 }); + const mockSendMessage = createCommittedValueSender(); const mockMessage = { sendMessage: mockSendMessage, } as unknown as Message; @@ -1185,7 +1208,7 @@ return { value1, value2, value3, values1,values2, allValues1, allValues2, value4 GM_setValue("param2", 456); }); `; - const mockSendMessage = vi.fn().mockResolvedValue({ code: 0 }); + const mockSendMessage = createCommittedValueSender(); const mockMessage = { sendMessage: mockSendMessage, } as unknown as Message; @@ -1212,46 +1235,275 @@ return { value1, value2, value3, values1,values2, allValues1, allValues2, value4 const ret2 = await retPromise; expect(ret2).toEqual({ name: "param2", oldValue: undefined, newValue: 456, remote: true }); }); - it.concurrent("异步GM.setValue,等待回调", async () => { - const script = Object.assign({}, scriptRes) as ScriptLoadInfo; - script.metadata.grant = ["GM.getValue", "GM.setValue"]; - script.code = `await GM.setValue("a", 123); return await GM.getValue("a");`; - const mockSendMessage = vi.fn().mockResolvedValue({ code: 0 }); - const mockMessage = { - sendMessage: mockSendMessage, - } as unknown as Message; - const exec = new ExecScript(script, { - envPrefix: "scripting", - message: mockMessage, - contentMsg: undefined as any, - code: nilFn, - envInfo, + it("异步 GM.setValue 以持久化回执结算,即使 Port 通知未抵达", async () => { + const script = { ...scriptRes, uuid: uuidv4(), value: {}, metadata: { grant: ["GM.setValue"] } } as ScriptLoadInfo; + const updates: ValueUpdateDataEncoded[] = []; + const mockSendMessage = vi.fn().mockImplementation(async (request) => { + const update: ValueUpdateDataEncoded = { + id: request.data.params[0], + entries: [["a", encodeRValue(123), encodeRValue(undefined)]], + uuid: script.uuid, + storageName: script.uuid, + sender: { runFlag: "writer", tabId: 1 }, + valueUpdated: true, + }; + updates.push(update); + return { code: 0, data: { committed: true, update } }; }); - exec.scriptFunc = compileScript(compileScriptCode(script)); - const retPromise = exec.exec(); - - await Promise.resolve(); // 等待一轮微任务,让GM.setValue执行 - - expect(mockSendMessage).toHaveBeenCalled(); - expect(mockSendMessage).toHaveBeenCalledTimes(1); - // 获取调用参数 - const actualCall = mockSendMessage.mock.calls[0][0]; - const id = actualCall.data.params[0]; + const api = new GMApi( + "scripting", + { sendMessage: mockSendMessage } as unknown as Message, + {} as Message, + script as unknown as ScriptRunResource + ); + Object.assign(api, { runFlag: "writer" }); + const listener = vi.fn(); + api.GM_addValueChangeListener("a", listener); + + await expect(api["GM.setValue"]("a", 123)).resolves.toBeUndefined(); + expect(listener).toHaveBeenCalledExactlyOnceWith("a", undefined, 123, false, 1); + api.valueUpdate(updates[0]); // Delayed delivery over the Port must not notify twice. + expect(listener).toHaveBeenCalledTimes(1); + }); - expect(id).toBeTypeOf("string"); - expect(id.length).greaterThan(0); - // 触发valueUpdate - exec.valueUpdate({ - id: id, - entries: [["a", encodeRValue(123), encodeRValue(undefined)]], + it("先到达 Port 通知、后到达写入回执时仍只触发一次 listener", async () => { + const script = { ...scriptRes, uuid: uuidv4(), value: {}, metadata: { grant: ["GM.setValue"] } } as ScriptLoadInfo; + let complete!: (value: unknown) => void; + const mockSendMessage = vi.fn().mockImplementation( + () => new Promise((resolve) => { complete = resolve; }) + ); + const api = new GMApi( + "scripting", + { sendMessage: mockSendMessage } as unknown as Message, + {} as Message, + script as unknown as ScriptRunResource + ); + Object.assign(api, { runFlag: "writer" }); + const listener = vi.fn(); + api.GM_addValueChangeListener("a", listener); + const pending = api["GM.setValue"]("a", 2); + await vi.waitFor(() => expect(mockSendMessage).toHaveBeenCalledOnce()); + const update: ValueUpdateDataEncoded = { + id: mockSendMessage.mock.calls[0][0].data.params[0], + entries: [["a", encodeRValue(2), encodeRValue(undefined)]], uuid: script.uuid, storageName: script.uuid, - sender: { runFlag: exec.sandboxContext!.runFlag, tabId: -2 }, + sender: { runFlag: "writer", tabId: 1 }, valueUpdated: true, + }; + api.valueUpdate(update); + complete({ code: 0, data: { committed: true, update } }); + await expect(pending).resolves.toBeUndefined(); + expect(listener).toHaveBeenCalledOnce(); + }); + + it("缺失或虚假的写入回执不能视为持久化成功", async () => { + const script = { + ...scriptRes, uuid: uuidv4(), value: {}, metadata: { grant: ["GM.setValue", "GM.setValues"] }, + } as ScriptLoadInfo; + const mockSendMessage = vi.fn().mockResolvedValue({ code: 0, data: undefined }); + const api = new GMApi( + "scripting", + { sendMessage: mockSendMessage } as unknown as Message, + {} as Message, + script as unknown as ScriptRunResource + ); + await expect(api["GM.setValue"]("x", 1)).rejects.toThrow("acknowledgement missing"); + await expect(api["GM.setValues"]({ x: 2 })).rejects.toThrow("acknowledgement missing"); + const actions = mockSendMessage.mock.calls.map(([message]) => message.data.api); + expect(actions.filter((action) => action === "GM_setValue" || action === "GM_setValues")).toEqual([ + "GM_setValue", + "GM_setValues", + ]); + }); + + it("同值写入和删除按提交回执结算,只在实际变更时通知", async () => { + const script = { + ...scriptRes, uuid: uuidv4(), value: { a: 1 }, metadata: { grant: ["GM.setValues", "GM.deleteValue"] }, + } as ScriptLoadInfo; + const replies: ValueUpdateDataEncoded[] = []; + const mockSendMessage = vi.fn().mockImplementation(async (request) => { + const params = request.data.params; + const isDelete = request.data.api === "GM_setValue"; + const update: ValueUpdateDataEncoded = { + id: params[0], + entries: isDelete ? [["a", encodeRValue(undefined), encodeRValue(1)]] : [], + uuid: script.uuid, + storageName: script.uuid, + sender: { runFlag: "writer", tabId: 1 }, + valueUpdated: isDelete, + }; + replies.push(update); + return { code: 0, data: { committed: true, update } }; }); + const api = new GMApi( + "scripting", + { sendMessage: mockSendMessage } as unknown as Message, + {} as Message, + script as unknown as ScriptRunResource + ); + Object.assign(api, { runFlag: "writer" }); + const listener = vi.fn(); + api.GM_addValueChangeListener("a", listener); + await api["GM.setValues"]({ a: 1 }); + expect(listener).not.toHaveBeenCalled(); + await api["GM.deleteValue"]("a"); + expect(listener).toHaveBeenCalledExactlyOnceWith("a", 1, undefined, false, 1); + api.valueUpdate(replies[1]); + expect(listener).toHaveBeenCalledTimes(1); + }); - const ret = await retPromise; - expect(ret).toEqual(123); +}); + +describe("GM fire-and-forget logging errors", () => { + it("GM_log catches a lost extension RPC without leaving a rejected promise", async () => { + const script = { ...scriptRes, uuid: uuidv4(), value: {} } as ScriptLoadInfo; + const sender = vi.fn().mockRejectedValue(new Error("Extension context invalidated")); + const api = new GMApi("scripting", { sendMessage: sender } as unknown as Message, {} as Message, script); + expect(() => api.GM_log("test")).not.toThrow(); + await Promise.resolve(); + expect(sender).toHaveBeenCalledOnce(); + }); +}); + +describe("GM value version ordering and reconciliation", () => { + const versioned = (id: string, revision: number, value: number) => ({ + id, + uuid: "ordered-script", + storageName: "ordered-script", + entries: [["x", encodeRValue(value), encodeRValue(revision - 1)]], + sender: { runFlag: "writer", tabId: 1 }, + valueUpdated: true, + revision, + epoch: "epoch-1", + } satisfies ValueUpdateDataEncoded); + + it("B 的提交回执先于 A 到达,cache 不会回退且不会触发逆序事件", async () => { + const script = { + ...scriptRes, uuid: "ordered-script", value: { x: 0 }, valueRevision: 0, valueEpoch: "epoch-1", + } as ScriptLoadInfo; + const writers = new Map void>(); + const transport = vi.fn().mockImplementation((message) => { + if (message.data.api === "GM_valueSnapshot") { + return Promise.resolve({ code: 0, data: { + storageName: script.uuid, revision: 2, epoch: "epoch-1", values: { x: 2 }, + } }); + } + return new Promise((resolve) => writers.set(message.data.params[0], resolve)); + }); + const api = new GMApi("scripting", { sendMessage: transport } as unknown as Message, {} as Message, script); + Object.assign(api, { runFlag: "writer" }); + const listener = vi.fn(); + api.GM_addValueChangeListener("x", listener); + const first = api["GM.setValue"]("x", 1); + const second = api["GM.setValue"]("x", 2); + await vi.waitFor(() => expect(writers.size).toBe(2)); + const [idA, idB] = [...writers.keys()]; + writers.get(idB)?.({ code: 0, data: { committed: true, update: versioned(idB, 2, 2) } }); + await second; + writers.get(idA)?.({ code: 0, data: { committed: true, update: versioned(idA, 1, 1) } }); + await first; + expect(api.GM_getValue("x")).toBe(2); + expect(script.valueRevision).toBe(2); + expect(listener).not.toHaveBeenCalled(); + }); + + it("Port 先送 A,超过 128 条其他事件后才送 ACK(A),不得再次应用 A", async () => { + const script = { + ...scriptRes, uuid: "ordered-script", value: {}, valueRevision: 0, valueEpoch: "epoch-1", + } as ScriptLoadInfo; + let finish!: (response: unknown) => void; + const transport = vi.fn().mockImplementation(() => new Promise((resolve) => { finish = resolve; })); + const api = new GMApi("scripting", { sendMessage: transport } as unknown as Message, {} as Message, script); + Object.assign(api, { runFlag: "writer" }); + const listener = vi.fn(); + api.GM_addValueChangeListener("x", listener); + const pending = api["GM.setValue"]("x", 1); + await vi.waitFor(() => expect(transport).toHaveBeenCalledOnce()); + const id = transport.mock.calls[0][0].data.params[0] as string; + api.valueUpdate(versioned(id, 1, 1)); + for (let revision = 2; revision <= 130; revision++) { + api.valueUpdate(versioned(`other-${revision}`, revision, revision)); + } + finish({ code: 0, data: { committed: true, update: versioned(id, 1, 1) } }); + await pending; + expect(script.valueRevision).toBe(130); + expect(api.GM_getValue("x")).toBe(130); + expect(listener).toHaveBeenCalledTimes(130); + }); + + it("r3 reconcile 尚在飞行时又观察到 r5,必须再读直到 r5", async () => { + const script = { + ...scriptRes, uuid: "ordered-script", value: { x: 1 }, + valueRevision: 1, valueEpoch: "epoch-1", + } as ScriptLoadInfo; + const reads: Array<(response: unknown) => void> = []; + const sender = vi.fn().mockImplementation((message) => { + if (message.data.api !== "GM_valueSnapshot") throw new Error("Unexpected GM API"); + return new Promise((resolve) => reads.push(resolve)); + }); + const api = new GMApi("scripting", { sendMessage: sender } as unknown as Message, {} as Message, script); + const listener = vi.fn(); + api.GM_addValueChangeListener("x", listener); + const first = api.valueUpdate(versioned("gap-r3", 3, 3)); + await vi.waitFor(() => expect(reads).toHaveLength(1)); + const second = api.valueUpdate(versioned("gap-r5", 5, 5)); + reads[0]({ code: 0, data: { + storageName: "ordered-script", revision: 3, epoch: "epoch-1", values: { x: 3 }, + } }); + await vi.waitFor(() => expect(reads).toHaveLength(2)); + reads[1]({ code: 0, data: { + storageName: "ordered-script", revision: 5, epoch: "epoch-1", values: { x: 5 }, + } }); + await Promise.all([first, second]); + expect(sender).toHaveBeenCalledTimes(2); + expect(api.GM_getValue("x")).toBe(5); + expect(script.valueRevision).toBe(5); + expect(listener).not.toHaveBeenCalled(); + }); + + it("远端事件出现 revision 缺口时读取权威 snapshot,不伪造缺失 listener 事件", async () => { + const script = { + ...scriptRes, uuid: "ordered-script", value: { x: 1 }, valueRevision: 1, valueEpoch: "epoch-1", + } as ScriptLoadInfo; + const transport = vi.fn().mockResolvedValue({ code: 0, data: { + storageName: script.uuid, revision: 3, epoch: "epoch-1", values: { x: 3, y: 9 }, + } }); + const api = new GMApi("scripting", { sendMessage: transport } as unknown as Message, {} as Message, script); + const listener = vi.fn(); + api.GM_addValueChangeListener("x", listener); + await api.valueUpdate(versioned("remote-3", 3, 3)); + expect(api.GM_getValue("x")).toBe(3); + expect(api.GM_getValue("y")).toBe(9); + expect(listener).not.toHaveBeenCalled(); + expect(transport.mock.calls[0][0].data.api).toBe("GM_valueSnapshot"); + }); +}); + +describe("GM write acknowledgement timeout", () => { + it("无回执时写入 Promise 有界超时,不在全局 Map 永久悬挂", async () => { + vi.useFakeTimers(); + try { + const script = { + ...scriptRes, + uuid: uuidv4(), + value: {}, + metadata: { grant: ["GM.setValue"] }, + } as ScriptLoadInfo; + const mockSendMessage = vi.fn().mockImplementation(() => new Promise(() => undefined)); + const api = new GMApi( + "scripting", + { sendMessage: mockSendMessage } as unknown as Message, + {} as Message, + script as unknown as ScriptRunResource + ); + const pending = api["GM.setValue"]("x", 1); + const assertion = expect(pending).rejects.toThrow("acknowledgement timed out"); + await vi.advanceTimersByTimeAsync(31000); + await assertion; + } finally { + vi.useRealTimers(); + } }); }); diff --git a/src/app/service/content/gm_api/gm_api.ts b/src/app/service/content/gm_api/gm_api.ts index d9c52c8e4..63f579288 100644 --- a/src/app/service/content/gm_api/gm_api.ts +++ b/src/app/service/content/gm_api/gm_api.ts @@ -16,7 +16,7 @@ import LoggerCore from "@App/app/logger/core"; import EventEmitter from "eventemitter3"; import GMContext from "./gm_context"; import { type ScriptRunResource } from "@App/app/repo/scripts"; -import type { ValueUpdateDataEncoded } from "../types"; +import type { ValueSnapshot, ValueUpdateDataEncoded, ValueVersion, ValueWriteReceipt } from "../types"; import { connect, sendMessage } from "@Packages/message/client"; import { ScriptEnvTag } from "@Packages/message/consts"; import { getStorageName } from "@App/pkg/utils/utils"; @@ -44,7 +44,7 @@ void CATAgentOPFSApi; export interface IGM_Base { sendMessage(api: string, params: any[]): Promise; connect(api: string, params: any[]): Promise; - valueUpdate(data: ValueUpdateDataEncoded): void; + valueUpdate(data: ValueUpdateDataEncoded): void | Promise; emitEvent(event: string, eventId: string, data: any): void; } @@ -59,7 +59,7 @@ let valChangeCounterId = 0; let valChangeRandomId = `${randNum(8e11, 2e12).toString(36)}`; -const valueChangePromiseMap = new Map(); + const execEnvInit = (execEnv: GMApi) => { if (!execEnv.contentEnvKey) { @@ -113,6 +113,16 @@ class GM_Base implements IGM_Base { @GMContext.protected() protected loadScriptPromise: Promise | undefined; + // Bounded per-script deduplication; a write may arrive through the Port before its RPC receipt. + @GMContext.protected() + protected readonly recentValueUpdateIds = new Set(); + + @GMContext.protected() + protected reconcilePromise?: Promise; + + @GMContext.protected() + protected desiredValueVersion?: ValueVersion; + constructor(options: any = null, obj: any = null) { if (obj !== integrity) throw new TypeError("Illegal invocation"); Object.assign(this, options); @@ -132,33 +142,28 @@ class GM_Base implements IGM_Base { // 单次回调使用 @GMContext.protected() public async sendMessage(api: string, params: any[]) { - if (!this.message || !this.scriptRes) return; - if (this.loadScriptPromise) { - await this.loadScriptPromise; - } - let ret; + if (!this.message || !this.scriptRes) throw new Error("Extension context invalidated"); + if (this.loadScriptPromise) await this.loadScriptPromise; + if (!this.message || !this.scriptRes) throw new Error("Extension context invalidated"); try { - ret = await sendMessage(this.message, `${this.prefix}/runtime/gmApi`, { + return await sendMessage(this.message, `${this.prefix}/runtime/gmApi`, { uuid: this.scriptRes.uuid, api, params, runFlag: this.runFlag, } as MessageRequest); } catch (e: any) { - if (`${e?.message || e}`.includes("Extension context invalidated.")) { - this.setInvalidContext(); // 之后不再进行 sendMessage 跟 EE操作 - console.error(e); - } else { - throw e; + if (/Extension context invalidated|Extension context was invalidated/i.test(`${e?.message || e}`)) { + this.setInvalidContext(); } + throw e; } - return ret; } // 长连接使用,connect只用于接受消息,不发送消息 @GMContext.protected() public connect(api: string, params: any[]) { - if (!this.message || !this.scriptRes) return new Promise(() => {}); + if (!this.message || !this.scriptRes) return Promise.reject(new Error("Extension context invalidated")); return connect(this.message, `${this.prefix}/runtime/gmApi`, { uuid: this.scriptRes.uuid, api, @@ -168,35 +173,137 @@ class GM_Base implements IGM_Base { } @GMContext.protected() - public valueUpdate(data: ValueUpdateDataEncoded) { - if (!this.scriptRes || !this.valueChangeListener) return; - const scriptRes = this.scriptRes; - const { id, uuid, entries, storageName, sender, valueUpdated } = data; - if (uuid === scriptRes.uuid || storageName === getStorageName(scriptRes)) { - const valueStore = scriptRes.value; - const remote = sender.runFlag !== this.runFlag; - if (!remote && id) { - const fn = valueChangePromiseMap.get(id); - if (fn) { - valueChangePromiseMap.delete(id); - fn(); + public valueSnapshot(snapshot: ValueSnapshot) { + const script = this.scriptRes; + if (!script || snapshot.storageName !== getStorageName(script)) return; + const epoch = script.valueEpoch ?? ""; + const revision = script.valueRevision ?? 0; + if (snapshot.epoch === epoch && snapshot.revision < revision) return; + // A snapshot replaces state without fabricating intermediate listener events. + const values = { ...snapshot.values }; + const config = script.config; + if (config) { + for (const tabKey of Object.keys(config)) { + const tab = config[tabKey]; + if (!(tab instanceof Object)) continue; + for (const key of Object.keys(tab)) { + const option = tab[key]; + if (!option) continue; + const field = `${tabKey}.${key}`; + if (option.bind) { + const bindKey = option.bind.substring(1); + if (values[bindKey] === undefined) values[bindKey] = undefined; + } + if (values[field] === undefined) values[field] = option.default; } } - if (valueUpdated) { - const valueChanges = entries; - for (const [key, rTyped1, rTyped2] of valueChanges) { - const value = decodeRValue(rTyped1); - const oldValue = decodeRValue(rTyped2); - // 触发,并更新值 - if (value === undefined) { - if (valueStore[key] !== undefined) { - delete valueStore[key]; - } - } else { - valueStore[key] = value; - } - this.valueChangeListener.execute(key, oldValue, value, remote, sender.tabId); + } + script.value = values; + script.valueEpoch = snapshot.epoch; + script.valueRevision = snapshot.revision; + const desired = this.desiredValueVersion; + if (desired?.epoch === snapshot.epoch && snapshot.revision >= desired.revision) { + this.desiredValueVersion = undefined; + } + } + + @GMContext.protected() + protected reconcileValue(): Promise { + if (this.reconcilePromise) return this.reconcilePromise; + const promise = (async () => { + let delay = 100; + // Bounded attempts, bounded wait, and no unbounded history of missed changes. + for (let attempt = 0; attempt < 5; attempt++) { + const current = this.scriptRes; + if (!current || this.isInvalidContext()) throw new Error("Extension context invalidated"); + const requestedEpoch = current.valueEpoch ?? ""; + const requestedRevision = current.valueRevision ?? 0; + let timeout: ReturnType | undefined; + let snapshot: ValueSnapshot; + try { + snapshot = await Promise.race([ + this.sendMessage("GM_valueSnapshot", []), + new Promise((_, reject) => { + timeout = setTimeout(() => reject(new Error("GM snapshot request timed out")), 30000); + }), + ]); + } finally { + if (timeout !== undefined) clearTimeout(timeout); + } + if (!snapshot || typeof snapshot.revision !== "number" || typeof snapshot.epoch !== "string") { + throw new Error("Invalid GM value snapshot"); } + const script = this.scriptRes; + if (!script || this.isInvalidContext()) throw new Error("Extension context invalidated"); + // An older storage generation cannot overwrite a new one applied while the RPC was pending. + if ( + script.valueEpoch === snapshot.epoch || + ((script.valueEpoch ?? "") === requestedEpoch && (script.valueRevision ?? 0) === requestedRevision) + ) { + this.valueSnapshot(snapshot); + } + const desired = this.desiredValueVersion; + if (!desired) return; + if ((script.valueEpoch ?? "") === desired.epoch && (script.valueRevision ?? 0) >= desired.revision) { + this.desiredValueVersion = undefined; + return; + } + if (attempt === 4) break; + await new Promise((resolve) => setTimeout(resolve, delay)); + delay = Math.min(delay * 2, 1600); + } + throw new Error("GM snapshot did not reach observed value revision"); + })().finally(() => { + if (this.reconcilePromise === promise) this.reconcilePromise = undefined; + }); + this.reconcilePromise = promise; + return promise; + } + + @GMContext.protected() + public valueUpdate(data: ValueUpdateDataEncoded): void | Promise { + const script = this.scriptRes; + const listeners = this.valueChangeListener; + if (!script || !listeners || (data.uuid !== script.uuid && data.storageName !== getStorageName(script))) return; + if (data.revision !== undefined && data.epoch !== undefined) { + const revision = script.valueRevision ?? 0; + const epoch = script.valueEpoch ?? ""; + if (data.epoch === epoch && data.revision <= revision) return; + if ((epoch && data.epoch !== epoch) || data.revision > revision + 1) { + // Keep the highest observed revision while an older snapshot RPC is still pending. + const desired = this.desiredValueVersion; + if (!desired || desired.epoch !== data.epoch || data.revision > desired.revision) { + this.desiredValueVersion = { epoch: data.epoch, revision: data.revision }; + } + return this.reconcileValue(); + } + script.valueRevision = data.revision; + script.valueEpoch = data.epoch; + const desired = this.desiredValueVersion; + if (desired?.epoch === data.epoch && data.revision >= desired.revision) { + this.desiredValueVersion = undefined; + } + } + if (data.id) { + if (this.recentValueUpdateIds.has(data.id)) return; + if (this.recentValueUpdateIds.size >= 128) { + const oldest = this.recentValueUpdateIds.values().next().value; + if (oldest !== undefined) this.recentValueUpdateIds.delete(oldest); + } + this.recentValueUpdateIds.add(data.id); + } + if (!data.valueUpdated) return; + const remote = data.sender.runFlag !== this.runFlag; + for (const [key, encoded, oldEncoded] of data.entries) { + const value = decodeRValue(encoded); + const oldValue = decodeRValue(oldEncoded); + if (value === undefined) delete script.value[key]; + else script.value[key] = value; + try { + listeners.execute(key, oldValue, value, remote, data.sender.tabId); + } catch (error) { + // A listener throwing must not prevent the remaining keys from reaching committed state. + console.error("GM value-change listener failed", error); } } } @@ -239,6 +346,7 @@ export default class GMApi extends GM_Base { invalid = true; this.valueChangeListener.clear(); this.EE.removeAllListeners(); + this.recentValueUpdateIds.clear(); // 释放记忆 this.message = null; this.scriptRes = null; @@ -280,93 +388,96 @@ export default class GMApi extends GM_Base { }); } - static _GM_setValue(a: GMApi, promise: any, key: string, value: any) { + // The RPC receipt settles the promise independently of the Port subscription. + // Retain notifications for other frames; process the writer receipt through the same listener path. + static async commitValueWrite(a: GMApi, api: "GM_setValue" | "GM_setValues", id: string, params: unknown[]) { + let timeout: ReturnType | undefined; + try { + const receipt = await Promise.race([ + a.sendMessage(api, params), + new Promise((_, reject) => { + timeout = setTimeout(() => reject(new Error("GM value write acknowledgement timed out")), 30000); + }), + ]) as ValueWriteReceipt | undefined; + if (receipt?.committed !== true || receipt.update?.id !== id) { + throw new Error("GM value write acknowledgement missing or invalid"); + } + // A script's listener may throw after persistence succeeds. Do not turn a committed + // write into a false failure; the listener error is local to that execution context. + try { + const update = a.valueUpdate(receipt.update); + if (update instanceof Promise) { + // The commit is already durable. Do not make its success depend on a + // subsequent snapshot RPC, which may fail during another SW restart. + void update.catch((error) => console.error("GM value reconciliation failed", error)); + } + } catch (error) { + console.error("GM value update listener failed", error); + } + } catch (error) { + // The transport may have lost its reply after the write committed; never retry + // a potentially non-idempotent mutation. Re-read state when the context survives. + if (a.scriptRes && !a.isInvalidContext()) { + void a.reconcileValue().catch(() => undefined); + } + throw error; + } finally { + if (timeout !== undefined) clearTimeout(timeout); + } + } + + static _GM_setValue(a: GMApi, key: string, value: any): Promise { key = `${key}`; - if (!a.scriptRes) return; + if (!a.scriptRes) return Promise.reject(new Error("Extension context invalidated")); if (valChangeCounterId > 1e8) { - // 防止 valChangeCounterId 过大导致无法正常工作 valChangeCounterId = 0; valChangeRandomId = `${randNum(8e11, 2e12).toString(36)}`; } const id = `${valChangeRandomId}::${++valChangeCounterId}`; - if (promise) { - valueChangePromiseMap.set(id, promise); - } - if (value === undefined) { - delete a.scriptRes.value[key]; - a.sendMessage("GM_setValue", [id, key]); - } else { - // 对object的value进行一次转化 - if (value && typeof value === "object") { - value = customClone(value); - } - // customClone 可能返回 undefined - a.scriptRes.value[key] = value; - if (value === undefined) { - a.sendMessage("GM_setValue", [id, key]); - } else { - a.sendMessage("GM_setValue", [id, key, value]); - } - } - return id; + if (value && typeof value === "object") value = customClone(value); + if (value === undefined) delete a.scriptRes.value[key]; + else a.scriptRes.value[key] = value; + const params = value === undefined ? [id, key] : [id, key, value]; + return GMApi.commitValueWrite(a, "GM_setValue", id, params); } - static _GM_setValues(a: GMApi, promise: any, values: TGMKeyValue) { - if (!a.scriptRes) return; + static _GM_setValues(a: GMApi, values: TGMKeyValue): Promise { + if (!a.scriptRes) return Promise.reject(new Error("Extension context invalidated")); if (valChangeCounterId > 1e8) { - // 防止 valChangeCounterId 过大导致无法正常工作 valChangeCounterId = 0; valChangeRandomId = `${randNum(8e11, 2e12).toString(36)}`; } const id = `${valChangeRandomId}::${++valChangeCounterId}`; - if (promise) { - valueChangePromiseMap.set(id, promise); - } const valueStore = a.scriptRes.value; const keyValuePairs = [] as [string, REncoded][]; for (const [key, value] of Object.entries(values)) { let value_ = value; - if (value_ === undefined) { - if (valueStore[key]) delete valueStore[key]; - } else { - // 对object的value进行一次转化 - if (value_ && typeof value_ === "object") { - value_ = customClone(value_); - } - // customClone 可能返回 undefined - valueStore[key] = value_; - } - // 避免undefined 等空值流失,先进行映射处理 + if (value_ && typeof value_ === "object") value_ = customClone(value_); + if (value_ === undefined) delete valueStore[key]; + else valueStore[key] = value_; keyValuePairs.push([key, encodeRValue(value_)]); } - a.sendMessage("GM_setValues", [id, keyValuePairs]); - return id; + return GMApi.commitValueWrite(a, "GM_setValues", id, [id, keyValuePairs]); } @GMContext.API() public GM_setValue(key: string, value: any) { - _GM_setValue(this, null, key, value); + void _GM_setValue(this, key, value).catch(console.error); } @GMContext.API() public "GM.setValue"(key: string, value: any): Promise { - // Asynchronous wrapper for GM_setValue to support GM.setValue - return new Promise((resolve) => { - _GM_setValue(this, resolve, key, value); - }); + return _GM_setValue(this, key, value); } @GMContext.API() public GM_deleteValue(key: string): void { - _GM_setValue(this, null, key, undefined); + void _GM_setValue(this, key, undefined).catch(console.error); } @GMContext.API() public "GM.deleteValue"(key: string): Promise { - // Asynchronous wrapper for GM_deleteValue to support GM.deleteValue - return new Promise((resolve) => { - _GM_setValue(this, resolve, key, undefined); - }); + return _GM_setValue(this, key, undefined); } @GMContext.API() @@ -391,7 +502,7 @@ export default class GMApi extends GM_Base { if (!values || typeof values !== "object") { throw new Error("GM_setValues: values must be an object"); } - _GM_setValues(this, null, values); + void _GM_setValues(this, values).catch(console.error); } @GMContext.API() @@ -430,7 +541,7 @@ export default class GMApi extends GM_Base { // Asynchronous wrapper for GM.getValues @GMContext.API({ depend: ["GM_getValues"] }) public "GM.getValues"(keysOrDefaults: TGMKeyValue | string[] | null | undefined): Promise { - if (!this.scriptRes) return new Promise(() => {}); + if (!this.scriptRes) return Promise.reject(new Error("Extension context invalidated")); return new Promise((resolve) => { const ret = this.GM_getValues(keysOrDefaults); resolve(ret); @@ -439,13 +550,10 @@ export default class GMApi extends GM_Base { @GMContext.API() public "GM.setValues"(values: { [key: string]: any }): Promise { - if (!this.scriptRes) return new Promise(() => {}); - return new Promise((resolve) => { - if (!values || typeof values !== "object") { - throw new Error("GM.setValues: values must be an object"); - } - _GM_setValues(this, resolve, values); - }); + if (!values || typeof values !== "object") { + return Promise.reject(new Error("GM.setValues: values must be an object")); + } + return _GM_setValues(this, values); } @GMContext.API() @@ -459,24 +567,16 @@ export default class GMApi extends GM_Base { for (const key of keys) { req[key] = undefined; } - _GM_setValues(this, null, req); + void _GM_setValues(this, req).catch(console.error); } // Asynchronous wrapper for GM.deleteValues @GMContext.API() public "GM.deleteValues"(keys: string[]): Promise { - if (!this.scriptRes) return new Promise(() => {}); - return new Promise((resolve) => { - if (!Array.isArray(keys)) { - throw new Error("GM.deleteValues: keys must be string[]"); - } else { - const req = {} as Record; - for (const key of keys) { - req[key] = undefined; - } - _GM_setValues(this, resolve, req); - } - }); + if (!Array.isArray(keys)) return Promise.reject(new Error("GM.deleteValues: keys must be string[]")); + const req = {} as Record; + for (const key of keys) req[key] = undefined; + return _GM_setValues(this, req); } @GMContext.API() @@ -513,7 +613,7 @@ export default class GMApi extends GM_Base { if (typeof message !== "string") { message = Native.jsonStringify(message); } - this.sendMessage("GM_log", [`${message}`, `${level}`, labels]); + void this.sendMessage("GM_log", [`${message}`, `${level}`, labels]).catch(() => undefined); } @GMContext.API({ depend: ["GM_log"] }) @@ -730,7 +830,9 @@ export default class GMApi extends GM_Base { this.EE.addListener("menuClick:" + menuKey, listener); } // 发送至 service worker 处理(唯一键,显示名字,不包括id的其他设定) - this.sendMessage("GM_registerMenuCommand", [menuKey, `${name}`, options] as GMRegisterMenuCommandParam); + void this.sendMessage("GM_registerMenuCommand", [menuKey, `${name}`, options] as GMRegisterMenuCommandParam).catch( + () => undefined + ); return ret; } @@ -871,7 +973,9 @@ export default class GMApi extends GM_Base { this.menuKeyRegistered!.delete(menuKey); this.EE.removeAllListeners("menuClick:" + menuKey); // 发送至 service worker 处理(唯一键) - this.sendMessage("GM_unregisterMenuCommand", [menuKey] as GMUnRegisterMenuCommandParam); + void this.sendMessage("GM_unregisterMenuCommand", [menuKey] as GMUnRegisterMenuCommandParam).catch( + () => undefined + ); } @GMContext.API({ depend: ["GM_unregisterMenuCommand"] }) @@ -899,7 +1003,7 @@ export default class GMApi extends GM_Base { }) public async CAT_fileStorage(action: "list" | "download" | "upload" | "delete" | "config", details: any) { if (action === "config") { - this.sendMessage("CAT_fileStorage", ["config"]); + await this.sendMessage("CAT_fileStorage", ["config"]); return; } const sendDetails: CATType.CATFileStorageDetails = { @@ -912,7 +1016,7 @@ export default class GMApi extends GM_Base { const url = await toBlobURL(this, details.data); sendDetails.data = url; } - this.sendMessage("CAT_fileStorage", [`${action}`, sendDetails]).then( + void this.sendMessage("CAT_fileStorage", [`${action}`, sendDetails]).then( async (resp: { action: string; data: any }) => { switch (resp.action) { case "onload": { @@ -934,7 +1038,9 @@ export default class GMApi extends GM_Base { } } } - ); + ).catch((error) => { + details.onerror?.({ code: -1, message: String(error) }); + }); } // 用于脚本跨域请求,需要@connect domain指定允许的域名 @@ -1285,7 +1391,7 @@ export default class GMApi extends GM_Base { if (typeof data.tag === "string") { notificationId = notificationTagMap.get(data.tag); } - gmApi.sendMessage("GM_notification", [customClone(data), notificationId]).then((id) => { + const request = gmApi.sendMessage("GM_notification", [customClone(data), notificationId]).then((id) => { if (!gmApi.EE) return; if (create) { create.apply({ id }, [id]); @@ -1352,7 +1458,7 @@ export default class GMApi extends GM_Base { } }); }); - return Promise.resolve(); + return request.then(() => undefined); } @GMContext.API() @@ -1372,19 +1478,19 @@ export default class GMApi extends GM_Base { image?: string, onclick?: GMTypes.NotificationOnClick ): void { - _GM_notification(this, detail, ondone, image, onclick); + void _GM_notification(this, detail, ondone, image, onclick).catch(() => undefined); } // ScriptCat 额外API @GMContext.API({ alias: "GM.closeNotification" }) public GM_closeNotification(id: string): void { - this.sendMessage("GM_closeNotification", [`${id}`]); + void this.sendMessage("GM_closeNotification", [`${id}`]).catch(() => undefined); } // ScriptCat 额外API @GMContext.API({ alias: "GM.updateNotification" }) public GM_updateNotification(id: string, details: GMTypes.NotificationDetails): void { - this.sendMessage("GM_updateNotification", [`${id}`, customClone(details)]); + void this.sendMessage("GM_updateNotification", [`${id}`, customClone(details)]).catch(() => undefined); } @GMContext.API({ depend: ["GM_closeInTab"] }) @@ -1420,7 +1526,7 @@ export default class GMApi extends GM_Base { onclose() {}, }; - this.sendMessage("GM_openInTab", [url, option as GMTypes.SWOpenTabOptions]).then((id) => { + void this.sendMessage("GM_openInTab", [url, option as GMTypes.SWOpenTabOptions]).then((id) => { if (!this.EE) return; if (id) { tabid = id; @@ -1446,6 +1552,8 @@ export default class GMApi extends GM_Base { ret.onclose && ret.onclose(); ret.closed = true; } + }).catch(() => { + ret.closed = true; }); return ret; @@ -1469,18 +1577,14 @@ export default class GMApi extends GM_Base { @GMContext.API() public GM_getTab(callback: (tabData: object) => void) { if (this.isInvalidContext()) return; - this.sendMessage("GM_getTab", []).then((tabData) => { + void this.sendMessage("GM_getTab", []).then((tabData) => { callback(tabData ?? {}); - }); + }).catch(() => undefined); } @GMContext.API({ depend: ["GM_getTab"] }) public "GM.getTab"(): Promise { - return new Promise((resolve) => { - this.GM_getTab((data) => { - resolve(data); - }); - }); + return this.sendMessage("GM_getTab", []).then((data) => data ?? {}); } @GMContext.API() @@ -1489,32 +1593,25 @@ export default class GMApi extends GM_Base { if (typeof tabData === "object") { tabData = customClone(tabData); } - this.sendMessage("GM_saveTab", [tabData]); + void this.sendMessage("GM_saveTab", [tabData]).catch(() => undefined); } @GMContext.API({ depend: ["GM_saveTab"] }) public "GM.saveTab"(tabData: object): Promise { - return new Promise((resolve) => { - this.GM_saveTab(tabData); - resolve(); - }); + return this.sendMessage("GM_saveTab", [customClone(tabData)]).then(() => undefined); } @GMContext.API() public GM_getTabs(callback: (tabsData: { [key: number]: object }) => any) { if (this.isInvalidContext()) return; - this.sendMessage("GM_getTabs", []).then((tabsData) => { + void this.sendMessage("GM_getTabs", []).then((tabsData) => { callback(tabsData); - }); + }).catch(() => undefined); } @GMContext.API({ depend: ["GM_getTabs"] }) public "GM.getTabs"(): Promise<{ [key: number]: object }> { - return new Promise<{ [key: number]: object }>((resolve) => { - this.GM_getTabs((tabsData) => { - resolve(tabsData); - }); - }); + return this.sendMessage("GM_getTabs", []).then((tabsData) => tabsData ?? {}); } @GMContext.API() @@ -1547,7 +1644,7 @@ export default class GMApi extends GM_Base { @GMContext.API({ depend: ["GM_setClipboard"] }) public "GM.setClipboard"(data: string, info?: string | { type?: string; mimetype?: string }): Promise { - if (this.isInvalidContext()) return new Promise(() => {}); + if (this.isInvalidContext()) return Promise.reject(new Error("Extension context invalidated")); return new Promise((resolve) => { this.GM_setClipboard(data, info, () => { resolve(); diff --git a/src/app/service/content/page_load_contract.ts b/src/app/service/content/page_load_contract.ts index fdb53dd5b..789da197e 100644 --- a/src/app/service/content/page_load_contract.ts +++ b/src/app/service/content/page_load_contract.ts @@ -22,6 +22,8 @@ const PAGE_LOAD_SCRIPT_OPTIONAL_KEYS = [ "downloadUrl", "config", "updatetime", + "valueRevision", + "valueEpoch", "requireCssResource", "userConfig", "scriptUrlPatterns", diff --git a/src/app/service/content/script_executor.test.ts b/src/app/service/content/script_executor.test.ts index a4fe6c02a..d23c48a06 100644 --- a/src/app/service/content/script_executor.test.ts +++ b/src/app/service/content/script_executor.test.ts @@ -3,6 +3,7 @@ import type { Message } from "@Packages/message/types"; import type { ScriptLoadInfo } from "../service_worker/types"; import type { TScriptInfo } from "@App/app/repo/scripts"; import { initEnvInfo, ScriptExecutor } from "./script_executor"; +import { encodeRValue } from "@App/pkg/utils/message_value"; const styleUrl = "https://example.com/style.css"; const secondStyleUrl = "https://example.com/second-style.css"; @@ -31,6 +32,75 @@ function makeScript(overrides: Partial { + it("一个尚未出现脚本 flag 的 userscript 可先接收 r2,再只执行一次", () => { + const executor = new ScriptExecutor({} as Message, {} as Message); + const script = makeScript({ + uuid: "late-value-1", + flag: "late-executor-1", + value: { k: 1 }, valueRevision: 1, valueEpoch: "epoch", + metadata: { grant: ["GM_getValue"] }, + }); + const actual: unknown[] = []; + executor.startScripts([script as TScriptInfo], initEnvInfo); + expect(executor.execScriptMap.size).toBe(0); + executor.valueUpdate({ + id: "r2", uuid: script.uuid, storageName: script.uuid, + entries: [["k", encodeRValue(2), encodeRValue(1)]], valueUpdated: true, + sender: { runFlag: "other" }, revision: 2, epoch: "epoch", + }); + (window as any)[script.flag] = function (this: any) { + actual.push(this.GM_getValue("k")); + }; + expect(actual).toEqual([2]); + expect(executor.execScriptMap.size).toBe(1); + }); + + it("两个独立 world 等待同一 storageName,接收 snapshot 后首次运行均读到新值", () => { + const executions: unknown[] = []; + const worlds = ["content", "inject"].map((name) => { + const executor = new ScriptExecutor({} as Message, {} as Message); + const script = makeScript({ + uuid: `late-${name}`, flag: `late-script-${name}`, + metadata: { storagename: ["shared"], grant: ["GM_getValue"], "run-at": ["document-body"] }, + value: { k: 1 }, valueRevision: 1, valueEpoch: "epoch", + }); + executor.startScripts([script as TScriptInfo], initEnvInfo); + executor.valueSnapshot({ storageName: "shared", epoch: "epoch", revision: 2, values: { k: 2 } }); + return { executor, script, name }; + }); + for (const { script, name } of worlds) { + (window as any)[script.flag] = function (this: any) { + executions.push([name, this.GM_getValue("k")]); + }; + } + expect(executions).toEqual([["content", 2], ["inject", 2]]); + expect(worlds.map(({ executor }) => executor.execScriptMap.size)).toEqual([1, 1]); + }); + + it("一个已运行脚本处理失败时,仍尝试通知共享存储的其他脚本", () => { + const executor = new ScriptExecutor({} as Message, {} as Message); + for (const uuid of ["bad", "good"]) { + const script = makeScript({ uuid, flag: `flag-${uuid}`, + metadata: { storagename: ["shared"], grant: [] } }); + executor.execScriptEntry({ + scriptLoadInfo: script as TScriptInfo, + scriptFlag: script.flag, + envInfo: initEnvInfo, + scriptFunc: () => undefined, + }); + } + const bad = vi.spyOn(executor.execScriptMap.get("bad")!, "valueUpdate").mockImplementation(() => { + throw new Error("bad GM script"); + }); + const good = vi.spyOn(executor.execScriptMap.get("good")!, "valueUpdate").mockReturnValue(undefined); + expect(() => executor.valueUpdate({ + id: "x", uuid: "bad", storageName: "shared", entries: [], + sender: { runFlag: "remote" }, valueUpdated: false, revision: 1, epoch: "e", + })).toThrow("bad GM script"); + expect(bad).toHaveBeenCalledOnce(); + expect(good).toHaveBeenCalledOnce(); + }); + describe("resource execution", () => { let adoptedSheets: CSSStyleSheet[]; diff --git a/src/app/service/content/script_executor.ts b/src/app/service/content/script_executor.ts index b4ccc0e44..ea0125ba9 100644 --- a/src/app/service/content/script_executor.ts +++ b/src/app/service/content/script_executor.ts @@ -2,7 +2,7 @@ import type { Message } from "@Packages/message/types"; import { getStorageName } from "@App/pkg/utils/utils"; import type { EmitEventRequest } from "../service_worker/types"; import ExecScript from "./exec_script"; -import type { GMInfoEnv, ScriptFunc, ValueUpdateDataEncoded } from "./types"; +import type { GMInfoEnv, ScriptFunc, ValueSnapshot, ValueUpdateDataEncoded } from "./types"; import { addStyleSheet, definePropertyListener, waitBody } from "./utils"; import type { ScriptLoadInfo, TScriptInfo } from "@App/app/repo/scripts"; import { DefinedFlags } from "../service_worker/runtime.consts"; @@ -10,6 +10,7 @@ import { pageAddEventListener, pageDispatchEvent } from "@Packages/message/commo import { isUrlExcluded } from "@App/pkg/utils/match"; import type { ScriptEnvTag } from "@Packages/message/consts"; import { localizeObject } from "./global"; +import { decodeRValue } from "@App/pkg/utils/message_value"; export type ExecScriptEntry = { scriptLoadInfo: TScriptInfo; @@ -34,6 +35,9 @@ export const initEnvInfo: GMInfoEnv = { export class ScriptExecutor { earlyScriptFlag: Set = new Set(); execScriptMap: Map = new Map(); + // A pageLoad acknowledgement may precede the compiled userscript flag being set. + // Retain only the initial descriptor and its latest value state, never an event log. + private readonly pendingScripts = new Map(); constructor( private msg: Message, @@ -48,14 +52,95 @@ export class ScriptExecutor { } } - valueUpdate(data: ValueUpdateDataEncoded) { - // runtime/valueUpdate + valueUpdate(data: ValueUpdateDataEncoded): void | Promise { const { uuid, storageName } = data; + let handled = false; + let failed = false; + let firstError: unknown; + let recoveries: Promise[] | undefined; for (const val of this.execScriptMap.values()) { - if (val.scriptRes.uuid === uuid || getStorageName(val.scriptRes) === storageName) { - val.valueUpdate(data); + if (val.scriptRes.uuid !== uuid && getStorageName(val.scriptRes) !== storageName) continue; + handled = true; + try { + const recovery = val.valueUpdate(data); + if (recovery instanceof Promise) (recoveries ??= []).push(recovery); + } catch (error) { + if (!failed) firstError = error; + failed = true; + } + } + for (const script of this.pendingScripts.values()) { + if (script.uuid !== uuid && getStorageName(script) !== storageName) continue; + handled = true; + try { + if (data.revision !== undefined && data.epoch !== undefined) { + const oldRevision = script.valueRevision ?? 0; + const oldEpoch = script.valueEpoch ?? ""; + if (data.epoch === oldEpoch && data.revision <= oldRevision) continue; + if ((oldEpoch && data.epoch !== oldEpoch) || data.revision > oldRevision + 1) { + throw new Error("Pending GM script requires a full value snapshot"); + } + script.valueRevision = data.revision; + script.valueEpoch = data.epoch; + } + if (!data.valueUpdated) continue; + for (const [key, encoded] of data.entries) { + const value = decodeRValue(encoded); + if (value === undefined) delete script.value[key]; + else script.value[key] = value; + } + } catch (error) { + if (!failed) firstError = error; + failed = true; + } + } + if (!handled) throw new Error("No script world recipient for GM value update"); + if (failed) { + // A single failing script must not block peers; the frame still needs a repair snapshot. + for (const recovery of recoveries ?? []) void recovery.catch(() => undefined); + throw firstError; + } + if (recoveries) return Promise.all(recoveries).then(() => undefined); + } + + valueSnapshot(snapshot: ValueSnapshot) { + let handled = false; + let failed = false; + let firstError: unknown; + for (const exec of this.execScriptMap.values()) { + if (getStorageName(exec.scriptRes) !== snapshot.storageName) continue; + handled = true; + try { + exec.valueSnapshot(snapshot); + } catch (error) { + if (!failed) firstError = error; + failed = true; + } + } + for (const script of this.pendingScripts.values()) { + if (getStorageName(script) !== snapshot.storageName) continue; + handled = true; + try { + if (script.valueEpoch === snapshot.epoch && (script.valueRevision ?? 0) > snapshot.revision) continue; + const values = { ...snapshot.values }; + for (const [tabName, tab] of Object.entries(script.config ?? {})) { + if (!tab || typeof tab !== "object") continue; + for (const [key, option] of Object.entries(tab)) { + if (!option || typeof option !== "object" || !("default" in option)) continue; + const field = `${tabName}.${key}`; + if (values[field] === undefined) values[field] = option.default; + } + } + script.value = values; + script.valueRevision = snapshot.revision; + script.valueEpoch = snapshot.epoch; + } catch (error) { + if (!failed) firstError = error; + failed = true; } } + if (!handled) throw new Error("No script world recipient for GM value snapshot"); + if (failed) throw firstError; } startScripts(scripts: TScriptInfo[], envInfo: GMInfoEnv) { @@ -76,10 +161,18 @@ export class ScriptExecutor { if (val.scriptRes.flag === flag) { // 处理早期脚本的沙盒环境 val.updateEarlyScriptGMInfo(envInfo); + // Early-start code already runs; refresh its GM cache without running it again. + val.valueSnapshot({ + storageName: getStorageName(script), + values: script.value, + revision: script.valueRevision ?? 0, + epoch: script.valueEpoch ?? "", + }); return; } } } + this.pendingScripts.set(script.uuid, script); definePropertyListener(window, flag, (val: ScriptFunc) => { loadExec(script, val); }); @@ -153,6 +246,7 @@ export class ScriptExecutor { envInfo, }); this.execScriptMap.set(scriptLoadInfo.uuid, execScript); + this.pendingScripts.delete(scriptLoadInfo.uuid); const metadata = scriptLoadInfo.metadata || {}; const resource = scriptLoadInfo.requireCssResource ?? scriptLoadInfo.resource; // 注入css diff --git a/src/app/service/content/script_runtime.ts b/src/app/service/content/script_runtime.ts index 817dd2a23..dd24a19cd 100644 --- a/src/app/service/content/script_runtime.ts +++ b/src/app/service/content/script_runtime.ts @@ -3,7 +3,7 @@ import type { Message } from "@Packages/message/types"; import { initEnvInfo, type ScriptExecutor } from "./script_executor"; import type { TScriptInfo } from "@App/app/repo/scripts"; import type { EmitEventRequest } from "../service_worker/types"; -import type { GMInfoEnv, ValueUpdateDataEncoded } from "./types"; +import type { GMInfoEnv, ValueSnapshot, ValueUpdateDataEncoded } from "./types"; import type { ScriptEnvTag } from "@Packages/message/consts"; import { onInjectPageLoaded } from "./external"; import type { CustomEventMessage } from "@Packages/message/custom_event_message"; @@ -60,7 +60,12 @@ export class ScriptRuntime { this.scriptExecutor.emitEvent(data); }); this.server.on("runtime/valueUpdate", (data: ValueUpdateDataEncoded) => { - this.scriptExecutor.valueUpdate(data); + const result = this.scriptExecutor.valueUpdate(data); + return result instanceof Promise ? result.then(() => true) : true; + }); + this.server.on("runtime/valueSnapshot", (data: ValueSnapshot) => { + this.scriptExecutor.valueSnapshot(data); + return true; }); this.server.on("pageLoad", (data: { scripts: TScriptInfo[]; envInfo: GMInfoEnv }) => { diff --git a/src/app/service/content/scripting.test.ts b/src/app/service/content/scripting.test.ts new file mode 100644 index 000000000..b53624ef4 --- /dev/null +++ b/src/app/service/content/scripting.test.ts @@ -0,0 +1,400 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import type { Server } from "@Packages/message/server"; +import type { MessageConnect, MessageSend, TMessage } from "@Packages/message/types"; +import type { CustomEventMessage } from "@Packages/message/custom_event_message"; +import ScriptingRuntime from "./scripting"; +import type { ValueUpdateDataEncoded } from "./types"; +import { MessageResponseLostError } from "@Packages/message/errors"; + +type Handler = (data: any) => any; + +const createServer = () => { + const handlers = new Map(); + return { + server: { on: (name: string, fn: Handler) => handlers.set(name, fn) } as unknown as Server, + handlers, + }; +}; + +const createPageSender = () => { + const sendMessage = vi.fn().mockResolvedValue({ code: 0, data: true }); + return { sender: { sendMessage } as unknown as CustomEventMessage, sendMessage }; +}; + +const valueUpdate = (storageName: string): ValueUpdateDataEncoded => ({ + id: "id-1", + entries: [["k", "v", undefined] as any], + uuid: "uuid-1", + storageName, + sender: { runFlag: "", tabId: 1 }, + valueUpdated: true, +}); + +const actionsOf = (fn: ReturnType) => fn.mock.calls.map(([msg]) => msg.action); + +describe("ScriptingRuntime 值更新投递", () => { + let storageListeners: Array<(changes: Record) => void>; + let originalOnChanged: unknown; + + beforeEach(() => { + storageListeners = []; + originalOnChanged = (chrome.storage.local as any).onChanged; + (chrome.storage.local as any).onChanged = { + addListener: (fn: (typeof storageListeners)[number]) => storageListeners.push(fn), + }; + }); + + afterEach(() => { + (chrome.storage.local as any).onChanged = originalOnChanged; + }); + + const setup = (pageLoadData?: unknown) => { + const ext = createServer(); + const page = createServer(); + const toContent = createPageSender(); + const toInject = createPageSender(); + let portMessage: (message: TMessage) => void = () => undefined; + const portSend = vi.fn(); + const onPortMessage = vi.fn((fn: (message: TMessage) => void) => (portMessage = fn)); + const port = { + sendMessage: portSend, + onMessage: onPortMessage, + onDisconnect: vi.fn(), + disconnect: vi.fn(), + } as unknown as MessageConnect; + const senderToExt = { + sendMessage: vi.fn().mockResolvedValue({ code: 0, data: pageLoadData ?? { ok: false } }), + connect: vi.fn().mockResolvedValue(port), + } as unknown as MessageSend; + const runtime = new ScriptingRuntime(ext.server, page.server, senderToExt, toContent.sender, toInject.sender); + runtime.init(); + return { + runtime, + ext, + toContent, + toInject, + portSend, + onPortMessage, + senderToExt, + receive: (message: TMessage) => portMessage(message), + }; + }; + + // 每个页面的每个 frame 都有 scripting.js;若它监听 storage.local,任何一次 local 写入 + // (包括整包 value:*)的新旧值都会被序列化投递到所有 frame,见 #1834。 + it("chrome.storage.local 的变化不会被转发给页面", async () => { + const { toContent, toInject } = setup(); + + for (const fn of storageListeners) { + fn({ + valueUpdateDelivery: { newValue: { rId: "1", sendData: valueUpdate("s1") } }, + "value:s1": { newValue: { data: { k: "v" } }, oldValue: { data: {} } }, + }); + } + await Promise.resolve(); + + expect(storageListeners).toHaveLength(0); + expect(toContent.sendMessage).not.toHaveBeenCalled(); + expect(toInject.sendMessage).not.toHaveBeenCalled(); + }); + + it("Port 只转发给当前 frame 运行的脚本世界,且先订阅再启动脚本", async () => { + const { runtime, toContent, toInject, portSend, onPortMessage, receive } = setup({ + ok: true, + injectScriptList: [ + { uuid: "a", metadata: { storagename: ["page-store"] } }, + { uuid: "c", metadata: { storagename: ["shared"] } }, + ], + contentScriptList: [ + { uuid: "b", metadata: { storagename: ["content-store"] } }, + { uuid: "d", metadata: { storagename: ["shared"] } }, + { uuid: "e", metadata: { storagename: ["__proto__"] } }, + ], + envInfo: {}, + }); + runtime.pageLoad(); + await vi.waitFor(() => expect(onPortMessage).toHaveBeenCalledOnce()); + receive({ code: 0, data: { ready: true } }); + await vi.waitFor(() => + expect(portSend).toHaveBeenCalledWith({ + action: "runtime/subscribeValueUpdates", + data: { + names: ["page-store", "shared", "content-store", "__proto__"], + requestId: 1, + versions: expect.objectContaining({ + "page-store": { epoch: "", revision: 0 }, + shared: { epoch: "", revision: 0 }, + }), + }, + }) + ); + expect(toContent.sendMessage).not.toHaveBeenCalled(); + expect(toInject.sendMessage).not.toHaveBeenCalled(); + + receive({ action: "runtime/valueSubscriptionsReady", data: { requestId: 1 } }); + await vi.waitFor(() => expect(actionsOf(toInject.sendMessage)).toContain("inject/pageLoad")); + toContent.sendMessage.mockClear(); + toInject.sendMessage.mockClear(); + + receive({ action: "runtime/valueUpdate", data: valueUpdate("shared") }); + await Promise.resolve(); + expect(actionsOf(toContent.sendMessage)).toEqual(["content/runtime/valueUpdate"]); + expect(actionsOf(toInject.sendMessage)).toEqual(["inject/runtime/valueUpdate"]); + toContent.sendMessage.mockClear(); + toInject.sendMessage.mockClear(); + + receive({ action: "runtime/valueUpdate", data: valueUpdate("__proto__") }); + await Promise.resolve(); + expect(actionsOf(toContent.sendMessage)).toEqual(["content/runtime/valueUpdate"]); + expect(toInject.sendMessage).not.toHaveBeenCalled(); + toContent.sendMessage.mockClear(); + + receive({ action: "runtime/valueUpdate", data: valueUpdate("page-store") }); + await Promise.resolve(); + expect(actionsOf(toInject.sendMessage)).toEqual(["inject/runtime/valueUpdate"]); + expect(toContent.sendMessage).not.toHaveBeenCalled(); + + toInject.sendMessage.mockClear(); + receive({ action: "runtime/valueUpdate", data: valueUpdate("content-store") }); + await Promise.resolve(); + expect(actionsOf(toContent.sendMessage)).toEqual(["content/runtime/valueUpdate"]); + expect(toInject.sendMessage).not.toHaveBeenCalled(); + + toContent.sendMessage.mockClear(); + receive({ action: "runtime/valueUpdate", data: valueUpdate("other-store") }); + await Promise.resolve(); + expect(toContent.sendMessage).not.toHaveBeenCalled(); + expect(toInject.sendMessage).not.toHaveBeenCalled(); + }); + + it("初始 pageLoad 短暂失败后恢复,且仅下发一次脚本初始化", async () => { + const { runtime, senderToExt, toContent, toInject } = setup({ ok: false }); + const send = vi.mocked(senderToExt.sendMessage); + send.mockRejectedValueOnce(new MessageResponseLostError("Service Worker is starting")); + runtime.pageLoad(); + await vi.waitFor(() => expect(send).toHaveBeenCalledTimes(2)); + expect(toContent.sendMessage).not.toHaveBeenCalled(); + expect(toInject.sendMessage).not.toHaveBeenCalled(); + }); + + it("扩展 context 失效时不重试初始 pageLoad", async () => { + vi.useFakeTimers(); + try { + const { runtime, senderToExt } = setup(); + const send = vi.mocked(senderToExt.sendMessage); + send.mockRejectedValue(new Error("Extension context invalidated")); + runtime.pageLoad(); + await Promise.resolve(); + await vi.advanceTimersByTimeAsync(1200); + expect(send).toHaveBeenCalledOnce(); + } finally { + vi.useRealTimers(); + } + }); + + it("同一 storageName 的脚本在 pageLoad 读取到不同 revision 时统一为最新快照", async () => { + const { runtime, receive, onPortMessage, toInject } = setup({ + ok: true, + injectScriptList: [ + { uuid: "older", metadata: { storagename: ["shared"] }, value: { x: 1 }, + valueRevision: 1, valueEpoch: "g" }, + { uuid: "newer", metadata: { storagename: ["shared"] }, value: { x: 2 }, + valueRevision: 2, valueEpoch: "g" }, + ], + contentScriptList: [], + envInfo: {}, + }); + runtime.pageLoad(); + await vi.waitFor(() => expect(onPortMessage).toHaveBeenCalledOnce()); + receive({ code: 0, data: { ready: true } }); + receive({ action: "runtime/valueSubscriptionsReady", data: { requestId: 1 } }); + await vi.waitFor(() => expect(actionsOf(toInject.sendMessage)).toContain("inject/pageLoad")); + const payload = toInject.sendMessage.mock.calls.find(([message]) => message.action === "inject/pageLoad")?.[0]; + expect(payload.data.scripts.map((script: { value: { x: number }; valueRevision: number }) => + [script.value.x, script.valueRevision] + )).toEqual([[2, 2], [2, 2]]); + }); + + it("注入前收到较新的 snapshot 时保留用户配置的默认值", async () => { + const { runtime, receive, onPortMessage, toInject } = setup({ + ok: true, + injectScriptList: [{ + uuid: "config", metadata: { storagename: ["settings"] }, + value: { "general.theme": "light" }, valueRevision: 1, valueEpoch: "e", + config: { general: { theme: { default: "light" } } }, + }], + contentScriptList: [], + envInfo: {}, + }); + runtime.pageLoad(); + await vi.waitFor(() => expect(onPortMessage).toHaveBeenCalledOnce()); + receive({ code: 0, data: { ready: true } }); + receive({ action: "runtime/valueSubscriptionsReady", data: { + requestId: 1, + snapshots: [{ storageName: "settings", revision: 2, epoch: "e", values: { x: 2 } }], + } }); + await vi.waitFor(() => expect(actionsOf(toInject.sendMessage)).toContain("inject/pageLoad")); + const script = toInject.sendMessage.mock.calls.find(([msg]) => msg.action === "inject/pageLoad")?.[0].data + .scripts[0]; + expect(script.value).toMatchObject({ x: 2, "general.theme": "light" }); + }); + + it("Port snapshot 与后续 updates 按 revision 收敛,丢失中间事件时刷新权威状态", async () => { + const { runtime, receive, onPortMessage, toInject, portSend } = setup({ + ok: true, + contentScriptList: [], + injectScriptList: [{ + uuid: "a", metadata: { storagename: ["shared"] }, value: { k: 1 }, + valueRevision: 1, valueEpoch: "epoch-1", + }], + envInfo: {}, + }); + runtime.pageLoad(); + await vi.waitFor(() => expect(onPortMessage).toHaveBeenCalledOnce()); + receive({ code: 0, data: { ready: true } }); + await vi.waitFor(() => expect(portSend).toHaveBeenCalledOnce()); + receive({ action: "runtime/valueSubscriptionsReady", data: { + requestId: 1, + snapshots: [{ storageName: "shared", revision: 2, epoch: "epoch-1", values: { k: 2 } }], + } }); + await vi.waitFor(() => expect(actionsOf(toInject.sendMessage)).toContain("inject/pageLoad")); + const started = toInject.sendMessage.mock.calls.find(([msg]) => msg.action === "inject/pageLoad")?.[0]; + expect(started?.data.scripts[0].value.k).toBe(2); + toInject.sendMessage.mockClear(); + const update = (rev: number, k: number) => ({ + id: `revision-${rev}`, uuid: "a", storageName: "shared", + entries: [["k", k, k - 1] as any], sender: { runFlag: "remote", tabId: 2 }, + valueUpdated: true, revision: rev, epoch: "epoch-1", + }); + receive({ action: "runtime/valueUpdate", data: update(3, 3) }); + receive({ action: "runtime/valueUpdate", data: update(2, 2) }); + await vi.waitFor(() => expect(actionsOf(toInject.sendMessage)).toContain("inject/runtime/valueUpdate")); + expect(actionsOf(toInject.sendMessage).filter((action) => action === "inject/runtime/valueUpdate")).toHaveLength(1); + receive({ action: "runtime/valueUpdate", data: update(5, 5) }); + expect(portSend).toHaveBeenCalledTimes(2); // The version gap requests a fresh subscription snapshot. + receive({ action: "runtime/valueSubscriptionsReady", data: { + requestId: 2, + snapshots: [{ storageName: "shared", revision: 5, epoch: "epoch-1", values: { k: 5 } }], + } }); + await vi.waitFor(() => expect(actionsOf(toInject.sendMessage)).toContain("inject/runtime/valueSnapshot")); + }); + + it("r3 snapshot 被延迟而 r5 缺口到达时,必须补做第二次 refresh", async () => { + const { runtime, receive, onPortMessage, portSend, toInject } = setup({ + ok: true, + injectScriptList: [{ uuid: "a", metadata: { storagename: ["shared"] }, + value: { k: 1 }, valueRevision: 1, valueEpoch: "g" }], + contentScriptList: [], + envInfo: {}, + }); + runtime.pageLoad(); + await vi.waitFor(() => expect(onPortMessage).toHaveBeenCalledOnce()); + receive({ code: 0, data: { ready: true } }); + receive({ action: "runtime/valueSubscriptionsReady", data: { requestId: 1 } }); + await vi.waitFor(() => expect(actionsOf(toInject.sendMessage)).toContain("inject/pageLoad")); + toInject.sendMessage.mockClear(); + const update = (revision: number) => ({ + id: `gap-${revision}`, uuid: "a", storageName: "shared", + entries: [["k", revision, revision - 1] as any], + sender: { runFlag: "other", tabId: 1 }, valueUpdated: true, + revision, epoch: "g", + }); + receive({ action: "runtime/valueUpdate", data: update(3) }); + expect(portSend).toHaveBeenCalledTimes(2); + receive({ action: "runtime/valueUpdate", data: update(5) }); + expect(portSend).toHaveBeenCalledTimes(2); + receive({ action: "runtime/valueSubscriptionsReady", data: { + requestId: 2, + snapshots: [{ storageName: "shared", epoch: "g", revision: 3, values: { k: 3 } }], + } }); + await vi.waitFor(() => expect(portSend).toHaveBeenCalledTimes(3)); + receive({ action: "runtime/valueSubscriptionsReady", data: { + requestId: 3, + snapshots: [{ storageName: "shared", epoch: "g", revision: 5, values: { k: 5 } }], + } }); + await vi.waitFor(() => expect(actionsOf(toInject.sendMessage).filter((name) => + name === "inject/runtime/valueSnapshot")).toHaveLength(2)); + const values = toInject.sendMessage.mock.calls + .filter(([message]) => message.action === "inject/runtime/valueSnapshot") + .map(([message]) => message.data.values.k); + expect(values).toEqual([3, 5]); + expect(actionsOf(toInject.sendMessage)).not.toContain("inject/runtime/valueUpdate"); + }); + + it("content 送达失败不会使 inject world 停摆;仅重新同步失败的 world", async () => { + const { runtime, receive, onPortMessage, portSend, toContent, toInject } = setup({ + ok: true, + injectScriptList: [{ uuid: "page", metadata: { storagename: ["shared"] }, + value: { k: 1 }, valueRevision: 1, valueEpoch: "g" }], + contentScriptList: [{ uuid: "content", metadata: { storagename: ["shared"] }, + value: { k: 1 }, valueRevision: 1, valueEpoch: "g" }], + envInfo: {}, + }); + runtime.pageLoad(); + await vi.waitFor(() => expect(onPortMessage).toHaveBeenCalledOnce()); + receive({ code: 0, data: { ready: true } }); + receive({ action: "runtime/valueSubscriptionsReady", data: { requestId: 1 } }); + await vi.waitFor(() => expect(actionsOf(toInject.sendMessage)).toContain("inject/pageLoad")); + toContent.sendMessage.mockClear(); + toInject.sendMessage.mockClear(); + toContent.sendMessage.mockRejectedValueOnce(new Error("content bridge unavailable")); + receive({ action: "runtime/valueUpdate", data: { + uuid: "page", storageName: "shared", id: "update-2", + entries: [["k", 2, 1] as any], sender: { runFlag: "other", tabId: 1 }, + valueUpdated: true, revision: 2, epoch: "g", + } }); + await vi.waitFor(() => expect(portSend).toHaveBeenCalledTimes(2)); + expect(actionsOf(toInject.sendMessage)).toContain("inject/runtime/valueUpdate"); + const refresh = portSend.mock.calls[1][0]; + expect(refresh.data.versions.shared).toEqual({ epoch: "", revision: -1 }); + receive({ action: "runtime/valueSubscriptionsReady", data: { + requestId: 2, + snapshots: [{ storageName: "shared", epoch: "g", revision: 2, values: { k: 2 } }], + } }); + await vi.waitFor(() => expect(actionsOf(toContent.sendMessage)).toContain("content/runtime/valueSnapshot")); + expect(actionsOf(toInject.sendMessage)).not.toContain("inject/runtime/valueSnapshot"); + }); + + it("world 只返回空 reply 时不能确认值更新,必须申请修复 snapshot", async () => { + const { runtime, receive, onPortMessage, portSend, toContent } = setup({ + ok: true, + injectScriptList: [], + contentScriptList: [{ uuid: "c", metadata: { storagename: ["shared"] }, + value: { k: 1 }, valueRevision: 1, valueEpoch: "g" }], + envInfo: {}, + }); + runtime.pageLoad(); + await vi.waitFor(() => expect(onPortMessage).toHaveBeenCalledOnce()); + receive({ code: 0, data: { ready: true } }); + receive({ action: "runtime/valueSubscriptionsReady", data: { requestId: 1 } }); + await vi.waitFor(() => expect(actionsOf(toContent.sendMessage)).toContain("content/pageLoad")); + toContent.sendMessage.mockClear(); + toContent.sendMessage.mockResolvedValueOnce({ code: 0, data: undefined }); + receive({ action: "runtime/valueUpdate", data: { + uuid: "c", storageName: "shared", id: "r2", entries: [], + sender: { runFlag: "remote" }, valueUpdated: true, revision: 2, epoch: "g", + } }); + await vi.waitFor(() => expect(portSend).toHaveBeenCalledTimes(2)); + expect(portSend.mock.calls[1][0].data.versions.shared).toEqual({ epoch: "", revision: -1 }); + }); + + it("永久协议错误仅调用一次 pageLoad,不能进入无限 SW retry", async () => { + const { runtime, senderToExt } = setup(); + const send = vi.mocked(senderToExt.sendMessage); + send.mockRejectedValue(new Error("no such api serviceWorker/runtime/pageLoad")); + runtime.pageLoad(); + await vi.waitFor(() => expect(send).toHaveBeenCalledOnce()); + await new Promise((resolve) => setTimeout(resolve, 650)); + expect(send).toHaveBeenCalledOnce(); + }); + + it("pageLoad 没有运行脚本的 frame 不会订阅,释放 Port", async () => { + const { runtime, toContent, toInject, portSend } = setup(); + runtime.pageLoad(); + await Promise.resolve(); + await Promise.resolve(); + expect(portSend).not.toHaveBeenCalled(); + expect(toContent.sendMessage).not.toHaveBeenCalled(); + expect(toInject.sendMessage).not.toHaveBeenCalled(); + }); +}); diff --git a/src/app/service/content/scripting.ts b/src/app/service/content/scripting.ts index 7286d82b0..2a400c563 100644 --- a/src/app/service/content/scripting.ts +++ b/src/app/service/content/scripting.ts @@ -6,7 +6,11 @@ import { RuntimeClient } from "../service_worker/client"; import { getStorageName, makeBlobURL } from "@App/pkg/utils/utils"; import type { Logger } from "@App/app/repo/logger"; import LoggerCore from "@App/app/logger/core"; -import type { ValueUpdateDataEncoded } from "./types"; +import type { ValueSnapshot, ValueUpdateDataEncoded, ValueVersion } from "./types"; +import type { TScriptInfo } from "@App/app/repo/scripts"; +import { decodeRValue } from "@App/pkg/utils/message_value"; +import { MessageResponseLostError } from "@Packages/message/errors"; +import ScriptingValuePort from "./value_port"; const PageOrContent = { PAGE: 1, @@ -16,14 +20,19 @@ const PageOrContent = { type PageOrContent = ValueOf; -// For Firefox, StorageArea.setAccessLevel is not implemented. -// See https://bugzilla.mozilla.org/show_bug.cgi?id=1724754 -// const deliveryStorage = isFirefox() ? chrome.storage.local : chrome.storage.session; -const deliveryStorage = chrome.storage.local; // 日后再处理 - // scripting页的处理 export default class ScriptingRuntime { - private activeStorageNames: Map | null = null; + private activeStorageNames = new Map(); + private readonly versions = new Map(); + private readonly desiredVersions = new Map(); + // Only worlds which failed delivery need a full snapshot; no event journal. + private readonly dirtyWorlds = new Map(); + private readonly failureGenerations = new Map(); + private failureSequence = 0; + private stagedScripts?: { injectScriptList: TScriptInfo[]; contentScriptList: TScriptInfo[] }; + private readonly stagedDirty = new Set(); + private scriptsStarted = false; + private readonly valuePort: ScriptingValuePort; constructor( // 监听来自service_worker的消息 private readonly extServer: Server, @@ -35,7 +44,160 @@ export default class ScriptingRuntime { private readonly senderToContent: CustomEventMessage, // 发送给inject的消息接口 private readonly senderToInject: CustomEventMessage - ) {} + ) { + this.valuePort = new ScriptingValuePort( + this.senderToExt, + (data) => this.forwardValueUpdate(data), + (snapshot) => this.forwardValueSnapshot(snapshot), + () => this.subscriptionVersions(), + () => this.desiredVersions.size > 0 || this.dirtyWorlds.size > 0 + ); + } + + private isNewer(storageName: string, version: ValueVersion): boolean { + const known = this.versions.get(storageName); + if (!known) return true; + if (known.epoch !== version.epoch) return true; + return version.revision > known.revision; + } + + private subscriptionVersions(): Record { + const versions = Object.fromEntries(this.versions); + for (const name of this.dirtyWorlds.keys()) { + // A successful frame-level receipt is not proof that either script world applied it. + versions[name] = { epoch: "", revision: -1 }; + } + return versions; + } + + private forEachStaged(storageName: string, callback: (script: TScriptInfo) => void) { + if (!this.stagedScripts) return; + for (const script of [...this.stagedScripts.injectScriptList, ...this.stagedScripts.contentScriptList]) { + if (getStorageName(script) === storageName) callback(script); + } + } + + private deliverValue( + action: "runtime/valueUpdate" | "runtime/valueSnapshot", + data: ValueUpdateDataEncoded | ValueSnapshot, + worlds: PageOrContent + ) { + const { storageName } = data; + const revision = data.revision; + const epoch = data.epoch; + const failureGeneration = this.failureGenerations.get(storageName); + const deliver = (bit: PageOrContent, target: CustomEventMessage, prefix: string) => { + if (!(worlds & bit)) return; + void sendMessage(target, prefix + "/" + action, data) + .then((receipt) => { + if (receipt !== true) throw new Error("Script world did not acknowledge GM value delivery"); + if (action !== "runtime/valueSnapshot") return; + const current = this.versions.get(storageName); + // A late ACK from an older snapshot cannot mark a damaged world as repaired. + if ( + current && current.epoch === epoch && current.revision === revision && + this.failureGenerations.get(storageName) === failureGeneration + ) { + const remaining = (this.dirtyWorlds.get(storageName) ?? 0) & ~bit; + if (remaining) this.dirtyWorlds.set(storageName, remaining as PageOrContent); + else { + this.dirtyWorlds.delete(storageName); + this.failureGenerations.delete(storageName); + } + } + }) + .catch((error) => { + const dirty = (this.dirtyWorlds.get(storageName) ?? 0) | bit; + this.dirtyWorlds.set(storageName, dirty as PageOrContent); + this.failureGenerations.set(storageName, ++this.failureSequence); + LoggerCore.logger().error("forward GM value to script world failed", { storageName, prefix, error }); + this.valuePort.refresh(); + }); + }; + deliver(PageOrContent.CONTENT, this.senderToContent, "content"); + deliver(PageOrContent.PAGE, this.senderToInject, "inject"); + } + + private forwardValueUpdate(data: ValueUpdateDataEncoded) { + const activeOn = this.activeStorageNames.get(data.storageName); + if (!activeOn) return; + if (data.revision !== undefined && data.epoch !== undefined) { + const known = this.versions.get(data.storageName); + if (!this.isNewer(data.storageName, data)) return; + if ( + (known?.epoch && known.epoch !== data.epoch) || + (known?.epoch === data.epoch && data.revision > known.revision + 1) + ) { + const previous = this.desiredVersions.get(data.storageName); + if (!previous || previous.epoch !== data.epoch || data.revision > previous.revision) { + this.desiredVersions.set(data.storageName, { epoch: data.epoch, revision: data.revision }); + } + this.valuePort.refresh(); + return; + } + this.versions.set(data.storageName, { revision: data.revision, epoch: data.epoch }); + const desired = this.desiredVersions.get(data.storageName); + if (desired?.epoch === data.epoch && data.revision >= desired.revision) { + this.desiredVersions.delete(data.storageName); + } + } + if (!this.scriptsStarted) { + this.forEachStaged(data.storageName, (script) => { + for (const [key, encoded] of data.entries) { + const value = decodeRValue(encoded); + if (value === undefined) delete script.value[key]; + else script.value[key] = value; + } + script.valueRevision = data.revision; + script.valueEpoch = data.epoch; + }); + this.stagedDirty.add(data.storageName); + return; + } + this.deliverValue("runtime/valueUpdate", data, activeOn); + } + + private forwardValueSnapshot(snapshot: ValueSnapshot) { + const activeOn = this.activeStorageNames.get(snapshot.storageName); + if (!activeOn) return; + const current = this.versions.get(snapshot.storageName); + const newer = this.isNewer(snapshot.storageName, snapshot); + const same = current?.epoch === snapshot.epoch && current.revision === snapshot.revision; + if (!newer && !same) { + // A newer delta beat this snapshot; preserve the dirty/desired state. + if (this.desiredVersions.has(snapshot.storageName) || this.dirtyWorlds.has(snapshot.storageName)) { + this.valuePort.refresh(); + } + return; + } + if (newer) this.versions.set(snapshot.storageName, { revision: snapshot.revision, epoch: snapshot.epoch }); + const desired = this.desiredVersions.get(snapshot.storageName); + if (desired && (desired.epoch !== snapshot.epoch || snapshot.revision >= desired.revision)) { + // A fresh authoritative snapshot supersedes the requested old generation. + if (desired.epoch === snapshot.epoch || newer) this.desiredVersions.delete(snapshot.storageName); + } + if (!this.scriptsStarted) { + this.forEachStaged(snapshot.storageName, (script) => { + const values = { ...snapshot.values }; + for (const [tabName, tab] of Object.entries(script.config ?? {})) { + if (!tab || typeof tab !== "object") continue; + for (const [key, option] of Object.entries(tab)) { + if (!option || typeof option !== "object" || !("default" in option)) continue; + const field = `${tabName}.${key}`; + if (values[field] === undefined) values[field] = option.default; + } + } + script.value = values; + script.valueRevision = snapshot.revision; + script.valueEpoch = snapshot.epoch; + }); + this.stagedDirty.add(snapshot.storageName); + return; + } + const dirty = this.dirtyWorlds.get(snapshot.storageName) ?? 0; + // A same-revision snapshot is still required by a world whose prior delivery failed. + if (newer || dirty) this.deliverValue("runtime/valueSnapshot", snapshot, (newer ? activeOn : dirty) as PageOrContent); + } // 广播消息给 content 和 inject broadcastToPage( @@ -50,41 +212,15 @@ export default class ScriptingRuntime { } init() { + this.valuePort.start(); this.extServer.on("runtime/emitEvent", (data) => { // 转发给inject和content return this.broadcastToPage("runtime/emitEvent", data); }); - this.extServer.on("runtime/valueUpdate", (data) => { - // 转发给inject和content - return this.broadcastToPage("runtime/valueUpdate", data); - }); this.server.on("logger", (data: Logger) => { LoggerCore.logger().log(data.level, data.message, data.label); }); - // ================================ - // 来自 service_worker 的投递:storage 广播(类似 UDP) - // ================================ - - // 接收 service_worker 的 chrome.storage.local 值改变通知 (一对多广播) - // 类似 UDP 原理,service_worker 不会有任何「等待处理」 - // 由于 changes 会包括新旧值 (Chrome: JSON serialization, Firefox: Structured Clone) - // 因此需要注意资讯量不要过大导致 onChanged 的触发过慢 - deliveryStorage.onChanged.addListener((changes) => { - const record = changes["valueUpdateDelivery"]; - if (record?.newValue) { - const sendData = (record.newValue as { sendData: ValueUpdateDataEncoded }).sendData; - const activeOn = - this.activeStorageNames === null - ? PageOrContent.PAGE_AND_CONTENT - : this.activeStorageNames.get(sendData.storageName); - if (activeOn) { - // 转发给 content 和 inject - this.broadcastToPage("runtime/valueUpdate", sendData, activeOn); - } - } - }); - forwardMessage("serviceWorker", "script/isInstalled", this.server, this.senderToExt); forwardMessage( "serviceWorker", @@ -153,34 +289,143 @@ export default class ScriptingRuntime { // 只有顶层 frame 参与判定,子 frame 不必上报。 if (window.top === window) { window.addEventListener("pageshow", (e) => { - if (e.persisted) client.pageShow(); + if (e.persisted && chrome.runtime?.id) { + void client.pageShow().catch((error) => { + LoggerCore.logger().error("bfcache restore report failed", { error }); + }); + } }); } - // 向service_worker请求脚本列表及环境信息 - client.pageLoad().then((o) => { - if (!o.ok) return; + // Retry only typed transport ambiguity. Server-side protocol, permission and + // configuration failures must not repeatedly wake the service worker. + const requestPageLoad = async () => { + let retryDelay = 250; + let active = true; + let retryTimer: ReturnType | undefined; + let wakeRetry: (() => void) | undefined; + const onPageHide = (event: PageTransitionEvent) => { + if (event.persisted) return; // bfcache preserves this document. + active = false; + if (retryTimer !== undefined) clearTimeout(retryTimer); + wakeRetry?.(); + }; + window.addEventListener("pagehide", onPageHide); + try { + while (active) { + let requestTimer: ReturnType | undefined; + try { + const result = await Promise.race([ + client.pageLoad(), + new Promise((_, reject) => { + requestTimer = setTimeout( + () => reject(new MessageResponseLostError("Initial pageLoad response timed out")), + 30000 + ); + }), + ]); + if (!active) throw new Error("pageLoad cancelled by document unload"); + return result; + } catch (error) { + if ( + !active || + !chrome.runtime?.id || + !(error instanceof MessageResponseLostError) || + /Extension context (?:was )?invalidated|Extension has been disconnected/i.test(error.message) + ) { + throw error; + } + await new Promise((resolve) => { + wakeRetry = resolve; + retryTimer = setTimeout(resolve, retryDelay + Math.random() * retryDelay); + }); + wakeRetry = undefined; + retryTimer = undefined; + retryDelay = Math.min(retryDelay * 2, 10000); + } finally { + if (requestTimer !== undefined) clearTimeout(requestTimer); + } + } + throw new Error("pageLoad cancelled by document unload"); + } finally { + if (retryTimer !== undefined) clearTimeout(retryTimer); + window.removeEventListener("pagehide", onPageHide); + } + }; + void requestPageLoad().then(async (o) => { + if (!o.ok) { + this.valuePort.stop(); + return; + } const { injectScriptList, contentScriptList, envInfo } = o; - const pairs = {} as Record; + const pairs = new Map(); for (const script of injectScriptList) { - pairs[getStorageName(script)] |= PageOrContent.PAGE; + const name = getStorageName(script); + pairs.set(name, ((pairs.get(name) || 0) | PageOrContent.PAGE) as PageOrContent); } for (const script of contentScriptList) { - pairs[getStorageName(script)] |= PageOrContent.CONTENT; + const name = getStorageName(script); + pairs.set(name, ((pairs.get(name) || 0) | PageOrContent.CONTENT) as PageOrContent); + } + this.activeStorageNames = pairs; + this.stagedScripts = { injectScriptList, contentScriptList }; + const latestScripts = new Map(); + for (const script of [...injectScriptList, ...contentScriptList]) { + const name = getStorageName(script); + const version = { revision: script.valueRevision ?? 0, epoch: script.valueEpoch ?? "" }; + const known = this.versions.get(name); + if (!known || (known.epoch === version.epoch && version.revision > known.revision)) { + this.versions.set(name, version); + latestScripts.set(name, script); + } + } + // Shared storageName scripts can be read at different revisions during pageLoad. + // Normalize only stale snapshots; do not duplicate large value objects on the common path. + for (const script of [...injectScriptList, ...contentScriptList]) { + const latest = latestScripts.get(getStorageName(script)); + if (latest && latest !== script && + latest.valueEpoch === script.valueEpoch && + (latest.valueRevision ?? 0) > (script.valueRevision ?? 0)) { + script.value = { ...latest.value }; + script.valueRevision = latest.valueRevision; + } } - this.activeStorageNames = new Map(Object.entries(pairs)); - // 向页面 发送脚本列表及环境信息 + // The subscription handshake covers updates between pageLoad's snapshot and script execution. + await this.valuePort.subscribe([...pairs.keys()]); + const starts: Promise[] = []; if (contentScriptList.length) { - const contentClient = new Client(this.senderToContent, "content"); - // 根据@inject-into content过滤脚本 - contentClient.do("pageLoad", { scripts: contentScriptList, envInfo }); + starts.push( + new Client(this.senderToContent, "content").do("pageLoad", { scripts: contentScriptList, envInfo }) + ); } - if (injectScriptList.length) { - const injectClient = new Client(this.senderToInject, "inject"); - // 根据@inject-into content过滤脚本 - injectClient.do("pageLoad", { scripts: injectScriptList, envInfo }); + starts.push(new Client(this.senderToInject, "inject").do("pageLoad", { scripts: injectScriptList, envInfo })); + } + const outcomes = await Promise.allSettled(starts); + for (const outcome of outcomes) { + if (outcome.status === "rejected") { + LoggerCore.logger().error("script world startup failed", { error: outcome.reason }); + } + } + this.scriptsStarted = true; + // Changes which raced with the world startup are reconciled once, not replayed as listeners. + for (const name of this.stagedDirty) { + const script = [...injectScriptList, ...contentScriptList].find((item) => getStorageName(item) === name); + const version = this.versions.get(name); + const activeOn = pairs.get(name); + if (script && version && activeOn) { + void this.broadcastToPage( + "runtime/valueSnapshot", + { storageName: name, ...version, values: script.value } satisfies ValueSnapshot, + activeOn + ).catch((error) => LoggerCore.logger().error("startup value snapshot failed", { error })); + } } + this.stagedDirty.clear(); + this.stagedScripts = undefined; + }).catch((error) => { + if (!this.scriptsStarted) this.valuePort.stop(); + LoggerCore.logger().error("pageLoad or value subscription failed", { error }); }); } } diff --git a/src/app/service/content/types.ts b/src/app/service/content/types.ts index 87962e4a4..b415f354b 100644 --- a/src/app/service/content/types.ts +++ b/src/app/service/content/types.ts @@ -23,6 +23,10 @@ export type ValueUpdateData = { sender: ValueUpdateSender; }; +export type ValueVersion = { revision: number; epoch: string }; + +export type ValueSnapshot = ValueVersion & { storageName: string; values: Record }; + export type ValueUpdateDataEncoded = { id?: string; entries: ValueUpdateDataREntry[]; @@ -30,6 +34,15 @@ export type ValueUpdateDataEncoded = { storageName: string; // 储存name sender: ValueUpdateSender; valueUpdated: boolean; + revision?: number; + epoch?: string; +}; + +// An explicit write receipt, issued only after ValueDAO.save succeeds. +// Value notifications are independent and may be lost while a Port reconnects. +export type ValueWriteReceipt = { + committed: true; + update: ValueUpdateDataEncoded; }; // gm_api.ts diff --git a/src/app/service/content/value_port.integration.test.ts b/src/app/service/content/value_port.integration.test.ts new file mode 100644 index 000000000..49ac40a56 --- /dev/null +++ b/src/app/service/content/value_port.integration.test.ts @@ -0,0 +1,39 @@ +import EventEmitter from "eventemitter3"; +import { describe, expect, it, vi } from "vitest"; +import { MockMessage } from "@Packages/message/mock_message"; +import { Server } from "@Packages/message/server"; +import ValueUpdatePorts from "../service_worker/value_port"; +import ScriptingValuePort from "./value_port"; +import type { ValueUpdateDataEncoded } from "./types"; + +describe("scripting ↔ serviceWorker Port 通道", () => { + it("实际消息 Server/Group 协议能完成订阅确认并精准传递 GM 更新", async () => { + const transport = new MockMessage(new EventEmitter()); + const server = new Server("serviceWorker", transport); + const failures = vi.fn(); + const ports = new ValueUpdatePorts(failures); + server.group("runtime").on("valueUpdates", (_, sender) => ports.connect(sender)); + const received = vi.fn(); + const channel = new ScriptingValuePort(transport, received); + channel.start(); + + await channel.subscribe(["script-a"]); + const update: ValueUpdateDataEncoded = { + uuid: "uuid-a", + storageName: "script-a", + id: "set-1", + entries: [], + sender: { runFlag: "", tabId: 1 }, + valueUpdated: true, + }; + ports.push("script-a", update); + ports.push("script-b", { ...update, storageName: "script-b" }); + + expect(received).toHaveBeenCalledExactlyOnceWith(update); + expect(failures).not.toHaveBeenCalled(); + channel.stop(); + received.mockClear(); + ports.push("script-a", update); + expect(received).not.toHaveBeenCalled(); + }); +}); diff --git a/src/app/service/content/value_port.test.ts b/src/app/service/content/value_port.test.ts new file mode 100644 index 000000000..6bdc1ffb6 --- /dev/null +++ b/src/app/service/content/value_port.test.ts @@ -0,0 +1,307 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { MessageConnect, MessageSend, TMessage } from "@Packages/message/types"; +import ScriptingValuePort from "./value_port"; + +class TestPort implements MessageConnect { + sent: TMessage[] = []; + private messageListener: (message: TMessage) => void = () => undefined; + private disconnectListener: (self: boolean) => void = () => undefined; + sendMessage(message: TMessage) { + this.sent.push(message); + } + onMessage(callback: (message: TMessage) => void) { + this.messageListener = callback; + } + onDisconnect(callback: (self: boolean) => void) { + this.disconnectListener = callback; + } + disconnect() { + this.disconnectListener(false); + } + receive(message: TMessage) { + this.messageListener(message); + } +} + +const createSender = (...ports: TestPort[]) => { + const connect = vi.fn().mockImplementation(async () => { + const port = ports.shift(); + if (!port) throw new Error("no test port available"); + return port; + }); + return { sender: { connect } as unknown as MessageSend, connect }; +}; + +describe("ScriptingValuePort 生命周期", () => { + afterEach(() => { + vi.useRealTimers(); + vi.unstubAllGlobals(); + }); + + it("启动即连接,待 SW 确认订阅后才放行页面脚本,按 Port 接收值更新", async () => { + const port = new TestPort(); + const { sender, connect } = createSender(port); + const delivered = vi.fn(); + const channel = new ScriptingValuePort(sender, delivered); + channel.start(); + const ready = channel.subscribe(["shared", "shared", "content"]); + await vi.waitFor(() => expect(connect).toHaveBeenCalledOnce()); + expect(connect).toHaveBeenCalledWith({ action: "serviceWorker/runtime/valueUpdates" }); + port.receive({ code: 0, data: { ready: true } }); + expect(port.sent).toEqual([{ action: "runtime/subscribeValueUpdates", data: ["shared", "content"] }]); + + let subscribed = false; + void ready.then(() => (subscribed = true)); + await Promise.resolve(); + expect(subscribed).toBe(false); + port.receive({ action: "runtime/valueSubscriptionsReady" }); + await ready; + expect(subscribed).toBe(true); + + const update = { storageName: "shared", entries: [] }; + port.receive({ action: "runtime/valueUpdate", data: update }); + expect(delivered).toHaveBeenCalledWith(update); + channel.stop(); + }); + + it("断连重建 Port 并恢复存储订阅,旧 Port 不再使用", async () => { + vi.useFakeTimers(); + const oldPort = new TestPort(); + const newPort = new TestPort(); + const { sender, connect } = createSender(oldPort, newPort); + const channel = new ScriptingValuePort(sender, vi.fn()); + channel.start(); + const ready = channel.subscribe(["a"]); + await Promise.resolve(); + oldPort.receive({ code: 0, data: { ready: true } }); + oldPort.receive({ action: "runtime/valueSubscriptionsReady" }); + await ready; + + oldPort.disconnect(); + await vi.advanceTimersByTimeAsync(1000); + expect(connect).toHaveBeenCalledTimes(2); + newPort.receive({ code: 0, data: { ready: true } }); + expect(newPort.sent).toEqual([{ action: "runtime/subscribeValueUpdates", data: ["a"] }]); + newPort.receive({ action: "runtime/valueSubscriptionsReady" }); + channel.stop(); + }); + + it("没有脚本的 frame 释放 Port,不再尝试重连", async () => { + vi.useFakeTimers(); + const port = new TestPort(); + const { sender, connect } = createSender(port); + const channel = new ScriptingValuePort(sender, vi.fn()); + channel.start(); + await Promise.resolve(); + await channel.subscribe([]); + port.disconnect(); + await vi.advanceTimersByTimeAsync(5000); + expect(connect).toHaveBeenCalledOnce(); + }); + + it("bfcache 恢复时主动重建 Port,确保新 SW 知道订阅", async () => { + const oldPort = new TestPort(); + const newPort = new TestPort(); + const { sender, connect } = createSender(oldPort, newPort); + const channel = new ScriptingValuePort(sender, vi.fn()); + channel.start(); + const ready = channel.subscribe(["a"]); + await Promise.resolve(); + expect(connect).toHaveBeenCalledOnce(); + oldPort.receive({ code: 0, data: { ready: true } }); + oldPort.receive({ action: "runtime/valueSubscriptionsReady" }); + await ready; + + const pageshow = new PageTransitionEvent("pageshow"); + // happy-dom 未实现 PageTransitionEvent.persisted,补上浏览器会提供的字段。 + Object.defineProperty(pageshow, "persisted", { value: true }); + expect(pageshow.persisted).toBe(true); + window.dispatchEvent(pageshow); + await Promise.resolve(); + expect(connect).toHaveBeenCalledTimes(2); + newPort.receive({ code: 0, data: { ready: true } }); + expect(newPort.sent).toEqual([{ action: "runtime/subscribeValueUpdates", data: ["a"] }]); + channel.stop(); + }); + + it("bfcache 恢复时旧连接仍在建立也能重连,迟到的旧 Port 不覆盖新 Port", async () => { + let resolveOld!: (port: MessageConnect) => void; + const oldPortPromise = new Promise((resolve) => (resolveOld = resolve)); + const newPort = new TestPort(); + const oldPort = new TestPort(); + const oldDisconnect = vi.spyOn(oldPort, "disconnect"); + const connect = vi.fn().mockReturnValueOnce(oldPortPromise).mockResolvedValueOnce(newPort); + const channel = new ScriptingValuePort({ connect } as unknown as MessageSend, vi.fn()); + channel.start(); + const ready = channel.subscribe(["a"]); + + const pageshow = new PageTransitionEvent("pageshow"); + Object.defineProperty(pageshow, "persisted", { value: true }); + window.dispatchEvent(pageshow); + await vi.waitFor(() => expect(connect).toHaveBeenCalledTimes(2)); + + resolveOld(oldPort); + await Promise.resolve(); + newPort.receive({ code: 0, data: { ready: true } }); + expect(newPort.sent).toEqual([{ action: "runtime/subscribeValueUpdates", data: ["a"] }]); + expect(oldPort.sent).toEqual([]); + expect(oldDisconnect).toHaveBeenCalledOnce(); + newPort.receive({ action: "runtime/valueSubscriptionsReady" }); + await ready; + channel.stop(); + }); + + it("订阅发送时 Port 已经断开则重试,而非永久卡住 pageLoad", async () => { + vi.useFakeTimers(); + const oldPort = new TestPort(); + const newPort = new TestPort(); + const { sender, connect } = createSender(oldPort, newPort); + const channel = new ScriptingValuePort(sender, vi.fn()); + const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined); + try { + channel.start(); + const ready = channel.subscribe(["a"]); + await Promise.resolve(); + oldPort.sendMessage = () => { + throw new Error("closed"); + }; + oldPort.receive({ code: 0, data: { ready: true } }); + await vi.advanceTimersByTimeAsync(1000); + expect(connect).toHaveBeenCalledTimes(2); + newPort.receive({ code: 0, data: { ready: true } }); + newPort.receive({ action: "runtime/valueSubscriptionsReady" }); + await ready; + expect(errorSpy).toHaveBeenCalledOnce(); + channel.stop(); + } finally { + errorSpy.mockRestore(); + } + }); + it("被动断线立即重连,仅连接失败才退避", async () => { + const oldPort = new TestPort(); + const newPort = new TestPort(); + const { sender, connect } = createSender(oldPort, newPort); + const channel = new ScriptingValuePort(sender, vi.fn()); + channel.start(); + const ready = channel.subscribe(["a"]); + await Promise.resolve(); + oldPort.receive({ code: 0, data: { ready: true } }); + oldPort.receive({ action: "runtime/valueSubscriptionsReady" }); + await ready; + oldPort.disconnect(); + expect(connect).toHaveBeenCalledTimes(2); + await Promise.resolve(); + newPort.receive({ code: 0, data: { ready: true } }); + expect(newPort.sent).toEqual([{ action: "runtime/subscribeValueUpdates", data: ["a"] }]); + channel.stop(); + }); + + it("Port 已连接但 SW 从未发送初始 ready 时也能恢复", async () => { + vi.useFakeTimers(); + const first = new TestPort(); + const second = new TestPort(); + const { sender, connect } = createSender(first, second); + const channel = new ScriptingValuePort(sender, vi.fn()); + channel.start(); + const subscribed = channel.subscribe(["a"]); + await Promise.resolve(); + expect(connect).toHaveBeenCalledOnce(); + await vi.advanceTimersByTimeAsync(31000); + expect(connect).toHaveBeenCalledTimes(2); + second.receive({ code: 0, data: { ready: true } }); + second.receive({ action: "runtime/valueSubscriptionsReady" }); + await subscribed; + channel.stop(); + }); + + it("新存储世代更新抢先送达时,忽略旧世代的迟到 snapshot", async () => { + const port = new TestPort(); + const { sender } = createSender(port); + let version = { epoch: "old", revision: 2 }; + const snapshots = vi.fn(); + const channel = new ScriptingValuePort( + sender, + (update) => { version = { epoch: update.epoch!, revision: update.revision! }; }, + snapshots, + () => ({ shared: version }) + ); + channel.start(); + const ready = channel.subscribe(["shared"]); + await Promise.resolve(); + port.receive({ code: 0, data: { ready: true } }); + port.receive({ action: "runtime/valueUpdate", data: { + storageName: "shared", epoch: "new", revision: 1, + } }); + port.receive({ action: "runtime/valueSubscriptionsReady", data: { + requestId: 1, + snapshots: [{ storageName: "shared", epoch: "old", revision: 3, values: { x: "stale" } }], + } }); + await ready; + expect(snapshots).not.toHaveBeenCalled(); + channel.stop(); + }); + + it("订阅握手超过 30 秒是可恢复的,不会永久终止 pageLoad", async () => { + vi.useFakeTimers(); + const first = new TestPort(); + const second = new TestPort(); + const { sender, connect } = createSender(first, second); + const snapshots = vi.fn(); + const channel = new ScriptingValuePort(sender, vi.fn(), snapshots, () => ({ + "my-store": { epoch: "e", revision: 1 }, + })); + channel.start(); + const ready = channel.subscribe(["my-store"]); + await Promise.resolve(); + first.receive({ code: 0, data: { ready: true } }); + expect(first.sent[0]).toEqual({ + action: "runtime/subscribeValueUpdates", + data: { names: ["my-store"], versions: { "my-store": { epoch: "e", revision: 1 } }, requestId: 1 }, + }); + await vi.advanceTimersByTimeAsync(31000); + expect(connect).toHaveBeenCalledTimes(2); + second.receive({ code: 0, data: { ready: true } }); + second.receive({ action: "runtime/valueSubscriptionsReady", data: { + requestId: 2, + snapshots: [{ storageName: "my-store", epoch: "e", revision: 2, values: { k: 2 } }], + } }); + await ready; + expect(snapshots).toHaveBeenCalledExactlyOnceWith({ + storageName: "my-store", epoch: "e", revision: 2, values: { k: 2 }, + }); + channel.stop(); + }); + + it("旧扩展 context 失效后停止重试,并结算待确认订阅", async () => { + vi.useFakeTimers(); + const connect = vi.fn().mockRejectedValue(new Error("Extension context invalidated")); + const channel = new ScriptingValuePort({ connect } as unknown as MessageSend, vi.fn()); + channel.start(); + const ready = channel.subscribe(["a"]); + const rejected = expect(ready).rejects.toThrow("Extension context invalidated"); + await vi.advanceTimersByTimeAsync(120000); + await rejected; + expect(connect).toHaveBeenCalledOnce(); + channel.stop(); + }); + + it("bfcache 恢复遇到已撤销的 extension context 不再建立连接", async () => { + const port = new TestPort(); + const { sender, connect } = createSender(port); + const channel = new ScriptingValuePort(sender, vi.fn()); + channel.start(); + const ready = channel.subscribe(["a"]); + await Promise.resolve(); + port.receive({ code: 0, data: { ready: true } }); + port.receive({ action: "runtime/valueSubscriptionsReady" }); + await ready; + vi.stubGlobal("chrome", { runtime: { id: undefined } }); + const pageshow = new PageTransitionEvent("pageshow"); + Object.defineProperty(pageshow, "persisted", { value: true }); + window.dispatchEvent(pageshow); + await Promise.resolve(); + expect(connect).toHaveBeenCalledOnce(); + channel.stop(); + }); + +}); diff --git a/src/app/service/content/value_port.ts b/src/app/service/content/value_port.ts new file mode 100644 index 000000000..644775d24 --- /dev/null +++ b/src/app/service/content/value_port.ts @@ -0,0 +1,311 @@ +import type { MessageConnect, MessageSend } from "@Packages/message/types"; +import type { ValueSnapshot, ValueUpdateDataEncoded, ValueVersion } from "./types"; + +type ConnectionState = "active" | "reconnecting" | "terminal" | "stopped"; + +/** One frame owns one Port. Only subscription names survive a recoverable SW restart. */ +export default class ScriptingValuePort { + private port: MessageConnect | undefined; + private connecting = false; + private generation = 0; + private portReady = false; + private state: ConnectionState = "reconnecting"; + private storageNames: string[] | undefined; + private subscription: { resolve: () => void; reject: (error: Error) => void } | undefined; + private subscriptionTimer: ReturnType | undefined; + private retryTimer: ReturnType | undefined; + private retryDelay = 250; + private refreshInFlight = false; + private refreshDirty = false; + private refreshTimer: ReturnType | undefined; + private refreshDelay = 100; + private requestId = 0; + private requestedVersions: Record | undefined; + private readonly onPageShow = (event: PageTransitionEvent) => { + if (!event.persisted || this.isStopped()) return; + if (this.invalidContext()) return this.terminate(); + const port = this.port; + this.port = undefined; + this.portReady = false; + this.generation++; + this.connecting = false; + this.disconnectPort(port); + this.clearRefresh(); + if (this.retryTimer !== undefined) clearTimeout(this.retryTimer); + this.retryTimer = undefined; + this.connect(); + }; + + constructor( + private readonly sender: MessageSend, + private readonly onValueUpdate: (data: ValueUpdateDataEncoded) => void, + private readonly onSnapshot?: (snapshot: ValueSnapshot) => void, + private readonly getVersions?: () => Record, + private readonly needsRefresh?: () => boolean + ) {} + + start() { + if (this.isStopped()) return; + this.connect(); + window.addEventListener("pageshow", this.onPageShow); + } + + subscribe(names: string[]): Promise { + if (!names.length) { + this.stop(); + return Promise.resolve(); + } + if (this.isStopped()) return Promise.reject(new Error("Value update connection is unavailable")); + this.storageNames = [...new Set(names)]; + this.subscription?.reject(new Error("Value subscriptions replaced")); + if (this.subscriptionTimer !== undefined) clearTimeout(this.subscriptionTimer); + return new Promise((resolve, reject) => { + this.subscription = { resolve, reject }; + this.sendSubscriptions(); + }); + } + + stop() { + if (this.state === "stopped") return; + this.state = "stopped"; + this.clearRefresh(); + this.generation++; + this.connecting = false; + window.removeEventListener("pageshow", this.onPageShow); + if (this.retryTimer !== undefined) clearTimeout(this.retryTimer); + this.retryTimer = undefined; + if (this.subscriptionTimer !== undefined) clearTimeout(this.subscriptionTimer); + this.subscriptionTimer = undefined; + this.subscription?.reject(new Error("Value update connection stopped")); + this.subscription = undefined; + const port = this.port; + this.port = undefined; + this.portReady = false; + this.storageNames = undefined; + this.disconnectPort(port); + } + + private isStopped() { + return this.state === "terminal" || this.state === "stopped"; + } + + private invalidContext(error?: unknown): boolean { + if (/Extension context (?:was )?invalidated|context invalidated|Extension has been disconnected/i.test( + String((error as Error | undefined)?.message ?? error ?? "") + )) return true; + // An absent runtime id is a reliable terminal signal in extension content scripts, + // but not necessarily in test/mocked message environments. + try { + return typeof chrome !== "undefined" && !!chrome.runtime && !chrome.runtime.id; + } catch { + return true; + } + } + + private terminate(error = new Error("Extension context invalidated")) { + if (this.isStopped()) return; + this.state = "terminal"; + this.subscription?.reject(error); + this.subscription = undefined; + this.stopResources(); + } + + private stopResources() { + this.clearRefresh(); + this.generation++; + this.connecting = false; + window.removeEventListener("pageshow", this.onPageShow); + if (this.retryTimer !== undefined) clearTimeout(this.retryTimer); + this.retryTimer = undefined; + if (this.subscriptionTimer !== undefined) clearTimeout(this.subscriptionTimer); + this.subscriptionTimer = undefined; + const port = this.port; + this.port = undefined; + this.portReady = false; + this.storageNames = undefined; + this.disconnectPort(port); + } + + private disconnectPort(port?: MessageConnect) { + try { + port?.disconnect(true); + } catch { + // Already invalidated ports cannot always be disconnected through the browser API. + } + } + + private connect() { + if (this.isStopped() || this.connecting || this.port) return; + if (this.invalidContext()) return this.terminate(); + this.connecting = true; + this.state = "reconnecting"; + const generation = this.generation; + let pending: Promise; + try { + pending = this.sender.connect({ action: "serviceWorker/runtime/valueUpdates" }); + } catch (error) { + this.connectionFailed(generation, error); + return; + } + pending.then((port) => { + if (this.isStopped() || generation !== this.generation) { + this.disconnectPort(port); + return; + } + this.connecting = false; + this.port = port; + this.portReady = false; + // A connected Port may never send its initial ready message. Treat that as a + // failed attempt, not an indefinitely pending pageLoad or a terminal context. + this.armSubscriptionTimeout(port); + try { + port.onMessage((message) => { + if (this.port !== port) return; + if (message.code === 0 && message.data?.ready === true) { + this.portReady = true; + this.sendSubscriptions(); + } else if (message.action === "runtime/valueSubscriptionsReady") { + // A previous snapshot read can finish after a newer request on the same Port. + if (this.getVersions && message.data?.requestId !== this.requestId) return; + const snapshots = message.data?.snapshots as ValueSnapshot[] | undefined; + try { + if (Array.isArray(snapshots)) { + const current = this.getVersions?.(); + for (const snapshot of snapshots) { + const sent = this.requestedVersions?.[snapshot.storageName]; + const now = current?.[snapshot.storageName]; + if ( + now && now.epoch !== snapshot.epoch && + (!sent || now.epoch !== sent.epoch || now.revision !== sent.revision) + ) continue; + this.onSnapshot?.(snapshot); + } + } + } catch (error) { + this.failPort(port, error); + return; + } + this.refreshInFlight = false; + const refreshDirty = this.refreshDirty; + this.refreshDirty = false; + if (refreshDirty || this.needsRefresh?.()) this.scheduleRefresh(); + else this.refreshDelay = 100; + this.retryDelay = 250; + this.state = "active"; + const subscription = this.subscription; + this.subscription = undefined; + if (this.subscriptionTimer !== undefined) clearTimeout(this.subscriptionTimer); + this.subscriptionTimer = undefined; + subscription?.resolve(); + } else if (message.code === -1) { + this.failPort(port, message.message); + } else if (message.action === "runtime/valueUpdate") { + this.onValueUpdate(message.data as ValueUpdateDataEncoded); + } + }); + port.onDisconnect(() => { + if (this.port !== port) return; + this.port = undefined; + this.portReady = false; + this.clearRefresh(); + if (this.subscriptionTimer !== undefined) clearTimeout(this.subscriptionTimer); + this.subscriptionTimer = undefined; + if (this.invalidContext()) this.terminate(); + else this.connect(); // First recovery attempt is immediate; back off only after failure. + }); + } catch (error) { + this.failPort(port, error); + } + }).catch((error: unknown) => this.connectionFailed(generation, error)); + } + + private connectionFailed(generation: number, error: unknown) { + if (this.isStopped() || generation !== this.generation) return; + this.connecting = false; + if (this.invalidContext(error)) return this.terminate(new Error("Extension context invalidated")); + this.scheduleReconnect(); + } + + private sendSubscriptions() { + if (!this.portReady || !this.port || !this.storageNames) return; + this.refreshInFlight = true; + this.refreshDirty = false; + try { + const versions = this.getVersions?.(); + const requestId = ++this.requestId; + this.requestedVersions = versions; + this.port.sendMessage({ + action: "runtime/subscribeValueUpdates", + data: versions ? { names: this.storageNames, versions, requestId } : this.storageNames, + }); + this.armSubscriptionTimeout(this.port); + } catch (error) { + this.failPort(this.port, error); + } + } + + // A stalled handshake is a recoverable failed attempt, not a terminal context. + // Keep the initial subscription promise alive across successive connections. + private armSubscriptionTimeout(port: MessageConnect) { + if (this.subscriptionTimer !== undefined) clearTimeout(this.subscriptionTimer); + this.subscriptionTimer = setTimeout(() => { + this.subscriptionTimer = undefined; + if (this.port === port) this.failPort(port, new Error("Value subscription handshake timed out")); + }, 30000); + } + + /** Coalesce gaps without forgetting one observed while a snapshot is in flight. */ + refresh() { + if (!this.portReady || !this.port || this.refreshInFlight) { + this.refreshDirty = true; + return; + } + if (this.refreshTimer !== undefined) return; + this.sendSubscriptions(); + } + + private scheduleRefresh() { + if (this.refreshTimer !== undefined) return; + // A follow-up read must not busy-loop if the database is still catching up. + const delay = this.refreshDelay + Math.random() * this.refreshDelay; + this.refreshDelay = Math.min(this.refreshDelay * 2, 10000); + this.refreshTimer = setTimeout(() => { + this.refreshTimer = undefined; + if (!this.isStopped() && this.portReady && this.port && (this.needsRefresh?.() ?? true)) { + this.sendSubscriptions(); + } else { + this.refreshDelay = 100; + } + }, delay); + } + + private clearRefresh() { + this.refreshInFlight = false; + this.refreshDirty = false; + this.refreshDelay = 100; + if (this.refreshTimer !== undefined) clearTimeout(this.refreshTimer); + this.refreshTimer = undefined; + } + + private failPort(port: MessageConnect, error: unknown) { + if (this.port !== port) return; + this.port = undefined; + this.portReady = false; + this.clearRefresh(); + if (this.subscriptionTimer !== undefined) clearTimeout(this.subscriptionTimer); + this.subscriptionTimer = undefined; + this.disconnectPort(port); + if (this.invalidContext(error)) this.terminate(new Error("Extension context invalidated")); + else this.scheduleReconnect(); + } + + private scheduleReconnect() { + if (this.isStopped() || this.retryTimer !== undefined) return; + const delay = this.retryDelay + Math.random() * this.retryDelay; + this.retryDelay = Math.min(this.retryDelay * 2, 10000); + this.retryTimer = setTimeout(() => { + this.retryTimer = undefined; + this.connect(); + }, delay); + } +} diff --git a/src/app/service/service_worker/client.ts b/src/app/service/service_worker/client.ts index 27ca0a303..459145278 100644 --- a/src/app/service/service_worker/client.ts +++ b/src/app/service/service_worker/client.ts @@ -18,6 +18,7 @@ import type { TPopupPageStatus, } from "./types"; import { Client } from "@Packages/message/client"; +import { MessageResponseLostError } from "@Packages/message/errors"; import type { MessageSend } from "@Packages/message/types"; import type PermissionVerify from "./permission_verify"; import { type UserConfirm } from "./permission_verify"; @@ -122,6 +123,9 @@ export class NetworkRuleClient extends Client { try { result = await this.do(action, data); } catch (error) { + if (error instanceof MessageResponseLostError && action !== "getState") { + throw new NetworkRuleAmbiguousResponseError(); + } throw parseNetworkRuleError(error); } if (result === undefined) { diff --git a/src/app/service/service_worker/client_transport.test.ts b/src/app/service/service_worker/client_transport.test.ts new file mode 100644 index 000000000..c72037250 --- /dev/null +++ b/src/app/service/service_worker/client_transport.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it, vi } from "vitest"; +import type { MessageSend } from "@Packages/message/types"; +import { MessageResponseLostError } from "@Packages/message/errors"; +import { NetworkRuleAmbiguousResponseError, NetworkRuleClient } from "./client"; + +describe("Network Rules ambiguous transport responses", () => { + it("a lost mutation response remains ambiguous, not a confirmed failed write", async () => { + const sender = { + sendMessage: vi.fn().mockRejectedValue(new MessageResponseLostError("message channel closed")), + } as unknown as MessageSend; + const client = new NetworkRuleClient(sender); + await expect(client.retryApply()).rejects.toBeInstanceOf(NetworkRuleAmbiguousResponseError); + }); + + it("an explicit server-side failure retains its structured error code", async () => { + const sender = { + sendMessage: vi.fn().mockResolvedValue({ + code: -1, + message: JSON.stringify({ code: "revision_conflict" }), + }), + } as unknown as MessageSend; + const client = new NetworkRuleClient(sender); + await expect(client.retryApply()).rejects.toEqual({ code: "revision_conflict" }); + }); +}); diff --git a/src/app/service/service_worker/gm_api/gm_api.ts b/src/app/service/service_worker/gm_api/gm_api.ts index a658951ed..da1403df1 100644 --- a/src/app/service/service_worker/gm_api/gm_api.ts +++ b/src/app/service/service_worker/gm_api/gm_api.ts @@ -589,6 +589,31 @@ export default class GMApi { return true; } + // Internal reconciliation for an already authorized GM context. The script identity + // comes from parseRequest, not from a storageName supplied by the page. + @PermissionVerify.API({ + link: [ + "GM_getValue", + "GM_getValues", + "GM_listValues", + "GM_setValue", + "GM_setValues", + "GM_deleteValue", + "GM_deleteValues", + "GM_addValueChangeListener", + "GM_removeValueChangeListener", + ], + }) + async GM_valueSnapshot(request: GMApiRequest, _sender: IGetSender) { + const [values, model] = await this.value.getScriptValueDetails(request.script); + return { + storageName: getStorageName(request.script), + values, + revision: model?.revision ?? 0, + epoch: model?.epoch ?? "", + }; + } + @PermissionVerify.API({ link: ["GM_deleteValue", "GM_deleteValues"] }) async GM_setValue(request: GMApiRequest<[string, string, any?]>, sender: IGetSender) { if (!request.params || request.params.length < 2) { @@ -600,7 +625,7 @@ export default class GMApi { runFlag: request.runFlag, tabId: sender.getSender()?.tab?.id || -1, }; - await this.value.setValues({ uuid: request.script.uuid, id, keyValuePairs, isReplace: false, valueSender }); + return this.value.setValues({ uuid: request.script.uuid, id, keyValuePairs, isReplace: false, valueSender }); } @PermissionVerify.API({ link: ["GM_deleteValues"] }) @@ -613,7 +638,7 @@ export default class GMApi { runFlag: request.runFlag, tabId: sender.getSender()?.tab?.id || -1, }; - await this.value.setValues({ uuid: request.script.uuid, id, keyValuePairs, isReplace: false, valueSender }); + return this.value.setValues({ uuid: request.script.uuid, id, keyValuePairs, isReplace: false, valueSender }); } @PermissionVerify.API() diff --git a/src/app/service/service_worker/index.ts b/src/app/service/service_worker/index.ts index 70b9d7e92..e74d1bd32 100644 --- a/src/app/service/service_worker/index.ts +++ b/src/app/service/service_worker/index.ts @@ -156,7 +156,7 @@ export default class ServiceWorkerManager { runtime.init(); const popup = new PopupService(this.api.group("popup"), this.mq, runtime, scriptDAO, systemConfig); popup.init(); - value.init(runtime, popup); + value.init(runtime); const synchronize = new SynchronizeService( this.offscreenSend, this.api.group("synchronize"), diff --git a/src/app/service/service_worker/runtime.test.ts b/src/app/service/service_worker/runtime.test.ts index ac35581be..c4abc0c11 100644 --- a/src/app/service/service_worker/runtime.test.ts +++ b/src/app/service/service_worker/runtime.test.ts @@ -11,7 +11,7 @@ import { } from "@App/app/repo/scripts"; import { buildScriptRunResourceBasic, getCombinedMeta, scriptURLPatternResults } from "./utils"; import type { SystemConfig } from "@App/pkg/config/config"; -import { SenderRuntime, type Group } from "@Packages/message/server"; +import { SenderRuntime, type Group, type IGetSender } from "@Packages/message/server"; import type { ServiceWorkerMessageSend, WindowMessageBody } from "@Packages/message/window_message"; import type { IMessageQueue } from "@Packages/message/message_queue"; import type { ValueService } from "./value"; @@ -541,7 +541,7 @@ describe.concurrent("RuntimeService - getPageScriptMatchingResultByUrl 脚本匹 }; const mockValueService = { - getScriptValue: vi.fn().mockResolvedValue({}), + getScriptValueDetails: vi.fn().mockResolvedValue([{}, undefined]), }; (mockScriptDAO as any).gets = vi.fn().mockResolvedValue([script]); @@ -573,7 +573,7 @@ describe.concurrent("RuntimeService - getPageScriptMatchingResultByUrl 脚本匹 expect(result).not.toBeNull(); expect(mockCompiledResourceDAO.gets).toHaveBeenCalledTimes(1); expect(mockScriptCodeDAO.get).toHaveBeenCalledWith(script.uuid); - expect(mockValueService.getScriptValue).toHaveBeenCalledTimes(1); + expect(mockValueService.getScriptValueDetails).toHaveBeenCalledTimes(1); expect(result!.injectScriptList.length + result!.contentScriptList.length).toBe(1); }); @@ -587,7 +587,7 @@ describe.concurrent("RuntimeService - getPageScriptMatchingResultByUrl 脚本匹 expect(mockCompiledResourceDAO.gets).toHaveBeenCalledTimes(1); expect(mockScriptCodeDAO.get).toHaveBeenCalledTimes(1); - expect(mockValueService.getScriptValue).toHaveBeenCalledTimes(2); + expect(mockValueService.getScriptValueDetails).toHaveBeenCalledTimes(2); }); it("deleteScriptRuntimeCache 后下一次请求重新从 DAO 获取 compiledResource", async () => { @@ -995,7 +995,7 @@ describe("getScriptsForTab 附加边界场景", () => { getScriptResourceValue: vi.fn().mockResolvedValue({}), getScriptResourceValueByType: vi.fn().mockResolvedValue({ require: {}, "require-css": {}, resource: {} }), }; - const mockValueService = { getScriptValue: vi.fn().mockResolvedValue({}) }; + const mockValueService = { getScriptValueDetails: vi.fn().mockResolvedValue([{}, undefined]) }; (mockScriptDAO as any).gets = vi.fn().mockResolvedValue([script]); (mockScriptDAO as any).scriptCodeDAO = mockScriptCodeDAO; @@ -1480,6 +1480,41 @@ describe("pushValueUpdate 判断是否需要为 early-start 脚本重新编译", }); }); +describe("pushValueUpdate 页面投递", () => { + it("直接向订阅 storageName 的 Port 投递,不使用 tabs API 或 storage 广播", async () => { + const { runtime } = _createRuntimeContext(); + const script = _createMockScript(); + const sendData = { + id: "id-1", + entries: [], + uuid: script.uuid, + storageName: "test-storage", + sender: { runFlag: "", tabId: 2 }, + valueUpdated: false, + }; + let onMessage: (message: TMessage) => void = () => undefined; + const postMessage = vi.fn(); + const port = { + sendMessage: postMessage, + onMessage: (callback: (message: TMessage) => void) => (onMessage = callback), + onDisconnect: vi.fn(), + } as unknown as MessageConnect; + runtime.connectValueUpdates(undefined, { getConnect: () => port } as unknown as IGetSender); + onMessage({ action: "runtime/subscribeValueUpdates", data: ["test-storage"] }); + postMessage.mockClear(); + const tabsSpy = vi.spyOn(chrome.tabs, "sendMessage"); + const querySpy = vi.spyOn(chrome.tabs, "query"); + const setSpy = vi.spyOn(chrome.storage.local, "set"); + + await runtime.pushValueUpdate(script, sendData); + + expect(postMessage).toHaveBeenCalledExactlyOnceWith({ action: "runtime/valueUpdate", data: sendData }); + expect(tabsSpy).not.toHaveBeenCalled(); + expect(querySpy).not.toHaveBeenCalled(); + expect(setSpy).not.toHaveBeenCalled(); + }); +}); + describe("registerUserscripts 注册健康检查", () => { let runtime: RuntimeService; let originalScripting: unknown; diff --git a/src/app/service/service_worker/runtime.ts b/src/app/service/service_worker/runtime.ts index ec2ba95d6..065c38784 100644 --- a/src/app/service/service_worker/runtime.ts +++ b/src/app/service/service_worker/runtime.ts @@ -64,6 +64,7 @@ import { parseUserConfig } from "@App/pkg/utils/yaml"; import type { CompiledResource, Resource, ResourceType } from "@App/app/repo/resource"; import { CompiledResourceDAO, CompiledResourceNamespace } from "@App/app/repo/resource"; import { setOnTabURLChanged } from "./url_monitor"; +import ValueUpdatePorts from "./value_port"; import { scriptToMenu, type TPopupPageLoadInfo, type TPopupPageRestoreInfo } from "./popup_scriptmenu"; import { getExtensionUserAgentData } from "../extension/extension_env"; @@ -131,12 +132,11 @@ export type TScriptsForTab = { const bgScriptStorageNames = new Set(); -// For Firefox, StorageArea.setAccessLevel is not implemented. -// See https://bugzilla.mozilla.org/show_bug.cgi?id=1724754 -// const deliveryStorage = isFirefox() ? chrome.storage.local : chrome.storage.session; -const deliveryStorage = chrome.storage.local; // 日后再处理 - export class RuntimeService { + private readonly valuePorts = new ValueUpdatePorts( + (context, error) => this.logger.error("value update Port delivery failed", context, Logger.E(error)), + (storageName) => this.value.getValueSnapshot(storageName) + ); scriptMatchEnable: UrlMatch = new UrlMatch(); blackMatch: UrlMatch = new UrlMatch(); private gmApi?: GMApi; @@ -477,13 +477,8 @@ export class RuntimeService { public async pushValueUpdate(script: Script, sendData: ValueUpdateDataEncoded) { try { - // 前台腳本 (推送值到tab) - await deliveryStorage!.set({ - valueUpdateDelivery: { - rId: `${Date.now()}.${Math.random()}`, // 用于区分不同的更新,确保 deliveryStorage.onChanged 必能触发 - sendData, - }, - }); + // 直接推送给订阅该 storageName 的存活 frame,不经过 tabs API 或无关 iframe(#1834)。 + this.valuePorts.push(sendData.storageName, sendData); // 後台腳本 if (bgScriptStorageNames.has(sendData.storageName)) { @@ -511,19 +506,12 @@ export class RuntimeService { } } - async setSessionAccessLevel() { - try { - // 让 scripting 存取 chrome.storage.session - await chrome.storage.session.setAccessLevel({ accessLevel: "TRUSTED_AND_UNTRUSTED_CONTEXTS" }); - } catch (e) { - this.logger.error("set session storage access level failed", Logger.E(e)); - } + public connectValueUpdates(_: unknown, sender: IGetSender) { + return this.valuePorts.connect(sender); } init() { - if (deliveryStorage === chrome.storage.session) { - this.setSessionAccessLevel(); - } + this.group.on("valueUpdates", this.connectValueUpdates.bind(this)); // 启动gm api const permission = new PermissionVerify(this.group.group("permission"), this.mq); this.gmApi = new GMApi( @@ -1619,7 +1607,10 @@ export class RuntimeService { await Promise.all( enableScriptList.map(async (script) => { // value(GM 值)会在页面间变化,必须每次页面加载都实时读取,绝不能走页面加载缓存。 - script.value = await value.getScriptValue(script); + const [data, model] = await value.getScriptValueDetails(script); + script.value = data; + script.valueRevision = model?.revision ?? 0; + script.valueEpoch = model?.epoch ?? ""; }) ); diff --git a/src/app/service/service_worker/trash_freeze.test.ts b/src/app/service/service_worker/trash_freeze.test.ts index 67baf063f..9ccd06629 100644 --- a/src/app/service/service_worker/trash_freeze.test.ts +++ b/src/app/service/service_worker/trash_freeze.test.ts @@ -13,7 +13,6 @@ import EventEmitter from "eventemitter3"; import type { ResourceService } from "./resource"; import { createMockOPFS } from "@App/app/repo/test-helpers"; import type { RuntimeService } from "./runtime"; -import type { PopupService } from "./popup"; initTestEnv(); @@ -61,7 +60,7 @@ describe("回收站期间的数据冻结", () => { valueDAO = new ValueDAO(); // 真实挂载 ValueService,使其订阅 deleteScripts const valueService = new ValueService(server.group("value"), mq); - valueService.init({} as RuntimeService, {} as PopupService); + valueService.init({} as RuntimeService); service = new ScriptService( systemConfig, server.group("script"), diff --git a/src/app/service/service_worker/value.test.ts b/src/app/service/service_worker/value.test.ts index 7dcc2ae9a..6637d3217 100644 --- a/src/app/service/service_worker/value.test.ts +++ b/src/app/service/service_worker/value.test.ts @@ -20,7 +20,6 @@ import { TrashScriptDAO, type TrashScript } from "@App/app/repo/trash_script"; import type { TDeleteScript } from "@App/app/service/queue"; import { createMockOPFS } from "@App/app/repo/test-helpers"; import type { RuntimeService } from "./runtime"; -import type { PopupService } from "./popup"; initTestEnv(); @@ -100,6 +99,56 @@ describe("ValueService - setValue 方法测试", () => { vi.restoreAllMocks(); }); + it("用户配置默认值不应污染持久化 GM 数据或版本快照", async () => { + const script = createMockScript({ + config: { + general: { + theme: { title: "Theme", description: "", index: 0, default: "light" }, + }, + }, + }); + const stored = { + uuid: script.uuid, storageName: getStorageName(script), + data: { x: 1 }, revision: 4, epoch: "g", + createtime: 1, updatetime: 1, + } satisfies Value; + vi.mocked(mockValueDAO.get).mockResolvedValue(stored); + + const [pageValue] = await valueService.getScriptValueDetails(script); + expect(pageValue).toEqual({ x: 1, "general.theme": "light" }); + expect(stored.data).toEqual({ x: 1 }); + + const snapshot = await valueService.getValueSnapshot(getStorageName(script)); + expect(snapshot).toEqual({ + storageName: getStorageName(script), values: { x: 1 }, revision: 4, epoch: "g", + }); + }); + + it("持久化 revision 随真实写入单调递增;同值更新不增加 revision", async () => { + const script = createMockScript(); + let record: Value | undefined; + vi.mocked(mockScriptDAO.get).mockResolvedValue(script); + vi.mocked(mockValueDAO.get).mockImplementation(async () => record); + vi.mocked(mockValueDAO.save).mockImplementation(async (_key, value) => { + record = value; + return value; + }); + const commit = (value: number) => valueService.setValues({ + uuid: script.uuid, + id: `write-${value}`, + keyValuePairs: [["x", encodeRValue(value)]], + isReplace: false, + }); + const first = await commit(1); + const repeated = await commit(1); + const second = await commit(2); + expect(first.update.revision).toBe(1); + expect(repeated.update.revision).toBe(1); + expect(second.update.revision).toBe(2); + expect(second.update.epoch).toBe(first.update.epoch); + expect(record?.revision).toBe(2); + }); + it("应该成功设置新脚本的值", async () => { // 准备测试数据 const mockScript = createMockScript(); @@ -113,7 +162,7 @@ describe("ValueService - setValue 方法测试", () => { vi.mocked(mockValueDAO.save).mockResolvedValue({} as any); // 执行测试 - await valueService.setValues({ + const receipt = await valueService.setValues({ uuid: mockScript.uuid, id: "testId-4021", keyValuePairs: [[key, encodeRValue(value)]], @@ -125,6 +174,10 @@ describe("ValueService - setValue 方法测试", () => { expect(mockScriptDAO.get).toHaveBeenCalledWith(mockScript.uuid); expect(mockValueDAO.get).toHaveBeenCalled(); expect(mockValueDAO.save).toHaveBeenCalled(); + expect(receipt).toMatchObject({ + committed: true, + update: { id: "testId-4021", uuid: mockScript.uuid, valueUpdated: true }, + }); expect(valueService.pushValueUpdate).toHaveBeenCalledTimes(1); expect(valueService.pushValueUpdate).toHaveBeenNthCalledWith( 1, @@ -151,6 +204,21 @@ describe("ValueService - setValue 方法测试", () => { expect(savedValue.updatetime).toBeTypeOf("number"); }); + it("持久化失败必须拒绝写入,不能返回已提交的 receipt 或推送消息", async () => { + const script = createMockScript(); + vi.mocked(mockScriptDAO.get).mockResolvedValue(script); + vi.mocked(mockValueDAO.get).mockResolvedValue(undefined); + vi.mocked(mockValueDAO.save).mockRejectedValue(new Error("storage quota exceeded")); + + await expect(valueService.setValues({ + uuid: script.uuid, + id: "failed-write", + keyValuePairs: [["k", encodeRValue("v")]], + isReplace: false, + })).rejects.toThrow("storage quota exceeded"); + expect(valueService.pushValueUpdate).not.toHaveBeenCalled(); + }); + it("应该成功设置新脚本的值 (storageName fallback)", async () => { // 准备测试数据 const mockScript = createMockScript(); @@ -463,7 +531,7 @@ describe("ValueService —— 共享 storagename 的回收站感知", () => { const server = new Server("test", new MockMessage(eventEmitter)); const mq = new MessageQueue(); const service = new ValueService(server.group("value"), mq); - service.init({} as RuntimeService, {} as PopupService); + service.init({} as RuntimeService); const trashDAO = new TrashScriptDAO(); const valueDAO = new ValueDAO(); @@ -510,7 +578,7 @@ describe("ValueService —— 共享 storagename 的回收站感知", () => { const server = new Server("test", new MockMessage(eventEmitter)); const mq = new MessageQueue(); const service = new ValueService(server.group("value"), mq); - service.init({} as RuntimeService, {} as PopupService); + service.init({} as RuntimeService); const valueDAO = new ValueDAO(); const lonely = "lonely-storage"; @@ -528,3 +596,32 @@ describe("ValueService —— 共享 storagename 的回收站感知", () => { expect(await valueDAO.get(lonely)).toBeUndefined(); }); }); + +describe("ValueService pushValueUpdate 投递目标", () => { + const setup = () => { + const server = new Server("test", new MockMessage(new EventEmitter())); + const service = new ValueService(server.group("value"), new MessageQueue()); + const runtime = { pushValueUpdate: vi.fn().mockResolvedValue(undefined) }; + service.init(runtime as unknown as RuntimeService); + return { service, runtime }; + }; + const script = { uuid: "uuid-1", metadata: {} } as Script; + const sendData = (tabId: number) => ({ + id: "id-1", + entries: [], + uuid: "uuid-1", + storageName: "store", + sender: { runFlag: "", tabId }, + valueUpdated: true, + }); + + it("直接交给 Port 索引投递,发起方 tabId 不影响选择", async () => { + const { service, runtime } = setup(); + + await service.pushValueUpdate(script, sendData(1)); + await service.pushValueUpdate(script, sendData(-1)); + + expect(runtime.pushValueUpdate).toHaveBeenNthCalledWith(1, script, sendData(1)); + expect(runtime.pushValueUpdate).toHaveBeenNthCalledWith(2, script, sendData(-1)); + }); +}); diff --git a/src/app/service/service_worker/value.ts b/src/app/service/service_worker/value.ts index 6f5af7ba5..4640e444a 100644 --- a/src/app/service/service_worker/value.ts +++ b/src/app/service/service_worker/value.ts @@ -5,15 +5,21 @@ import { type Value, ValueDAO } from "@App/app/repo/value"; import { TrashScriptDAO } from "@App/app/repo/trash_script"; import type { IGetSender, Group } from "@Packages/message/server"; import { type RuntimeService } from "./runtime"; -import { type PopupService } from "./popup"; import { getStorageName } from "@App/pkg/utils/utils"; -import type { ValueUpdateDataEncoded, ValueUpdateDataREntry, ValueUpdateSender } from "../content/types"; +import type { + ValueUpdateDataEncoded, + ValueUpdateDataREntry, + ValueUpdateSender, + ValueWriteReceipt, +} from "../content/types"; import { type TDeleteScript } from "../queue"; import { type IMessageQueue } from "@Packages/message/message_queue"; import { CACHE_KEY_SET_VALUE } from "@App/app/cache_key"; import { stackAsyncTask } from "@App/pkg/utils/async_queue"; import type { TKeyValuePair } from "@App/pkg/utils/message_value"; import { decodeRValue, R_UNDEFINED, encodeRValue } from "@App/pkg/utils/message_value"; +import { uuidv4 } from "@App/pkg/utils/uuid"; +import type { ValueSnapshot } from "../content/types"; export type TSetValuesParams = { uuid: string; @@ -29,7 +35,6 @@ export class ValueService { scriptDAO: ScriptDAO = new ScriptDAO(); valueDAO: ValueDAO = new ValueDAO(); trashScriptDAO: TrashScriptDAO = new TrashScriptDAO(); - private popup: PopupService | undefined; private runtime: RuntimeService | undefined; constructor( @@ -46,9 +51,11 @@ export class ValueService { if (ret) { data = ret.data; } - const newValues = data; - // 和userconfig组装 + // User-config defaults belong to the page payload, not to persisted GM data. + // Avoid copying a potentially large store for scripts without custom config. const { config } = script; + const newValues = config ? { ...data } : data; + // 和userconfig组装 if (config) { for (const tabKey of Object.keys(config)) { const tab = config![tabKey]; @@ -72,6 +79,16 @@ export class ValueService { return [newValues, ret] as const; } + async getValueSnapshot(storageName: string): Promise { + const value = await this.valueDAO.get(storageName); + return { + storageName, + revision: value?.revision ?? 0, + epoch: value?.epoch ?? "", + values: value?.data ?? {}, + }; + } + getScriptValue(script: Script): Promise> { return this.getScriptValueDetails(script).then((res) => res[0]); } @@ -99,7 +116,9 @@ export class ValueService { let oldValueRecord: ValueStore = {}; const cacheKey = `${CACHE_KEY_SET_VALUE}${storageName}`; const entries = [] as ValueUpdateDataREntry[]; - const _flag = await stackAsyncTask(cacheKey, async () => { + let revision = 0; + let epoch = ""; + await stackAsyncTask(cacheKey, async () => { let valueModel: Value | undefined = await this.valueDAO.get(storageName); if (!valueModel) { const now = Date.now(); @@ -119,6 +138,8 @@ export class ValueService { data: dataModel, createtime: ts ? Math.min(ts, now) : now, updatetime: ts ? Math.min(ts, now) : now, + revision: 1, + epoch: uuidv4(), }; } else { let changed = false; @@ -151,13 +172,21 @@ export class ValueService { } } } - if (!changed) return false; - valueModel.data = dataModel; // 每次储存使用新参考 + if (!changed) { + revision = valueModel.revision ?? 0; + epoch = valueModel.epoch ?? ""; + return false; + } + valueModel.data = dataModel; + valueModel.revision = (valueModel.revision ?? 0) + 1; + valueModel.epoch ||= uuidv4(); // 每次储存使用新参考 } await this.valueDAO.save(storageName, valueModel); + revision = valueModel.revision ?? 0; + epoch = valueModel.epoch ?? ""; return true; }); - // 推送到所有加载了本脚本的tab中 + // 保存成功后只通知在线订阅者;RPC 回执不依赖通知送达。 const valueUpdated = entries.length > 0; const sendData = { id, @@ -166,16 +195,18 @@ export class ValueService { storageName, sender: valueSender, valueUpdated, + revision, + epoch, } as ValueUpdateDataEncoded; this.pushValueUpdate(script, sendData); + return { committed: true, update: sendData } satisfies ValueWriteReceipt; } setScriptValues(params: Pick, _sender: IGetSender) { return this.setValues(params); } - init(runtime: RuntimeService, popup: PopupService) { - this.popup = popup; + init(runtime: RuntimeService) { this.runtime = runtime; this.group.on("getScriptValue", this.getScriptValue.bind(this)); this.group.on("setScriptValues", this.setScriptValues.bind(this)); diff --git a/src/app/service/service_worker/value_port.test.ts b/src/app/service/service_worker/value_port.test.ts new file mode 100644 index 000000000..987198dc1 --- /dev/null +++ b/src/app/service/service_worker/value_port.test.ts @@ -0,0 +1,155 @@ +import { describe, expect, it, vi } from "vitest"; +import type { IGetSender } from "@Packages/message/server"; +import type { MessageConnect, TMessage } from "@Packages/message/types"; +import ValueUpdatePorts from "./value_port"; + +class TestPort implements MessageConnect { + sent: TMessage[] = []; + private messageListener: (message: TMessage) => void = () => undefined; + private disconnectListener: (self: boolean) => void = () => undefined; + sendMessage(message: TMessage) { + this.sent.push(message); + } + onMessage(callback: (message: TMessage) => void) { + this.messageListener = callback; + } + onDisconnect(callback: (self: boolean) => void) { + this.disconnectListener = callback; + } + disconnect() { + this.disconnectListener(true); + } + receive(message: TMessage) { + this.messageListener(message); + } +} + +const senderOf = (port: TestPort) => ({ getConnect: () => port }) as unknown as IGetSender; +const update = { + storageName: "a", + uuid: "script-a", + entries: [], + sender: { runFlag: "", tabId: 1 }, + valueUpdated: true, +}; + +describe("ValueUpdatePorts 精准推送", () => { + it("只向订阅指定 storageName 的 frame Port 推送,同名脚本不重复投递", () => { + const ports = new ValueUpdatePorts(vi.fn()); + const first = new TestPort(); + const second = new TestPort(); + const unrelated = new TestPort(); + expect(ports.connect(senderOf(first))).toEqual({ ready: true }); + ports.connect(senderOf(second)); + ports.connect(senderOf(unrelated)); + first.receive({ action: "runtime/subscribeValueUpdates", data: ["a", "c", "a"] }); + second.receive({ action: "runtime/subscribeValueUpdates", data: ["b", "a"] }); + unrelated.receive({ action: "runtime/subscribeValueUpdates", data: ["b"] }); + + ports.push("a", update); + expect(first.sent).toEqual([ + { action: "runtime/valueSubscriptionsReady" }, + { action: "runtime/valueUpdate", data: update }, + ]); + expect(second.sent).toEqual(first.sent); + expect(unrelated.sent).toEqual([{ action: "runtime/valueSubscriptionsReady" }]); + }); + + it("改订阅和断连立刻清理索引,其他 Port 继续接收", () => { + const ports = new ValueUpdatePorts(vi.fn()); + const first = new TestPort(); + const second = new TestPort(); + ports.connect(senderOf(first)); + ports.connect(senderOf(second)); + first.receive({ action: "runtime/subscribeValueUpdates", data: ["a"] }); + second.receive({ action: "runtime/subscribeValueUpdates", data: ["a"] }); + first.receive({ action: "runtime/subscribeValueUpdates", data: ["b"] }); + second.disconnect(); + + first.sent = []; + second.sent = []; + ports.push("a", update); + expect(first.sent).toEqual([]); + expect(second.sent).toEqual([]); + ports.push("b", update); + expect(first.sent).toEqual([{ action: "runtime/valueUpdate", data: update }]); + }); + + it("坏 Port 发送失败后释放,且不会阻断其他收件方", () => { + const onError = vi.fn(); + const ports = new ValueUpdatePorts(onError); + const bad = new TestPort(); + const good = new TestPort(); + ports.connect(senderOf(bad)); + ports.connect(senderOf(good)); + bad.receive({ action: "runtime/subscribeValueUpdates", data: ["a"] }); + good.receive({ action: "runtime/subscribeValueUpdates", data: ["a"] }); + const error = new Error("disconnected"); + bad.sendMessage = () => { + throw error; + }; + const disconnect = vi.spyOn(bad, "disconnect"); + good.sent = []; + + ports.push("a", update); + ports.push("a", update); + expect(good.sent).toEqual([ + { action: "runtime/valueUpdate", data: update }, + { action: "runtime/valueUpdate", data: update }, + ]); + expect(onError).toHaveBeenCalledOnce(); + expect(onError).toHaveBeenCalledWith({ kind: "push", storageName: "a" }, error); + // 只删除 SW 索引不够:客户端仍可能认为 Port 正常,无法自动重连并重新订阅。 + expect(disconnect).toHaveBeenCalledOnce(); + }); + + it("版本相同不复制 snapshot,版本不同仅发送变化的存储空间", async () => { + const reader = vi.fn(async (storageName: string) => ({ + storageName, + epoch: "generation-1", + revision: 5, + values: { k: 5 }, + })); + const ports = new ValueUpdatePorts(vi.fn(), reader); + const port = new TestPort(); + ports.connect(senderOf(port)); + port.receive({ + action: "runtime/subscribeValueUpdates", + data: { + names: ["matching", "changed"], + requestId: 42, + versions: { + matching: { epoch: "generation-1", revision: 5 }, + changed: { epoch: "generation-1", revision: 4 }, + }, + }, + }); + await vi.waitFor(() => expect(port.sent).toHaveLength(1)); + expect(reader).toHaveBeenCalledTimes(2); + expect(port.sent[0]).toEqual({ + action: "runtime/valueSubscriptionsReady", + data: { + requestId: 42, + snapshots: [{ storageName: "changed", epoch: "generation-1", revision: 5, values: { k: 5 } }], + }, + }); + }); + + it("订阅确认发送失败时关闭 Port,不保留不能确认的订阅", () => { + const onError = vi.fn(); + const ports = new ValueUpdatePorts(onError); + const broken = new TestPort(); + const error = new Error("closed before acknowledgement"); + ports.connect(senderOf(broken)); + broken.sendMessage = () => { + throw error; + }; + const disconnect = vi.spyOn(broken, "disconnect"); + + broken.receive({ action: "runtime/subscribeValueUpdates", data: ["a"] }); + ports.push("a", update); + + expect(disconnect).toHaveBeenCalledOnce(); + expect(onError).toHaveBeenCalledExactlyOnceWith({ kind: "subscribe" }, error); + }); +}); diff --git a/src/app/service/service_worker/value_port.ts b/src/app/service/service_worker/value_port.ts new file mode 100644 index 000000000..06488948a --- /dev/null +++ b/src/app/service/service_worker/value_port.ts @@ -0,0 +1,113 @@ +import type { IGetSender } from "@Packages/message/server"; +import type { MessageConnect } from "@Packages/message/types"; +import type { ValueSnapshot, ValueUpdateDataEncoded, ValueVersion } from "../content/types"; + +// 每个 Port 对应一个 frame,索引只保存该 frame 实际运行的 storageName。 +export default class ValueUpdatePorts { + private readonly byStorageName = new Map>(); + private readonly byPort = new Map>(); + + constructor( + private readonly onSendError: ( + context: { kind: "subscribe" } | { kind: "push"; storageName: string }, + error: unknown + ) => void, + private readonly readSnapshot?: (storageName: string) => Promise + ) {} + + connect(sender: IGetSender) { + const port = sender.getConnect(); + if (!port) throw new Error("valueUpdates requires a Port connection"); + this.byPort.set(port, new Set()); + port.onMessage((message) => { + if (message.action !== "runtime/subscribeValueUpdates") return; + const request = message.data as + | string[] + | { names: string[]; versions?: Record; requestId?: number }; + const names = Array.isArray(request) ? request : request?.names; + if (!Array.isArray(names)) return; + const versions = Array.isArray(request) ? undefined : request.versions; + const requestId = Array.isArray(request) ? undefined : request.requestId; + const storageNames = new Set(names.filter((name): name is string => typeof name === "string")); + this.removeSubscriptions(port); + this.byPort.set(port, storageNames); + for (const name of storageNames) { + let ports = this.byStorageName.get(name); + if (!ports) this.byStorageName.set(name, (ports = new Set())); + ports.add(port); + } + if (!this.readSnapshot || !versions) { + try { + port.sendMessage({ action: "runtime/valueSubscriptionsReady" }); + } catch (error) { + this.removeSubscriptions(port); + this.onSendError({ kind: "subscribe" }, error); + port.disconnect(true); + } + return; + } + // Register first, then read. Concurrent pushes cannot be lost; older snapshots + // are discarded by the receiver's version checks. + void Promise.all( + [...storageNames].map(async (name) => { + if (!this.readSnapshot || !versions) return undefined; + const snapshot = await this.readSnapshot(name); + const known = versions[name]; + return known?.revision === snapshot.revision && known.epoch === snapshot.epoch ? undefined : snapshot; + }) + ) + .then((snapshots) => { + if (!this.byPort.has(port)) return; + port.sendMessage({ + action: "runtime/valueSubscriptionsReady", + data: { + snapshots: snapshots.filter((snapshot): snapshot is ValueSnapshot => !!snapshot), + ...(requestId === undefined ? {} : { requestId }), + }, + }); + }) + .catch((error: unknown) => { + this.removeSubscriptions(port); + this.onSendError({ kind: "subscribe" }, error); + try { + port.disconnect(true); + } catch { + // Port may already have been torn down by the browser. + } + }); + }); + port.onDisconnect(() => this.removeSubscriptions(port)); + return { ready: true }; + } + + push(storageName: string, data: ValueUpdateDataEncoded) { + const ports = this.byStorageName.get(storageName); + if (!ports) return; + for (const port of ports) { + try { + port.sendMessage({ action: "runtime/valueUpdate", data }); + } catch (error) { + // Port 关闭可能先于 onDisconnect 事件;一次失败不影响其他 frame。 + this.removeSubscriptions(port); + // 连接仍可能存活(如 postMessage 序列化失败),必须通知 frame 重连。 + try { + port.disconnect(true); + } catch { + // 清理索引已完成;断开失败也不能阻碍其他 frame。 + } + this.onSendError({ kind: "push", storageName }, error); + } + } + } + + private removeSubscriptions(port: MessageConnect) { + const names = this.byPort.get(port); + if (!names) return; + this.byPort.delete(port); + for (const name of names) { + const ports = this.byStorageName.get(name); + ports?.delete(port); + if (ports?.size === 0) this.byStorageName.delete(name); + } + } +}