All files / server/src/kompassi getProgramItemsFromKompassi.ts

73.11% Statements 68/93
51.78% Branches 29/56
100% Functions 14/14
73.11% Lines 68/93

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 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319                                            49x       23x 23x 1x     22x   22x 1x     1x     21x 1x 1x     20x   20x   20x         49x 2002x             49x               49x       1044x               1044x   1044x 369x     675x 675x   958x           958x           675x                     49x     10x   10x             49x       49x 10x   10x   10x               10x     49x           49x 2x               2x           49x   49x     2x   2x   2x 2x                                                                   2x   2x 2x                 1x 1x         1x                               1x         1x         49x       20x 1044x       1044x 8353x       20x 1x               49x     31x 124x   31x                 31x                 31x                 31x              
import fs from "node:fs";
import path from "node:path";
import { unique } from "remeda";
import { ZodError, z } from "zod";
import { config } from "shared/config";
import { EventName } from "shared/config/eventConfigTypes";
import { KompassiError } from "shared/types/api/errors";
import { ProgramType } from "shared/types/models/programItem";
import { exhaustiveSwitchGuard } from "shared/utils/exhaustiveSwitchGuard";
import {
  Result,
  makeErrorResult,
  makeSuccessResult,
} from "shared/utils/result";
import { getProgramItemsFromFullProgram } from "server/kompassi/getProgramItemsFromFullProgram";
import {
  KompassiKonstiProgramType,
  KompassiProgramItem,
  KompassiProgramItemSchema,
} from "server/kompassi/kompassiProgramItem";
import { logger } from "server/utils/logger";
 
export const getProgramItemsFromKompassi = async (): Promise<
  Result<KompassiProgramItem[], KompassiError>
> => {
  const eventProgramItemsResult =
    await testHelperWrapper.getEventProgramItems();
  if (!eventProgramItemsResult.ok) {
    return eventProgramItemsResult;
  }
 
  const eventProgramItems = eventProgramItemsResult.value;
 
  if (!Array.isArray(eventProgramItems)) {
    logger.error(
      new Error("Invalid Kompassi response format, should be array"),
    );
    return makeErrorResult(KompassiError.INVALID_RESPONSE);
  }
 
  if (eventProgramItems.length === 0) {
    logger.error(new Error("No program items found"));
    return makeErrorResult(KompassiError.NO_PROGRAM_ITEMS);
  }
 
  logger.info(`Loaded ${eventProgramItems.length} event program items`);
 
  const programItems = getProgramItemsFromFullProgram(eventProgramItems);
 
  return programItems.length === 0
    ? makeErrorResult(KompassiError.NO_PROGRAM_ITEMS)
    : makeSuccessResult(programItems);
};
 
const getProgramItemId = (programItem: unknown): unknown => {
  return !!programItem &&
    typeof programItem === "object" &&
    "slug" in programItem
    ? programItem.slug
    : "<unknown>";
};
 
const getProgramItemIsCancelled = (programItem: unknown): unknown => {
  return !!programItem &&
    typeof programItem === "object" &&
    "isCancelled" in programItem
    ? programItem.isCancelled
    : "<unknown>";
};
 
export const parseProgramItem = (
  programItem: unknown,
  schema: typeof KompassiProgramItemSchema,
): KompassiProgramItem | undefined => {
  Iif (
    config
      .event()
      .ignoreProgramItemsIds.includes(getProgramItemId(programItem) as string)
  ) {
    return;
  }
 
  const result = schema.safeParse(programItem);
 
  if (result.success) {
    return result.data;
  }
 
  Eif (result.error instanceof ZodError) {
    result.error.issues.map((issue) => {
      // Don't log missing scheduleItems error if program item is cancelled
      Iif (String(issue.path) === "scheduleItems") {
        const isCancelled = getProgramItemIsCancelled(programItem);
        if (isCancelled) {
          return;
        }
      }
      logger.error(
        new Error(
          `Invalid program item ${String(getProgramItemId(programItem))} at path ${issue.path.join(".")}: ${issue.message}`,
        ),
      );
    });
    return;
  }
 
  logger.error(
    new Error(
      `Unknown error while parsing program item ${String(getProgramItemId(programItem))}`,
      { cause: result.error },
    ),
  );
};
 
const getEventProgramItems = async (): Promise<
  Result<unknown, KompassiError>
> => {
  const { useLocalProgramFile } = config.server();
 
  return useLocalProgramFile
    ? getProgramFromLocalFile()
    : await getProgramFromServer();
};
 
// This helper wrapper is needed to make Vitest spyOn() work
//  https://github.com/vitest-dev/vitest/issues/1329
export const testHelperWrapper = {
  getEventProgramItems,
};
 
const getProgramFromLocalFile = (): Result<unknown, KompassiError> => {
  logger.info("GET event program from local filesystem");
 
  const { localKompassiFile } = config.server();
 
  const rawData = fs.readFileSync(
    path.join(
      import.meta.dirname,
      `../test/kompassi-data-dumps/${localKompassiFile}`,
    ),
    "utf8",
  );
 
  return makeSuccessResult(JSON.parse(rawData));
};
 
