@@ -929,33 +929,45 @@ export const cleanupOldEmails = mutation({
929929 args : { olderThan : v . optional ( v . number ( ) ) } ,
930930 returns : v . null ( ) ,
931931 handler : async ( ctx , args ) => {
932+ const BATCH_SIZE = 100 ;
932933 const olderThan = args . olderThan ?? FINALIZED_EMAIL_RETENTION_MS ;
933934 const oldAndDone = await ctx . db
934935 . query ( "emails" )
935936 . withIndex ( "by_finalizedAt" , ( q ) =>
936937 q . lt ( "finalizedAt" , Date . now ( ) - olderThan ) ,
937938 )
938- . take ( 500 ) ;
939+ . take ( BATCH_SIZE ) ;
939940 for ( const email of oldAndDone ) {
940- await ctx . db . delete ( email . _id ) ;
941- if ( email . text ) {
942- await ctx . db . delete ( email . text ) ;
943- }
944- if ( email . html ) {
945- await ctx . db . delete ( email . html ) ;
946- }
941+ await cleanupEmail ( ctx , email ) ;
947942 }
948943 if ( oldAndDone . length > 0 ) {
949944 console . log ( `Cleaned up ${ oldAndDone . length } emails` ) ;
950945 }
951- if ( oldAndDone . length === 500 ) {
946+ if ( oldAndDone . length === BATCH_SIZE ) {
952947 await ctx . scheduler . runAfter ( 0 , api . lib . cleanupOldEmails , {
953948 olderThan,
954949 } ) ;
955950 }
956951 } ,
957952} ) ;
958953
954+ async function cleanupEmail ( ctx : MutationCtx , email : Doc < "emails" > ) {
955+ await ctx . db . delete ( email . _id ) ;
956+ if ( email . text ) {
957+ await ctx . db . delete ( email . text ) ;
958+ }
959+ if ( email . html ) {
960+ await ctx . db . delete ( email . html ) ;
961+ }
962+ const events = await ctx . db
963+ . query ( "deliveryEvents" )
964+ . withIndex ( "by_emailId_eventType" , ( q ) => q . eq ( "emailId" , email . _id ) )
965+ . collect ( ) ;
966+ for ( const event of events ) {
967+ await ctx . db . delete ( event . _id ) ;
968+ }
969+ }
970+
959971// Periodic background job to clean up old emails that have been abandoned.
960972// Meaning, even if they're not finalized, we should just get rid of them.
961973export const cleanupAbandonedEmails = mutation ( {
@@ -972,13 +984,7 @@ export const cleanupAbandonedEmails = mutation({
972984
973985 for ( const email of oldAndAbandoned ) {
974986 // No webhook to finalize these. We'll just delete them.
975- await ctx . db . delete ( email . _id ) ;
976- if ( email . text ) {
977- await ctx . db . delete ( email . text ) ;
978- }
979- if ( email . html ) {
980- await ctx . db . delete ( email . html ) ;
981- }
987+ cleanupEmail ( ctx , email ) ;
982988 }
983989 if ( oldAndAbandoned . length > 0 ) {
984990 console . log ( `Cleaned up ${ oldAndAbandoned . length } emails` ) ;
0 commit comments