Repository navigation
feat(websocket): post approved regulations to Telegram on the backend's request - #161
Conversation
…'s request Handle the backend's new `postRegulation` Socket.IO command: post an Italian HTML announcement (title, approving body, delibera date, opposition/appeal deadline, release link) with the new regulation PDF and the differences PDF to the chat and topic the backend names. The documents go out as one media group captioned on the last document, or as a message followed by the documents when the text does not fit in a caption. Telegram 429s are waited out and retried (5 attempts, 120 s of waiting at most); nothing else is retried, so a post is never duplicated. The ack reports the posted message ids and time, or the error plus any messages already posted.
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 49 minutes. View limit details
No actionable comments were generated in the recent review. WalkthroughThe change adds payload validation, Telegram text and document delivery, rate-limit retries, and in-memory idempotency. A WebSocket event handler invokes the posting operation and acknowledges with message IDs and any error. ChangesRegulation posting
Sequence Diagram(s)sequenceDiagram
participant WebSocketClient
participant IdempotentPosts
participant postRegulation
participant TelegramAPI
WebSocketClient->>IdempotentPosts: Run posting with optional idempotency key
IdempotentPosts->>postRegulation: Invoke posting operation
postRegulation->>TelegramAPI: Send text or documents
TelegramAPI-->>postRegulation: Return message IDs or error
postRegulation-->>IdempotentPosts: Return posting result
IdempotentPosts-->>WebSocketClient: Return result for acknowledgement
Change: Feature Merge Risk:
|
Build against the shape the backend defines in src/websocket/telegram.ts:
post the backend's ready `text` (no formatting in the bot), files carry a
contentType, and the ack is `cb(error, { messageIds })`.
Wait at most 30 s on rate limits so the bot answers inside the backend's
60 s ack timeout, and dedupe on an optional `idempotencyKey`: a command
repeated while the first is in flight, or after it succeeded, gets the first
answer instead of posting again. Failures are forgotten so a retry reposts.
BREAKING CHANGE: the postRegulation payload and ack changed; nothing sends
the command yet.
… idempotency key The backend's Bun socket.io engine does not deliver binary attachments, so the backend now sends each file as `base64: string`; the bot decodes it and refuses non-base64 content. `idempotencyKey` is now always sent (the backend's notification id), so it is required: a payload without it is refused before any Telegram call. BREAKING CHANGE: postRegulation files carry `base64` instead of `data`, and `idempotencyKey` is required.
The backend replaced regulation.releaseUrl with dashboardUrl (the legal repo is private). The bot does not read regulation, so only its declared type and the test fixture change.
Telegram side of the regulations editor (spec decision 12,
postRegulationcontract). The backend sendspostRegulationover the existing Socket.IO channel. The bot posts the backend's text with the new regulation PDF and the differences PDF to the chat and topic it is given, then acks with the message ids so the backend can record the send.Contract
PostRegulationfrom PoliNetworkOrg/backend#117 (src/websocket/telegram.ts):The files travel as base64, not bytes:
@socket.io/bun-engine0.1.0 doesn't deliver socket.io binary attachments. The bot decodes withBuffer.from(base64, "base64").@polinetwork/backendv4 doesn't export the command yet, so the type is declared locally (PostRegulationEvents). Once a published SDK has it, theBotSockettype inwebsocket.tscan go. The bot validates with zod only the fields it uses.Behaviour
sendMediaGroupof documents in the topic, withtextas the caption (HTML) of the last document. Telegram shows a document's caption under that document: on the last one it reads as the album's caption, on the first it would sit between the two PDFs. A single file goes out withsendDocument. A text longer than 1024 visible characters goes out first as its own message, and the documents follow uncaptioned. The backend's ~600 characters fit as a caption.cb(null, { messageIds }). On failure:cb(reason, { messageIds }), wheremessageIdslists anything posted before the failure (usually empty). A payload that fails validation is refused before any Telegram call.retry_afterand tries again, up to 5 attempts and 30 s of waiting in total. With the uploads, that keeps the answer inside the backend's 60 s ack timeout. No other error is retried, because a retry could post twice.idempotencyKeyit has already seen, repeated while the first is still running waits for it and gets its answer. One repeated after a success, within 24 h, gets the same message ids without posting again. Failures are forgotten so a retry posts again. The keys live in memory, so a bot restart forgets them.Backend notes (PoliNetworkOrg/backend#117)
timeout(60_000).emit(..., (timeout, err, result) => …).href.regulation.releaseUrlbecamedashboardUrl: string | null; the bot never read it.Verification
pnpm test: 224 passed after merging currentmain(1 skipped test was already skipped before this PR);pnpm typecheckandpnpm checkare clean.tests/post-regulation.test.tscovers media group vs. single document vs. separate message, the topic going through, base64 decoding to the exact bytes, the caption limit counted on visible text, 429 retry with its attempt and 30 s limits, a partial send being reported, invalid payloads (including non-base64 content and a missing key), and idempotency (repeat while in flight, after success, after the TTL, after a failure, no key).socket.ioserver with@socket.io/devalue-parser, standing in for the backend, sent the backend's exact shape with a 3 MB and a 200 KB PDF. It sent the same command twice with the same key, 0.5 s apart.autoRetry+parseMode("MarkdownV2")transformers asbot.ts.Apipointed at a local fake Bot API server that parses the multipart upload and answers the firstsendMediaGroupwith a 429 (retry_after: 4).parse_mode: "HTML"andmessage_thread_idwent through, the bot retried after 4 s, the repeated command made no extra Telegram call, andemitwith a callback received(null, null, { messageIds: [500, 501] }).@socket.io/bun-engine0.1.0 +socket.io4.8.3 + devalue parser):server.ts:/ws/routed toengine.handleRequest, with the engine's websocket handlers.timeout(60_000).emitcallback asWebSocketServer.postRegulationand the backend's exact text.RaccoltaRegolamentiInterni.pdf(4 MB) anddifferenze-rri-v2026.11.02.pdf(300 KB), as base64.WS_PATH, both with default transports (polling, then upgrade) and websocket-only.{ messageIds: [500, 501] }. A second notification to a chat Telegram refuses came back to the backend assendMediaGroup: 400 Bad Request: chat not found.Uint8Arrayfiles failed: the bot's decoder threwgot plaintext data when reconstructing a packetand dropped the connection, matching what the backend thread found.