All files / publisher/pages/Releases releasesState.ts

66.19% Statements 47/71
51.35% Branches 19/37
52.63% Functions 10/19
65.71% Lines 46/70

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                            3x 3x 5x 5x     3x                   3x       5x 5x   5x 5x       5x 5x             5x 5x       2x 1x 1x     1x                         2x     5x 5x     5x         3x                                                                     2x 2x 2x   2x 2x 2x     2x 2x 2x   2x 2x   2x   2x               2x                                                         2x                       1x   1x   1x 2x   2x 1x 1x         1x                                                    
import {
  ArchitectureRevisionsMap,
  Channel,
  ChannelArchitectureRevisionsMap,
  ChannelMap,
  CPUArchitecture,
  FailedRevision,
  Release,
  Revision,
  RevisionsMap,
} from "../../types/releaseTypes";
import { RISKS } from "./constants";
 
function getRevisionsMap(revisions: Revision[]): RevisionsMap {
  const revisionsMap: { [revision: number]: Revision } = {};
  revisions.forEach((rev) => {
    rev.channels = [];
    revisionsMap[rev.revision] = rev;
  });
 
  return revisionsMap;
}
 
// init channels data in revision history
function initReleasesData(
  revisionsMap: RevisionsMap,
  releases: Release[],
  channelMap?: ChannelMap[]
): Release[] {
  // go through releases from older to newest
  releases
    .slice()
    .reverse()
    .forEach((release) => {
      Eif (release.revision) {
        const rev = revisionsMap[release.revision];
 
        Eif (rev) {
          const channel = release.branch
            ? `${release.track}/${release.risk}/${release.branch}`
            : `${release.track}/${release.risk}`;
 
          Eif (rev.channels?.indexOf(channel) === -1) {
            rev.channels.push(channel);
          }
 
          // Technically, we should not modify the release object,
          // but to simplify other parts of the code, we do it
          // here - nice and early during initialization.
          // Sorry, love Luke xox.
          release.isProgressive = false;
          if (release.progressive?.percentage) {
            // Based on the note at the top of
            // https://dashboard.snapcraft.io/docs/reference/v1/snap.html#progressive-releases
            // We need to get the channelMap to hydrate the current percentage
            if (channelMap) {
              const currentChannel = channelMap.find(
                (c) => c.channel === channel && c.revision === release.revision
              );
 
              Iif (currentChannel) {
                // the current channel might have different percentages
                // compared to the release object, so we need to update
                // it to match the current channel's percentages
                release.progressive = { ...currentChannel.progressive };
              }
            }
 
            // Now that we have the updated percentages, we can determine if
            // this is a still ongoing progressive release: the target
            // percentage coming from the channel map might be `null`, which
            // means that the release has been completed. If that's the case,
            // we shouldn't mark it as progressive
            release.isProgressive = release.progressive.percentage !== null;
          }
 
          Eif (!rev.releases) {
            rev.releases = [];
          }
 
          rev.releases.unshift(release);
        }
      }
    });
 
  return releases;
}
 
// Get specific revision based on snapName and a channelMap object
function fetchMissingRevision(
  snapName: string,
  info: ChannelMap
): Promise<
  | {
      info: ChannelMap;
      revision: Revision;
    }
  | { info: ChannelMap; error: string; revision: never }
> {
  return fetch(`/${snapName}/releases/revision/${info.revision}`)
    .then((res) => res.json() as Promise<{ revision: Revision }>)
    .then((revision) => ({
      info,
      revision: revision.revision,
    }))
    .catch((err) =>
      Promise.reject({
        info,
        error: err.message,
      })
    );
}
 
// transforming channel map list data into format used by this component
// https://dashboard.snapcraft.io/docs/v2/en/snaps.html#snap-channel-map
async function getReleaseDataFromChannelMap(
  channelMaps: ChannelMap[],
  revisionList: Revision[],
  snapName: string
): Promise<[ChannelArchitectureRevisionsMap, Revision[], FailedRevision[]]> {
  return new Promise((resolve) => {
    const releasedChannels: ChannelArchitectureRevisionsMap = {};
    const missingRevisions: ReturnType<typeof fetchMissingRevision>[] = [];
 
    channelMaps.forEach((mapInfo) => {
      Eif (!releasedChannels[mapInfo.channel]) {
        releasedChannels[mapInfo.channel] = {} as ArchitectureRevisionsMap;
      }
 
      Eif (!releasedChannels[mapInfo.channel][mapInfo.architecture]) {
        const revisionInfo = revisionList.find(
          (r) => r.revision === mapInfo.revision
        );
        if (revisionInfo) {
          releasedChannels[mapInfo.channel][mapInfo.architecture] =
            revisionInfo;
          releasedChannels[mapInfo.channel][mapInfo.architecture]!.expiration =
            mapInfo["expiration-date"];
          releasedChannels[mapInfo.channel][mapInfo.architecture]!.progressive =
            mapInfo["progressive"];
        } else E{
          missingRevisions.push(fetchMissingRevision(snapName, mapInfo));
        }
      }
    });
 
    Iif (missingRevisions.length > 0) {
      Promise.allSettled(missingRevisions)
        .then((results) => {
          const successfulRevisions: Revision[] = [];
          const failedRevisions: FailedRevision[] = [];
 
          results.forEach((result) => {
            if (result.status === "fulfilled") {
              const { info, revision } = result.value;
              releasedChannels[info.channel][info.architecture] = revision;
              releasedChannels[info.channel][info.architecture]!.expiration =
                info?.["expiration-date"];
              successfulRevisions.push(revision);
            } else {
              const { info } = result.reason;
              failedRevisions.push({
                channel: info.channel,
                architecture: info.architecture,
              });
            }
          });
 
          resolve([releasedChannels, successfulRevisions, failedRevisions]);
        })
        .catch(() => {
          // if a call doesn't work for whatever reason
          resolve([releasedChannels, [], []]);
        });
    } else {
      resolve([releasedChannels, [], []]);
    }
  });
}
 
// for channel without release get next (less risk) channel with a release
function getTrackingChannel(
  releasedChannels: ChannelArchitectureRevisionsMap,
  track: Channel["track"],
  risk: Channel["risk"],
  arch: CPUArchitecture
): string | null {
  let tracking = null;
  // if there is no revision for this arch in given channel (track/risk)
  Eif (!releasedChannels?.[`${track}/${risk}`]?.[arch]) {
    // find the next channel that has any revision
    for (let i = RISKS.indexOf(risk); i >= 0; i--) {
      const trackingChannel = `${track}/${RISKS[i]}`;
 
      if (releasedChannels?.[trackingChannel]?.[arch]) {
        tracking = trackingChannel;
        break;
      }
    }
  }
 
  return tracking;
}
 
function getUnassignedRevisions(
  revisionsMap: RevisionsMap,
  arch: CPUArchitecture
): Revision[] {
  let filteredRevisions = Object.values(revisionsMap).reverse();
  if (arch) {
    filteredRevisions = filteredRevisions.filter((revision) => {
      return (
        revision.architectures.includes(arch) &&
        (!revision.channels || revision.channels.length === 0)
      );
    });
  }
  return filteredRevisions;
}
 
export {
  getReleaseDataFromChannelMap,
  getRevisionsMap,
  getTrackingChannel,
  getUnassignedRevisions,
  initReleasesData,
};