Debian Codegraph @

paho/session/state/sendquota.go

raw
1 /*
2 * Copyright (c) 2024 Contributors to the Eclipse Foundation
3 *
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v2.0
6 * and Eclipse Distribution License v1.0 which accompany this distribution.
7 *
8 * The Eclipse Public License is available at
9 * https://www.eclipse.org/legal/epl-2.0/
10 * and the Eclipse Distribution License is available at
11 * http://www.eclipse.org/org/documents/edl-v10.php.
12 *
13 * SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
14 */
15
16 package state
17
18 import (
19 "context"
20 "errors"
21 "fmt"
22 "sync"
23 )
24
25 // Implements send quota as described in section 4.9 of the spec. This is used to honour the receive-maximum
26 // received from the broker; each time a qos1/2 PUBLISH is to be sent `Acquire` must be called, and this will
27 // block until a slot is available (`Release` is called when the message is fully acknowledged).
28
29 // This function was previously performed by `golang.org/x/sync/semaphore` but, as per the MQTT spec:
30 //
31 // > The send quota is not incremented if it is already equal to the initial send quota. The attempt to increment above
32 // > the initial send quota might be caused by the re-transmission of a PUBREL packet after a new Network Connection is
33 // > established.
34 //
35 // The result of this happening with `semaphore` is a `panic` which is not ideal.
36 // It is also possible (as per issue #179) that bugs, or unexpected circumstances, may result in the same situation. For
37 // example: if the local session state is lost but there is a session state on the server (meaning it sends an unexpected
38 // PUBACK).
39 //
40 // Note: If the broker does not correctly acknowledge messages, then the quota will be consumed over time. There
41 // should probably be a process to drop the connection if there are no slots available and no acknowledgements have been
42 // received recently.
43
44 // ErrUnexpectedRelease is for logging only (to help identify if there are issues with state management)
45 var ErrUnexpectedRelease = errors.New("release called when quota at initial value")
46
47 // newSendQuota creates a new tracker limited to quota concurrent messages
48 func newSendQuota(quota uint16) *sendQuota {
49 w := &sendQuota{initialQuota: quota, quota: quota}
50 return w
51 }
52
53 // sendQuota provides a way to bound concurrent access to a resource.
54 // The callers can request access with a given weight.
55 type sendQuota struct {
56 mu sync.Mutex
57 initialQuota uint16
58 quota uint16
59 waiters []chan<- struct{} // using a slice because would generally expect this to be small
60 }
61
62 // Retransmit takes a slot for a message that is being redelivered and will never block.
63 // This is not in compliance with the MQTT v5 spec and should be removed in the future.
64 func (s *sendQuota) Retransmit() error {
65 return s.acquire(context.Background(), true)
66 }
67
68 // Acquire waits for a slot to become available so a message can be published
69 // If ctx is already done, Acquire may still succeed without blocking.
70 func (s *sendQuota) Acquire(ctx context.Context) error {
71 return s.acquire(ctx, false)
72 }
73
74 // acquire attempts to allocate a slot for a message to be published
75 // If noWait is true quota will be ignored and the call will return immediately, otherwise acquire will block
76 // until a slot is available.
77 func (s *sendQuota) acquire(ctx context.Context, noWait bool) error {
78 s.mu.Lock()
79 if noWait || (s.quota > 0 && len(s.waiters) == 0) {
80 s.quota-- // Note: can go < 0 if noWait used
81 s.mu.Unlock()
82 return nil
83 }
84
85 // We need to join the queue
86 ready := make(chan struct{})
87 s.waiters = append(s.waiters, ready)
88 s.mu.Unlock()
89
90 var err error
91 select {
92 case <-ctx.Done():
93 err = ctx.Err()
94 s.mu.Lock()
95 select {
96 case <-ready: // If ready then already removed from s.waiters
97 // Acquired the semaphore after we were cancelled. Rather than trying to
98 // fix up the queue, just pretend we didn't notice the cancellation.
99 err = nil
100 fmt.Println("quota released entry but ready so nil error ", s.quota)
101 default:
102 // Remove ourselves from the list of waiters
103 for i, r := range s.waiters {
104 if ready == r {
105 s.waiters = append(s.waiters[:i], s.waiters[i+1:]...)
106 }
107 }
108 }
109 s.mu.Unlock()
110 case <-ready: // Note that quota already accounts for this item
111 }
112 return err
113 }
114
115 // Release releases slot
116 func (s *sendQuota) Release() error {
117 s.mu.Lock()
118 defer s.mu.Unlock()
119
120 if s.quota >= 0 && len(s.waiters) > 0 { // Possible quota could go negative when using noWait
121 close(s.waiters[0])
122 s.waiters = append(s.waiters[:0], s.waiters[1:]...)
123 return nil
124 }
125 if s.quota < s.initialQuota {
126 s.quota++
127 return nil
128 }
129 return ErrUnexpectedRelease
130 }