All files / server/src/features/settings settingsRepository.ts

68.98% Statements 109/158
66.66% Branches 32/48
100% Functions 13/13
68.98% Lines 109/158

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 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470                                      58x     58x 2x         58x 423x 423x 423x 423x                 58x     476x 476x 476x 476x   474x 474x                 474x   474x       2x 2x 2x 2x 2x 2x               2x                                   58x     3251x 3251x   3251x 452x 452x     452x     3144x   2799x 3144x                 3144x                 58x         13x 13x       13x 13x                 13x       13x   13x 13x                 13x                     58x     442x 442x                           442x 2x   440x       440x 440x                 440x                     58x     5x 5x                 5x 1x 1x   4x   4x 4x                 4x                     58x         245x 245x       245x 245x             245x     245x   245x 245x                 245x                 58x     5x 5x                     5x 2x   3x     3x                           58x         58x     51x 51x   51x                                   51x       5x 5x           46x 46x                     58x     41x 41x                 41x 41x                     58x     40x 40x     40x     40x 40x                     58x     14x 14x 14x       14x 14x                 14x                    
import dayjs from "dayjs";
import { MongoDbError } from "shared/types/api/errors";
import { PostSettingsRequest } from "shared/types/api/settings";
import { Settings, SignupQuestion } from "shared/types/models/settings";
import {
  Result,
  makeErrorResult,
  makeSuccessResult,
} from "shared/utils/result";
import {
  SETTINGS_SINGLETON_KEY,
  SettingsModel,
  SettingsSchemaDb,
} from "server/features/settings/settingsSchema";
import { logger } from "server/utils/logger";
 
// All queries target the single settings document by its unique key, so a
// concurrent create loses on duplicate key instead of inserting a second
// document that would shadow the first
const settingsFilter = { singleton: SETTINGS_SINGLETON_KEY };
 
// Mongo's duplicate key error: another caller created the document first
const isDuplicateKeyError = (error: unknown): boolean =>
  typeof error === "object" &&
  error !== null &&
  "code" in error &&
  error.code === 11000;
 
export const removeSettings = async (): Promise<Result<void, MongoDbError>> => {
  logger.info("MongoDB: remove ALL settings from db");
  try {
    await SettingsModel.deleteMany({});
    return makeSuccessResult();
  } catch (error) {
    logger.error(
      new Error("MongoDB: Error removing settings", { cause: error }),
    );
    return makeErrorResult(MongoDbError.UNKNOWN_ERROR);
  }
};
 
export const createSettings = async (): Promise<
  Result<Settings, MongoDbError>
> => {
  logger.info("MongoDB: Create default settings");
  const defaultSettings = new SettingsModel();
  try {
    const settings = await defaultSettings.save();
 
    const result = SettingsSchemaDb.safeParse(settings.toObject());
    Iif (!result.success) {
      logger.error(
        new Error(`Error validating createSettings DB value`, {
          cause: result.error,
        }),
      );
      return makeErrorResult(MongoDbError.UNKNOWN_ERROR);
    }
 
    logger.info("MongoDB: Default settings saved to DB");
 
    return makeSuccessResult(result.data);
  } catch (error) {
    // Another caller won the race and created the document; read theirs
    // instead of failing or inserting a duplicate
    Eif (isDuplicateKeyError(error)) {
      logger.info("MongoDB: Default settings already created, reading those");
      try {
        const existing = await SettingsModel.findOne(settingsFilter).lean();
        const existingResult = SettingsSchemaDb.safeParse(existing);
        Iif (!existingResult.success) {
          logger.error(
            new Error("Error validating existing settings DB value", {
              cause: existingResult.error,
            }),
          );
          return makeErrorResult(MongoDbError.UNKNOWN_ERROR);
        }
        return makeSuccessResult(existingResult.data);
      } catch (readError) {
        logger.error(
          new Error("MongoDB: Error reading existing settings", {
            cause: readError,
          }),
        );
        return makeErrorResult(MongoDbError.UNKNOWN_ERROR);
      }
    }
 
    logger.error(
      new Error("MongoDB: Add default settings error", { cause: error }),
    );
    return makeErrorResult(MongoDbError.UNKNOWN_ERROR);
  }
};
 
