Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions changes/fix-serve-wait-longer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
### Исправлено

- **Повтор отправки больше не идёт одновременно с первой попыткой.** Команда и `max serve` ждали ответа MAX одинаково,
по 30 секунд. Если MAX отвечал на границе этого срока, команда успевала отправить сообщение повторно, пока сервер ещё
ждал ответа на первое. Теперь команда ждёт сервер на 5 секунд дольше: сначала приходит ответ сервера, и повтор
уходит только после первой попытки. Второй копии не было и раньше в проверенных случаях: MAX узнаёт повтор по тому же
номеру отправки и не создаёт сообщение заново. Но одновременную отправку двух таких запросов никто не проверял.
3 changes: 3 additions & 0 deletions docs/dev/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 7 additions & 2 deletions src/server/server-connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>) => void
reject: (error: Error) => void
Expand Down Expand Up @@ -162,10 +166,11 @@ export class ServerConnection implements Wire {
this.#id += 1
const id = this.#id
const answer = await new Promise<Record<string, unknown>>((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 }))
})
Expand Down
35 changes: 34 additions & 1 deletion src/server/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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<void>((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<void>((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) =>
Expand Down
Loading