ProjectSampler.mjs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // @ts-check
  2. import { objectIdFromDate } from './utils.mjs'
  3. import { db } from '../storage/lib/mongodb.js'
  4. import config from 'config'
  5. const projectsCollection = db.collection('projects')
  6. const HAS_PROJECTS_WITHOUT_HISTORY =
  7. config.get('hasProjectsWithoutHistory') === 'true'
  8. /**
  9. * @param {Date} start
  10. * @param {Date} end
  11. * @param {number} N
  12. * @yields {string}
  13. */
  14. export async function* getProjectsCreatedInDateRangeCursor(start, end, N) {
  15. yield* getSampleProjectsCursor(N, [
  16. {
  17. $match: {
  18. _id: {
  19. $gt: objectIdFromDate(start),
  20. $lte: objectIdFromDate(end),
  21. },
  22. },
  23. },
  24. ])
  25. }
  26. export async function* getProjectsUpdatedInDateRangeCursor(start, end, N) {
  27. yield* getSampleProjectsCursor(N, [
  28. {
  29. $match: {
  30. 'overleaf.history.updatedAt': {
  31. $gt: start,
  32. $lte: end,
  33. },
  34. },
  35. },
  36. ])
  37. }
  38. /**
  39. * @typedef {import('mongodb').Document} Document
  40. */
  41. /**
  42. *
  43. * @generator
  44. * @param {number} N
  45. * @param {Array<Document>} preSampleAggregationStages
  46. * @yields {string}
  47. */
  48. export async function* getSampleProjectsCursor(
  49. N,
  50. preSampleAggregationStages = []
  51. ) {
  52. const cursor = projectsCollection.aggregate([
  53. ...preSampleAggregationStages,
  54. { $sample: { size: N } },
  55. { $project: { 'overleaf.history.id': 1 } },
  56. ])
  57. let validProjects = 0
  58. let hasInvalidProject = false
  59. for await (const project of cursor) {
  60. if (HAS_PROJECTS_WITHOUT_HISTORY && !project.overleaf?.history?.id) {
  61. hasInvalidProject = true
  62. continue
  63. }
  64. validProjects++
  65. yield project.overleaf.history.id.toString()
  66. }
  67. if (validProjects === 0 && hasInvalidProject) {
  68. yield* getSampleProjectsCursor(N, preSampleAggregationStages)
  69. }
  70. }