|
| 1 | +// concurrency/semaphore.go |
| 2 | +/* package provides utilities to manage concurrency control. The Concurrency Manager |
| 3 | +ensures no more than a certain number of concurrent requests (e.g., 5 for Jamf Pro) |
| 4 | +are sent at the same time. This is managed using a semaphore */ |
| 5 | +package concurrency |
| 6 | + |
| 7 | +import ( |
| 8 | + "context" |
| 9 | + "time" |
| 10 | + |
| 11 | + "github.com/google/uuid" |
| 12 | + "go.uber.org/zap" |
| 13 | +) |
| 14 | + |
| 15 | +// AcquireConcurrencyToken acquires a concurrency token to regulate the number of concurrent |
| 16 | +// operations within predefined limits, ensuring system stability and adherence to concurrency policies. |
| 17 | +// This function initiates a token acquisition process that involves generating a unique request ID |
| 18 | +// for tracking purposes and attempting to acquire a token within a specified timeout to prevent |
| 19 | +// indefinite blocking. Successful acquisition updates performance metrics and associates the |
| 20 | +// unique request ID with the provided context for enhanced traceability and management of |
| 21 | +// concurrent requests. |
| 22 | +// |
| 23 | +// Parameters: |
| 24 | +// - ctx: A parent context used as the basis for the token acquisition attempt, facilitating |
| 25 | +// appropriate cancellation and timeout handling in line with best practices for concurrency control. |
| 26 | +// |
| 27 | +// Returns: |
| 28 | +// - context.Context: A derived context that includes the unique request ID, offering a mechanism |
| 29 | +// for associating subsequent operations with the acquired concurrency token and facilitating |
| 30 | +// effective request tracking and management. |
| 31 | +// - uuid.UUID: The unique request ID generated as part of the token acquisition process, serving |
| 32 | +// as an identifier for the acquired token and enabling detailed tracking and auditing of |
| 33 | +// concurrent operations. |
| 34 | +// - error: An error that signals failure to acquire a concurrency token within the allotted timeout, |
| 35 | +// or due to other encountered issues, ensuring that potential problems in concurrency control |
| 36 | +// are surfaced and can be addressed. |
| 37 | +// |
| 38 | +// Usage: |
| 39 | +// This function is a critical component of concurrency control and should be invoked prior to |
| 40 | +// executing operations that require regulation of concurrency. The returned context, enhanced |
| 41 | +// with the unique request ID, should be utilized in the execution of these operations to maintain |
| 42 | +// consistency in tracking and managing concurrency tokens. The unique request ID also facilitates |
| 43 | +// detailed auditing and troubleshooting of the concurrency control mechanism. |
| 44 | +// |
| 45 | +// Example: |
| 46 | +// ctx, requestID, err := concurrencyHandler.AcquireConcurrencyToken(context.Background()) |
| 47 | +// |
| 48 | +// if err != nil { |
| 49 | +// // Handle token acquisition failure |
| 50 | +// } |
| 51 | +// |
| 52 | +// defer concurrencyHandler.Release(requestID) |
| 53 | +// // Proceed with the operation using the modified context |
| 54 | +func (ch *ConcurrencyHandler) AcquireConcurrencyToken(ctx context.Context) (context.Context, uuid.UUID, error) { |
| 55 | + log := ch.logger |
| 56 | + |
| 57 | + // Measure the token acquisition start time |
| 58 | + tokenAcquisitionStart := time.Now() |
| 59 | + |
| 60 | + // Generate a unique request ID for this acquisition |
| 61 | + requestID := uuid.New() |
| 62 | + |
| 63 | + // Create a new context with a timeout for acquiring the concurrency token |
| 64 | + ctxWithTimeout, cancel := context.WithTimeout(ctx, 10*time.Second) |
| 65 | + defer cancel() |
| 66 | + |
| 67 | + // Attempt to acquire a token from the semaphore within the given context timeout |
| 68 | + select { |
| 69 | + case ch.sem <- struct{}{}: // Successfully acquired a token |
| 70 | + // Calculate the duration it took to acquire the token and record it |
| 71 | + tokenAcquisitionDuration := time.Since(tokenAcquisitionStart) |
| 72 | + ch.lock.Lock() |
| 73 | + ch.AcquisitionTimes = append(ch.AcquisitionTimes, tokenAcquisitionDuration) |
| 74 | + ch.Metrics.Lock.Lock() |
| 75 | + ch.Metrics.TokenWaitTime += tokenAcquisitionDuration |
| 76 | + ch.Metrics.TotalRequests++ // Increment total requests count |
| 77 | + ch.Metrics.Lock.Unlock() |
| 78 | + ch.lock.Unlock() |
| 79 | + |
| 80 | + // Logging the acquisition |
| 81 | + utilizedTokens := len(ch.sem) |
| 82 | + availableTokens := cap(ch.sem) - utilizedTokens |
| 83 | + log.Debug("Acquired concurrency token", zap.String("RequestID", requestID.String()), zap.Duration("AcquisitionTime", tokenAcquisitionDuration), zap.Int("UtilizedTokens", utilizedTokens), zap.Int("AvailableTokens", availableTokens)) |
| 84 | + |
| 85 | + // Add the acquired request ID to the context for use in subsequent operations |
| 86 | + ctxWithRequestID := context.WithValue(ctx, RequestIDKey{}, requestID) |
| 87 | + |
| 88 | + // Return the updated context, the request ID, and nil error to indicate success |
| 89 | + return ctxWithRequestID, requestID, nil |
| 90 | + |
| 91 | + case <-ctxWithTimeout.Done(): // Failed to acquire a token within the timeout |
| 92 | + log.Error("Failed to acquire concurrency token", zap.Error(ctxWithTimeout.Err())) |
| 93 | + return ctx, requestID, ctxWithTimeout.Err() |
| 94 | + } |
| 95 | +} |
| 96 | + |
| 97 | +// ReleaseConcurrencyToken returns a token back to the semaphore pool, allowing other |
| 98 | +// operations to proceed. It uses the provided requestID for structured logging, |
| 99 | +// aiding in tracking and debugging the release of concurrency tokens. |
| 100 | +func (ch *ConcurrencyHandler) ReleaseConcurrencyToken(requestID uuid.UUID) { |
| 101 | + <-ch.sem // Release a token back to the semaphore |
| 102 | + |
| 103 | + ch.lock.Lock() |
| 104 | + defer ch.lock.Unlock() |
| 105 | + |
| 106 | + // Update the list of acquisition times by removing the time related to the released token |
| 107 | + // This step is optional and depends on whether you track acquisition times per token or not |
| 108 | + |
| 109 | + utilizedTokens := len(ch.sem) // Tokens currently in use |
| 110 | + availableTokens := cap(ch.sem) - utilizedTokens // Tokens available for use |
| 111 | + |
| 112 | + // Log the release of the concurrency token for auditing and debugging purposes |
| 113 | + ch.logger.Debug("Released concurrency token", |
| 114 | + zap.String("RequestID", requestID.String()), |
| 115 | + zap.Int("UtilizedTokens", utilizedTokens), |
| 116 | + zap.Int("AvailableTokens", availableTokens), |
| 117 | + ) |
| 118 | +} |
0 commit comments