All files / src/models addon.js

16.33% Statements 49/300
100% Branches 1/1
0% Functions 0/18
16.33% Lines 49/300

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 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x     193x 193x               193x 193x                   193x 193x                                     193x                                                                                                                                       193x 193x                                                                                 193x                           193x               193x 193x       193x 193x       193x 193x                 193x 193x       193x 193x     193x 193x 193x     193x 193x                             193x 193x                       193x 193x                                                           193x                            
import {
  create as createAddon,
  get as getAddon,
  getAll as getAllAddons,
  getAllEnvVars,
  remove as removeAddon,
  update as updateAddon,
} from '@clevercloud/client/esm/api/v2/addon.js';
import { getAllLinkedAddons, linkAddon, unlinkAddon } from '@clevercloud/client/esm/api/v2/application.js';
import { getAllAddonProviders } from '@clevercloud/client/esm/api/v2/product.js';
import { getSummary } from '@clevercloud/client/esm/api/v2/user.js';
import { getAddonProvider } from '@clevercloud/client/esm/api/v4/addon-providers.js';
import { confirm } from '../lib/prompts.js';
import { Logger } from '../logger.js';
import { resolveOwnerId } from './ids-resolver.js';
import { sendToApi } from './send-to-api.js';
 
export function listProviders(orgaId) {
  return getAllAddonProviders({ orgaId }).then(sendToApi);
}
 
export async function getProvider(providerName, orgaId) {
  const providers = await listProviders(orgaId);
  const provider = providers.find((p) => p.id === providerName);
  if (provider == null) {
    throw new Error(`Invalid provider name. Available providers: ${providers.map((p) => p.id).join(', ')}`);
  }
  return provider;
}
 
export function getProviderInfos(providerName) {
  return getAddonProvider({ providerId: providerName })
    .then(sendToApi)
    .catch(() => {
      // An error can occur because the add-on api doesn't implement this endpoint yet
      // This is fine, just ignore it
      Logger.debug(`${providerName} doesn't yet implement the provider info endpoint`);
      return Promise.resolve(null);
    });
}
 
export async function list(ownerId, appId, showAll) {
  const allAddons = await getAllAddons({ id: ownerId }).then(sendToApi);

  if (appId == null) {
    // Not linked to a specific app, show everything
    return allAddons;
  }

  const myAddons = await getAllLinkedAddons({ id: ownerId, appId }).then(sendToApi);
  if (!showAll) {
    return myAddons.map((addon) => ({ ...addon, isLinked: true }));
  }

  const myAddonIds = myAddons.map((addon) => addon.id);
  return allAddons.map((addon) => {
    const isLinked = myAddonIds.includes(addon.id);
    return { ...addon, isLinked };
  });
}
 
function validateAddonVersionAndOptions(region, version, addonOptions, providerInfos, planType) {
  if (providerInfos != null) {
    if (version != null) {
      const type = planType.value.toLowerCase();
      if (type === 'shared') {
        const cluster = providerInfos.clusters.find(({ zone }) => zone === region);
        if (cluster == null) {
          throw new Error(`Can't find cluster for region ${region}`);
        } else if (cluster.version !== version) {
          throw new Error(
            `Invalid version ${version}, selected shared cluster only supports version ${cluster.version}`,
          );
        }
      } else if (type === 'dedicated') {
        const availableVersions = Object.keys(providerInfos.dedicated);
        const hasVersion = availableVersions.find((availableVersion) => availableVersion === version);
        if (hasVersion == null) {
          throw new Error(`Invalid version ${version}, available versions are: ${availableVersions.join(', ')}`);
        }
      }
    }

    const chosenVersion = version != null ? version : providerInfos.defaultDedicatedVersion;

    // Check the selected options to see if the chosen plan / region offers them
    // If not, abort the creation
    if (Object.keys(addonOptions).length > 0) {
      const type = planType.value.toLowerCase();
      let availableOptions = [];
      if (type === 'shared') {
        const cluster = providerInfos.clusters.find(({ zone }) => zone === region);
        if (cluster == null) {
          throw new Error(`Can't find cluster for region ${region}`);
        }

        availableOptions = cluster.features;
      } else if (type === 'dedicated') {
        availableOptions = providerInfos.dedicated[chosenVersion].features;
      }

      for (const selectedOption in addonOptions) {
        const isAvailable = availableOptions.find(({ name }) => name === selectedOption);
        if (isAvailable == null) {
          const optionNames = availableOptions.map(({ name }) => name).join(',');
          let availableOptionsError = null;
          if (optionNames.length > 0) {
            availableOptionsError = `Available options are: ${optionNames}.`;
          } else {
            availableOptionsError = 'No options are available for this plan.';
          }

          throw new Error(`Option "${selectedOption}" is not available on this plan. ${availableOptionsError}`);
        }
      }
    }

    return {
      version: chosenVersion,
      ...addonOptions,
    };
  } else {
    if (version != null) {
      throw new Error("You provided a version for an add-on that doesn't support choosing the version.");
    }
    return {};
  }
}
 