export const findOrCreateSettings = async (): Promise<
  Result<Settings, MongoDbError>
> => {
  try {
    const settings = await SettingsModel.findOne(settingsFilter).lean();
 
    if (!settings) {
      const createSettingsResult = await createSettings();
      Iif (!createSettingsResult.ok) {
        return createSettingsResult;
      }
      return makeSuccessResult(createSettingsResult.value);
    }
 
    logger.debug("MongoDB: Settings data found");
 
    const result = SettingsSchemaDb.safeParse(settings);
    Iif (!result.success) {
      logger.error(
        new Error(`Error validating findOrCreateSettings DB value`, {
          cause: result.error,
        }),
      );
      return makeErrorResult(MongoDbError.UNKNOWN_ERROR);
    }
 
    return makeSuccessResult(result.data);
  } catch (error) {
    logger.error(
      new Error("MongoDB: Error finding settings data", { cause: error }),
    );
    return makeErrorResult(MongoDbError.UNKNOWN_ERROR);
  }
};
 
export const saveHidden = async (
  hiddenProgramItemIds: readonly string[],
): Promise<Result<Settings, MongoDbError>> => {
  // Create through the one designated creator rather than upserting here: a
  // second creator is what lets two documents exist in the first place
  const settingsResult = await findOrCreateSettings();
  Iif (!settingsResult.ok) {
    return settingsResult;
  }
 
  try {
    const settings = await SettingsModel.findOneAndUpdate(
      settingsFilter,
      {
        hiddenProgramItemIds,
      },
      {
        returnDocument: "after",
      },
    ).lean();
    Iif (!settings) {
      return makeErrorResult(MongoDbError.SETTINGS_NOT_FOUND);
    }
 
    logger.info("MongoDB: Hidden data updated");
 
    const result = SettingsSchemaDb.safeParse(settings);
    Iif (!result.success) {
      logger.error(
        new Error(`Error validating saveHidden DB value`, {
          cause: result.error,
        }),
      );
      return makeErrorResult(MongoDbError.UNKNOWN_ERROR);
    }
 
    return makeSuccessResult(result.data);
  } catch (error) {
    logger.error(
      new Error("MongoDB: Error updating hidden program items", {
        cause: error,
      }),
    );
    return makeErrorResult(MongoDbError.UNKNOWN_ERROR);
  }
};
 
export const saveSignupQuestion = async (
  signupQuestionData: SignupQuestion,
): Promise<Result<Settings, MongoDbError>> => {
  try {
    const settings = await SettingsModel.findOneAndUpdate(
      {
        ...settingsFilter,
        "signupQuestions.programItemId": {
          $ne: signupQuestionData.programItemId,
        },
      },
      {
        $addToSet: { signupQuestions: signupQuestionData },
      },
      {
        returnDocument: "after",
      },
    ).lean();
    if (!settings) {
      return makeErrorResult(MongoDbError.SETTINGS_NOT_FOUND);
    }
    logger.info(
      `MongoDB: Signup question updated: ${JSON.stringify(signupQuestionData)}`,
    );
 
    const result = SettingsSchemaDb.safeParse(settings);
    Iif (!result.success) {
      logger.error(
        new Error(`Error validating saveSignupQuestion DB value`, {
          cause: result.error,
        }),
      );
      return makeErrorResult(MongoDbError.UNKNOWN_ERROR);
    }
 
    return makeSuccessResult(result.data);
  } catch (error) {
    logger.error(
      new Error("MongoDB: Error updating program item signup question", {
        cause: error,
      }),
    );
    return makeErrorResult(MongoDbError.UNKNOWN_ERROR);
  }
};
 
