Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions apps/notifications/src/__tests__/activeUsers.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { describe, expect, jest, test } from '@jest/globals'
import type { Knex } from 'knex'
import {
EMAIL_ACTIVE_WITHIN_DAYS,
getRecentlyActiveUserIds
} from '../email/notifications/activeUsers'

// Minimal knex double: records the chain and resolves to `rows`.
const mockDb = (rows: { user_id: number }[]) => {
const calls: { method: string; args: any[] }[] = []
const builder: any = {}
for (const method of ['select', 'from', 'whereIn', 'andWhere']) {
builder[method] = (...args: any[]) => {
calls.push({ method, args })
return builder
}
}
builder.then = (resolve: (v: any) => any) =>
Promise.resolve(rows).then(resolve)
const db = { select: builder.select } as unknown as Knex
return { db, calls }
}

describe('getRecentlyActiveUserIds', () => {
test('returns the active subset', async () => {
const { db } = mockDb([{ user_id: 1 }, { user_id: 3 }])
const result = await getRecentlyActiveUserIds(db, [1, 2, 3])
expect([...result].sort()).toEqual([1, 3])
})

test('filters on last_active_at within the cutoff', async () => {
const now = new Date('2026-10-07T00:00:00Z').getTime()
const spy = jest.spyOn(Date, 'now').mockReturnValue(now)
const { db, calls } = mockDb([])
await getRecentlyActiveUserIds(db, [1, 2])
spy.mockRestore()

expect(calls.find((c) => c.method === 'from')?.args).toEqual(['users'])
expect(calls.find((c) => c.method === 'whereIn')?.args).toEqual([
'user_id',
[1, 2]
])
const [column, op, cutoff] = calls.find((c) => c.method === 'andWhere')!
.args as [string, string, Date]
expect(column).toBe('last_active_at')
expect(op).toBe('>=')
expect(cutoff.getTime()).toBe(
now - EMAIL_ACTIVE_WITHIN_DAYS * 24 * 60 * 60 * 1000
)
})

test('skips the query for an empty list', async () => {
const { db, calls } = mockDb([])
const result = await getRecentlyActiveUserIds(db, [])
expect(result.size).toBe(0)
expect(calls).toHaveLength(0)
})
})
26 changes: 26 additions & 0 deletions apps/notifications/src/email/notifications/activeUsers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { Knex } from 'knex'

// Digest and announcement emails only go to users who opened the app within
// this many days. Transactional emails are not affected.
export const EMAIL_ACTIVE_WITHIN_DAYS = 90

/**
* Returns the subset of userIds whose users.last_active_at (set on app open by
* POST /v1/users/me/ping) is within EMAIL_ACTIVE_WITHIN_DAYS. Users with no
* last_active_at count as inactive.
*/
export async function getRecentlyActiveUserIds(
discoveryDb: Knex,
userIds: number[]
): Promise<Set<number>> {
if (userIds.length === 0) return new Set()
const cutoff = new Date(
Date.now() - EMAIL_ACTIVE_WITHIN_DAYS * 24 * 60 * 60 * 1000
)
const rows = await discoveryDb
.select<{ user_id: number }[]>('user_id')
.from('users')
.whereIn('user_id', userIds)
.andWhere('last_active_at', '>=', cutoff)
return new Set(rows.map((r) => r.user_id))
}
23 changes: 22 additions & 1 deletion apps/notifications/src/email/notifications/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ import { DMEntityType } from './types'

import { logger } from '../../logger'
import { sendNotificationEmail } from './sendEmail'
import {
EMAIL_ACTIVE_WITHIN_DAYS,
getRecentlyActiveUserIds
} from './activeUsers'
import {
EmailFrequency,
buildUserNotificationSettings
Expand Down Expand Up @@ -513,11 +517,28 @@ export async function processEmailNotifications(
const processGroupOfEmails = async (
dnDb: Knex,
identityDb: Knex,
users: EmailUsers,
allUsers: EmailUsers,
frequency: EmailFrequency,
startOffset: Moment,
remoteConfig: RemoteConfig
) => {
const activeUserIds = await getRecentlyActiveUserIds(
dnDb,
Object.keys(allUsers).map(Number)
)
const inactiveCount = Object.keys(allUsers).length - activeUserIds.size
if (inactiveCount > 0) {
logger.info(
`processEmailNotifications | skipping ${inactiveCount} users inactive for over ${EMAIL_ACTIVE_WITHIN_DAYS} days`
)
}
const users: EmailUsers = Object.fromEntries(
Object.entries(allUsers).filter(([userId]) =>
activeUserIds.has(Number(userId))
)
)
if (Object.keys(users).length === 0) return

const userNotificationSettings = await buildUserNotificationSettings(
identityDb,
Object.keys(users).map(Number)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { BaseNotification } from './base'
import { sendPushNotification } from '../../sns'
import { ResourceIds, Resources } from '../../email/notifications/renderEmail'
import { sendNotificationEmail } from '../../email/notifications/sendEmail'
import { getRecentlyActiveUserIds } from '../../email/notifications/activeUsers'
import {
buildUserNotificationSettings,
Device
Expand Down Expand Up @@ -191,6 +192,9 @@ export class Announcement extends BaseNotification<AnnouncementNotificationRow>
frequency: 'live'
})
) {
const activeUserIds = await getRecentlyActiveUserIds(this.dnDB, [userId])
if (!activeUserIds.has(userId)) return

const notification: AppEmailNotification = {
receiver_user_id: userId,
...this.notification
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ export class UserNotificationSettings {
getUserEmailFrequency(userId: number) {
const emailSettings = this.email?.[userId]
if (emailSettings === undefined) {
return 'daily'
return 'weekly'
}
return emailSettings.frequency
}
Expand Down
1 change: 1 addition & 0 deletions apps/notifications/src/utils/populateDB.ts
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,7 @@ export const createUsers = async (db: Knex, users: CreateUser[]) => {
wallet: `0x${user.user_id}`,
creator_node_endpoint: `https://dn1.io,https://dn2.io,https://dn3.io`,
is_available: true,
last_active_at: new Date(Date.now()),
...user
}))
)
Expand Down
Loading