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

69.4% Statements 93/134
68.75% Branches 22/32
100% Functions 12/12
69.4% Lines 93/134

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                              54x 288x 288x 288x 288x                 54x     344x 344x 344x 344x   344x 344x                 344x   344x                 54x     1993x 1993x   1993x 322x 322x     322x     1902x   1671x 1902x                 1902x                 54x     13x 13x                     13x   13x 13x                 13x                     54x     81x 81x                         81x 2x   79x       79x 79x                 79x                     54x     5x 5x                 5x 1x 1x   4x   4x 4x                 4x                     54x     187x 187x       187x   187x 187x                 187x                 54x     5x 5x                   5x 2x   3x     3x                           54x         54x     33x 33x   33x                                 33x       5x 5x           28x 28x                     54x     23x 23x               23x 23x                     54x     22x 22x           22x     22x 22x                     54x     14x 14x 14x       14x 14x                 14x                    
import dayjs from "dayjs";
import { logger } from "server/utils/logger";
import {
  SettingsModel,
  SettingsSchemaDb,
} from "server/features/settings/settingsSchema";
import { Settings, SignupQuestion } from "shared/types/models/settings";
import { PostSettingsRequest } from "shared/types/api/settings";
import {
  Result,
  makeSuccessResult,
  makeErrorResult,
} from "shared/utils/result";
import { MongoDbError } from "shared/types/api/errors";
 
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: ${JSON.stringify(result.error)}`,
        ),
      );
      return makeErrorResult(MongoDbError.UNKNOWN_ERROR);
    }
 
    logger.info("MongoDB: Default settings saved to DB");
 
    return makeSuccessResult(result.data);
  } catch (error) {
    logger.error(
      new Error("MongoDB: Add default settings error", { cause: error }),
    );
    return makeErrorResult(MongoDbError.UNKNOWN_ERROR);
  }
};
 
export const findSettings = async (): Promise<
  Result<Settings, MongoDbError>
> => {
  try {
    const settings = await SettingsModel.findOne({}).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 findSettings DB value: ${JSON.stringify(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>> => {
  try {
    const settings = await SettingsModel.findOneAndUpdate(
      {},
      {
        hiddenProgramItemIds,
      },
      {
        returnDocument: "after",
        upsert: true,
      },
    ).lean();
 
    logger.info("MongoDB: Hidden data updated");
 
    const result = SettingsSchemaDb.safeParse(settings);
    Iif (!result.success) {
      logger.error(
        new Error(
          `Error validating saveHidden DB value: ${JSON.stringify(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(
      {
        "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: ${JSON.stringify(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(
      {},
      {
        $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: ${JSON.stringify(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>> => {
  try {
    const updatedSettings = await SettingsModel.findOneAndUpdate({}, settings, {
      returnDocument: "after",
      upsert: true,
    }).lean();
    logger.info("MongoDB: App settings updated");
 
    const result = SettingsSchemaDb.safeParse(updatedSettings);
    Iif (!result.success) {
      logger.error(
        new Error(
          `Error validating saveSettings DB value: ${JSON.stringify(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(
      {
        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(
      {
        $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({});
      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(
      {
        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(
      {},
      {
        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({}).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: ${JSON.stringify(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);
  }
};