@@ -3,10 +3,14 @@ import { performance } from 'node:perf_hooks'
33import { parseArgs } from 'node:util'
44import { CronParseError , getScheduleWindow } from '#app/utils/cron.server.ts'
55import { prisma } from '#app/utils/db.server.ts'
6- import { getrecipientsforcron } from '#app/utils/prisma-generated.server/sql.ts'
6+ import {
7+ getrecipientsforcron ,
8+ getunsentmessagecounts ,
9+ } from '#app/utils/prisma-generated.server/sql.ts'
710import { NEXT_SCHEDULE_SENTINEL_DATE } from '#app/utils/schedule-constants.server.ts'
811
912const MESSAGES_PER_PAGE = 100
13+ const RECIPIENTS_PAGE_SIZE = 200
1014
1115type Summary = {
1216 min : number
@@ -120,14 +124,31 @@ async function benchmarkRecipientsList(
120124 disabled : true ,
121125 prevScheduledAt : true ,
122126 nextScheduledAt : true ,
123- _count : { select : { messages : { where : { sentAt : null } } } } ,
124127 } ,
128+ orderBy : { id : 'asc' } ,
129+ take : RECIPIENTS_PAGE_SIZE ,
125130 } )
131+ const recipientIds = recipients . map ( ( recipient ) => recipient . id )
132+ const messageCounts = recipientIds . length
133+ ? await prisma . $queryRawTyped (
134+ getunsentmessagecounts ( JSON . stringify ( recipientIds ) ) ,
135+ )
136+ : [ ]
137+ const messageCountByRecipientId = new Map (
138+ messageCounts . map ( ( row ) => [
139+ row . recipientId ,
140+ Number ( row . unsentCount ?? 0 ) ,
141+ ] ) ,
142+ )
143+ const recipientsWithCounts = recipients . map ( ( recipient ) => ( {
144+ ...recipient ,
145+ messageCount : messageCountByRecipientId . get ( recipient . id ) ?? 0 ,
146+ } ) )
126147 const queryMs = performance . now ( ) - queryStart
127148
128149 const computeStart = performance . now ( )
129150 let errors = 0
130- const sortedRecipients = recipients
151+ const sortedRecipients = recipientsWithCounts
131152 . map ( ( recipient ) => {
132153 try {
133154 const isSentinel =
@@ -184,7 +205,7 @@ async function benchmarkRecipientsList(
184205 querySamples . push ( queryMs )
185206 computeSamples . push ( computeMs )
186207 cronErrors . push ( errors )
187- lastCount = recipients . length
208+ lastCount = recipientsWithCounts . length
188209 }
189210
190211 return {
0 commit comments