11import { db } from '@sim/db'
2- import { subscription , user , workflowExecutionLogs , workspace } from '@sim/db/schema'
2+ import { subscription , workflowExecutionLogs , workspace } from '@sim/db/schema'
33import { createLogger } from '@sim/logger'
44import { and , eq , inArray , isNull , lt } from 'drizzle-orm'
55import { type NextRequest , NextResponse } from 'next/server'
@@ -26,38 +26,19 @@ export async function GET(request: NextRequest) {
2626 const retentionDate = new Date ( )
2727 retentionDate . setDate ( retentionDate . getDate ( ) - Number ( env . FREE_PLAN_LOG_RETENTION_DAYS || '7' ) )
2828
29- const freeUsers = await db
30- . select ( { userId : user . id } )
31- . from ( user )
29+ const freeWorkspacesSubquery = db
30+ . select ( { id : workspace . id } )
31+ . from ( workspace )
3232 . leftJoin (
3333 subscription ,
3434 and (
35- eq ( user . id , subscription . referenceId ) ,
35+ eq ( subscription . referenceId , workspace . billedAccountUserId ) ,
3636 inArray ( subscription . status , ENTITLED_SUBSCRIPTION_STATUSES ) ,
3737 sqlIsPaid ( subscription . plan )
3838 )
3939 )
4040 . where ( isNull ( subscription . id ) )
4141
42- if ( freeUsers . length === 0 ) {
43- logger . info ( 'No free users found for log cleanup' )
44- return NextResponse . json ( { message : 'No free users found for cleanup' } )
45- }
46-
47- const freeUserIds = freeUsers . map ( ( u ) => u . userId )
48-
49- const workspacesQuery = await db
50- . select ( { id : workspace . id } )
51- . from ( workspace )
52- . where ( inArray ( workspace . billedAccountUserId , freeUserIds ) )
53-
54- if ( workspacesQuery . length === 0 ) {
55- logger . info ( 'No workspaces found for free users' )
56- return NextResponse . json ( { message : 'No workspaces found for cleanup' } )
57- }
58-
59- const workspaceIds = workspacesQuery . map ( ( w ) => w . id )
60-
6142 const results = {
6243 enhancedLogs : {
6344 total : 0 ,
@@ -83,7 +64,7 @@ export async function GET(request: NextRequest) {
8364 let batchesProcessed = 0
8465 let hasMoreLogs = true
8566
86- logger . info ( ` Starting enhanced logs cleanup for ${ workspaceIds . length } workspaces` )
67+ logger . info ( ' Starting enhanced logs cleanup for free-plan workspaces' )
8768
8869 while ( hasMoreLogs && batchesProcessed < MAX_BATCHES ) {
8970 const oldEnhancedLogs = await db
@@ -105,8 +86,8 @@ export async function GET(request: NextRequest) {
10586 . from ( workflowExecutionLogs )
10687 . where (
10788 and (
108- inArray ( workflowExecutionLogs . workspaceId , workspaceIds ) ,
109- lt ( workflowExecutionLogs . createdAt , retentionDate )
89+ inArray ( workflowExecutionLogs . workspaceId , freeWorkspacesSubquery ) ,
90+ lt ( workflowExecutionLogs . startedAt , retentionDate )
11091 )
11192 )
11293 . limit ( BATCH_SIZE )
0 commit comments