|
| 1 | +package responselimit |
| 2 | + |
| 3 | +import ( |
| 4 | + "math/rand" |
| 5 | + "sync" |
| 6 | + "time" |
| 7 | + |
| 8 | + "github.com/smartcontractkit/libocr/networking/internal/ocrendpointv3/types" |
| 9 | +) |
| 10 | + |
| 11 | +type ResponseCheckResult byte |
| 12 | + |
| 13 | +// Enum specifying the list of return values for responseChecker.CheckResponse(...). |
| 14 | +const ( |
| 15 | + // A response is rejected if the policy |
| 16 | + // (1) was not found, or |
| 17 | + // (2) was expired, or |
| 18 | + // (3) was found but decided to reject the request. |
| 19 | + // |
| 20 | + // As policies are automatically cleaned up (in some non-deterministic manner), there is no way to distinguish |
| 21 | + // cases (1) and (2), and for simplicity also case (3) is handled identically. |
| 22 | + // |
| 23 | + // We intentionally use 0 as the first enum value for Reject as a safe default here. |
| 24 | + ResponseCheckResultReject ResponseCheckResult = iota |
| 25 | + |
| 26 | + // A (non-expired) policy was found, and the policy did decide that the response should be allowed. |
| 27 | + ResponseCheckResultAllow |
| 28 | +) |
| 29 | + |
| 30 | +type responseCheckerMapEntry struct { |
| 31 | + index int |
| 32 | + policy ResponsePolicy |
| 33 | + streamID types.StreamID |
| 34 | +} |
| 35 | + |
| 36 | +// Data structure for keeping track of open requests until a set expiry date. |
| 37 | +// |
| 38 | +// Cleanup of expired entries is performed automatically. Whenever a new entry is added, two random entries are checked |
| 39 | +// and removed if expired. This ensures that, on expectation, the number of tracked entries is approx. 2x the number |
| 40 | +// of non-expired entries. |
| 41 | +// |
| 42 | +// SetPolicy(...) and CheckResponse(...) are O(1) operations. |
| 43 | +type ResponseChecker struct { |
| 44 | + mutex sync.Mutex |
| 45 | + rids []types.RequestID |
| 46 | + policies map[types.RequestID]responseCheckerMapEntry |
| 47 | + rng *rand.Rand |
| 48 | +} |
| 49 | + |
| 50 | +func NewResponseChecker() *ResponseChecker { |
| 51 | + return &ResponseChecker{ |
| 52 | + sync.Mutex{}, |
| 53 | + make([]types.RequestID, 0), |
| 54 | + make(map[types.RequestID]responseCheckerMapEntry), |
| 55 | + rand.New(rand.NewSource(time.Now().UnixNano())), |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +// Sets the policy for a given (fresh) request ID. After setting the policy, calling Pop(...) for the same ID before the |
| 60 | +// policy expires returns the policy Set with this function. If a policy with the provided ID is already present, it |
| 61 | +// will be overwritten. |
| 62 | +func (c *ResponseChecker) SetPolicy(sid types.StreamID, rid types.RequestID, policy ResponsePolicy) { |
| 63 | + c.mutex.Lock() |
| 64 | + defer c.mutex.Unlock() |
| 65 | + |
| 66 | + // Lookup an existing policy for the provided request ID. |
| 67 | + // If it exists, we override the policy, keeping its location at the prior index. |
| 68 | + // Otherwise, we need use a new index and also track the request ID in the c.rids list. |
| 69 | + entry, exists := c.policies[rid] |
| 70 | + if exists { |
| 71 | + entry = responseCheckerMapEntry{entry.index, policy, sid} |
| 72 | + } else { |
| 73 | + // We set entry.index = len(c.rids) to let it point to the request ID we will append to c.rids list. |
| 74 | + entry = responseCheckerMapEntry{len(c.rids), policy, sid} |
| 75 | + c.rids = append(c.rids, rid) |
| 76 | + } |
| 77 | + |
| 78 | + // Actually save the policy update back to the c.policies map. |
| 79 | + c.policies[rid] = entry |
| 80 | + |
| 81 | + // If the number of tracked policies increased, we check 2 random policies and remove them if expired. This way |
| 82 | + // the number of tracked policies only grows to 2x the number of non-expired policies in expectation. |
| 83 | + if !exists { |
| 84 | + c.cleanupExpired() |
| 85 | + } |
| 86 | +} |
| 87 | + |
| 88 | +// Lookup the policy for a given response and check if it should be allowed or rejected. |
| 89 | +// See responseCheckResult for additional documentation on the potential return values of this function. |
| 90 | +func (c *ResponseChecker) CheckResponse(sid types.StreamID, rid types.RequestID, size int) ResponseCheckResult { |
| 91 | + c.mutex.Lock() |
| 92 | + defer c.mutex.Unlock() |
| 93 | + |
| 94 | + entry, exists := c.policies[rid] |
| 95 | + if !exists { |
| 96 | + return ResponseCheckResultReject |
| 97 | + } |
| 98 | + if entry.streamID != sid { |
| 99 | + return ResponseCheckResultReject |
| 100 | + } |
| 101 | + |
| 102 | + now := time.Now() |
| 103 | + if entry.policy.isPolicyExpired(now) { |
| 104 | + c.removeEntry(rid, entry.index) |
| 105 | + return ResponseCheckResultReject |
| 106 | + } |
| 107 | + |
| 108 | + policyResult := entry.policy.checkResponse(rid, size, now) |
| 109 | + |
| 110 | + // Recheck the policy of expiry, useful to cleanup one-time-use policies immediately. |
| 111 | + if entry.policy.isPolicyExpired(now) { |
| 112 | + c.removeEntry(rid, entry.index) |
| 113 | + } |
| 114 | + |
| 115 | + return policyResult |
| 116 | +} |
| 117 | + |
| 118 | +// Removes all currently tracked policies for the given stream ID. To ensure that responses sent to a stream cannot be |
| 119 | +// accepted after this stream is closed and reopened, this function is called when the Stream is closed (and removed |
| 120 | +// from the demuxer). |
| 121 | +func (c *ResponseChecker) ClearPoliciesForStream(sid types.StreamID) { |
| 122 | + c.mutex.Lock() |
| 123 | + defer c.mutex.Unlock() |
| 124 | + |
| 125 | + for i := 0; i < len(c.rids); i++ { |
| 126 | + rid := c.rids[i] |
| 127 | + policy := c.policies[rid] |
| 128 | + |
| 129 | + if policy.streamID == sid { |
| 130 | + // We found a policy which matches the given stream ID. |
| 131 | + // So we remove the entry from the list of request IDs and policies. |
| 132 | + c.removeEntry(rid, i) |
| 133 | + |
| 134 | + // The above removeEntry(...) removes c.rids[i], thus in the next iteration index its value is replaced |
| 135 | + // by a different request ID. We decrement index i to ensure that we don't skip the new value at index i. |
| 136 | + i-- |
| 137 | + } |
| 138 | + } |
| 139 | +} |
| 140 | + |
| 141 | +// Check two random policies. A checked policy is removed if it is found to be expired. |
| 142 | +func (c *ResponseChecker) cleanupExpired() { |
| 143 | + now := time.Now() |
| 144 | + |
| 145 | + // At most 2 iterations, enter loop body only if c.rids is non empty. |
| 146 | + for i := 0; i < 2 && len(c.rids) > 0; i++ { |
| 147 | + // Select a random policy. |
| 148 | + index := c.rng.Intn(len(c.rids)) |
| 149 | + id := c.rids[index] |
| 150 | + policy := c.policies[id].policy |
| 151 | + |
| 152 | + // Remove it if it is expired. |
| 153 | + if policy.isPolicyExpired(now) { |
| 154 | + c.removeEntry(id, index) |
| 155 | + } |
| 156 | + } |
| 157 | +} |
| 158 | + |
| 159 | +// Remove the policy for a given request ID from (1) the map of policies and (2) the list of request IDs. |
| 160 | +func (c *ResponseChecker) removeEntry(id types.RequestID, index int) { |
| 161 | + // Remove the entry from the map of polices. |
| 162 | + delete(c.policies, id) |
| 163 | + |
| 164 | + // Handle the "index == last-index" corner case separately. |
| 165 | + // This avoids wrongfully reinserting the deleted policy. |
| 166 | + if index == len(c.rids)-1 { |
| 167 | + c.rids = c.rids[0 : len(c.rids)-1] |
| 168 | + return |
| 169 | + } |
| 170 | + |
| 171 | + // Swap the last entry's id to the position of the to be removed id, and remove the last value from the rids list. |
| 172 | + lastID := c.rids[len(c.rids)-1] |
| 173 | + c.rids[index] = lastID |
| 174 | + c.rids = c.rids[0 : len(c.rids)-1] |
| 175 | + |
| 176 | + // Update the index point for the c.policies[lastId] to point to the now changed position. |
| 177 | + lastEntry := c.policies[lastID] |
| 178 | + lastEntry.index = index |
| 179 | + c.policies[lastID] = lastEntry |
| 180 | +} |
0 commit comments