From ad0c2310325154b59b8bb5523e29a132a82326f8 Mon Sep 17 00:00:00 2001 From: Stephan Richter Date: Wed, 8 Apr 2026 16:16:55 -0400 Subject: [PATCH 01/10] feat(jsonrpc2): add manual receive mode to prevent message loss MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In the default 'on-start' receive mode, signal-cli's daemon auto-pulls inbound messages and pushes them to its JSON-RPC clients the moment they arrive from the Signal servers. If no websocket subscriber is currently attached to /v1/receive/{number} — for example during a brief subscriber redeploy — the receiver loop in signal-cli-rest-api drops the message via a non-blocking channel send (see the 'no receiver' debug log in ReceiveData). signal-cli has already acknowledged the message to Signal, so it is never redelivered. Add support for signal-cli's --receive-mode=manual, opt-in via the new JSON_RPC_RECEIVE_MODE=manual environment variable. In manual mode signal-cli does NOT auto-receive; signal-cli-rest-api now issues subscribeReceive when a websocket subscriber attaches and unsubscribeReceive when the last subscriber detaches. While no subscriber is attached, signal-cli does not pull messages from the Signal servers, so they remain buffered server-side under Signal's normal retention rules and are delivered to the next subscriber that attaches. Implementation: * jsonrpc2-helper.go: thread JSON_RPC_RECEIVE_MODE through to the daemon launch command line. * jsonrpc2.go: add per-account subscription tracking with refcounting; subscribeReceive/unsubscribeReceive helpers; an unwrap step in ReceiveData so manual-mode notifications ({subscription,result}) and auto-mode notifications (envelope directly) reach downstream consumers in the same shape. * client.go, api.go: thread the account number through GetReceiveChannel so the JsonRpc2Client can attach the right subscription. The change is fully backward compatible: when JSON_RPC_RECEIVE_MODE is unset or set to 'on-start', signal-cli runs in auto mode and the new subscribeReceive code path is bypassed (account is empty, no RPC issued). Closes #255 (the same root cause: no subscriber → 'no receiver' drop). --- src/api/api.go | 2 +- src/client/client.go | 4 +- src/client/jsonrpc2.go | 140 ++++++++++++++++++++++++++++++--- src/scripts/jsonrpc2-helper.go | 20 ++++- 4 files changed, 150 insertions(+), 16 deletions(-) diff --git a/src/api/api.go b/src/api/api.go index a0304fc..ce447eb 100644 --- a/src/api/api.go +++ b/src/api/api.go @@ -572,7 +572,7 @@ func (a *Api) SendV2(c *gin.Context) { } func (a *Api) handleSignalReceive(ws *websocket.Conn, number string, stop chan struct{}) { - receiveChannel, channelUuid, err := a.signalClient.GetReceiveChannel() + receiveChannel, channelUuid, err := a.signalClient.GetReceiveChannel(number) if err != nil { log.Error("Couldn't get receive channel: ", err.Error()) return diff --git a/src/client/client.go b/src/client/client.go index d02eb36..5ba9fa5 100644 --- a/src/client/client.go +++ b/src/client/client.go @@ -1059,12 +1059,12 @@ func (s *SignalClient) Receive(number string, timeout int64, ignoreAttachments b } } -func (s *SignalClient) GetReceiveChannel() (chan JsonRpc2ReceivedMessage, string, error) { +func (s *SignalClient) GetReceiveChannel(number string) (chan JsonRpc2ReceivedMessage, string, error) { jsonRpc2Client, err := s.getJsonRpc2Client() if err != nil { return nil, "", err } - return jsonRpc2Client.GetReceiveChannel() + return jsonRpc2Client.GetReceiveChannel(number) } func (s *SignalClient) RemoveReceiveChannel(channelUuid string) { diff --git a/src/client/jsonrpc2.go b/src/client/jsonrpc2.go index ef00633..5d0d62f 100644 --- a/src/client/jsonrpc2.go +++ b/src/client/jsonrpc2.go @@ -5,6 +5,7 @@ import ( "bytes" "encoding/json" "errors" + "fmt" "net" "net/http" "strconv" @@ -56,15 +57,26 @@ func (r *RateLimitErrorType) Error() string { return r.Err.Error() } +// receiveSubscription tracks the state of a manual-mode signal-cli +// subscribeReceive call: the subscription id assigned by signal-cli and +// a refcount of websocket subscribers attached to that account. +type receiveSubscription struct { + id int64 + refcount int +} + type JsonRpc2Client struct { - conn net.Conn - receivedResponsesById map[string]chan JsonRpc2MessageResponse - receivedMessagesChannels map[string]chan JsonRpc2ReceivedMessage - signalCliApiConfig *utils.SignalCliApiConfig - number string - receivedMessagesMutex sync.Mutex - receivedResponsesMutex sync.Mutex - address string + conn net.Conn + receivedResponsesById map[string]chan JsonRpc2MessageResponse + receivedMessagesChannels map[string]chan JsonRpc2ReceivedMessage + receiveSubscriptions map[string]*receiveSubscription // account -> sub state + channelAccountByUuid map[string]string // channelUuid -> account + signalCliApiConfig *utils.SignalCliApiConfig + number string + receivedMessagesMutex sync.Mutex + receivedResponsesMutex sync.Mutex + receiveSubscriptionsMutex sync.Mutex + address string } func NewJsonRpc2Client(signalCliApiConfig *utils.SignalCliApiConfig, number string) *JsonRpc2Client { @@ -73,6 +85,8 @@ func NewJsonRpc2Client(signalCliApiConfig *utils.SignalCliApiConfig, number stri number: number, receivedResponsesById: make(map[string]chan JsonRpc2MessageResponse), receivedMessagesChannels: make(map[string]chan JsonRpc2ReceivedMessage), + receiveSubscriptions: make(map[string]*receiveSubscription), + channelAccountByUuid: make(map[string]string), } } @@ -236,6 +250,19 @@ func (r *JsonRpc2Client) ReceiveData(number string, receiveWebhookUrl string) { var resp1 JsonRpc2ReceivedMessage json.Unmarshal([]byte(str), &resp1) if resp1.Method == "receive" { + // In manual receive-mode signal-cli wraps the envelope in + // {"subscription":N,"result":{...}}; in auto mode it sends + // the envelope directly. Unwrap so the broadcast format is + // the same in both modes and downstream consumers (e.g. the + // websocket handler) don't have to know which mode is in use. + var manualWrapper struct { + Subscription int64 `json:"subscription"` + Result json.RawMessage `json:"result"` + } + if err := json.Unmarshal(resp1.Params, &manualWrapper); err == nil && len(manualWrapper.Result) > 0 { + resp1.Params = manualWrapper.Result + } + r.receivedMessagesMutex.Lock() for _, c := range r.receivedMessagesChannels { select { @@ -244,7 +271,6 @@ func (r *JsonRpc2Client) ReceiveData(number string, receiveWebhookUrl string) { default: log.Debug("Couldn't send message to golang channel, as there's no receiver") } - continue } r.receivedMessagesMutex.Unlock() @@ -270,16 +296,102 @@ func (r *JsonRpc2Client) ReceiveData(number string, receiveWebhookUrl string) { } } -func (r *JsonRpc2Client) GetReceiveChannel() (chan JsonRpc2ReceivedMessage, string, error) { - c := make(chan JsonRpc2ReceivedMessage) +// subscribeReceive starts receiving messages for an account by calling +// signal-cli's subscribeReceive JSON-RPC method. Only relevant when +// signal-cli was launched with --receive-mode=manual; in auto mode the +// daemon pushes notifications without an explicit subscribe call. +// Returns the subscription id assigned by signal-cli. +func (r *JsonRpc2Client) subscribeReceive(account string) (int64, error) { + type subscribeReceiveArgs struct{} + resultStr, err := r.getRaw("subscribeReceive", &account, subscribeReceiveArgs{}) + if err != nil { + return 0, err + } + var subscriptionId int64 + if err := json.Unmarshal([]byte(resultStr), &subscriptionId); err != nil { + return 0, fmt.Errorf("subscribeReceive: couldn't parse subscription id from %q: %w", resultStr, err) + } + return subscriptionId, nil +} + +// unsubscribeReceive cancels a manual-mode subscription previously +// returned by subscribeReceive. +func (r *JsonRpc2Client) unsubscribeReceive(account string, subscriptionId int64) error { + type unsubscribeReceiveArgs struct { + Subscription int64 `json:"subscription"` + } + _, err := r.getRaw("unsubscribeReceive", &account, unsubscribeReceiveArgs{Subscription: subscriptionId}) + return err +} + +// acquireReceiveSubscription ensures an active manual-mode subscription +// exists for the given account, refcounting concurrent websocket +// subscribers. The first caller for an account triggers a real +// subscribeReceive RPC; subsequent callers just bump the refcount. +func (r *JsonRpc2Client) acquireReceiveSubscription(account string) error { + r.receiveSubscriptionsMutex.Lock() + defer r.receiveSubscriptionsMutex.Unlock() + + if sub, ok := r.receiveSubscriptions[account]; ok { + sub.refcount++ + return nil + } + id, err := r.subscribeReceive(account) + if err != nil { + return err + } + r.receiveSubscriptions[account] = &receiveSubscription{id: id, refcount: 1} + log.Infof("Subscribed to receive notifications for account %s (subscription=%d)", account, id) + return nil +} + +// releaseReceiveSubscription decrements the per-account refcount and +// cancels the subscription with signal-cli if it drops to zero. +func (r *JsonRpc2Client) releaseReceiveSubscription(account string) { + r.receiveSubscriptionsMutex.Lock() + defer r.receiveSubscriptionsMutex.Unlock() + + sub, ok := r.receiveSubscriptions[account] + if !ok { + return + } + sub.refcount-- + if sub.refcount > 0 { + return + } + if err := r.unsubscribeReceive(account, sub.id); err != nil { + log.Warnf("unsubscribeReceive failed for account %s (subscription=%d): %s", account, sub.id, err.Error()) + } else { + log.Infof("Unsubscribed from receive notifications for account %s (subscription=%d)", account, sub.id) + } + delete(r.receiveSubscriptions, account) +} + +// GetReceiveChannel returns a channel that will receive messages for the +// given account. If signal-cli is in manual receive-mode, it also acquires +// a subscription so that signal-cli starts forwarding messages for the +// account; in auto mode, account is unused (notifications flow regardless). +// +// account may be empty when the caller does not need a subscription +// (e.g. legacy callers in auto mode); in that case no subscribeReceive +// RPC is issued. +func (r *JsonRpc2Client) GetReceiveChannel(account string) (chan JsonRpc2ReceivedMessage, string, error) { + c := make(chan JsonRpc2ReceivedMessage, 64) channelUuid, err := uuid.NewV4() if err != nil { return c, "", err } + if account != "" { + if err := r.acquireReceiveSubscription(account); err != nil { + return c, "", fmt.Errorf("subscribeReceive failed for account %s: %w", account, err) + } + } + r.receivedMessagesMutex.Lock() r.receivedMessagesChannels[channelUuid.String()] = c + r.channelAccountByUuid[channelUuid.String()] = account r.receivedMessagesMutex.Unlock() return c, channelUuid.String(), nil @@ -288,5 +400,11 @@ func (r *JsonRpc2Client) GetReceiveChannel() (chan JsonRpc2ReceivedMessage, stri func (r *JsonRpc2Client) RemoveReceiveChannel(channelUuid string) { r.receivedMessagesMutex.Lock() delete(r.receivedMessagesChannels, channelUuid) + account := r.channelAccountByUuid[channelUuid] + delete(r.channelAccountByUuid, channelUuid) r.receivedMessagesMutex.Unlock() + + if account != "" { + r.releaseReceiveSubscription(account) + } } diff --git a/src/scripts/jsonrpc2-helper.go b/src/scripts/jsonrpc2-helper.go index 96a4c34..2c8a75b 100644 --- a/src/scripts/jsonrpc2-helper.go +++ b/src/scripts/jsonrpc2-helper.go @@ -13,7 +13,7 @@ import ( const supervisorctlConfigTemplate = ` [program:%s] process_name=%s -command=%s --output=json --config %s%s daemon %s%s%s%s --tcp 127.0.0.1:%d +command=%s --output=json --config %s%s daemon%s %s%s%s%s --tcp 127.0.0.1:%d autostart=true autorestart=true startretries=10 @@ -75,6 +75,22 @@ func main() { signalCliIgnoreStickers = " --ignore-stickers" } + // Receive mode: by default signal-cli auto-receives messages on the + // daemon and pushes them as JSON-RPC notifications, regardless of + // whether any websocket subscriber is connected. In a deploy where + // the subscribing client briefly disconnects, those notifications + // have nowhere to go and are silently dropped. With manual receive + // mode, signal-cli only fetches messages when explicitly requested + // via subscribeReceive — see jsonrpc2.go — so messages stay buffered + // on the Signal servers until a subscriber re-attaches. + signalCliReceiveMode := "" + receiveMode := utils.GetEnv("JSON_RPC_RECEIVE_MODE", "") + if receiveMode == "manual" { + signalCliReceiveMode = " --receive-mode=manual" + } else if receiveMode != "" && receiveMode != "on-start" { + log.Fatal("Invalid JSON_RPC_RECEIVE_MODE environment variable set! Must be 'manual' or 'on-start'.") + } + supervisorctlProgramName := "signal-cli-json-rpc-1" supervisorctlLogFolder := "/var/log/" + supervisorctlProgramName _, err := exec.Command("mkdir", "-p", supervisorctlLogFolder).Output() @@ -100,7 +116,7 @@ func main() { supervisorctlConfigFilename := "/etc/supervisor/conf.d/" + "signal-cli-json-rpc-1.conf" supervisorctlConfig := fmt.Sprintf(supervisorctlConfigTemplate, supervisorctlProgramName, supervisorctlProgramName, signalCliBinary, - signalCliConfigDir, trustNewIdentities, signalCliIgnoreAttachments, signalCliIgnoreStories, + signalCliConfigDir, trustNewIdentities, signalCliReceiveMode, signalCliIgnoreAttachments, signalCliIgnoreStories, signalCliIgnoreAvatars, signalCliIgnoreStickers, tcpPort, supervisorctlProgramName, supervisorctlProgramName) From e98c03e702efaed305be0d1a5379ea1b3a8d2f2f Mon Sep 17 00:00:00 2001 From: Stephan Richter Date: Wed, 8 Apr 2026 16:59:19 -0400 Subject: [PATCH 02/10] docs: document JSON_RPC_RECEIVE_MODE in README --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 316bb21..9c73d36 100644 --- a/README.md +++ b/README.md @@ -160,3 +160,4 @@ There are a bunch of environmental variables that can be set inside the docker c * `JSON_RPC_IGNORE_AVATARS`: When set to `true`, avatars are not automatically downloaded in json-rpc mode (default: `false`) * `JSON_RPC_IGNORE_STICKERS`: When set to `true`, sticker packs are not automatically downloaded in json-rpc mode (default: `false`) * `JSON_RPC_TRUST_NEW_IDENTITIES`: Choose how to trust new identities in json-rpc mode. Supported values: `on-first-use`, `always`, `never`. (default: `on-first-use`) +* `JSON_RPC_RECEIVE_MODE`: Controls when signal-cli pulls inbound messages from the Signal servers in json-rpc mode. Supported values: `on-start` (default), `manual`. In the default `on-start` mode, signal-cli auto-receives messages and pushes them as JSON-RPC notifications regardless of whether any websocket subscriber is currently attached to `/v1/receive/{number}` — messages arriving while no subscriber is attached (e.g. during a brief subscriber redeploy) are silently dropped. In `manual` mode signal-cli only fetches messages while at least one websocket subscriber is attached; while no subscriber is attached, messages remain queued server-side under Signal's normal retention rules and are delivered on the next subscriber re-attach. Recommended for any deployment where the websocket consumer is restarted or scaled. From 453fcfad902b632f3d1b7c2b99040c4d59bd4463 Mon Sep 17 00:00:00 2001 From: Mykola Balakin Date: Wed, 12 Aug 2026 00:03:27 +0300 Subject: [PATCH 03/10] Delete excess check (review fixes) --- src/client/jsonrpc2.go | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/client/jsonrpc2.go b/src/client/jsonrpc2.go index 5d0d62f..b3bfb43 100644 --- a/src/client/jsonrpc2.go +++ b/src/client/jsonrpc2.go @@ -383,10 +383,8 @@ func (r *JsonRpc2Client) GetReceiveChannel(account string) (chan JsonRpc2Receive return c, "", err } - if account != "" { - if err := r.acquireReceiveSubscription(account); err != nil { - return c, "", fmt.Errorf("subscribeReceive failed for account %s: %w", account, err) - } + if err := r.acquireReceiveSubscription(account); err != nil { + return c, "", fmt.Errorf("subscribeReceive failed for account %s: %w", account, err) } r.receivedMessagesMutex.Lock() From 68ca0107f9c69adfccc4762dc1ae27120359f996 Mon Sep 17 00:00:00 2001 From: Mykola Balakin Date: Tue, 13 Oct 2026 22:44:13 +0300 Subject: [PATCH 04/10] Fix double subscription in the on-start receive mode --- src/client/client.go | 6 ++-- src/client/jsonrpc2.go | 74 +++++++++++++++++++----------------------- src/main.go | 4 ++- 3 files changed, 40 insertions(+), 44 deletions(-) diff --git a/src/client/client.go b/src/client/client.go index 276eed6..1df7b47 100644 --- a/src/client/client.go +++ b/src/client/client.go @@ -406,10 +406,11 @@ type SignalClient struct { signalCliApiConfig *utils.SignalCliApiConfig cliClient *CliClient receiveWebhookUrl string + receiveManualMode bool } func NewSignalClient(signalCliConfig string, attachmentTmpDir string, avatarTmpDir string, signalCliMode SignalCliMode, - jsonRpc2ClientConfigPath string, signalCliApiConfigPath string, receiveWebhookUrl string) *SignalClient { + jsonRpc2ClientConfigPath string, signalCliApiConfigPath string, receiveWebhookUrl string, receiveManualMode bool) *SignalClient { return &SignalClient{ signalCliConfig: signalCliConfig, attachmentTmpDir: attachmentTmpDir, @@ -419,6 +420,7 @@ func NewSignalClient(signalCliConfig string, attachmentTmpDir string, avatarTmpD jsonRpc2Clients: make(map[string]*JsonRpc2Client), signalCliApiConfigPath: signalCliApiConfigPath, receiveWebhookUrl: receiveWebhookUrl, + receiveManualMode: receiveManualMode, } } @@ -442,7 +444,7 @@ func (s *SignalClient) Init(maxRetries int) error { tcpPortsNumberMapping := s.jsonRpc2ClientConfig.GetTcpPortsForNumbers() for number, tcpPort := range tcpPortsNumberMapping { - s.jsonRpc2Clients[number] = NewJsonRpc2Client(s.signalCliApiConfig, number) + s.jsonRpc2Clients[number] = NewJsonRpc2Client(s.signalCliApiConfig, number, s.receiveManualMode) err := s.jsonRpc2Clients[number].Dial("127.0.0.1:"+strconv.FormatInt(tcpPort, 10), maxRetries) if err != nil { return err diff --git a/src/client/jsonrpc2.go b/src/client/jsonrpc2.go index 93f171a..69935eb 100644 --- a/src/client/jsonrpc2.go +++ b/src/client/jsonrpc2.go @@ -66,23 +66,25 @@ type receiveSubscription struct { } type JsonRpc2Client struct { - conn net.Conn - receivedResponsesById map[string]chan JsonRpc2MessageResponse - receivedMessagesChannels map[string]chan JsonRpc2ReceivedMessage - receiveSubscriptions map[string]*receiveSubscription // account -> sub state - channelAccountByUuid map[string]string // channelUuid -> account - signalCliApiConfig *utils.SignalCliApiConfig - number string - receivedMessagesMutex sync.Mutex - receivedResponsesMutex sync.Mutex - receiveSubscriptionsMutex sync.Mutex - address string + conn net.Conn + receivedResponsesById map[string]chan JsonRpc2MessageResponse + receivedMessagesChannels map[string]chan JsonRpc2ReceivedMessage + receiveSubscriptions map[string]*receiveSubscription // account -> sub state + channelAccountByUuid map[string]string // channelUuid -> account + signalCliApiConfig *utils.SignalCliApiConfig + number string + manualReceiveMode bool + receivedMessagesMutex sync.Mutex + receivedResponsesMutex sync.Mutex + receiveSubscriptionsMutex sync.Mutex + address string } -func NewJsonRpc2Client(signalCliApiConfig *utils.SignalCliApiConfig, number string) *JsonRpc2Client { +func NewJsonRpc2Client(signalCliApiConfig *utils.SignalCliApiConfig, number string, manualRcpReceiveMode bool) *JsonRpc2Client { return &JsonRpc2Client{ signalCliApiConfig: signalCliApiConfig, number: number, + manualReceiveMode: manualRcpReceiveMode, receivedResponsesById: make(map[string]chan JsonRpc2MessageResponse), receivedMessagesChannels: make(map[string]chan JsonRpc2ReceivedMessage), receiveSubscriptions: make(map[string]*receiveSubscription), @@ -301,11 +303,6 @@ func (r *JsonRpc2Client) ReceiveData(number string, receiveWebhookUrl string) { } } -// subscribeReceive starts receiving messages for an account by calling -// signal-cli's subscribeReceive JSON-RPC method. Only relevant when -// signal-cli was launched with --receive-mode=manual; in auto mode the -// daemon pushes notifications without an explicit subscribe call. -// Returns the subscription id assigned by signal-cli. func (r *JsonRpc2Client) subscribeReceive(account string) (int64, error) { type subscribeReceiveArgs struct{} resultStr, err := r.getRaw("subscribeReceive", &account, subscribeReceiveArgs{}) @@ -319,8 +316,6 @@ func (r *JsonRpc2Client) subscribeReceive(account string) (int64, error) { return subscriptionId, nil } -// unsubscribeReceive cancels a manual-mode subscription previously -// returned by subscribeReceive. func (r *JsonRpc2Client) unsubscribeReceive(account string, subscriptionId int64) error { type unsubscribeReceiveArgs struct { Subscription int64 `json:"subscription"` @@ -329,10 +324,6 @@ func (r *JsonRpc2Client) unsubscribeReceive(account string, subscriptionId int64 return err } -// acquireReceiveSubscription ensures an active manual-mode subscription -// exists for the given account, refcounting concurrent websocket -// subscribers. The first caller for an account triggers a real -// subscribeReceive RPC; subsequent callers just bump the refcount. func (r *JsonRpc2Client) acquireReceiveSubscription(account string) error { r.receiveSubscriptionsMutex.Lock() defer r.receiveSubscriptionsMutex.Unlock() @@ -341,45 +332,42 @@ func (r *JsonRpc2Client) acquireReceiveSubscription(account string) error { sub.refcount++ return nil } + id, err := r.subscribeReceive(account) if err != nil { return err } + r.receiveSubscriptions[account] = &receiveSubscription{id: id, refcount: 1} log.Infof("Subscribed to receive notifications for account %s (subscription=%d)", account, id) return nil } -// releaseReceiveSubscription decrements the per-account refcount and -// cancels the subscription with signal-cli if it drops to zero. -func (r *JsonRpc2Client) releaseReceiveSubscription(account string) { +func (r *JsonRpc2Client) releaseReceiveSubscription(account string) error { r.receiveSubscriptionsMutex.Lock() defer r.receiveSubscriptionsMutex.Unlock() sub, ok := r.receiveSubscriptions[account] if !ok { - return + return nil } + sub.refcount-- if sub.refcount > 0 { - return + return nil } - if err := r.unsubscribeReceive(account, sub.id); err != nil { + + err := r.unsubscribeReceive(account, sub.id) + if err != nil { log.Warnf("unsubscribeReceive failed for account %s (subscription=%d): %s", account, sub.id, err.Error()) } else { log.Infof("Unsubscribed from receive notifications for account %s (subscription=%d)", account, sub.id) } + delete(r.receiveSubscriptions, account) + return err } -// GetReceiveChannel returns a channel that will receive messages for the -// given account. If signal-cli is in manual receive-mode, it also acquires -// a subscription so that signal-cli starts forwarding messages for the -// account; in auto mode, account is unused (notifications flow regardless). -// -// account may be empty when the caller does not need a subscription -// (e.g. legacy callers in auto mode); in that case no subscribeReceive -// RPC is issued. func (r *JsonRpc2Client) GetReceiveChannel(account string) (chan JsonRpc2ReceivedMessage, string, error) { c := make(chan JsonRpc2ReceivedMessage, 64) @@ -388,8 +376,10 @@ func (r *JsonRpc2Client) GetReceiveChannel(account string) (chan JsonRpc2Receive return c, "", err } - if err := r.acquireReceiveSubscription(account); err != nil { - return c, "", fmt.Errorf("subscribeReceive failed for account %s: %w", account, err) + if r.manualReceiveMode { + if err := r.acquireReceiveSubscription(account); err != nil { + return c, "", fmt.Errorf("Couldn't create subscription for account %s: %w", account, err) + } } r.receivedMessagesMutex.Lock() @@ -407,7 +397,9 @@ func (r *JsonRpc2Client) RemoveReceiveChannel(channelUuid string) { delete(r.channelAccountByUuid, channelUuid) r.receivedMessagesMutex.Unlock() - if account != "" { - r.releaseReceiveSubscription(account) + if r.manualReceiveMode { + if err := r.releaseReceiveSubscription(account); err != nil { + log.Errorf("Couldn't release subscription for account %s: %s", account, err.Error()) + } } } diff --git a/src/main.go b/src/main.go index ede0cc1..bbeb8fa 100644 --- a/src/main.go +++ b/src/main.go @@ -156,6 +156,8 @@ func main() { } } + signalCliManualReceive := utils.GetEnv("JSON_RPC_RECEIVE_MODE", "") == "manual" + webhookUrl := utils.GetEnv("RECEIVE_WEBHOOK_URL", "") if webhookUrl != "" && signalCliMode != client.JsonRpc { log.Fatal("Env variable RECEIVE_WEBHOOK_URL can only be used with mode json-rpc!") @@ -163,7 +165,7 @@ func main() { jsonRpc2ClientConfigPathPath := *signalCliConfig + "/jsonrpc2.yml" signalCliApiConfigPath := *signalCliConfig + "/api-config.yml" - signalClient := client.NewSignalClient(*signalCliConfig, *attachmentTmpDir, *avatarTmpDir, signalCliMode, jsonRpc2ClientConfigPathPath, signalCliApiConfigPath, webhookUrl) + signalClient := client.NewSignalClient(*signalCliConfig, *attachmentTmpDir, *avatarTmpDir, signalCliMode, jsonRpc2ClientConfigPathPath, signalCliApiConfigPath, webhookUrl, signalCliManualReceive) err = signalClient.Init(60) if err != nil { log.Fatal("Couldn't init Signal Client: ", err.Error()) From 955f78f0839a05b0af07c053a93732f353547d10 Mon Sep 17 00:00:00 2001 From: Mykola Balakin Date: Tue, 13 Oct 2026 23:01:54 +0300 Subject: [PATCH 05/10] Parse the payload as manual only in manual mode --- src/client/jsonrpc2.go | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/client/jsonrpc2.go b/src/client/jsonrpc2.go index 69935eb..15afadf 100644 --- a/src/client/jsonrpc2.go +++ b/src/client/jsonrpc2.go @@ -259,12 +259,14 @@ func (r *JsonRpc2Client) ReceiveData(number string, receiveWebhookUrl string) { // the envelope directly. Unwrap so the broadcast format is // the same in both modes and downstream consumers (e.g. the // websocket handler) don't have to know which mode is in use. - var manualWrapper struct { - Subscription int64 `json:"subscription"` - Result json.RawMessage `json:"result"` - } - if err := json.Unmarshal(resp1.Params, &manualWrapper); err == nil && len(manualWrapper.Result) > 0 { - resp1.Params = manualWrapper.Result + if r.manualReceiveMode { + var manualWrapper struct { + Subscription int64 `json:"subscription"` + Result json.RawMessage `json:"result"` + } + if err := json.Unmarshal(resp1.Params, &manualWrapper); err == nil && len(manualWrapper.Result) > 0 { + resp1.Params = manualWrapper.Result + } } r.receivedMessagesMutex.Lock() From 53fa03881f61215ea27b0d7d195b711f6e542e2a Mon Sep 17 00:00:00 2001 From: Mykola Balakin Date: Wed, 14 Oct 2026 17:00:53 +0300 Subject: [PATCH 06/10] Minor style fixes --- src/client/jsonrpc2.go | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/client/jsonrpc2.go b/src/client/jsonrpc2.go index 15afadf..9c8c6de 100644 --- a/src/client/jsonrpc2.go +++ b/src/client/jsonrpc2.go @@ -69,8 +69,8 @@ type JsonRpc2Client struct { conn net.Conn receivedResponsesById map[string]chan JsonRpc2MessageResponse receivedMessagesChannels map[string]chan JsonRpc2ReceivedMessage - receiveSubscriptions map[string]*receiveSubscription // account -> sub state - channelAccountByUuid map[string]string // channelUuid -> account + receiveSubscriptions map[string]*receiveSubscription + accountsByChannelUuid map[string]string signalCliApiConfig *utils.SignalCliApiConfig number string manualReceiveMode bool @@ -88,7 +88,7 @@ func NewJsonRpc2Client(signalCliApiConfig *utils.SignalCliApiConfig, number stri receivedResponsesById: make(map[string]chan JsonRpc2MessageResponse), receivedMessagesChannels: make(map[string]chan JsonRpc2ReceivedMessage), receiveSubscriptions: make(map[string]*receiveSubscription), - channelAccountByUuid: make(map[string]string), + accountsByChannelUuid: make(map[string]string), } } @@ -313,7 +313,7 @@ func (r *JsonRpc2Client) subscribeReceive(account string) (int64, error) { } var subscriptionId int64 if err := json.Unmarshal([]byte(resultStr), &subscriptionId); err != nil { - return 0, fmt.Errorf("subscribeReceive: couldn't parse subscription id from %q: %w", resultStr, err) + return 0, err } return subscriptionId, nil } @@ -361,7 +361,7 @@ func (r *JsonRpc2Client) releaseReceiveSubscription(account string) error { err := r.unsubscribeReceive(account, sub.id) if err != nil { - log.Warnf("unsubscribeReceive failed for account %s (subscription=%d): %s", account, sub.id, err.Error()) + log.Warnf("Couldn't unsubscribed from receive notifications for account %s (subscription=%d): %s", account, sub.id, err.Error()) } else { log.Infof("Unsubscribed from receive notifications for account %s (subscription=%d)", account, sub.id) } @@ -386,7 +386,7 @@ func (r *JsonRpc2Client) GetReceiveChannel(account string) (chan JsonRpc2Receive r.receivedMessagesMutex.Lock() r.receivedMessagesChannels[channelUuid.String()] = c - r.channelAccountByUuid[channelUuid.String()] = account + r.accountsByChannelUuid[channelUuid.String()] = account r.receivedMessagesMutex.Unlock() return c, channelUuid.String(), nil @@ -395,8 +395,8 @@ func (r *JsonRpc2Client) GetReceiveChannel(account string) (chan JsonRpc2Receive func (r *JsonRpc2Client) RemoveReceiveChannel(channelUuid string) { r.receivedMessagesMutex.Lock() delete(r.receivedMessagesChannels, channelUuid) - account := r.channelAccountByUuid[channelUuid] - delete(r.channelAccountByUuid, channelUuid) + account := r.accountsByChannelUuid[channelUuid] + delete(r.accountsByChannelUuid, channelUuid) r.receivedMessagesMutex.Unlock() if r.manualReceiveMode { From 801b015516edbb942efd167c10f7d9706a117a56 Mon Sep 17 00:00:00 2001 From: Mykola Balakin Date: Sat, 17 Oct 2026 15:49:53 +0300 Subject: [PATCH 07/10] Refactor JSON RPC receive mode into an enum --- src/client/client.go | 15 +++++++++++---- src/client/jsonrpc2.go | 12 ++++++------ src/main.go | 12 ++++++++++-- 3 files changed, 27 insertions(+), 12 deletions(-) diff --git a/src/client/client.go b/src/client/client.go index 1df7b47..c892fd4 100644 --- a/src/client/client.go +++ b/src/client/client.go @@ -53,6 +53,13 @@ const ( JsonRpc ) +type JsonRpcReceiveMode int + +const ( + OnStart JsonRpcReceiveMode = iota + 1 + Manual +) + type GroupLinkState int const ( @@ -406,11 +413,11 @@ type SignalClient struct { signalCliApiConfig *utils.SignalCliApiConfig cliClient *CliClient receiveWebhookUrl string - receiveManualMode bool + jsonRpcReceiveMode JsonRpcReceiveMode } func NewSignalClient(signalCliConfig string, attachmentTmpDir string, avatarTmpDir string, signalCliMode SignalCliMode, - jsonRpc2ClientConfigPath string, signalCliApiConfigPath string, receiveWebhookUrl string, receiveManualMode bool) *SignalClient { + jsonRpc2ClientConfigPath string, signalCliApiConfigPath string, receiveWebhookUrl string, jsonRpcReceiveMode JsonRpcReceiveMode) *SignalClient { return &SignalClient{ signalCliConfig: signalCliConfig, attachmentTmpDir: attachmentTmpDir, @@ -420,7 +427,7 @@ func NewSignalClient(signalCliConfig string, attachmentTmpDir string, avatarTmpD jsonRpc2Clients: make(map[string]*JsonRpc2Client), signalCliApiConfigPath: signalCliApiConfigPath, receiveWebhookUrl: receiveWebhookUrl, - receiveManualMode: receiveManualMode, + jsonRpcReceiveMode: jsonRpcReceiveMode, } } @@ -444,7 +451,7 @@ func (s *SignalClient) Init(maxRetries int) error { tcpPortsNumberMapping := s.jsonRpc2ClientConfig.GetTcpPortsForNumbers() for number, tcpPort := range tcpPortsNumberMapping { - s.jsonRpc2Clients[number] = NewJsonRpc2Client(s.signalCliApiConfig, number, s.receiveManualMode) + s.jsonRpc2Clients[number] = NewJsonRpc2Client(s.signalCliApiConfig, number, s.jsonRpcReceiveMode) err := s.jsonRpc2Clients[number].Dial("127.0.0.1:"+strconv.FormatInt(tcpPort, 10), maxRetries) if err != nil { return err diff --git a/src/client/jsonrpc2.go b/src/client/jsonrpc2.go index 9c8c6de..f6876be 100644 --- a/src/client/jsonrpc2.go +++ b/src/client/jsonrpc2.go @@ -73,18 +73,18 @@ type JsonRpc2Client struct { accountsByChannelUuid map[string]string signalCliApiConfig *utils.SignalCliApiConfig number string - manualReceiveMode bool + jsonRpcReceiveMode JsonRpcReceiveMode receivedMessagesMutex sync.Mutex receivedResponsesMutex sync.Mutex receiveSubscriptionsMutex sync.Mutex address string } -func NewJsonRpc2Client(signalCliApiConfig *utils.SignalCliApiConfig, number string, manualRcpReceiveMode bool) *JsonRpc2Client { +func NewJsonRpc2Client(signalCliApiConfig *utils.SignalCliApiConfig, number string, jsonRpcReceiveMode JsonRpcReceiveMode) *JsonRpc2Client { return &JsonRpc2Client{ signalCliApiConfig: signalCliApiConfig, number: number, - manualReceiveMode: manualRcpReceiveMode, + jsonRpcReceiveMode: jsonRpcReceiveMode, receivedResponsesById: make(map[string]chan JsonRpc2MessageResponse), receivedMessagesChannels: make(map[string]chan JsonRpc2ReceivedMessage), receiveSubscriptions: make(map[string]*receiveSubscription), @@ -259,7 +259,7 @@ func (r *JsonRpc2Client) ReceiveData(number string, receiveWebhookUrl string) { // the envelope directly. Unwrap so the broadcast format is // the same in both modes and downstream consumers (e.g. the // websocket handler) don't have to know which mode is in use. - if r.manualReceiveMode { + if r.jsonRpcReceiveMode == Manual { var manualWrapper struct { Subscription int64 `json:"subscription"` Result json.RawMessage `json:"result"` @@ -378,7 +378,7 @@ func (r *JsonRpc2Client) GetReceiveChannel(account string) (chan JsonRpc2Receive return c, "", err } - if r.manualReceiveMode { + if r.jsonRpcReceiveMode == Manual { if err := r.acquireReceiveSubscription(account); err != nil { return c, "", fmt.Errorf("Couldn't create subscription for account %s: %w", account, err) } @@ -399,7 +399,7 @@ func (r *JsonRpc2Client) RemoveReceiveChannel(channelUuid string) { delete(r.accountsByChannelUuid, channelUuid) r.receivedMessagesMutex.Unlock() - if r.manualReceiveMode { + if r.jsonRpcReceiveMode == Manual { if err := r.releaseReceiveSubscription(account); err != nil { log.Errorf("Couldn't release subscription for account %s: %s", account, err.Error()) } diff --git a/src/main.go b/src/main.go index bbeb8fa..ee8cf0c 100644 --- a/src/main.go +++ b/src/main.go @@ -156,7 +156,15 @@ func main() { } } - signalCliManualReceive := utils.GetEnv("JSON_RPC_RECEIVE_MODE", "") == "manual" + jsonRpcReceiveMode := client.OnStart + jsonRpcReceiveModeValue := utils.GetEnv("JSON_RPC_RECEIVE_MODE", "") + if jsonRpcReceiveModeValue == "on-start" { + jsonRpcReceiveMode = client.OnStart + } else if jsonRpcReceiveModeValue == "manual" { + jsonRpcReceiveMode = client.Manual + } else if jsonRpcReceiveModeValue != "" { + log.Fatal("Invalid JSON_RPC_RECEIVE_MODE environment variable set!") + } webhookUrl := utils.GetEnv("RECEIVE_WEBHOOK_URL", "") if webhookUrl != "" && signalCliMode != client.JsonRpc { @@ -165,7 +173,7 @@ func main() { jsonRpc2ClientConfigPathPath := *signalCliConfig + "/jsonrpc2.yml" signalCliApiConfigPath := *signalCliConfig + "/api-config.yml" - signalClient := client.NewSignalClient(*signalCliConfig, *attachmentTmpDir, *avatarTmpDir, signalCliMode, jsonRpc2ClientConfigPathPath, signalCliApiConfigPath, webhookUrl, signalCliManualReceive) + signalClient := client.NewSignalClient(*signalCliConfig, *attachmentTmpDir, *avatarTmpDir, signalCliMode, jsonRpc2ClientConfigPathPath, signalCliApiConfigPath, webhookUrl, jsonRpcReceiveMode) err = signalClient.Init(60) if err != nil { log.Fatal("Couldn't init Signal Client: ", err.Error()) From 2cb7ad4fb1a4867480ece3a6a73554393b2a71a3 Mon Sep 17 00:00:00 2001 From: Mykola Balakin Date: Sat, 17 Oct 2026 19:23:35 +0300 Subject: [PATCH 08/10] Reduce the level of unimportant logs --- src/client/jsonrpc2.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/client/jsonrpc2.go b/src/client/jsonrpc2.go index f6876be..ceed337 100644 --- a/src/client/jsonrpc2.go +++ b/src/client/jsonrpc2.go @@ -341,7 +341,7 @@ func (r *JsonRpc2Client) acquireReceiveSubscription(account string) error { } r.receiveSubscriptions[account] = &receiveSubscription{id: id, refcount: 1} - log.Infof("Subscribed to receive notifications for account %s (subscription=%d)", account, id) + log.Debugf("Subscribed to receive notifications for account %s (subscription=%d)", account, id) return nil } @@ -363,7 +363,7 @@ func (r *JsonRpc2Client) releaseReceiveSubscription(account string) error { if err != nil { log.Warnf("Couldn't unsubscribed from receive notifications for account %s (subscription=%d): %s", account, sub.id, err.Error()) } else { - log.Infof("Unsubscribed from receive notifications for account %s (subscription=%d)", account, sub.id) + log.Debugf("Unsubscribed from receive notifications for account %s (subscription=%d)", account, sub.id) } delete(r.receiveSubscriptions, account) From 090d9b135ec5c40e0484daf4213fd99d24b07489 Mon Sep 17 00:00:00 2001 From: Mykola Balakin Date: Sat, 17 Oct 2026 19:24:17 +0300 Subject: [PATCH 09/10] Shorten the critical section --- src/client/jsonrpc2.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/client/jsonrpc2.go b/src/client/jsonrpc2.go index ceed337..0fd0093 100644 --- a/src/client/jsonrpc2.go +++ b/src/client/jsonrpc2.go @@ -347,26 +347,30 @@ func (r *JsonRpc2Client) acquireReceiveSubscription(account string) error { func (r *JsonRpc2Client) releaseReceiveSubscription(account string) error { r.receiveSubscriptionsMutex.Lock() - defer r.receiveSubscriptionsMutex.Unlock() sub, ok := r.receiveSubscriptions[account] if !ok { + r.receiveSubscriptionsMutex.Unlock() return nil } sub.refcount-- if sub.refcount > 0 { + r.receiveSubscriptionsMutex.Unlock() return nil } + delete(r.receiveSubscriptions, account) err := r.unsubscribeReceive(account, sub.id) + + r.receiveSubscriptionsMutex.Unlock() + if err != nil { log.Warnf("Couldn't unsubscribed from receive notifications for account %s (subscription=%d): %s", account, sub.id, err.Error()) } else { log.Debugf("Unsubscribed from receive notifications for account %s (subscription=%d)", account, sub.id) } - delete(r.receiveSubscriptions, account) return err } From d6e1ff2da19da324f68530078cdeb64734ecf114 Mon Sep 17 00:00:00 2001 From: Mykola Balakin Date: Sat, 17 Oct 2026 19:24:40 +0300 Subject: [PATCH 10/10] Exit if JSON_RCP_RECEIVE_MODE is set in non-JSON-RPC mode --- src/main.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main.go b/src/main.go index ee8cf0c..548d39b 100644 --- a/src/main.go +++ b/src/main.go @@ -158,7 +158,9 @@ func main() { jsonRpcReceiveMode := client.OnStart jsonRpcReceiveModeValue := utils.GetEnv("JSON_RPC_RECEIVE_MODE", "") - if jsonRpcReceiveModeValue == "on-start" { + if jsonRpcReceiveModeValue != "" && signalCliMode != client.JsonRpc { + log.Fatal("Env variable JSON_RPC_RECEIVE_MODE can't be used with normal or native mode") + } else if jsonRpcReceiveModeValue == "on-start" { jsonRpcReceiveMode = client.OnStart } else if jsonRpcReceiveModeValue == "manual" { jsonRpcReceiveMode = client.Manual