All files / src/oauth issued-tokens.ts

100% Statements 14/14
100% Branches 2/2
100% Functions 2/2
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34            233x     233x             233x 46x 67x 67x 40x   27x 27x 6x     6x   21x        
/**
 * Keeping tokens GitLab issued in exchange for a single-use grant (an authorization code
 * or a device code): once spent, the grant cannot be presented again, so losing the tokens
 * loses the user's approval.
 */
 
import { logWarn } from '../logger';
 
/** Delays before the retries of a failed write; about a second in all. */
const RETRY_DELAYS_MS = [100, 300, 600];
 
/**
 * Write tokens GitLab just issued, retrying a failed write. When every attempt fails the
 * caller completes the authorization with the tokens in hand, which stores them with the
 * session; so this never throws.
 */
export async function keepIssuedTokens(write: () => Promise<void>): Promise<void> {
  for (let attempt = 0; ; attempt++) {
    try {
      await write();
      return;
    } catch (error: unknown) {
      const delay = RETRY_DELAYS_MS[attempt];
      if (delay === undefined) {
        logWarn('Could not keep issued GitLab tokens; completing with them in hand', {
          err: error as Error,
        });
        return;
      }
      await new Promise((resolve) => setTimeout(resolve, delay));
    }
  }
}