OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
fix: async inserts from buffer
Carl-Gerhard Lindesvärd98772eb18ad0
diff --git a/packages/db/src/buffers/bot-buffer.ts b/packages/db/src/buffers/bot-buffer.tsindex 5babd4430..c54092cd6 100644--- a/packages/db/src/buffers/bot-buffer.ts+++ b/packages/db/src/buffers/bot-buffer.ts@@ -1,7 +1,6 @@-import { type Redis, getRedisCache } from '@openpanel/redis';-import { getSafeJson } from '@openpanel/json';-import { TABLE_NAMES, ch } from '../clickhouse/client';+import { getRedisCache, type Redis } from '@openpanel/redis';+import { ch, TABLE_NAMES } from '../clickhouse/client';import type { IClickhouseBotEvent } from '../services/event.service';import { BaseBuffer } from './base-buffer';@@ -50,7 +49,7 @@ export class BotBuffer extends BaseBuffer {const events = await this.redis.lrange(this.redisKey,0,- this.batchSize - 1,+ this.batchSize - 1);const lrangeMs = performance.now() - lrangeStart;@@ -59,9 +58,7 @@ export class BotBuffer extends BaseBuffer {return;}- const parsedEvents = events.map((e) =>- getSafeJson<IClickhouseBotEvent>(e),- );+ const parsedEvents = events.map((e) => getSafeJson<IClickhouseBotEvent>(e));const chStart = performance.now();await ch.insert({@@ -70,8 +67,9 @@ export class BotBuffer extends BaseBuffer {format: 'JSONEachRow',clickhouse_settings: {async_insert: 1,- parallel_view_processing: 1- }+ wait_for_async_insert: 0,+ parallel_view_processing: 1,+ },});const chInsertMs = performance.now() - chStart;diff --git a/packages/db/src/buffers/event-buffer.ts b/packages/db/src/buffers/event-buffer.tsindex f81449bee..517d937d7 100644--- a/packages/db/src/buffers/event-buffer.ts+++ b/packages/db/src/buffers/event-buffer.ts@@ -112,7 +112,7 @@ export class EventBuffer extends BaseBuffer {eventCount: eventsToFlush.length,flushRetryCount: this.flushRetryCount,},- 'Failed to flush local buffer to Redis; events re-queued',+ 'Failed to flush local buffer to Redis; events re-queued');} finally {this.isFlushing = false;@@ -137,7 +137,7 @@ export class EventBuffer extends BaseBuffer {const queueEvents = await redis.lrange(this.queueKey,0,- this.batchSize - 1,+ this.batchSize - 1);const lrangeMs = performance.now() - lrangeStart;@@ -165,7 +165,7 @@ export class EventBuffer extends BaseBuffer {eventsToClickhouse.sort((a, b) =>new Date(a.created_at || 0).getTime() -- new Date(b.created_at || 0).getTime(),+ new Date(b.created_at || 0).getTime());const chStart = performance.now();@@ -178,9 +178,10 @@ export class EventBuffer extends BaseBuffer {format: 'JSONEachRow',clickhouse_settings: {async_insert: 1,- parallel_view_processing: 1- }- }),+ wait_for_async_insert: 0,+ parallel_view_processing: 1,+ },+ }));const chInsertMs = performance.now() - chStart;@@ -188,7 +189,7 @@ export class EventBuffer extends BaseBuffer {for (const event of eventsToClickhouse) {countByProject.set(event.project_id,- (countByProject.get(event.project_id) ?? 0) + 1,+ (countByProject.get(event.project_id) ?? 0) + 1);}for (const [projectId, count] of countByProject) {diff --git a/packages/db/src/buffers/group-buffer.ts b/packages/db/src/buffers/group-buffer.tsindex 71136039a..5b8138efe 100644--- a/packages/db/src/buffers/group-buffer.ts+++ b/packages/db/src/buffers/group-buffer.ts@@ -3,7 +3,12 @@ import { getSafeJson } from '@openpanel/json';import { getRedisCache, type Redis } from '@openpanel/redis';import shallowEqual from 'fast-deep-equal';import sqlstring from 'sqlstring';-import { ch, chQuery, formatClickhouseDate, TABLE_NAMES } from '../clickhouse/client';+import {+ ch,+ chQuery,+ formatClickhouseDate,+ TABLE_NAMES,+} from '../clickhouse/client';import { BaseBuffer } from './base-buffer';type IGroupBufferEntry = {@@ -69,7 +74,9 @@ export class GroupBuffer extends BaseBuffer {id: string): Promise<IGroupCacheEntry | null> {const raw = await this.redis.get(this.getCacheKey(projectId, id));- if (!raw) return null;+ if (!raw) {+ return null;+ }return getSafeJson<IGroupCacheEntry>(raw);}@@ -108,7 +115,7 @@ export class GroupBuffer extends BaseBuffer {name: input.name,properties: mergedProperties,created_at: formatClickhouseDate(- existing?.created_at ? new Date(existing.created_at) : new Date(),+ existing?.created_at ? new Date(existing.created_at) : new Date()),version: String(Date.now()),deleted: 0,@@ -155,7 +162,6 @@ export class GroupBuffer extends BaseBuffer {});}-protected getRedisListKey(): string {return this.redisKey;}@@ -180,9 +186,10 @@ export class GroupBuffer extends BaseBuffer {format: 'JSONEachRow',clickhouse_settings: {async_insert: 1,- parallel_view_processing: 1- }- }),+ wait_for_async_insert: 0,+ parallel_view_processing: 1,+ },+ }));const chInsertMs = performance.now() - chStart;diff --git a/packages/db/src/buffers/profile-buffer.ts b/packages/db/src/buffers/profile-buffer.tsindex ca10b2cc1..2d7b25cde 100644--- a/packages/db/src/buffers/profile-buffer.ts+++ b/packages/db/src/buffers/profile-buffer.ts@@ -218,7 +218,7 @@ export class ProfileBuffer extends BaseBuffer {`SELECT ${PROFILE_LATEST_AGGREGATE_COLUMNS}FROM ${TABLE_NAMES.profiles} AS pWHERE (p.id, p.project_id) IN (${tuples})- ${withDateFilter ? `AND p.last_seen_at > now() - INTERVAL 2 DAY` : ''}+ ${withDateFilter ? 'AND p.last_seen_at > now() - INTERVAL 2 DAY' : ''}GROUP BY p.id, p.project_id`);for (const row of rows) {@@ -250,7 +250,7 @@ export class ProfileBuffer extends BaseBuffer {const rawProfiles = await this.redis.lrange(this.redisKey,0,- this.batchSize - 1,+ this.batchSize - 1);const lrangeMs = performance.now() - lrangeStart;@@ -269,7 +269,7 @@ export class ProfileBuffer extends BaseBuffer {const key = `${profile.project_id}:${profile.id}`;mergedInBatch.set(key,- this.mergeProfiles(mergedInBatch.get(key) ?? null, profile),+ this.mergeProfiles(mergedInBatch.get(key) ?? null, profile));}@@ -277,7 +277,7 @@ export class ProfileBuffer extends BaseBuffer {// Check Redis cache for all unique profiles in a single MGETconst cacheKeys = uniqueProfiles.map((p) =>- this.getProfileCacheKey({ profileId: p.id, projectId: p.project_id }),+ this.getProfileCacheKey({ profileId: p.id, projectId: p.project_id }));const cacheResults = await this.redis.mget(...cacheKeys);@@ -321,7 +321,7 @@ export class ProfileBuffer extends BaseBuffer {const key = `${profile.project_id}:${profile.id}`;const merged = this.mergeProfiles(existingByKey.get(key) ?? null,- profile,+ profile);toInsert.push(merged);multi.set(@@ -331,7 +331,7 @@ export class ProfileBuffer extends BaseBuffer {}),JSON.stringify(merged),'EX',- this.ttlInSeconds,+ this.ttlInSeconds);}@@ -343,9 +343,10 @@ export class ProfileBuffer extends BaseBuffer {format: 'JSONEachRow',clickhouse_settings: {async_insert: 1,- parallel_view_processing: 1- }- }),+ wait_for_async_insert: 0,+ parallel_view_processing: 1,+ },+ }));const chInsertMs = performance.now() - chStart;diff --git a/packages/db/src/buffers/replay-buffer.ts b/packages/db/src/buffers/replay-buffer.tsindex 469949844..a3e33f2c2 100644--- a/packages/db/src/buffers/replay-buffer.ts+++ b/packages/db/src/buffers/replay-buffer.ts@@ -1,6 +1,6 @@import { getSafeJson } from '@openpanel/json';import { getRedisCache } from '@openpanel/redis';-import { TABLE_NAMES, ch } from '../clickhouse/client';+import { ch, TABLE_NAMES } from '../clickhouse/client';import { BaseBuffer } from './base-buffer';export interface IClickhouseSessionReplayChunk {@@ -50,13 +50,12 @@ export class ReplayBuffer extends BaseBuffer {} catch (error) {this.logger.error({ err: error },- 'Failed to add replay chunk to buffer',+ 'Failed to add replay chunk to buffer');}});}-protected getRedisListKey(): string {return this.redisKey;}@@ -85,9 +84,10 @@ export class ReplayBuffer extends BaseBuffer {format: 'JSONEachRow',clickhouse_settings: {async_insert: 1,- parallel_view_processing: 1- }- }),+ wait_for_async_insert: 0,+ parallel_view_processing: 1,+ },+ }));const chInsertMs = performance.now() - chStart;diff --git a/packages/db/src/buffers/session-buffer.ts b/packages/db/src/buffers/session-buffer.tsindex 78930b413..d2a6e890d 100644--- a/packages/db/src/buffers/session-buffer.ts+++ b/packages/db/src/buffers/session-buffer.ts@@ -47,7 +47,9 @@ export class SessionBuffer extends BaseBuffer {const value = await this.redis.get(`session:${options.projectId}:${options.profileId}`);- if (!value) return null;+ if (!value) {+ return null;+ }// Backward compat: old keys stored full JSON, new keys store just the sessionIdif (value.startsWith('{')) {@@ -220,14 +222,14 @@ export class SessionBuffer extends BaseBuffer {`session:${newSession.id}`,JSON.stringify(newSession),'EX',- 60 * 60,+ 60 * 60);if (newSession.profile_id) {multi.set(`session:${newSession.project_id}:${newSession.profile_id}`,newSession.id,'EX',- 60 * 60,+ 60 * 60);}for (const session of sessions) {@@ -264,16 +266,21 @@ export class SessionBuffer extends BaseBuffer {* either way — keeping them is wasted work.*/private squashSessionsByVersion(- sessions: IClickhouseSession[],+ sessions: IClickhouseSession[]): IClickhouseSession[] {- if (sessions.length <= 1) return sessions;+ if (sessions.length <= 1) {+ return sessions;+ }const grouped = new Map<string, IClickhouseSession[]>();for (const s of sessions) {const key = s.id;const arr = grouped.get(key);- if (arr) arr.push(s);- else grouped.set(key, [s]);+ if (arr) {+ arr.push(s);+ } else {+ grouped.set(key, [s]);+ }}let squashedCount = 0;@@ -291,15 +298,20 @@ export class SessionBuffer extends BaseBuffer {if (!oldestNeg || e.version < oldestNeg.version) {oldestNeg = e;}- } else if (e.sign === 1) {- if (!newestPos || e.version > newestPos.version) {- newestPos = e;- }+ } else if (+ e.sign === 1 &&+ (!newestPos || e.version > newestPos.version)+ ) {+ newestPos = e;}}const emitted: IClickhouseSession[] = [];- if (oldestNeg) emitted.push(oldestNeg);- if (newestPos) emitted.push(newestPos);+ if (oldestNeg) {+ emitted.push(oldestNeg);+ }+ if (newestPos) {+ emitted.push(newestPos);+ }squashedCount += entries.length - emitted.length;out.push(...emitted);}@@ -312,13 +324,19 @@ export class SessionBuffer extends BaseBuffer {dropped: squashedCount,uniqueSessions: grouped.size,},- 'Session batch squashed',+ 'Session batch squashed');}console.log(- squashedCount > 0 ? 'Session batch squashed' : 'Session batch not squashed',- { inputRows: sessions.length, outputRows: out.length, dropped: squashedCount },+ squashedCount > 0+ ? 'Session batch squashed'+ : 'Session batch not squashed',+ {+ inputRows: sessions.length,+ outputRows: out.length,+ dropped: squashedCount,+ });return out;@@ -341,7 +359,9 @@ export class SessionBuffer extends BaseBuffer {const parsed: IClickhouseSession[] = [];for (const raw of events) {const session = getSafeJson<IClickhouseSession>(raw);- if (!session) continue;+ if (!session) {+ continue;+ }parsed.push({...session,duration: Math.max(0, session.duration || 0),@@ -372,9 +392,10 @@ export class SessionBuffer extends BaseBuffer {format: 'JSONEachRow',clickhouse_settings: {async_insert: 1,- parallel_view_processing: 1- }- }),+ wait_for_async_insert: 0,+ parallel_view_processing: 1,+ },+ }));const chInsertMs = performance.now() - chStart;