All files / src/tools/auth0 client.ts

66.66% Statements 44/66
77.41% Branches 24/31
73.33% Functions 11/15
67.74% Lines 42/62

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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 1741x 1x   1x                   1x     1x   1x     105x 63x 63x                                                                                                                 52x   52x     52x 52x     52x 52x 52x     52x     52x       52x 52x 52x   52x 2x       11x 11x   11x         2x   2x       52x           609x   693x 84x 68x               52x   16x         609x   609x 366x     243x           1x 243x                 243x    
import { PromisePoolExecutor } from 'promise-pool-executor';
import _ from 'lodash';
 
import { flatten } from '../utils';
import {
  Asset,
  ApiResponse,
  Auth0APIClient,
  CheckpointPaginationParams,
  PagePaginationParams,
  BaseAuth0APIClient,
} from '../../types';
 
const API_CONCURRENCY = 3;
// To ensure a complete deployment, limit the API requests generated to be 80% of the capacity
// https://auth0.com/docs/policies/rate-limits#management-api-v2
const API_FREQUENCY_PER_SECOND = 8;
 
const MAX_PAGE_SIZE = 100;
 
function getEntity(rsp: ApiResponse): Asset[] {
  const found = Object.values(rsp).filter((a) => Array.isArray(a));
  Eif (Array.isArray(found) && found.length === 1) {
    return found[0] as Asset[];
  }
  throw new Error('There was an error trying to find the entity within paginate');
}
 
function checkpointPaginator(
  client: Auth0APIClient,
  target,
  name: 'getAll'
): (arg0: CheckpointPaginationParams) => Promise<Asset[]> {
  return async function (...args: [CheckpointPaginationParams]) {
    const data: Asset[] = [];
 
    // remove the _checkpoint_ flag
    const { checkpoint, ...newArgs } = _.cloneDeep(args[0]);
 
    // fetch the total to validate records match
    const { total } = await client.pool
      .addSingleTask({
        data: newArgs,
        generator: (requestArgs) => target[name](requestArgs),
      })
      .promise();
 
    let done = false;
    // use checkpoint pagination to allow fetching 1000+ results
    newArgs.take = 50;
 
    while (!done) {
      const rsp = await client.pool
        .addSingleTask({
          data: newArgs,
          generator: (requestArgs) => target[name](requestArgs),
        })
        .promise();
 
      data.push(...getEntity(rsp));
      if (!rsp.next) {
        done = true;
      } else {
        newArgs.from = rsp.next;
      }
    }
 
    if (data.length !== total) {
      throw new Error('Fail to load data from tenant');
    }
 
    return data;
  };
}
 
function pagePaginator(
  client: Auth0APIClient,
  target,
  name: 'getAll'
): (arg0: PagePaginationParams) => Promise<Asset[]> {
  return async function (...args: [PagePaginationParams]): Promise<Asset[]> {
    // Where the entity data will be collected
    const data: Asset[] = [];
 
    // Create new args and inject the properties we require for pagination automation
    const newArgs = [...args];
    newArgs[0] = { ...newArgs[0], page: 0 };
 
    // Grab data we need from the request then delete the keys as they are only needed for this automation function to work
    const perPage = newArgs[0].per_page || MAX_PAGE_SIZE;
    newArgs[0].per_page = perPage;
    delete newArgs[0].paginate;
 
    // Run the first request to get the total number of entity items
    const rsp = await client.pool
      .addSingleTask({
        data: _.cloneDeep(newArgs),
        generator: (pageArgs) => target[name](...pageArgs),
      })
      .promise();
 
    data.push(...getEntity(rsp));
    const total = rsp.total || 0;
    const pagesLeft = Math.ceil(total / perPage) - 1;
    // Setup pool to get the rest of the pages
    if (pagesLeft > 0) {
      const pages = await client.pool
        .addEachTask({
          data: Array.from(Array(pagesLeft).keys()),
          generator: (page) => {
            const pageArgs = _.cloneDeep(newArgs);
            pageArgs[0].page = page + 1;
 
            return target[name](...pageArgs).then((r) => getEntity(r));
          },
        })
        .promise();
 
      data.push(...flatten(pages));
 
      Iif (data.length !== total) {
        throw new Error('Fail to load data from tenant');
      }
    }
    return data;
  };
}
 
// Warp around a <resource>Manager and detect when requesting specific pages to return all
function pagedManager(client: Auth0APIClient, manager: Auth0APIClient) {
  return new Proxy<Auth0APIClient>(manager, {
    get: function (target: Auth0APIClient, name: string, receiver: unknown) {
      if (name === 'getAll') {
        return async function (...args: [CheckpointPaginationParams | PagePaginationParams]) {
          switch (true) {
            case args[0] && typeof args[0] === 'object' && args[0].checkpoint:
              return checkpointPaginator(
                client,
                target,
                name
              )(...(args as [CheckpointPaginationParams]));
            case args[0] && typeof args[0] === 'object' && args[0].paginate:
              return pagePaginator(client, target, name)(...(args as [PagePaginationParams]));
            default:
              return target[name](...args);
          }
        };
      }
 
      const nestedManager = Reflect.get(target, name, receiver);
 
      if (typeof nestedManager === 'object' && nestedManager !== null) {
        return pagedManager(client, nestedManager);
      }
 
      return nestedManager;
    },
  });
}
 
// Warp around the ManagementClient and detect when requesting specific pages to return all
export default function pagedClient(client: BaseAuth0APIClient): Auth0APIClient {
  const clientWithPooling: Auth0APIClient = {
    ...client,
    pool: new PromisePoolExecutor({
      concurrencyLimit: API_CONCURRENCY,
      frequencyLimit: API_FREQUENCY_PER_SECOND,
      frequencyWindow: 1000, // 1 sec
    }),
  };
 
  return pagedManager(clientWithPooling, clientWithPooling);
}