| 1 | package github |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "net/http" |
| 7 | "time" |
| 8 | ) |
| 9 | |
| 10 | var errNotModified = errors.New("github: not modified") |
| 11 | |
| 12 | type inventoryReply struct { |
| 13 | Total *int `json:"total_count"` |
| 14 | Rows []Repository `json:"repositories"` |
| 15 | } |
| 16 | type inventoryPage struct { |
| 17 | etag string |
| 18 | reply inventoryReply |
| 19 | headers http.Header |
| 20 | } |
| 21 | |
| 22 | func (a *API) cachedPage(app App, token string, page int) inventoryPage { |
| 23 | a.mu.Lock() |
| 24 | defer a.mu.Unlock() |
| 25 | entry := a.tokens[app.ID] |
| 26 | if entry.value != token || entry.generation != app.generation { |
| 27 | return inventoryPage{} |
| 28 | } |
| 29 | return entry.pages[page] |
| 30 | } |
| 31 | func (a *API) cachePage(app App, token string, page int, value inventoryPage) { |
| 32 | a.mu.Lock() |
| 33 | defer a.mu.Unlock() |
| 34 | entry := a.tokens[app.ID] |
| 35 | if entry.value != token { |
| 36 | return |
| 37 | } |
| 38 | if entry.generation != app.generation { |
| 39 | entry.generation = app.generation |
| 40 | entry.pages = map[int]inventoryPage{} |
| 41 | } |
| 42 | entry.pages[page] = value |
| 43 | a.tokens[app.ID] = entry |
| 44 | } |
| 45 | |
| 46 | // Expire drops idle metadata credentials before expiry, even with the flag off. |
| 47 | // The serving loop runs every 15 seconds; the margin is 30 seconds. |
| 48 | func (a *API) Expire(ctx context.Context) { |
| 49 | a.mu.Lock() |
| 50 | var expired []string |
| 51 | for id, entry := range a.tokens { |
| 52 | if !a.now().Add(30 * time.Second).Before(entry.expires) { |
| 53 | expired = append(expired, entry.value) |
| 54 | delete(a.tokens, id) |
| 55 | } |
| 56 | } |
| 57 | a.mu.Unlock() |
| 58 | for _, value := range expired { |
| 59 | _, _ = a.request(ctx, "DELETE", "/installation/token", value, nil, nil) |
| 60 | } |
| 61 | } |
| 62 | |