withFreshConfigForRefresh runs fn, a credential-store read-modify-write (a token refresh, or a logout that must not race one), while holding both an in-process mutex and a cross-process advisory lock, and reloads the configuration from disk before running fn so it observes any credential another pro
(fn func(lockErr error) error)
| 94 | // The reload refreshes the shared configuration in place, so any config changes not yet written to disk are discarded. |
| 95 | // That is acceptable on the refresh path because mutations are persisted as they happen. |
| 96 | func (c *AuthConfig) withFreshConfigForRefresh(fn func(lockErr error) error) error { |
| 97 | c.refreshMu.Lock() |
| 98 | defer c.refreshMu.Unlock() |
| 99 | |
| 100 | // Best-effort cross-process lock; see the godoc. We proceed without it rather than fail the caller when the state |
| 101 | // directory cannot be created or the lock cannot be acquired. lockErr then lets fn decide what is unsafe or futile |
| 102 | // without serialized peers. The residual risk without the lock is two processes refreshing at once and spending a |
| 103 | // rotating token twice. |
| 104 | unlock := func() {} |
| 105 | ctx, cancel := context.WithTimeout(context.Background(), refreshLockTimeout) |
| 106 | defer cancel() |
| 107 | |
| 108 | acquire := c.acquireRefreshLock |
| 109 | if acquire == nil { |
| 110 | acquire = flockRefreshLock |
| 111 | } |
| 112 | |
| 113 | // Put the lock in the state directory, not the config directory. The config directory can be read-only: under nix |
| 114 | // home-manager and similar setups, managed config files are symlinked into the immutable nix store, so creating a |
| 115 | // lock file there always fails. The state directory is XDG's location for writable runtime state, home-manager |
| 116 | // leaves it writable, and gh already writes state there (state.yml, telemetry), so it is the safer bet. |
| 117 | u, lockErr := acquire(ctx, filepath.Join(ghConfig.StateDir(), refreshLockFile)) |
| 118 | if lockErr == nil { |
| 119 | unlock = u |
| 120 | } |
| 121 | defer unlock() |
| 122 | |
| 123 | if err := c.reload(); err != nil { |
| 124 | return fmt.Errorf("could not reload configuration: %w", err) |
| 125 | } |
| 126 | |
| 127 | return fn(lockErr) |
| 128 | } |
| 129 | |
| 130 | // reload re-reads the config from disk into the shared config, using the reloadConfig seam when set and the real |
| 131 | // ghConfig.Reload otherwise. The production fallback passes fallbackConfig so a config file deleted between reads is |