Conditions | 22 |
Total Lines | 119 |
Code Lines | 60 |
Lines | 0 |
Ratio | 0 % |
Changes | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
Complex classes like engines.*BulkChecker.ExecuteRequests often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
1 | package engines |
||
159 | func (bc *BulkChecker) ExecuteRequests(size uint32) error { |
||
160 | // Stop collecting new requests and close the RequestChan to ensure no more requests are added |
||
161 | bc.StopCollectingRequests() |
||
162 | |||
163 | // Wait for request collection to complete before proceeding |
||
164 | bc.wg.Wait() |
||
165 | |||
166 | // Create a context with cancellation that will be used to stop further processing |
||
167 | ctx, cancel := context.WithCancel(bc.ctx) |
||
168 | defer cancel() // Ensure the context is canceled when done |
||
169 | |||
170 | // Track the number of successful permission checks |
||
171 | successCount := int64(0) |
||
172 | // Semaphore to control the maximum number of concurrent permission checks |
||
173 | sem := semaphore.NewWeighted(int64(bc.concurrencyLimit)) |
||
174 | var mu sync.Mutex |
||
175 | |||
176 | // Sort and copy the list of requests |
||
177 | listCopy := bc.prepareRequestList() |
||
178 | |||
179 | // Pre-allocate a slice to store the results of the permission checks |
||
180 | results := make([]base.CheckResult, len(listCopy)) |
||
181 | // Track the index of the last processed request to ensure results are processed in order |
||
182 | processedIndex := 0 |
||
183 | |||
184 | // Loop through each request in the copied list |
||
185 | for i, currentRequest := range listCopy { |
||
186 | // If we've reached the success limit, stop processing further requests |
||
187 | if atomic.LoadInt64(&successCount) >= int64(size) { |
||
188 | cancel() // Cancel the context to stop further goroutines |
||
189 | break |
||
190 | } |
||
191 | |||
192 | index := i |
||
193 | req := currentRequest |
||
194 | |||
195 | // Use errgroup to manage the goroutines, which allows for error handling and synchronization |
||
196 | bc.g.Go(func() error { |
||
197 | // Check if the context has been canceled, and return without error if so |
||
198 | if err := ctx.Err(); err == context.Canceled { |
||
199 | return nil // Gracefully exit the goroutine if context is canceled |
||
200 | } |
||
201 | |||
202 | // Acquire a slot in the semaphore to control concurrency |
||
203 | if err := sem.Acquire(ctx, 1); err != nil { |
||
204 | // Return nil instead of error if the context was canceled during semaphore acquisition |
||
205 | if IsContextRelatedError(ctx, err) { |
||
206 | return nil |
||
207 | } |
||
208 | return err // Return an error if semaphore acquisition fails for other reasons |
||
209 | } |
||
210 | defer sem.Release(1) // Ensure the semaphore slot is released after processing |
||
211 | |||
212 | var result base.CheckResult |
||
213 | if req.Result == base.CheckResult_CHECK_RESULT_UNSPECIFIED { |
||
214 | // Perform the permission check if the result is not already specified |
||
215 | cr, err := bc.checker.Check(ctx, req.Request) |
||
216 | if err != nil { |
||
217 | // Handle context cancellation error here |
||
218 | if IsContextRelatedError(ctx, err) { |
||
219 | return nil // Ignore the cancellation error |
||
220 | } |
||
221 | return err // Return the actual error if it's not due to cancellation |
||
222 | } |
||
223 | result = cr.GetCan() // Get the result from the check |
||
224 | } else { |
||
225 | // Use the already specified result |
||
226 | result = req.Result |
||
227 | } |
||
228 | |||
229 | // Lock the mutex to safely update shared resources |
||
230 | mu.Lock() |
||
231 | results[index] = result // Store the result in the pre-allocated slice |
||
232 | |||
233 | // Process the results in order, starting from the current processed index |
||
234 | for processedIndex < len(listCopy) && results[processedIndex] != base.CheckResult_CHECK_RESULT_UNSPECIFIED { |
||
235 | // If the result at the processed index is allowed, call the callback function |
||
236 | if results[processedIndex] == base.CheckResult_CHECK_RESULT_ALLOWED { |
||
237 | if atomic.AddInt64(&successCount, 1) <= int64(size) { |
||
238 | ct := "" |
||
239 | if processedIndex+1 < len(listCopy) { |
||
240 | // If there is a next item, create a continuous token with the next ID |
||
241 | if bc.typ == BULK_ENTITY { |
||
242 | ct = utils.NewContinuousToken(listCopy[processedIndex+1].Request.GetEntity().GetId()).Encode().String() |
||
243 | } else if bc.typ == BULK_SUBJECT { |
||
244 | ct = utils.NewContinuousToken(listCopy[processedIndex+1].Request.GetSubject().GetId()).Encode().String() |
||
245 | } |
||
246 | } |
||
247 | // Depending on the type of check (entity or subject), call the appropriate callback |
||
248 | if bc.typ == BULK_ENTITY { |
||
249 | bc.callback(listCopy[processedIndex].Request.GetEntity().GetId(), ct) |
||
250 | } else if bc.typ == BULK_SUBJECT { |
||
251 | bc.callback(listCopy[processedIndex].Request.GetSubject().GetId(), ct) |
||
252 | } |
||
253 | } |
||
254 | } |
||
255 | processedIndex++ // Move to the next index for processing |
||
256 | } |
||
257 | mu.Unlock() // Unlock the mutex after updating the results and processed index |
||
258 | |||
259 | // If the success limit has been reached, cancel the context to stop further processing |
||
260 | if atomic.LoadInt64(&successCount) >= int64(size) { |
||
261 | cancel() |
||
262 | } |
||
263 | |||
264 | return nil // Return nil to indicate successful processing |
||
265 | }) |
||
266 | } |
||
267 | |||
268 | // Wait for all goroutines to complete and check for any errors |
||
269 | if err := bc.g.Wait(); err != nil { |
||
270 | // Ignore context cancellation as an error |
||
271 | if IsContextRelatedError(ctx, err) { |
||
272 | return nil |
||
273 | } |
||
274 | return err // Return other errors if any goroutine returned an error |
||
275 | } |
||
276 | |||
277 | return nil // Return nil if all processing completed successfully |
||
278 | } |
||
350 |