Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

9.3 KB
Raw Blame
import { ParsedMessageData } from '~/ingestion/pipelines/sessionreplay/kafka/types'

import { SessionRateLimiter } from './session-rate-limiter'

jest.mock('./metrics', () => ({
    SessionBatchMetrics: {
        incrementSessionsRateLimited: jest.fn(),
        incrementEventsRateLimited: jest.fn(),
    },
}))

const createMessage = (eventCount: number): ParsedMessageData => {
    const events = Array.from({ length: eventCount }, (_, i) => ({ timestamp: i }))
    return {
        eventsByWindowId: { window1: events },
    } as any
}

describe('SessionRateLimiter', () => {
    beforeEach(() => {
        jest.clearAllMocks()
    })

    describe('handleMessage', () => {
        it('should allow events up to the limit', () => {
            const limiter = new SessionRateLimiter(3)
            const session: [number, string] = [123, 'session456']

            expect(limiter.handleMessage(...session, createMessage(1))).toBe(true)
            expect(limiter.handleMessage(...session, createMessage(1))).toBe(true)
            expect(limiter.handleMessage(...session, createMessage(1))).toBe(true)
            expect(limiter.getEventCount(...session)).toBe(3)
        })

        it('counts pre-serialized events against the limit', () => {
            // Pre-serialized messages have an empty eventsByWindowId; the count must come from the
            // per-event metadata or rate limiting silently stops applying on the native path.
            const limiter = new SessionRateLimiter(3)
            const session: [number, string] = [123, 'session456']
            const preSerialized = {
                eventsByWindowId: {},
                preSerialized: {
                    lines: Buffer.from(''),
                    events: [
                        { ts: 1, flags: 0 },
                        { ts: 2, flags: 0 },
                    ],
                },
            } as any as ParsedMessageData

            expect(limiter.handleMessage(...session, preSerialized)).toBe(true)
            expect(limiter.getEventCount(...session)).toBe(2)
            expect(limiter.handleMessage(...session, preSerialized)).toBe(false)
        })

        it('should block messages after limit is exceeded', () => {
            const limiter = new SessionRateLimiter(2)
            const session: [number, string] = [123, 'session456']

            expect(limiter.handleMessage(...session, createMessage(1))).toBe(true)
            expect(limiter.handleMessage(...session, createMessage(1))).toBe(true)
            expect(limiter.handleMessage(...session, createMessage(1))).toBe(false)
            expect(limiter.handleMessage(...session, createMessage(1))).toBe(false)
        })

        it('should track multiple sessions independently', () => {
            const limiter = new SessionRateLimiter(2)
            const session1: [number, string] = [123, 'session1']
            const session2: [number, string] = [123, 'session2']

            expect(limiter.handleMessage(...session1, createMessage(1))).toBe(true)
            expect(limiter.handleMessage(...session2, createMessage(1))).toBe(true)
            expect(limiter.handleMessage(...session1, createMessage(1))).toBe(true)
            expect(limiter.handleMessage(...session2, createMessage(1))).toBe(true)

            expect(limiter.handleMessage(...session1, createMessage(1))).toBe(false)
            expect(limiter.handleMessage(...session2, createMessage(1))).toBe(false)
        })

        it('should continue blocking after limit is hit', () => {
            const limiter = new SessionRateLimiter(1)
            const session: [number, string] = [123, 'session456']

            expect(limiter.handleMessage(...session, createMessage(1))).toBe(true)
            expect(limiter.handleMessage(...session, createMessage(1))).toBe(false)
            expect(limiter.handleMessage(...session, createMessage(1))).toBe(false)
            expect(limiter.handleMessage(...session, createMessage(1))).toBe(false)
        })

        it('should count events across multiple windows', () => {
            const limiter = new SessionRateLimiter(5)
            const session: [number, string] = [123, 'session456']

            const messageWithMultipleWindows = {
                eventsByWindowId: {
                    window1: [{ timestamp: 1 }, { timestamp: 2 }],
                    window2: [{ timestamp: 3 }, { timestamp: 4 }],
                },
            } as any

            expect(limiter.handleMessage(...session, messageWithMultipleWindows)).toBe(true)
            expect(limiter.getEventCount(...session)).toBe(4)
        })

        it('should handle messages with varying event counts', () => {
            const limiter = new SessionRateLimiter(10)
            const session: [number, string] = [123, 'session456']

            expect(limiter.handleMessage(...session, createMessage(3))).toBe(true)
            expect(limiter.getEventCount(...session)).toBe(3)

            expect(limiter.handleMessage(...session, createMessage(5))).toBe(true)
            expect(limiter.getEventCount(...session)).toBe(8)

            expect(limiter.handleMessage(...session, createMessage(2))).toBe(true)
            expect(limiter.getEventCount(...session)).toBe(10)

            expect(limiter.handleMessage(...session, createMessage(1))).toBe(false)
            expect(limiter.getEventCount(...session)).toBe(11)
        })

        it('should allow unlimited events with MAX_SAFE_INTEGER', () => {
            const limiter = new SessionRateLimiter(Number.MAX_SAFE_INTEGER)
            const session: [number, string] = [123, 'session456']

            for (let i = 0; i < 1000; i++) {
                expect(limiter.handleMessage(...session, createMessage(1000))).toBe(true)
            }
            expect(limiter.getEventCount(...session)).toBe(1000000)
        })
    })

    describe('getEventCount', () => {
        it('should return 0 for new session', () => {
            const limiter = new SessionRateLimiter(10)
            expect(limiter.getEventCount(123, 'session456')).toBe(0)
        })

        it('should return current count for tracked session', () => {
            const limiter = new SessionRateLimiter(10)
            const session: [number, string] = [123, 'session456']

            limiter.handleMessage(...session, createMessage(1))
            expect(limiter.getEventCount(...session)).toBe(1)

            limiter.handleMessage(...session, createMessage(2))
            expect(limiter.getEventCount(...session)).toBe(3)
        })

        it('should increment count even after limit is hit', () => {
            const limiter = new SessionRateLimiter(2)
            const session: [number, string] = [123, 'session456']

            limiter.handleMessage(...session, createMessage(1))
            limiter.handleMessage(...session, createMessage(1))
            expect(limiter.getEventCount(...session)).toBe(2)

            limiter.handleMessage(...session, createMessage(1))
            limiter.handleMessage(...session, createMessage(1))
            expect(limiter.getEventCount(...session)).toBe(4)
        })
    })

    describe('clear', () => {
        it('should clear all sessions', () => {
            const limiter = new SessionRateLimiter(10)
            const session1: [number, string] = [123, 'session1']
            const session2: [number, string] = [123, 'session2']

            limiter.handleMessage(...session1, createMessage(2))
            limiter.handleMessage(...session2, createMessage(1))

            expect(limiter.getEventCount(...session1)).toBe(2)
            expect(limiter.getEventCount(...session2)).toBe(1)

            limiter.clear()

            expect(limiter.getEventCount(...session1)).toBe(0)
            expect(limiter.getEventCount(...session2)).toBe(0)
        })

        it('should clear limited session status', () => {
            const limiter = new SessionRateLimiter(1)
            const session: [number, string] = [123, 'session456']

            limiter.handleMessage(...session, createMessage(1))
            expect(limiter.handleMessage(...session, createMessage(1))).toBe(false)

            limiter.clear()
            expect(limiter.handleMessage(...session, createMessage(1))).toBe(true)
        })
    })

    describe('edge cases', () => {
        it('should handle limit of 0', () => {
            const limiter = new SessionRateLimiter(0)
            const session: [number, string] = [123, 'session456']

            expect(limiter.handleMessage(...session, createMessage(1))).toBe(false)
            expect(limiter.getEventCount(...session)).toBe(1)
        })

        it('should handle limit of 1', () => {
            const limiter = new SessionRateLimiter(1)
            const session: [number, string] = [123, 'session456']

            expect(limiter.handleMessage(...session, createMessage(1))).toBe(true)
            expect(limiter.handleMessage(...session, createMessage(1))).toBe(false)
        })

        it('should handle many concurrent sessions', () => {
            const limiter = new SessionRateLimiter(5)
            const sessions = Array.from({ length: 100 }, (_, i): [number, string] => [123, `session${i}`])

            for (const session of sessions) {
                for (let i = 0; i < 5; i++) {
                    expect(limiter.handleMessage(...session, createMessage(1))).toBe(true)
                }
                expect(limiter.handleMessage(...session, createMessage(1))).toBe(false)
            }
        })
    })
})