export async function create({ ownerId, name, providerName, planName, region, version, addonOptions }) {
  // TODO: We should be able to use it without {}
  const provider = await getProvider(providerName, ownerId);

  if (!provider.regions.includes(region)) {
    throw new Error(`Invalid region name. Available regions: ${provider.regions.join(', ')}`);
  }
  if (provider.plans.length === 0) {
    throw new Error(`No plans available for provider ${providerName}`);
  }

  const plan = getPlan(planName, provider.plans);

  const providerInfos = await getProviderInfos(provider.id);
  const planType = plan.features.find(({ name }) => name.toLowerCase() === 'type');

  // If we have a providerInfos but we don't have a planType, we won't be able to go further
  // The process should stop here to make sure users don't create something they don't intend to
  // This missing feature should have been added during the add-on's development phase
  // The console has a similar check so I believe we shouldn't hit this
  if (providerInfos != null && planType == null) {
    throw new Error(
      'Internal error. The selected plan misses the TYPE feature. Please contact our support with the command line you used',
    );
  }

  const createOptions = validateAddonVersionAndOptions(region, version, addonOptions, providerInfos, planType);

  const addonToCreate = {
    name,
    plan: plan.id,
    providerId: provider.id,
    region,
    options: createOptions,
  };

  const createdAddon = await createAddon({ id: ownerId }, addonToCreate).then(sendToApi);
  createdAddon.env = await getAllEnvVars({ id: ownerId, addonId: createdAddon.id }).then(sendToApi);

  return createdAddon;
}
 
async function getByName(ownerId, addonNameOrRealId) {
  const addons = await getAllAddons({ id: ownerId }).then(sendToApi);
  const filteredAddons = addons.filter(({ name, realId }) => {
    return name === addonNameOrRealId || realId === addonNameOrRealId;
  });
  if (filteredAddons.length === 1) {
    return filteredAddons[0];
  }
  if (filteredAddons.length === 0) {
    throw new Error('Addon not found');
  }
  throw new Error('Ambiguous addon name');
}
 
async function getId(ownerId, addon) {
  if (addon.addon_id) {
    return addon.addon_id;
  }
  const addonDetails = await getByName(ownerId, addon.addon_name);
  return addonDetails.id;
}
 
export async function link(ownerId, appId, addon) {
  const addonId = await getId(ownerId, addon);
  return linkAddon({ id: ownerId, appId }, JSON.stringify(addonId)).then(sendToApi);
}
 
export async function unlink(ownerId, appId, addon) {
  const addonId = await getId(ownerId, addon);
  return unlinkAddon({ id: ownerId, appId, addonId }).then(sendToApi);
}
 
export async function deleteAddon(ownerId, addonIdOrName, skipConfirmation) {
  const addonId = await getId(ownerId, addonIdOrName);

  if (!skipConfirmation) {
    await confirm("Deleting the add-on can't be undone, are you sure?", 'No confirmation, aborting add-on deletion');
  }

  return removeAddon({ id: ownerId, addonId }).then(sendToApi);
}
 
export async function rename(ownerId, addon, name) {
  const addonId = await getId(ownerId, addon);
  return updateAddon({ id: ownerId, addonId }, { name }).then(sendToApi);
}
 
export function completeRegion() {
  return ['par', 'mtl'];
}
 
// TODO: We need to fix this
export function completePlan() {
  return ['dev', 's', 'm', 'l', 'xl', 'xxl'];
}
 
export async function findByName(addonName) {
  const { user, organisations } = await getSummary({}).then(sendToApi);
  for (const orga of [user, ...organisations]) {
    for (const simpleAddon of orga.addons) {
      if (simpleAddon.name === addonName) {
        const addon = await getAddon({ id: orga.id, addonId: simpleAddon.id }).then(sendToApi);
        return {
          ...addon,
          orgaId: orga.id,
        };
      }
    }
  }
  throw new Error(`Could not find add-on with name ${addonName}`);
}
 
export async function findOwnerId(org, addonId) {
  if (org != null && org.orga_id != null) {
    return org.orga_id;
  }

  const ownerId = await resolveOwnerId(addonId);
  if (ownerId != null) {
    return ownerId;
  }

  throw new Error(`Add-on ${addonId} does not exist`);
}
 
export function parseAddonOptions(options) {
  if (options == null) {
    return {};
  }

  const pairs = options.split(/,(?=\w+(?:-\w+)*=)/) || [];

  return pairs.reduce((options, pair) => {
    const [key, ...valueParts] = pair.split('=');
    const value = valueParts.join('=');

    if (value == null) {
      throw new Error("Options are malformed. Usage is '--option name=enabled|disabled|true|false|plugin1,plugin2'");
    }

    let formattedValue = value;
    if (value === 'true' || value === 'enabled') {
      formattedValue = 'true';
    } else if (value === 'false' || value === 'disabled') {
      formattedValue = 'false';
    } else if (typeof key === 'string') {
      formattedValue = value;
    } else {
      throw new Error(`Can't parse option value: ${value}. Accepted values are: enabled, disabled, true, false`);
    }

    options[key] = formattedValue;
    return options;
  }, {});
}
 
function getPlan(planName, plans) {
  // if no plan specified, pick the cheapest one
  if (planName == null || planName === '') {
    return plans.sort((p1, p2) => p1.price - p2.price)[0];
  }

  const plan = plans.find((p) => p.slug.toLowerCase() === planName.toLowerCase());
  if (plan == null) {
    const availablePlans = plans.map((p) => p.slug);
    throw new Error(`Invalid plan name. Available plans: ${availablePlans.join(', ')}`);
  }
  return plan;
}