export const delSignupQuestion = async (
  programItemId: string,
): Promise<Result<Settings, MongoDbError>> => {
  try {
    const settings = await SettingsModel.findOneAndUpdate(
      settingsFilter,
      {
        $pull: { signupQuestions: { programItemId } },
      },
      {
        returnDocument: "after",
      },
    ).lean();
    if (!settings) {
      logger.error(new Error("MongoDB: Signup question not found"));
      return makeErrorResult(MongoDbError.SIGNUP_QUESTION_NOT_FOUND);
    }
    logger.info("MongoDB: Signup info deleted");
 
    const result = SettingsSchemaDb.safeParse(settings);
    Iif (!result.success) {
      logger.error(
        new Error(`Error validating delSignupQuestion DB value`, {
          cause: result.error,
        }),
      );
      return makeErrorResult(MongoDbError.UNKNOWN_ERROR);
    }
 
    return makeSuccessResult(result.data);
  } catch (error) {
    logger.error(
      new Error("MongoDB: Error deleting program item signup question", {
        cause: error,
      }),
    );
    return makeErrorResult(MongoDbError.UNKNOWN_ERROR);
  }
};
 
export const saveSettings = async (
  settings: PostSettingsRequest,
): Promise<Result<Settings, MongoDbError>> => {
  // Create through the one designated creator rather than upserting here: a
  // second creator is what lets two documents exist in the first place
  const existingSettingsResult = await findOrCreateSettings();
  Iif (!existingSettingsResult.ok) {
    return existingSettingsResult;
  }
 
  try {
    const updatedSettings = await SettingsModel.findOneAndUpdate(
      settingsFilter,
      settings,
      {
        returnDocument: "after",
      },
    ).lean();
    Iif (!updatedSettings) {
      return makeErrorResult(MongoDbError.SETTINGS_NOT_FOUND);
    }
    logger.info("MongoDB: App settings updated");
 
    const result = SettingsSchemaDb.safeParse(updatedSettings);
    Iif (!result.success) {
      logger.error(
        new Error(`Error validating saveSettings DB value`, {
          cause: result.error,
        }),
      );
      return makeErrorResult(MongoDbError.UNKNOWN_ERROR);
    }
 
    return makeSuccessResult(result.data);
  } catch (error) {
    logger.error(
      new Error("MongoDB: Error updating app settings", { cause: error }),
    );
    return makeErrorResult(MongoDbError.UNKNOWN_ERROR);
  }
};
 
export const setProgramUpdateLastRun = async (
  programUpdateNextRun: string,
): Promise<Result<void, MongoDbError>> => {
  try {
    const response = await SettingsModel.findOneAndUpdate(
      {
        ...settingsFilter,
        programUpdateLastRun: {
          $lt: dayjs(programUpdateNextRun).subtract(30, "seconds").toDate(),
        },
      },
      {
        programUpdateLastRun: programUpdateNextRun,
      },
    ).lean();
    if (!response) {
      return makeErrorResult(MongoDbError.SETTINGS_NOT_FOUND);
    }
    logger.info(
      `MongoDB: Program update last run set: ${programUpdateNextRun}`,
    );
    return makeSuccessResult();
  } catch (error) {
    logger.error(
      new Error("MongoDB: Error updating program update last run", {
        cause: error,
      }),
    );
    return makeErrorResult(MongoDbError.UNKNOWN_ERROR);
  }
};
 
// A held assignment lock older than this is treated as abandoned (a run that crashed without
// releasing it) and can be reclaimed, so a crash can't deadlock assignments forever. Keep it
// comfortably longer than any real assignment run so a slow run isn't reclaimed mid-flight
export const ASSIGNMENT_LOCK_STALE_TIMEOUT_MINUTES = 5;
 
// Acquire the assignment-in-progress lock if it is free or stale. Returns the lock token (the
// acquisition time) to pass to releaseAssignmentLock, or SETTINGS_NOT_FOUND if another run
// currently holds it
export const acquireAssignmentLock = async (): Promise<
  Result<string, MongoDbError>