const KompassiResponseFormSchema = z.object({
  data: z.object({
    event: z.object({ program: z.object({ programs: z.array(z.unknown()) }) }),
  }),
});
 
export const eventNameToKompassiEventName = (eventName: EventName): string => {
  switch (eventName) {
    case EventName.ROPECON:
      return "ropecon";
    case EventName.HITPOINT:
      return "hitpoint";
    case EventName.SOLMUKOHTA:
      return "solmukohta";
    case EventName.TRACON:
      return "tracon";
    default:
      return exhaustiveSwitchGuard(eventName);
  }
};
 
const fetchTimeoutMs = 1000 * 30;
 
export const getProgramFromServer = async (): Promise<
  Result<unknown, KompassiError>
> => {
  logger.info("GET event program from remote server");
 
  const { eventName, eventYear, activeProgramTypes } = config.event();
 
  const url = "https://kompassi.eu/graphql";
  const body = {
    query: `
      query ProgramListQuery($event: String!, $programTypes: [String!]! ) {
          event(slug: $event) {
              program {
                  programs(hidePast: false, filters: [{ dimension: "konsti", values: $programTypes }]) {
                      slug
                      title
                      description
                      cachedHosts
                      cachedDimensions
                      cachedAnnotations
                      isCancelled
                      scheduleItems {
                          slug
                          title
                          startTime
                          endTime
                          lengthMinutes
                          location
                          isCancelled
                          cachedAnnotations
                      }
                  }
              }
          }
      }
    `,
    variables: {
      event: `${eventNameToKompassiEventName(eventName)}${eventYear}`,
      programTypes:
        mapKonstiProgramTypesToKompassiProgramTypes(activeProgramTypes),
    },
  };
  const headers = { "Content-Type": "application/json" };
 
  try {
    const response = await fetch(url, {
      method: "POST",
      headers,
      body: JSON.stringify(body),
      // Well inside the 5-minute update interval, so a hung Kompassi fails this tick rather
      // than blocking the next one
      signal: AbortSignal.timeout(fetchTimeoutMs),
    });
    // An error page is not JSON, so parsing it would report a syntax error instead of the status
    Eif (!response.ok) {
      logger.error(
        new Error(
          `Error downloading program items from Kompassi: responded ${response.status} ${response.statusText}`,
        ),
      );
      return makeErrorResult(KompassiError.UNKNOWN_ERROR);
    }
    const responseData = await response.json();
    const result = KompassiResponseFormSchema.safeParse(responseData);
    if (!result.success) {
      logger.error(
        new Error(
          "Error downloading program items from Kompassi: Invalid return value format",
          { cause: result.error },
        ),
      );
      return makeErrorResult(KompassiError.UNKNOWN_ERROR);
    }
    const programItems = result.data.data.event.program.programs;
    return makeSuccessResult(programItems);
  } catch (error) {
    logger.error(
      new Error("Error downloading program items from Kompassi", {
        cause: error,
      }),
    );
    return makeErrorResult(KompassiError.UNKNOWN_ERROR);
  }
};
 
// TODO: Only checks top level object keys, not nested object keys
export const checkUnknownKeys = (
  programItems: unknown[],
  schema: typeof KompassiProgramItemSchema,
): void => {
  const unknownKeys: string[] = programItems.flatMap((programItem) => {
    Iif (!programItem || typeof programItem !== "object") {
      return [];
    }
 
    return Object.keys(programItem).filter(
      (key) => !Object.prototype.hasOwnProperty.call(schema.shape, key),
    );
  });
 
  if (unknownKeys.length > 0) {
    logger.error(
      new Error(
        `Found unknown keys for program items: ${unique(unknownKeys).join(" ")}`,
      ),
    );
  }
};
 
export const mapKonstiProgramTypesToKompassiProgramTypes = (
  programTypes: ProgramType[],
): KompassiKonstiProgramType[] => {
  return programTypes.map((programType) => {
    switch (programType) {
      case ProgramType.TABLETOP_RPG:
        return KompassiKonstiProgramType.TABLETOP_RPG;
 
      case ProgramType.LARP:
        return KompassiKonstiProgramType.LARP;
 
      case ProgramType.TOURNAMENT:
        return KompassiKonstiProgramType.TOURNAMENT;
 
      case ProgramType.WORKSHOP:
        return KompassiKonstiProgramType.WORKSHOP;
 
      case ProgramType.EXPERIENCE_POINT:
        return KompassiKonstiProgramType.EXPERIENCE_POINT;
 
      case ProgramType.OTHER:
        return KompassiKonstiProgramType.OTHER;
 
      case ProgramType.FLEAMARKET:
        return KompassiKonstiProgramType.FLEAMARKET;
 
      case ProgramType.ROUNDTABLE_DISCUSSION:
        return KompassiKonstiProgramType.ROUNDTABLE_DISCUSSION;
 
      case ProgramType.OTHER_GAMING:
        return KompassiKonstiProgramType.OTHER_GAMING;
 
      case ProgramType.BOARDGAME:
        return KompassiKonstiProgramType.BOARDGAME;
 
      default:
        return exhaustiveSwitchGuard(programType);
    }
  });
};