diff --git a/changes/fix-serve-wait-longer.md b/changes/fix-serve-wait-longer.md new file mode 100644 index 00000000..3a63a1bf --- /dev/null +++ b/changes/fix-serve-wait-longer.md @@ -0,0 +1,7 @@ +### Исправлено + +- **Повтор отправки больше не идёт одновременно с первой попыткой.** Команда и `max serve` ждали ответа MAX одинаково, + по 30 секунд. Если MAX отвечал на границе этого срока, команда успевала отправить сообщение повторно, пока сервер ещё + ждал ответа на первое. Теперь команда ждёт сервер на 5 секунд дольше: сначала приходит ответ сервера, и повтор + уходит только после первой попытки. Второй копии не было и раньше в проверенных случаях: MAX узнаёт повтор по тому же + номеру отправки и не создаёт сообщение заново. Но одновременную отправку двух таких запросов никто не проверял. diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 3012bb3e..5dfe36a2 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -228,6 +228,9 @@ message id** and **one** copy, also across two connections and logins — the ca - Measured in Saved messages — the same `cid` resent 5 and 15 minutes after the first send got the first message's id back each time, and one copy stayed. Fifteen minutes is the longest gap measured; beyond it is unproven, and `--operation-id` reuse hours later should not be relied on. +- Through `max serve`, the command waits 5 s longer than the server waits for MAX, so the server's "MAX did not + answer" comes first and the retry follows the first attempt instead of racing it. Two sends with one `cid` in flight + at once were never measured. - `cid` is monotonic per process. `Date.now()` alone gave two sends in one millisecond the same `cid`, and deduplication would have silently dropped the second. A test caught it. - `--silent` sends `notify: false` (normally `true`). ⚠ **Only `true` is measured**; what MAX does diff --git a/src/server/server-connection.ts b/src/server/server-connection.ts index c489e65e..0ecacc56 100644 --- a/src/server/server-connection.ts +++ b/src/server/server-connection.ts @@ -11,6 +11,10 @@ import type { SessionStore } from "../session/store.js" import type { Operation } from "../spec/define.js" import { fromLine, lineReader, toLine } from "./lines.js" +// The server waits for MAX as long as the command would; waiting longer lets its "MAX did not answer" arrive first, so +// a retried send never overlaps the first (RISK-2320): the same `cid` sent again after one is measured to be dropped. +const SERVER_GRACE_MS = 5_000 + interface Pending { resolve: (answer: Record) => void reject: (error: Error) => void @@ -162,10 +166,11 @@ export class ServerConnection implements Wire { this.#id += 1 const id = this.#id const answer = await new Promise>((resolve, reject) => { + const waitMs = this.#timeoutMs + SERVER_GRACE_MS const timer = setTimeout(() => { this.#pending.delete(id) - reject(new Error(`max serve did not answer within ${this.#timeoutMs}ms`)) - }, this.#timeoutMs) + reject(new Error(`max serve did not answer within ${waitMs}ms`)) + }, waitMs) this.#pending.set(id, { resolve, reject, timer }) socket.write(toLine({ id, ...request })) }) diff --git a/src/server/server.test.ts b/src/server/server.test.ts index 5ca05994..1d9836e1 100644 --- a/src/server/server.test.ts +++ b/src/server/server.test.ts @@ -8,7 +8,7 @@ import { rememberAccount, repliesPathFor } from "@wirecat/cli-core/cli" import { guardedWrite, RecipientList, SendJournal } from "@wirecat/cli-core/sends" import { openStore } from "@wirecat/cli-core/store" import { Command } from "commander" -import { afterEach, describe, expect, it } from "vitest" +import { afterEach, describe, expect, it, vi } from "vitest" import { MAX_APP } from "../app.js" import { MaxClient } from "../client.js" import { contextFor } from "../commands/context.js" @@ -1450,6 +1450,39 @@ describe("starting a server in the background", () => { server.close() }) + it("waits past its own timeout for the server, so a retried send never overlaps the first (RISK-2320)", async () => { + const store = new SessionStore({ profile: "v-grace", keyring: memoryKeyring() }) + let answer: (() => void) | undefined + let received: () => void = () => {} + const arrived = new Promise((resolve) => { + received = resolve + }) + const server = createServer((socket) => + socket.on( + "data", + lineReader((line) => { + const { id } = fromLine(line) + answer = () => socket.write(toLine({ id, payload: { ok: true } })) + received() + }), + ), + ) + await new Promise((resolve) => server.listen(store.socketPath(), () => resolve())) + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }) + try { + const wire = new ServerConnection({ path: store.socketPath(), store, timeoutMs: 30_000 }) + const reply = wire.invoke(Opcode.MSG_SEND, {}) + await arrived + vi.advanceTimersByTime(30_001) + answer?.() + await expect(reply).resolves.toEqual({ ok: true }) + await wire.close() + } finally { + vi.useRealTimers() + server.close() + } + }) + it("lets `ensure` check the server before the first request, even one that answers, and only once", async () => { const store = new SessionStore({ profile: "v-ensure", keyring: memoryKeyring() }) const server = createServer((socket) =>