> => {
  const lockStartTime = dayjs().toISOString();
  try {
    // Acquire if the lock is free (null) or stale (acquired longer ago than the timeout)
    const response = await SettingsModel.findOneAndUpdate(
      {
        ...settingsFilter,
        $or: [
          { assignmentInProgressStartTime: null },
          {
            assignmentInProgressStartTime: {
              $lt: dayjs(lockStartTime)
                .subtract(ASSIGNMENT_LOCK_STALE_TIMEOUT_MINUTES, "minutes")
                .toDate(),
            },
          },
        ],
      },
      {
        assignmentInProgressStartTime: lockStartTime,
      },
    ).lean();
    if (!response) {
      // No document matched the update: either another run holds the lock, or there is no
      // settings row at all — distinguish the two so the caller can treat a missing row as a
      // genuine error rather than as "already running"
      const settingsExists = await SettingsModel.exists(settingsFilter);
      return makeErrorResult(
        settingsExists
          ? MongoDbError.ASSIGNMENT_LOCK_HELD
          : MongoDbError.SETTINGS_NOT_FOUND,
      );
    }
    logger.info(`MongoDB: Assignment lock acquired at ${lockStartTime}`);
    return makeSuccessResult(lockStartTime);
  } catch (error) {
    logger.error(
      new Error("MongoDB: Error acquiring assignment lock", { cause: error }),
    );
    return makeErrorResult(MongoDbError.UNKNOWN_ERROR);
  }
};
 
// Release the assignment-in-progress lock, but only if we still hold it (the token matches) —
// if the lock was reclaimed as stale and re-acquired by another run, this must not clobber it
export const releaseAssignmentLock = async (
  lockToken: string,
): Promise<Result<void, MongoDbError>> => {
  try {
    await SettingsModel.findOneAndUpdate(
      {
        ...settingsFilter,
        assignmentInProgressStartTime: dayjs(lockToken).toDate(),
      },
      {
        assignmentInProgressStartTime: null,
      },
    ).lean();
    logger.info("MongoDB: Assignment lock released");
    return makeSuccessResult();
  } catch (error) {
    logger.error(
      new Error("MongoDB: Error releasing assignment lock", { cause: error }),
    );
    return makeErrorResult(MongoDbError.UNKNOWN_ERROR);
  }
};
 
// Record the time of the last completed assignment. This is informational only — the run lock
// is acquireAssignmentLock — so set it unconditionally to always reflect the latest run
export const setAssignmentLastRun = async (
  assignmentLastRun: string,
): Promise<Result<void, MongoDbError>> => {
  try {
    const response = await SettingsModel.findOneAndUpdate(settingsFilter, {
      assignmentLastRun,
    }).lean();
    Iif (!response) {
      return makeErrorResult(MongoDbError.SETTINGS_NOT_FOUND);
    }
    logger.info(`MongoDB: Assignment last run set: ${assignmentLastRun}`);
    return makeSuccessResult();
  } catch (error) {
    logger.error(
      new Error("MongoDB: Error updating assignment last run", {
        cause: error,
      }),
    );
    return makeErrorResult(MongoDbError.UNKNOWN_ERROR);
  }
};
 
export const getLatestServerStartTime = async (): Promise<
  Result<string, MongoDbError>
> => {
  try {
    const response = await SettingsModel.findOne(settingsFilter).lean();
    Iif (!response) {
      return makeErrorResult(MongoDbError.SETTINGS_NOT_FOUND);
    }
 
    const result = SettingsSchemaDb.safeParse(response);
    Iif (!result.success) {
      logger.error(
        new Error(`Error validating getLatestServerStartTime DB value`, {
          cause: result.error,
        }),
      );
      return makeErrorResult(MongoDbError.UNKNOWN_ERROR);
    }
 
    return makeSuccessResult(result.data.latestServerStartTime);
  } catch (error) {
    logger.error(
      new Error("MongoDB: Error getting latest server start time", {
        cause: error,
      }),
    );
    return makeErrorResult(MongoDbError.UNKNOWN_ERROR);
  }
};