tutorialCatalogNow returns the catalog, refreshing it when it is older than the TTL. One refresh runs at a time and never holds the lock while it waits on the network: a caller with a copy in hand gets that copy at once, and only a caller with NO copy waits for the refresh in progress, bounded by it
(ctx context.Context)
| 137 | // Failures are not retried more often than tutorialsRetryAfterFail, so an |
| 138 | // outage does not cost every request a timeout. |
| 139 | func (s *Server) tutorialCatalogNow(ctx context.Context) *tutorialCatalog { |
| 140 | c := &s.tutorials |
| 141 | c.mu.Lock() |
| 142 | now := time.Now() |
| 143 | fresh := c.catalog != nil && now.Sub(c.fetchedAt) < tutorialsTTL |
| 144 | backingOff := !c.failedAt.IsZero() && now.Sub(c.failedAt) < tutorialsRetryAfterFail |
| 145 | if fresh || backingOff { |
| 146 | cat := c.catalog |
| 147 | c.mu.Unlock() |
| 148 | return cat |
| 149 | } |
| 150 | wait := c.inflight |
| 151 | if wait == nil { |
| 152 | wait = make(chan struct{}) |
| 153 | c.inflight = wait |
| 154 | go s.refreshTutorialCatalog(wait) |
| 155 | } |
| 156 | cat := c.catalog |
| 157 | c.mu.Unlock() |
| 158 | if cat != nil { |
| 159 | return cat // stale but usable; the refresh lands for the next caller |
| 160 | } |
| 161 | select { |
| 162 | case <-wait: |
| 163 | case <-ctx.Done(): |
| 164 | } |
| 165 | c.mu.Lock() |
| 166 | defer c.mu.Unlock() |
| 167 | return c.catalog |
| 168 | } |
| 169 | |
| 170 | // refreshTutorialCatalog fetches the catalog and publishes the result, then |
| 171 | // closes done. It runs detached from any one request, so a client that goes |