📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
Data importer improvements
Blue Mouse67b10221285f
diff --git a/backend/apps/cloud/src/data-import/data-import.controller.ts b/backend/apps/cloud/src/data-import/data-import.controller.tsindex 2890e653a..c4223d52c 100644--- a/backend/apps/cloud/src/data-import/data-import.controller.ts+++ b/backend/apps/cloud/src/data-import/data-import.controller.ts@@ -120,7 +120,12 @@ export class DataImportController {)const { encryptedRefreshToken, clientId, clientSecret } =- await this.ga4ImportService.consumeTokenForImport(uid, projectId)+ await this.ga4ImportService+ .consumeTokenForImport(uid, projectId)+ .catch(async (error) => {+ await this.dataImportService.deleteImportRecord(dataImport.id)+ throw error+ })try {await this.importQueue.add(@@ -180,7 +185,8 @@ export class DataImportController {})@UseInterceptors(FileInterceptor('file', {- limits: { fileSize: MAX_FILE_SIZE },+ // Multer rejects at the threshold, so allow files exactly at the limit.+ limits: { fileSize: MAX_FILE_SIZE + 1 },storage: diskStorage({destination: (_req, _file, cb) => {fs.mkdirSync(IMPORT_TMP_DIR, { recursive: true })diff --git a/backend/apps/cloud/src/data-import/data-import.processor.ts b/backend/apps/cloud/src/data-import/data-import.processor.tsindex 019945a24..63e970d05 100644--- a/backend/apps/cloud/src/data-import/data-import.processor.ts+++ b/backend/apps/cloud/src/data-import/data-import.processor.ts@@ -134,6 +134,11 @@ export class DataImportProcessor extends WorkerHost {context,)) {totalRows+++ if (totalRows > 100_000_000) {+ throw new ImportError(+ 'Import exceeds 100 million events. Please import a shorter date range.',+ )+ }const created = row.data.created as stringif (created) {@@ -169,6 +174,12 @@ export class DataImportProcessor extends WorkerHost {}}+ if (totalRows === 0) {+ throw new ImportError(+ 'The export contains no importable events. Please check the file format and date range.',+ )+ }+if (eventsBatch.length > 0) {await this.flushBatch(eventsBatch)importedRows += eventsBatch.lengthdiff --git a/backend/apps/cloud/src/data-import/data-import.service.ts b/backend/apps/cloud/src/data-import/data-import.service.tsindex 834b53086..76683f678 100644--- a/backend/apps/cloud/src/data-import/data-import.service.ts+++ b/backend/apps/cloud/src/data-import/data-import.service.ts@@ -163,6 +163,7 @@ export class DataImportService {await clickhouse.command({query: `ALTER TABLE ${CLICKHOUSE_DB}.events DELETE WHERE pid = {pid:FixedString(12)} AND importID = {importID:UInt8} AND type IN ('pageview', 'custom_event')`,query_params: { pid: projectId, importID: importId },+ clickhouse_settings: { mutations_sync: '2' },})}diff --git a/backend/apps/cloud/src/data-import/mappers/csv.utils.ts b/backend/apps/cloud/src/data-import/mappers/csv.utils.tsnew file mode 100644index 000000000..ffcd834d3--- /dev/null+++ b/backend/apps/cloud/src/data-import/mappers/csv.utils.ts@@ -0,0 +1,36 @@+import { createReadStream } from 'fs'+import { pipeline } from 'stream/promises'+import { parse, Options } from 'csv-parse'++import { ImportError } from './mapper.interface'++export async function* readCsvRows(+ filePath: string,+ options: Options = {},+): AsyncIterable<Record<string, string>> {+ const input = createReadStream(filePath)+ const parser = parse({+ bom: true,+ columns: true,+ skip_empty_lines: true,+ trim: true,+ relax_quotes: true,+ relax_column_count: true,+ max_record_size: 1024 * 1024,+ ...options,+ })+ const completion = pipeline(input, parser).catch(() => {})++ try {+ for await (const row of parser) yield row+ } catch (error) {+ if (error instanceof ImportError) throw error+ throw new ImportError(+ 'Could not read the import CSV. Please check the export and upload it again.',+ )+ } finally {+ input.destroy()+ parser.destroy()+ await completion+ }+}diff --git a/backend/apps/cloud/src/data-import/mappers/fathom.mapper.ts b/backend/apps/cloud/src/data-import/mappers/fathom.mapper.tsindex b9dce040d..42877dd0b 100644--- a/backend/apps/cloud/src/data-import/mappers/fathom.mapper.ts+++ b/backend/apps/cloud/src/data-import/mappers/fathom.mapper.ts@@ -1,5 +1,4 @@-import * as fs from 'fs'-import { parse } from 'csv-parse'+import { readCsvRows } from './csv.utils'import {ImportMapper,@@ -136,31 +135,33 @@ export class FathomMapper implements ImportMapper {let fileType: FathomFileType | null = nulllet headerChecked = false- const parser = fs.createReadStream(filePath).pipe(- parse({- bom: true,- columns: (headers) => {- const result = detectFileType(headers)- fileType = result.type- headerChecked = true- return result.normalized- },- skip_empty_lines: true,- trim: true,- relax_quotes: true,- relax_column_count: true,- }),- )+ const parser = readCsvRows(filePath, {+ bom: true,+ columns: (headers) => {+ const result = detectFileType(headers)+ fileType = result.type+ headerChecked = true+ return result.normalized+ },+ skip_empty_lines: true,+ trim: true,+ relax_quotes: true,+ relax_column_count: true,+ })for await (const row of parser) {const datetime = normalizeNull(row.datetime)if (!datetime || !DATETIME_REGEX.test(datetime)) continue- const count = parseInt(- fileType === 'pageviews' ? row.pageviews : row.completions,- 10,- )- if (!count || count <= 0) continue+ const rawCount =+ fileType === 'pageviews' ? row.pageviews : row.completions+ const count = /^\d+$/.test(rawCount || '') ? Number(rawCount) : NaN+ if (!Number.isSafeInteger(count) || count > 100_000_000) {+ throw new ImportError(+ 'Fathom export contains an invalid or excessive event count.',+ )+ }+ if (count === 0) continueconst device = mapDevice(normalizeNull(row.device_type))const browser = mapBrowser(normalizeNull(row.browser), device)diff --git a/backend/apps/cloud/src/data-import/mappers/plausible.mapper.ts b/backend/apps/cloud/src/data-import/mappers/plausible.mapper.tsindex f0c5926d3..78fda941d 100644--- a/backend/apps/cloud/src/data-import/mappers/plausible.mapper.ts+++ b/backend/apps/cloud/src/data-import/mappers/plausible.mapper.ts@@ -1,8 +1,10 @@import * as fs from 'fs'import * as path from 'path'import * as crypto from 'crypto'-import { unzipSync, UnzipFileInfo } from 'fflate'-import { parse as parseSync } from 'csv-parse/sync'+import * as os from 'os'+import { Unzip, UnzipInflate } from 'fflate'+import { createInterface } from 'readline'+import { readCsvRows } from './csv.utils'import {ImportMapper,@@ -17,8 +19,8 @@ import {} from './mapper.utils'const MAX_PLAUSIBLE_ZIP_BYTES = 100 * 1024 * 1024-const MAX_PLAUSIBLE_UNCOMPRESSED_BYTES = 500 * 1024 * 1024-const MAX_CSV_BYTES = 50 * 1024 * 1024+const MAX_PLAUSIBLE_UNCOMPRESSED_BYTES = 2 * 1024 * 1024 * 1024+const MAX_DAILY_BYTES = 128 * 1024 * 1024const MIN_PAGE_GAP_SEC = 5const MAX_PAGE_GAP_SEC = 30 * 60const DATE_REGEX = /^\d{4}-\d{2}-\d{2}$/@@ -153,7 +155,7 @@ function seedFromString(s: string): number {function toInt(value: string | undefined, fieldName = 'value'): number {if (value === undefined || value === null || value === '') return 0- const n = parseInt(value, 10)+ const n = /^\d+$/.test(value) ? Number(value) : NaNif (!Number.isFinite(n) || Number.isNaN(n) || !Number.isSafeInteger(n)) {throw new ImportError(`Plausible export contains an invalid numeric ${fieldName}: ${value}`,@@ -167,20 +169,22 @@ function toInt(value: string | undefined, fieldName = 'value'): number {return Math.min(n, MAX_SAFE_COUNT)}-function parseCsv(bytes: Uint8Array): Record<string, string>[] {- if (bytes.length > MAX_CSV_BYTES) {- throw new ImportError(- `Plausible export contains a CSV larger than ${MAX_CSV_BYTES} bytes.`,- )+async function* readDailyRows(+ paths: string[],+): AsyncIterable<Record<string, string>> {+ for (const filePath of paths) {+ const input = fs.createReadStream(filePath)+ const lines = createInterface({ input, crlfDelay: Infinity })+ input.on('error', (error) => lines.emit('error', error))+ try {+ for await (const line of lines) {+ yield JSON.parse(line)+ }+ } finally {+ lines.close()+ input.destroy()+ }}- return parseSync(Buffer.from(bytes), {- bom: true,- columns: true,- skip_empty_lines: true,- trim: true,- relax_quotes: true,- relax_column_count: true,- }) as Record<string, string>[]}function mapBrowser(raw: string | null, device: string | null): string | null {@@ -413,89 +417,165 @@ export class PlausibleMapper implements ImportMapper {readonly provider = 'plausible'readonly expectedFileExtension = '.zip'- private extractCsvs(zipPath: string): Map<string, Uint8Array> {- const stat = fs.statSync(zipPath)+ private async extractCsvs(+ zipPath: string,+ tempDir: string,+ ): Promise<Map<string, string[]>> {+ const stat = await fs.promises.stat(zipPath)if (stat.size > MAX_PLAUSIBLE_ZIP_BYTES) {- throw new ImportError(- `Plausible ZIP exceeds the ${MAX_PLAUSIBLE_ZIP_BYTES} byte limit.`,- )+ throw new ImportError('Plausible ZIP exceeds the 100 MB upload limit.')}- const buf = fs.readFileSync(zipPath)-- const matchedKeys = new Set<string>()- const nameToKey = new Map<string, string>()+ const found = new Map<string, string[]>()+ const openFiles = new Set<number>()let totalUncompressed = 0-- const filter = (file: UnzipFileInfo): boolean => {- const base = path.basename(file.name).toLowerCase()- if (!base.endsWith('.csv')) return false- for (const [key, pattern] of Object.entries(FILE_PATTERNS)) {- if (matchedKeys.has(key)) continue- if (!pattern.test(file.name)) continue-- const declaredSize = Number.isSafeInteger(file.originalSize)- ? file.originalSize- : -1- if (declaredSize < 0) {- throw new ImportError(- `Plausible ZIP entry ${file.name} reports an invalid uncompressed size.`,- )- }- if (declaredSize > MAX_CSV_BYTES) {+ let entryCount = 0+ let pendingEntries = 0+ const unzipper = new Unzip((file) => {+ if (++entryCount > 1000) {+ throw new ImportError('Plausible ZIP contains too many files.')+ }+ const key = Object.keys(FILE_PATTERNS).find((key) =>+ FILE_PATTERNS[key].test(file.name),+ )+ if (file.originalSize > MAX_PLAUSIBLE_UNCOMPRESSED_BYTES) {+ throw new ImportError(+ 'Plausible ZIP exceeds the 2 GiB uncompressed limit. Please export a shorter date range.',+ )+ }+ let fd: number | undefined+ if (key) {+ const csvPath = path.join(tempDir, `${entryCount}.csv`)+ fd = fs.openSync(csvPath, 'wx')+ openFiles.add(fd)+ found.set(key, [...(found.get(key) ?? []), csvPath])+ }+ pendingEntries+++ file.ondata = (error, chunk, final) => {+ if (error) throw error+ totalUncompressed += chunk.length+ if (totalUncompressed > MAX_PLAUSIBLE_UNCOMPRESSED_BYTES) {throw new ImportError(- `Plausible ZIP entry ${file.name} exceeds the ${MAX_CSV_BYTES} byte CSV limit (declared ${declaredSize}).`,+ 'Plausible ZIP exceeds the 2 GiB uncompressed limit. Please export a shorter date range.',)}- if (- totalUncompressed + declaredSize >- MAX_PLAUSIBLE_UNCOMPRESSED_BYTES- ) {- throw new ImportError(- `Plausible ZIP uncompressed size exceeds the ${MAX_PLAUSIBLE_UNCOMPRESSED_BYTES} byte limit.`,- )+ if (fd !== undefined) {+ let offset = 0+ while (offset < chunk.length) {+ offset += fs.writeSync(fd, chunk, offset, chunk.length - offset)+ }+ if (final) {+ fs.closeSync(fd)+ openFiles.delete(fd)+ fd = undefined+ }}- totalUncompressed += declaredSize- matchedKeys.add(key)- nameToKey.set(file.name, key)- return true+ if (final) pendingEntries--}- return false- }+ file.start()+ })+ unzipper.register(UnzipInflate)- let entries: Record<string, Uint8Array>try {- entries = unzipSync(- new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength),- { filter },+ for await (const chunk of fs.createReadStream(zipPath, {+ highWaterMark: 16 * 1024,+ })) {+ unzipper.push(chunk as Buffer)+ }+ unzipper.push(new Uint8Array(0), true)+ if (pendingEntries > 0) throw new Error('Incomplete ZIP entry')+ } catch (error) {+ if (error instanceof ImportError) throw error+ throw new ImportError(+ 'Could not read the uploaded ZIP archive. Please upload the full export ZIP from Plausible again.',)- } catch (err) {- if (err instanceof ImportError) throw err+ } finally {+ for (const fd of openFiles) fs.closeSync(fd)+ }+ if (!found.has('visitors')) {throw new ImportError(- 'Could not read the uploaded file as a ZIP archive. Please upload the export ZIP from Plausible.',+ 'ZIP does not contain imported_visitors_*.csv. Please upload the full export ZIP from Plausible.',)}+ return found+ }- const found = new Map<string, Uint8Array>()- for (const [name, data] of Object.entries(entries)) {- const key = nameToKey.get(name)- if (!key || found.has(key)) continue- if (data.byteLength > MAX_CSV_BYTES) {- throw new ImportError(- `Plausible ZIP entry ${name} exceeds the ${MAX_CSV_BYTES} byte CSV limit after decompression.`,- )+ private async partitionCsvs(csvs: Map<string, string[]>, tempDir: string) {+ const days = new Map<string, Map<string, string[]>>()+ const daySizes = new Map<string, number>()+ const buffers = new Map<string, string[]>()+ let bufferedBytes = 0+ const flush = async () => {+ for (const [filePath, rows] of buffers) {+ await fs.promises.appendFile(filePath, rows.join(''))}- found.set(key, data)+ buffers.clear()+ bufferedBytes = 0}-- return found+ const required: Record<string, string[]> = {+ visitors: ['date', 'visits', 'pageviews'],+ pages: ['date', 'page', 'pageviews'],+ browsers: ['date', 'browser', 'visits'],+ devices: ['date', 'device', 'visits'],+ operatingSystems: ['date', 'operating_system', 'visits'],+ locations: ['date', 'country', 'visits'],+ sources: ['date', 'source', 'visits'],+ entryPages: ['date', 'entry_page', 'entrances'],+ exitPages: ['date', 'exit_page', 'exits'],+ customEvents: ['date', 'name', 'events'],+ }+ for (const [key, paths] of csvs) {+ for (const csvPath of paths) {+ for await (const row of readCsvRows(csvPath, {+ columns: (headers: string[]) => {+ const missing = required[key].filter(+ (column) => !headers.includes(column),+ )+ if (missing.length)+ throw new ImportError(+ `Plausible ${key} CSV is missing columns: ${missing.join(', ')}.`,+ )+ return headers+ },+ })) {+ const date = normalizeNull(row.date)+ if (!date || !DATE_REGEX.test(date)) continue+ const parsedDate = new Date(`${date}T00:00:00Z`)+ if (+ !Number.isFinite(parsedDate.getTime()) ||+ parsedDate.toISOString().slice(0, 10) !== date+ )+ continue+ const line = `${JSON.stringify(row)}\n`+ const bytes = Buffer.byteLength(line)+ const daySize = (daySizes.get(date) ?? 0) + bytes+ if (daySize > MAX_DAILY_BYTES)+ throw new ImportError(+ `Plausible data for ${date} exceeds the 128 MiB daily processing limit. Please contact support.`,+ )+ daySizes.set(date, daySize)+ const dayFiles = days.get(date) ?? new Map<string, string[]>()+ const filePath = path.join(tempDir, `${date}-${key}.jsonl`)+ dayFiles.set(key, [filePath])+ days.set(date, dayFiles)+ const rows = buffers.get(filePath) ?? []+ rows.push(line)+ buffers.set(filePath, rows)+ bufferedBytes += bytes+ if (bufferedBytes >= 1024 * 1024) await flush()+ }+ await fs.promises.unlink(csvPath)+ }+ }+ await flush()+ return days}- private buildDailyData(- csvs: Map<string, Uint8Array>,- ): Map<string, DailyData> {- const visitorsBytes = csvs.get('visitors')- if (!visitorsBytes) {+ private async buildDailyData(+ csvs: Map<string, string[]>,+ ): Promise<Map<string, DailyData>> {+ const visitorsFiles = csvs.get('visitors')+ if (!visitorsFiles) {throw new ImportError('ZIP does not contain imported_visitors_*.csv. Please upload the full export ZIP from Plausible.',)@@ -530,20 +610,21 @@ export class PlausibleMapper implements ImportMapper {return d}- for (const row of parseCsv(visitorsBytes)) {+ for await (const row of readDailyRows(visitorsFiles)) {const date = normalizeNull(row.date)if (!date || !DATE_REGEX.test(date)) continueconst visits = toInt(row.visits, 'visits')const pageviews = toInt(row.pageviews, 'pageviews')- if (visits <= 0 && pageviews <= 0) continueconst day = ensureDay(date)day.visitors = {date,- visitors: toInt(row.visitors, 'visitors'),- pageviews,- visits,- bounces: toInt(row.bounces, 'bounces'),- visit_duration: toInt(row.visit_duration, 'visit_duration'),+ visitors: day.visitors.visitors + toInt(row.visitors, 'visitors'),+ pageviews: day.visitors.pageviews + pageviews,+ visits: day.visitors.visits + visits,+ bounces: day.visitors.bounces + toInt(row.bounces, 'bounces'),+ visit_duration:+ day.visitors.visit_duration ++ toInt(row.visit_duration, 'visit_duration'),}}@@ -553,9 +634,9 @@ export class PlausibleMapper implements ImportMapper {)}- const pagesBytes = csvs.get('pages')- if (pagesBytes) {- for (const row of parseCsv(pagesBytes)) {+ const pagesFiles = csvs.get('pages')+ if (pagesFiles) {+ for await (const row of readDailyRows(pagesFiles)) {const date = normalizeNull(row.date)if (!date || !days.has(date)) continueconst pageviews = toInt(row.pageviews)@@ -568,9 +649,9 @@ export class PlausibleMapper implements ImportMapper {}}- const browsersBytes = csvs.get('browsers')- if (browsersBytes) {- for (const row of parseCsv(browsersBytes)) {+ const browsersFiles = csvs.get('browsers')+ if (browsersFiles) {+ for await (const row of readDailyRows(browsersFiles)) {const date = normalizeNull(row.date)if (!date || !days.has(date)) continueconst visits = toInt(row.visits)@@ -583,9 +664,9 @@ export class PlausibleMapper implements ImportMapper {}}- const devicesBytes = csvs.get('devices')- if (devicesBytes) {- for (const row of parseCsv(devicesBytes)) {+ const devicesFiles = csvs.get('devices')+ if (devicesFiles) {+ for await (const row of readDailyRows(devicesFiles)) {const date = normalizeNull(row.date)if (!date || !days.has(date)) continueconst visits = toInt(row.visits)@@ -597,9 +678,9 @@ export class PlausibleMapper implements ImportMapper {}}- const osBytes = csvs.get('operatingSystems')- if (osBytes) {- for (const row of parseCsv(osBytes)) {+ const osFiles = csvs.get('operatingSystems')+ if (osFiles) {+ for await (const row of readDailyRows(osFiles)) {const date = normalizeNull(row.date)if (!date || !days.has(date)) continueconst visits = toInt(row.visits)@@ -612,9 +693,9 @@ export class PlausibleMapper implements ImportMapper {}}- const locationsBytes = csvs.get('locations')- if (locationsBytes) {- for (const row of parseCsv(locationsBytes)) {+ const locationsFiles = csvs.get('locations')+ if (locationsFiles) {+ for await (const row of readDailyRows(locationsFiles)) {const date = normalizeNull(row.date)if (!date || !days.has(date)) continueconst visits = toInt(row.visits)@@ -627,9 +708,9 @@ export class PlausibleMapper implements ImportMapper {}}- const sourcesBytes = csvs.get('sources')- if (sourcesBytes) {- for (const row of parseCsv(sourcesBytes)) {+ const sourcesFiles = csvs.get('sources')+ if (sourcesFiles) {+ for await (const row of readDailyRows(sourcesFiles)) {const date = normalizeNull(row.date)if (!date || !days.has(date)) continueconst visits = toInt(row.visits)@@ -647,9 +728,9 @@ export class PlausibleMapper implements ImportMapper {}}- const entryPagesBytes = csvs.get('entryPages')- if (entryPagesBytes) {- for (const row of parseCsv(entryPagesBytes)) {+ const entryPagesFiles = csvs.get('entryPages')+ if (entryPagesFiles) {+ for await (const row of readDailyRows(entryPagesFiles)) {const date = normalizeNull(row.date)if (!date || !days.has(date)) continueconst entrances = toInt(row.entrances)@@ -661,9 +742,9 @@ export class PlausibleMapper implements ImportMapper {}}- const exitPagesBytes = csvs.get('exitPages')- if (exitPagesBytes) {- for (const row of parseCsv(exitPagesBytes)) {+ const exitPagesFiles = csvs.get('exitPages')+ if (exitPagesFiles) {+ for await (const row of readDailyRows(exitPagesFiles)) {const date = normalizeNull(row.date)if (!date || !days.has(date)) continueconst exits = toInt(row.exits)@@ -675,9 +756,9 @@ export class PlausibleMapper implements ImportMapper {}}- const customEventsBytes = csvs.get('customEvents')- if (customEventsBytes) {- for (const row of parseCsv(customEventsBytes)) {+ const customEventsFiles = csvs.get('customEvents')+ if (customEventsFiles) {+ for await (const row of readDailyRows(customEventsFiles)) {const date = normalizeNull(row.date)if (!date || !days.has(date)) continueconst name = normalizeNull(row.name)@@ -695,22 +776,57 @@ export class PlausibleMapper implements ImportMapper {pid: string,importID: number,): AsyncIterable<AnalyticsImportRow> {- const csvs = this.extractCsvs(filePath)- const days = this.buildDailyData(csvs)- const sortedDates = Array.from(days.keys()).sort()-- let yielded = 0- for (const date of sortedDates) {- const daily = days.get(date)!- for (const row of this.synthesizeDay(daily, pid, importID)) {- yielded += 1- if (yielded > MAX_GENERATED_ROWS_PER_IMPORT) {- throw new ImportError(- `Plausible export would generate more than ${MAX_GENERATED_ROWS_PER_IMPORT} rows. Please split the export into smaller archives and re-import.`,+ const tempDir = await fs.promises.mkdtemp(+ path.join(os.tmpdir(), 'swetrix-plausible-'),+ )+ try {+ const csvs = await this.extractCsvs(filePath, tempDir)+ const partitions = await this.partitionCsvs(csvs, tempDir)+ let yielded = 0+ let processedDays = 0+ for (const date of Array.from(partitions.keys()).sort()) {+ const files = partitions.get(date)!+ if (!files.has('visitors')) continue+ const days = await this.buildDailyData(files)+ for (const daily of days.values()) {+ processedDays+++ const events = daily.customEvents.reduce(+ (total, event) => total + event.events,+ 0,)+ if (+ daily.visitors.visits > MAX_SESSIONS_PER_DAY ||+ events > MAX_EVENTS_PER_DAY ||+ daily.visitors.pageviews >+ Math.max(daily.visitors.visits, 1) * MAX_PAGEVIEWS_PER_SESSION+ ) {+ throw new ImportError(+ `Plausible data for ${date} exceeds the daily event processing limits. Please contact support.`,+ )+ }+ if (+ yielded + daily.visitors.pageviews + events >+ MAX_GENERATED_ROWS_PER_IMPORT+ ) {+ throw new ImportError(+ `Plausible export would generate more than ${MAX_GENERATED_ROWS_PER_IMPORT} rows. Please export a shorter date range.`,+ )+ }+ for (const row of this.synthesizeDay(daily, pid, importID)) {+ yielded+++ if (yielded % 5000 === 0)+ await new Promise<void>((resolve) => setImmediate(resolve))+ yield row+ }+ }+ for (const paths of files.values()) {+ for (const filePath of paths) await fs.promises.unlink(filePath)}- yield row}+ if (!processedDays)+ throw new ImportError('Plausible export contains no valid daily rows.')+ } finally {+ await fs.promises.rm(tempDir, { recursive: true, force: true })}}@@ -728,7 +844,12 @@ export class PlausibleMapper implements ImportMapper {if (pageviews === 0 && daily.customEvents.length === 0) return- const sessionCount = visits > 0 ? visits : pageviews > 0 ? 1 : 0+ const sessionCount =+ visits > 0+ ? visits+ : pageviews > 0 || daily.customEvents.length > 0+ ? 1+ : 0if (sessionCount === 0) returnconst pools = buildPools(daily, importID, date)@@ -773,7 +894,7 @@ export class PlausibleMapper implements ImportMapper {const location = pickFromPool(pools.locations, i)const source = pickFromPool(pools.sources, i)- const startSec = dayStartSec + i * sessionSpacingSec+ const startSec = dayStartSec + Math.floor((i * 86400) / sessionCount)sessions.push({psid,diff --git a/backend/apps/cloud/src/data-import/mappers/simple-analytics.mapper.ts b/backend/apps/cloud/src/data-import/mappers/simple-analytics.mapper.tsindex b95e37380..49480084d 100644--- a/backend/apps/cloud/src/data-import/mappers/simple-analytics.mapper.ts+++ b/backend/apps/cloud/src/data-import/mappers/simple-analytics.mapper.ts@@ -1,5 +1,4 @@-import * as fs from 'fs'-import { parse } from 'csv-parse'+import { readCsvRows } from './csv.utils'import {ImportMapper,@@ -99,19 +98,17 @@ export class SimpleAnalyticsMapper implements ImportMapper {): AsyncIterable<AnalyticsImportRow> {let headerChecked = false- const parser = fs.createReadStream(filePath).pipe(- parse({- bom: true,- columns: (headers) => {- headerChecked = true- return validateHeaders(headers)- },- skip_empty_lines: true,- trim: true,- relax_quotes: true,- relax_column_count: true,- }),- )+ const parser = readCsvRows(filePath, {+ bom: true,+ columns: (headers) => {+ headerChecked = true+ return validateHeaders(headers)+ },+ skip_empty_lines: true,+ trim: true,+ relax_quotes: true,+ relax_column_count: true,+ })for await (const row of parser) {if (row.is_robot === 'true') continuediff --git a/backend/apps/cloud/src/data-import/mappers/umami.mapper.ts b/backend/apps/cloud/src/data-import/mappers/umami.mapper.tsindex 9e74827c6..ba160684a 100644--- a/backend/apps/cloud/src/data-import/mappers/umami.mapper.ts+++ b/backend/apps/cloud/src/data-import/mappers/umami.mapper.ts@@ -2,7 +2,8 @@ import * as fs from 'fs'import * as path from 'path'import * as os from 'os'import { Unzip, UnzipInflate } from 'fflate'-import { parse } from 'csv-parse'+import { randomUUID } from 'crypto'+import { readCsvRows } from './csv.utils'import {ImportMapper,@@ -139,7 +140,7 @@ export class UmamiMapper implements ImportMapper {readonly expectedFileExtension = '.zip'private async extractCsvFromZip(zipPath: string): Promise<string> {- const tempCsv = path.join(os.tmpdir(), `swetrix-umami-${Date.now()}.csv`)+ const tempCsv = path.join(os.tmpdir(), `swetrix-umami-${randomUUID()}.csv`)return new Promise((resolve, reject) => {const zipStream = fs.createReadStream(zipPath)@@ -200,7 +201,25 @@ export class UmamiMapper implements ImportMapper {}unzipper.onfile = (file) => {- if (path.basename(file.name) !== WEBSITE_EVENT_CSV || foundEntry) return+ if (path.basename(file.name) !== WEBSITE_EVENT_CSV || foundEntry) {+ let ignoredBytes = 0+ file.ondata = (error, chunk) => {+ if (error) {+ fail(error)+ return+ }+ ignoredBytes += chunk.length+ if (ignoredBytes > MAX_UMAMI_CSV_BYTES) {+ fail(+ new ImportError(+ 'Umami ZIP contains an entry above the 512 MiB decompression limit.',+ ),+ )+ }+ }+ file.start()+ return+ }foundEntry = true@@ -318,15 +337,13 @@ export class UmamiMapper implements ImportMapper {}try {- const parser = fs.createReadStream(csvPath).pipe(- parse({- columns: true,- skip_empty_lines: true,- trim: true,- relax_quotes: true,- relax_column_count: true,- }),- )+ const parser = readCsvRows(csvPath, {+ columns: true,+ skip_empty_lines: true,+ trim: true,+ relax_quotes: true,+ relax_column_count: true,+ })for await (const row of parser) {const sessionId = normalizeNull(row.session_id)diff --git a/backend/apps/community/src/data-import/data-import.controller.ts b/backend/apps/community/src/data-import/data-import.controller.tsindex 3178a840a..b545d1f76 100644--- a/backend/apps/community/src/data-import/data-import.controller.ts+++ b/backend/apps/community/src/data-import/data-import.controller.ts@@ -105,7 +105,15 @@ export class DataImportController {)const { encryptedRefreshToken, clientId, clientSecret } =- await this.ga4ImportService.consumeTokenForImport(uid, projectId)+ await this.ga4ImportService+ .consumeTokenForImport(uid, projectId)+ .catch(async (error) => {+ await this.dataImportService.deleteImportRecord(+ projectId,+ dataImport.id,+ )+ throw error+ })try {await this.importQueue.add(@@ -158,7 +166,8 @@ export class DataImportController {})@UseInterceptors(FileInterceptor('file', {- limits: { fileSize: MAX_FILE_SIZE },+ // Multer rejects at the threshold, so allow files exactly at the limit.+ limits: { fileSize: MAX_FILE_SIZE + 1 },storage: diskStorage({destination: (_req, _file, cb) => {fs.mkdirSync(IMPORT_TMP_DIR, { recursive: true })diff --git a/backend/apps/community/src/data-import/data-import.processor.ts b/backend/apps/community/src/data-import/data-import.processor.tsindex 9ebde1d6e..374de717f 100644--- a/backend/apps/community/src/data-import/data-import.processor.ts+++ b/backend/apps/community/src/data-import/data-import.processor.ts@@ -131,6 +131,11 @@ export class DataImportProcessor extends WorkerHost {context,)) {totalRows+++ if (totalRows > 100_000_000) {+ throw new ImportError(+ 'Import exceeds 100 million events. Please import a shorter date range.',+ )+ }const created = row.data.created as stringif (created) {@@ -166,6 +171,12 @@ export class DataImportProcessor extends WorkerHost {}}+ if (totalRows === 0) {+ throw new ImportError(+ 'The export contains no importable events. Please check the file format and date range.',+ )+ }+if (eventsBatch.length > 0) {await this.flushBatch(eventsBatch)importedRows += eventsBatch.lengthdiff --git a/backend/apps/community/src/data-import/data-import.service.ts b/backend/apps/community/src/data-import/data-import.service.tsindex 407915883..349fb7db9 100644--- a/backend/apps/community/src/data-import/data-import.service.ts+++ b/backend/apps/community/src/data-import/data-import.service.ts@@ -309,6 +309,7 @@ export class DataImportService {await clickhouse.command({query: `ALTER TABLE ${CLICKHOUSE_DB}.events DELETE WHERE pid = {pid:FixedString(12)} AND importID = {importID:UInt8} AND type IN ('pageview', 'custom_event')`,query_params: { pid: projectId, importID: importId },+ clickhouse_settings: { mutations_sync: '2' },})}diff --git a/backend/apps/community/src/data-import/mappers/csv.utils.ts b/backend/apps/community/src/data-import/mappers/csv.utils.tsnew file mode 100644index 000000000..ffcd834d3--- /dev/null+++ b/backend/apps/community/src/data-import/mappers/csv.utils.ts@@ -0,0 +1,36 @@+import { createReadStream } from 'fs'+import { pipeline } from 'stream/promises'+import { parse, Options } from 'csv-parse'++import { ImportError } from './mapper.interface'++export async function* readCsvRows(+ filePath: string,+ options: Options = {},+): AsyncIterable<Record<string, string>> {+ const input = createReadStream(filePath)+ const parser = parse({+ bom: true,+ columns: true,+ skip_empty_lines: true,+ trim: true,+ relax_quotes: true,+ relax_column_count: true,+ max_record_size: 1024 * 1024,+ ...options,+ })+ const completion = pipeline(input, parser).catch(() => {})++ try {+ for await (const row of parser) yield row+ } catch (error) {+ if (error instanceof ImportError) throw error+ throw new ImportError(+ 'Could not read the import CSV. Please check the export and upload it again.',+ )+ } finally {+ input.destroy()+ parser.destroy()+ await completion+ }+}diff --git a/backend/apps/community/src/data-import/mappers/fathom.mapper.ts b/backend/apps/community/src/data-import/mappers/fathom.mapper.tsindex 1ae5397ca..42877dd0b 100644--- a/backend/apps/community/src/data-import/mappers/fathom.mapper.ts+++ b/backend/apps/community/src/data-import/mappers/fathom.mapper.ts@@ -1,10 +1,9 @@-import * as fs from 'fs'-import { parse } from 'csv-parse'+import { readCsvRows } from './csv.utils'import {ImportMapper,- AnalyticsImportRow,ImportError,+ AnalyticsImportRow,} from './mapper.interface'import {normalizeNull,@@ -136,31 +135,33 @@ export class FathomMapper implements ImportMapper {let fileType: FathomFileType | null = nulllet headerChecked = false- const parser = fs.createReadStream(filePath).pipe(- parse({- bom: true,- columns: (headers) => {- const result = detectFileType(headers)- fileType = result.type- headerChecked = true- return result.normalized- },- skip_empty_lines: true,- trim: true,- relax_quotes: true,- relax_column_count: true,- }),- )+ const parser = readCsvRows(filePath, {+ bom: true,+ columns: (headers) => {+ const result = detectFileType(headers)+ fileType = result.type+ headerChecked = true+ return result.normalized+ },+ skip_empty_lines: true,+ trim: true,+ relax_quotes: true,+ relax_column_count: true,+ })for await (const row of parser) {const datetime = normalizeNull(row.datetime)if (!datetime || !DATETIME_REGEX.test(datetime)) continue- const count = parseInt(- fileType === 'pageviews' ? row.pageviews : row.completions,- 10,- )- if (!count || count <= 0) continue+ const rawCount =+ fileType === 'pageviews' ? row.pageviews : row.completions+ const count = /^\d+$/.test(rawCount || '') ? Number(rawCount) : NaN+ if (!Number.isSafeInteger(count) || count > 100_000_000) {+ throw new ImportError(+ 'Fathom export contains an invalid or excessive event count.',+ )+ }+ if (count === 0) continueconst device = mapDevice(normalizeNull(row.device_type))const browser = mapBrowser(normalizeNull(row.browser), device)diff --git a/backend/apps/community/src/data-import/mappers/plausible.mapper.ts b/backend/apps/community/src/data-import/mappers/plausible.mapper.tsindex f0c5926d3..78fda941d 100644--- a/backend/apps/community/src/data-import/mappers/plausible.mapper.ts+++ b/backend/apps/community/src/data-import/mappers/plausible.mapper.ts@@ -1,8 +1,10 @@import * as fs from 'fs'import * as path from 'path'import * as crypto from 'crypto'-import { unzipSync, UnzipFileInfo } from 'fflate'-import { parse as parseSync } from 'csv-parse/sync'+import * as os from 'os'+import { Unzip, UnzipInflate } from 'fflate'+import { createInterface } from 'readline'+import { readCsvRows } from './csv.utils'import {ImportMapper,@@ -17,8 +19,8 @@ import {} from './mapper.utils'const MAX_PLAUSIBLE_ZIP_BYTES = 100 * 1024 * 1024-const MAX_PLAUSIBLE_UNCOMPRESSED_BYTES = 500 * 1024 * 1024-const MAX_CSV_BYTES = 50 * 1024 * 1024+const MAX_PLAUSIBLE_UNCOMPRESSED_BYTES = 2 * 1024 * 1024 * 1024+const MAX_DAILY_BYTES = 128 * 1024 * 1024const MIN_PAGE_GAP_SEC = 5const MAX_PAGE_GAP_SEC = 30 * 60const DATE_REGEX = /^\d{4}-\d{2}-\d{2}$/@@ -153,7 +155,7 @@ function seedFromString(s: string): number {function toInt(value: string | undefined, fieldName = 'value'): number {if (value === undefined || value === null || value === '') return 0- const n = parseInt(value, 10)+ const n = /^\d+$/.test(value) ? Number(value) : NaNif (!Number.isFinite(n) || Number.isNaN(n) || !Number.isSafeInteger(n)) {throw new ImportError(`Plausible export contains an invalid numeric ${fieldName}: ${value}`,@@ -167,20 +169,22 @@ function toInt(value: string | undefined, fieldName = 'value'): number {return Math.min(n, MAX_SAFE_COUNT)}-function parseCsv(bytes: Uint8Array): Record<string, string>[] {- if (bytes.length > MAX_CSV_BYTES) {- throw new ImportError(- `Plausible export contains a CSV larger than ${MAX_CSV_BYTES} bytes.`,- )+async function* readDailyRows(+ paths: string[],+): AsyncIterable<Record<string, string>> {+ for (const filePath of paths) {+ const input = fs.createReadStream(filePath)+ const lines = createInterface({ input, crlfDelay: Infinity })+ input.on('error', (error) => lines.emit('error', error))+ try {+ for await (const line of lines) {+ yield JSON.parse(line)+ }+ } finally {+ lines.close()+ input.destroy()+ }}- return parseSync(Buffer.from(bytes), {- bom: true,- columns: true,- skip_empty_lines: true,- trim: true,- relax_quotes: true,- relax_column_count: true,- }) as Record<string, string>[]}function mapBrowser(raw: string | null, device: string | null): string | null {@@ -413,89 +417,165 @@ export class PlausibleMapper implements ImportMapper {readonly provider = 'plausible'readonly expectedFileExtension = '.zip'- private extractCsvs(zipPath: string): Map<string, Uint8Array> {- const stat = fs.statSync(zipPath)+ private async extractCsvs(+ zipPath: string,+ tempDir: string,+ ): Promise<Map<string, string[]>> {+ const stat = await fs.promises.stat(zipPath)if (stat.size > MAX_PLAUSIBLE_ZIP_BYTES) {- throw new ImportError(- `Plausible ZIP exceeds the ${MAX_PLAUSIBLE_ZIP_BYTES} byte limit.`,- )+ throw new ImportError('Plausible ZIP exceeds the 100 MB upload limit.')}- const buf = fs.readFileSync(zipPath)-- const matchedKeys = new Set<string>()- const nameToKey = new Map<string, string>()+ const found = new Map<string, string[]>()+ const openFiles = new Set<number>()let totalUncompressed = 0-- const filter = (file: UnzipFileInfo): boolean => {- const base = path.basename(file.name).toLowerCase()- if (!base.endsWith('.csv')) return false- for (const [key, pattern] of Object.entries(FILE_PATTERNS)) {- if (matchedKeys.has(key)) continue- if (!pattern.test(file.name)) continue-- const declaredSize = Number.isSafeInteger(file.originalSize)- ? file.originalSize- : -1- if (declaredSize < 0) {- throw new ImportError(- `Plausible ZIP entry ${file.name} reports an invalid uncompressed size.`,- )- }- if (declaredSize > MAX_CSV_BYTES) {+ let entryCount = 0+ let pendingEntries = 0+ const unzipper = new Unzip((file) => {+ if (++entryCount > 1000) {+ throw new ImportError('Plausible ZIP contains too many files.')+ }+ const key = Object.keys(FILE_PATTERNS).find((key) =>+ FILE_PATTERNS[key].test(file.name),+ )+ if (file.originalSize > MAX_PLAUSIBLE_UNCOMPRESSED_BYTES) {+ throw new ImportError(+ 'Plausible ZIP exceeds the 2 GiB uncompressed limit. Please export a shorter date range.',+ )+ }+ let fd: number | undefined+ if (key) {+ const csvPath = path.join(tempDir, `${entryCount}.csv`)+ fd = fs.openSync(csvPath, 'wx')+ openFiles.add(fd)+ found.set(key, [...(found.get(key) ?? []), csvPath])+ }+ pendingEntries+++ file.ondata = (error, chunk, final) => {+ if (error) throw error+ totalUncompressed += chunk.length+ if (totalUncompressed > MAX_PLAUSIBLE_UNCOMPRESSED_BYTES) {throw new ImportError(- `Plausible ZIP entry ${file.name} exceeds the ${MAX_CSV_BYTES} byte CSV limit (declared ${declaredSize}).`,+ 'Plausible ZIP exceeds the 2 GiB uncompressed limit. Please export a shorter date range.',)}- if (- totalUncompressed + declaredSize >- MAX_PLAUSIBLE_UNCOMPRESSED_BYTES- ) {- throw new ImportError(- `Plausible ZIP uncompressed size exceeds the ${MAX_PLAUSIBLE_UNCOMPRESSED_BYTES} byte limit.`,- )+ if (fd !== undefined) {+ let offset = 0+ while (offset < chunk.length) {+ offset += fs.writeSync(fd, chunk, offset, chunk.length - offset)+ }+ if (final) {+ fs.closeSync(fd)+ openFiles.delete(fd)+ fd = undefined+ }}- totalUncompressed += declaredSize- matchedKeys.add(key)- nameToKey.set(file.name, key)- return true+ if (final) pendingEntries--}- return false- }+ file.start()+ })+ unzipper.register(UnzipInflate)- let entries: Record<string, Uint8Array>try {- entries = unzipSync(- new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength),- { filter },+ for await (const chunk of fs.createReadStream(zipPath, {+ highWaterMark: 16 * 1024,+ })) {+ unzipper.push(chunk as Buffer)+ }+ unzipper.push(new Uint8Array(0), true)+ if (pendingEntries > 0) throw new Error('Incomplete ZIP entry')+ } catch (error) {+ if (error instanceof ImportError) throw error+ throw new ImportError(+ 'Could not read the uploaded ZIP archive. Please upload the full export ZIP from Plausible again.',)- } catch (err) {- if (err instanceof ImportError) throw err+ } finally {+ for (const fd of openFiles) fs.closeSync(fd)+ }+ if (!found.has('visitors')) {throw new ImportError(- 'Could not read the uploaded file as a ZIP archive. Please upload the export ZIP from Plausible.',+ 'ZIP does not contain imported_visitors_*.csv. Please upload the full export ZIP from Plausible.',)}+ return found+ }- const found = new Map<string, Uint8Array>()- for (const [name, data] of Object.entries(entries)) {- const key = nameToKey.get(name)- if (!key || found.has(key)) continue- if (data.byteLength > MAX_CSV_BYTES) {- throw new ImportError(- `Plausible ZIP entry ${name} exceeds the ${MAX_CSV_BYTES} byte CSV limit after decompression.`,- )+ private async partitionCsvs(csvs: Map<string, string[]>, tempDir: string) {+ const days = new Map<string, Map<string, string[]>>()+ const daySizes = new Map<string, number>()+ const buffers = new Map<string, string[]>()+ let bufferedBytes = 0+ const flush = async () => {+ for (const [filePath, rows] of buffers) {+ await fs.promises.appendFile(filePath, rows.join(''))}- found.set(key, data)+ buffers.clear()+ bufferedBytes = 0}-- return found+ const required: Record<string, string[]> = {+ visitors: ['date', 'visits', 'pageviews'],+ pages: ['date', 'page', 'pageviews'],+ browsers: ['date', 'browser', 'visits'],+ devices: ['date', 'device', 'visits'],+ operatingSystems: ['date', 'operating_system', 'visits'],+ locations: ['date', 'country', 'visits'],+ sources: ['date', 'source', 'visits'],+ entryPages: ['date', 'entry_page', 'entrances'],+ exitPages: ['date', 'exit_page', 'exits'],+ customEvents: ['date', 'name', 'events'],+ }+ for (const [key, paths] of csvs) {+ for (const csvPath of paths) {+ for await (const row of readCsvRows(csvPath, {+ columns: (headers: string[]) => {+ const missing = required[key].filter(+ (column) => !headers.includes(column),+ )+ if (missing.length)+ throw new ImportError(+ `Plausible ${key} CSV is missing columns: ${missing.join(', ')}.`,+ )+ return headers+ },+ })) {+ const date = normalizeNull(row.date)+ if (!date || !DATE_REGEX.test(date)) continue+ const parsedDate = new Date(`${date}T00:00:00Z`)+ if (+ !Number.isFinite(parsedDate.getTime()) ||+ parsedDate.toISOString().slice(0, 10) !== date+ )+ continue+ const line = `${JSON.stringify(row)}\n`+ const bytes = Buffer.byteLength(line)+ const daySize = (daySizes.get(date) ?? 0) + bytes+ if (daySize > MAX_DAILY_BYTES)+ throw new ImportError(+ `Plausible data for ${date} exceeds the 128 MiB daily processing limit. Please contact support.`,+ )+ daySizes.set(date, daySize)+ const dayFiles = days.get(date) ?? new Map<string, string[]>()+ const filePath = path.join(tempDir, `${date}-${key}.jsonl`)+ dayFiles.set(key, [filePath])+ days.set(date, dayFiles)+ const rows = buffers.get(filePath) ?? []+ rows.push(line)+ buffers.set(filePath, rows)+ bufferedBytes += bytes+ if (bufferedBytes >= 1024 * 1024) await flush()+ }+ await fs.promises.unlink(csvPath)+ }+ }+ await flush()+ return days}- private buildDailyData(- csvs: Map<string, Uint8Array>,- ): Map<string, DailyData> {- const visitorsBytes = csvs.get('visitors')- if (!visitorsBytes) {+ private async buildDailyData(+ csvs: Map<string, string[]>,+ ): Promise<Map<string, DailyData>> {+ const visitorsFiles = csvs.get('visitors')+ if (!visitorsFiles) {throw new ImportError('ZIP does not contain imported_visitors_*.csv. Please upload the full export ZIP from Plausible.',)@@ -530,20 +610,21 @@ export class PlausibleMapper implements ImportMapper {return d}- for (const row of parseCsv(visitorsBytes)) {+ for await (const row of readDailyRows(visitorsFiles)) {const date = normalizeNull(row.date)if (!date || !DATE_REGEX.test(date)) continueconst visits = toInt(row.visits, 'visits')const pageviews = toInt(row.pageviews, 'pageviews')- if (visits <= 0 && pageviews <= 0) continueconst day = ensureDay(date)day.visitors = {date,- visitors: toInt(row.visitors, 'visitors'),- pageviews,- visits,- bounces: toInt(row.bounces, 'bounces'),- visit_duration: toInt(row.visit_duration, 'visit_duration'),+ visitors: day.visitors.visitors + toInt(row.visitors, 'visitors'),+ pageviews: day.visitors.pageviews + pageviews,+ visits: day.visitors.visits + visits,+ bounces: day.visitors.bounces + toInt(row.bounces, 'bounces'),+ visit_duration:+ day.visitors.visit_duration ++ toInt(row.visit_duration, 'visit_duration'),}}@@ -553,9 +634,9 @@ export class PlausibleMapper implements ImportMapper {)}- const pagesBytes = csvs.get('pages')- if (pagesBytes) {- for (const row of parseCsv(pagesBytes)) {+ const pagesFiles = csvs.get('pages')+ if (pagesFiles) {+ for await (const row of readDailyRows(pagesFiles)) {const date = normalizeNull(row.date)if (!date || !days.has(date)) continueconst pageviews = toInt(row.pageviews)@@ -568,9 +649,9 @@ export class PlausibleMapper implements ImportMapper {}}- const browsersBytes = csvs.get('browsers')- if (browsersBytes) {- for (const row of parseCsv(browsersBytes)) {+ const browsersFiles = csvs.get('browsers')+ if (browsersFiles) {+ for await (const row of readDailyRows(browsersFiles)) {const date = normalizeNull(row.date)if (!date || !days.has(date)) continueconst visits = toInt(row.visits)@@ -583,9 +664,9 @@ export class PlausibleMapper implements ImportMapper {}}- const devicesBytes = csvs.get('devices')- if (devicesBytes) {- for (const row of parseCsv(devicesBytes)) {+ const devicesFiles = csvs.get('devices')+ if (devicesFiles) {+ for await (const row of readDailyRows(devicesFiles)) {const date = normalizeNull(row.date)if (!date || !days.has(date)) continueconst visits = toInt(row.visits)@@ -597,9 +678,9 @@ export class PlausibleMapper implements ImportMapper {}}- const osBytes = csvs.get('operatingSystems')- if (osBytes) {- for (const row of parseCsv(osBytes)) {+ const osFiles = csvs.get('operatingSystems')+ if (osFiles) {+ for await (const row of readDailyRows(osFiles)) {const date = normalizeNull(row.date)if (!date || !days.has(date)) continueconst visits = toInt(row.visits)@@ -612,9 +693,9 @@ export class PlausibleMapper implements ImportMapper {}}- const locationsBytes = csvs.get('locations')- if (locationsBytes) {- for (const row of parseCsv(locationsBytes)) {+ const locationsFiles = csvs.get('locations')+ if (locationsFiles) {+ for await (const row of readDailyRows(locationsFiles)) {const date = normalizeNull(row.date)if (!date || !days.has(date)) continueconst visits = toInt(row.visits)@@ -627,9 +708,9 @@ export class PlausibleMapper implements ImportMapper {}}- const sourcesBytes = csvs.get('sources')- if (sourcesBytes) {- for (const row of parseCsv(sourcesBytes)) {+ const sourcesFiles = csvs.get('sources')+ if (sourcesFiles) {+ for await (const row of readDailyRows(sourcesFiles)) {const date = normalizeNull(row.date)if (!date || !days.has(date)) continueconst visits = toInt(row.visits)@@ -647,9 +728,9 @@ export class PlausibleMapper implements ImportMapper {}}- const entryPagesBytes = csvs.get('entryPages')- if (entryPagesBytes) {- for (const row of parseCsv(entryPagesBytes)) {+ const entryPagesFiles = csvs.get('entryPages')+ if (entryPagesFiles) {+ for await (const row of readDailyRows(entryPagesFiles)) {const date = normalizeNull(row.date)if (!date || !days.has(date)) continueconst entrances = toInt(row.entrances)@@ -661,9 +742,9 @@ export class PlausibleMapper implements ImportMapper {}}- const exitPagesBytes = csvs.get('exitPages')- if (exitPagesBytes) {- for (const row of parseCsv(exitPagesBytes)) {+ const exitPagesFiles = csvs.get('exitPages')+ if (exitPagesFiles) {+ for await (const row of readDailyRows(exitPagesFiles)) {const date = normalizeNull(row.date)if (!date || !days.has(date)) continueconst exits = toInt(row.exits)@@ -675,9 +756,9 @@ export class PlausibleMapper implements ImportMapper {}}- const customEventsBytes = csvs.get('customEvents')- if (customEventsBytes) {- for (const row of parseCsv(customEventsBytes)) {+ const customEventsFiles = csvs.get('customEvents')+ if (customEventsFiles) {+ for await (const row of readDailyRows(customEventsFiles)) {const date = normalizeNull(row.date)if (!date || !days.has(date)) continueconst name = normalizeNull(row.name)@@ -695,22 +776,57 @@ export class PlausibleMapper implements ImportMapper {pid: string,importID: number,): AsyncIterable<AnalyticsImportRow> {- const csvs = this.extractCsvs(filePath)- const days = this.buildDailyData(csvs)- const sortedDates = Array.from(days.keys()).sort()-- let yielded = 0- for (const date of sortedDates) {- const daily = days.get(date)!- for (const row of this.synthesizeDay(daily, pid, importID)) {- yielded += 1- if (yielded > MAX_GENERATED_ROWS_PER_IMPORT) {- throw new ImportError(- `Plausible export would generate more than ${MAX_GENERATED_ROWS_PER_IMPORT} rows. Please split the export into smaller archives and re-import.`,+ const tempDir = await fs.promises.mkdtemp(+ path.join(os.tmpdir(), 'swetrix-plausible-'),+ )+ try {+ const csvs = await this.extractCsvs(filePath, tempDir)+ const partitions = await this.partitionCsvs(csvs, tempDir)+ let yielded = 0+ let processedDays = 0+ for (const date of Array.from(partitions.keys()).sort()) {+ const files = partitions.get(date)!+ if (!files.has('visitors')) continue+ const days = await this.buildDailyData(files)+ for (const daily of days.values()) {+ processedDays+++ const events = daily.customEvents.reduce(+ (total, event) => total + event.events,+ 0,)+ if (+ daily.visitors.visits > MAX_SESSIONS_PER_DAY ||+ events > MAX_EVENTS_PER_DAY ||+ daily.visitors.pageviews >+ Math.max(daily.visitors.visits, 1) * MAX_PAGEVIEWS_PER_SESSION+ ) {+ throw new ImportError(+ `Plausible data for ${date} exceeds the daily event processing limits. Please contact support.`,+ )+ }+ if (+ yielded + daily.visitors.pageviews + events >+ MAX_GENERATED_ROWS_PER_IMPORT+ ) {+ throw new ImportError(+ `Plausible export would generate more than ${MAX_GENERATED_ROWS_PER_IMPORT} rows. Please export a shorter date range.`,+ )+ }+ for (const row of this.synthesizeDay(daily, pid, importID)) {+ yielded+++ if (yielded % 5000 === 0)+ await new Promise<void>((resolve) => setImmediate(resolve))+ yield row+ }+ }+ for (const paths of files.values()) {+ for (const filePath of paths) await fs.promises.unlink(filePath)}- yield row}+ if (!processedDays)+ throw new ImportError('Plausible export contains no valid daily rows.')+ } finally {+ await fs.promises.rm(tempDir, { recursive: true, force: true })}}@@ -728,7 +844,12 @@ export class PlausibleMapper implements ImportMapper {if (pageviews === 0 && daily.customEvents.length === 0) return- const sessionCount = visits > 0 ? visits : pageviews > 0 ? 1 : 0+ const sessionCount =+ visits > 0+ ? visits+ : pageviews > 0 || daily.customEvents.length > 0+ ? 1+ : 0if (sessionCount === 0) returnconst pools = buildPools(daily, importID, date)@@ -773,7 +894,7 @@ export class PlausibleMapper implements ImportMapper {const location = pickFromPool(pools.locations, i)const source = pickFromPool(pools.sources, i)- const startSec = dayStartSec + i * sessionSpacingSec+ const startSec = dayStartSec + Math.floor((i * 86400) / sessionCount)sessions.push({psid,diff --git a/backend/apps/community/src/data-import/mappers/simple-analytics.mapper.ts b/backend/apps/community/src/data-import/mappers/simple-analytics.mapper.tsindex b95e37380..49480084d 100644--- a/backend/apps/community/src/data-import/mappers/simple-analytics.mapper.ts+++ b/backend/apps/community/src/data-import/mappers/simple-analytics.mapper.ts@@ -1,5 +1,4 @@-import * as fs from 'fs'-import { parse } from 'csv-parse'+import { readCsvRows } from './csv.utils'import {ImportMapper,@@ -99,19 +98,17 @@ export class SimpleAnalyticsMapper implements ImportMapper {): AsyncIterable<AnalyticsImportRow> {let headerChecked = false- const parser = fs.createReadStream(filePath).pipe(- parse({- bom: true,- columns: (headers) => {- headerChecked = true- return validateHeaders(headers)- },- skip_empty_lines: true,- trim: true,- relax_quotes: true,- relax_column_count: true,- }),- )+ const parser = readCsvRows(filePath, {+ bom: true,+ columns: (headers) => {+ headerChecked = true+ return validateHeaders(headers)+ },+ skip_empty_lines: true,+ trim: true,+ relax_quotes: true,+ relax_column_count: true,+ })for await (const row of parser) {if (row.is_robot === 'true') continuediff --git a/backend/apps/community/src/data-import/mappers/umami.mapper.ts b/backend/apps/community/src/data-import/mappers/umami.mapper.tsindex 9e74827c6..ba160684a 100644--- a/backend/apps/community/src/data-import/mappers/umami.mapper.ts+++ b/backend/apps/community/src/data-import/mappers/umami.mapper.ts@@ -2,7 +2,8 @@ import * as fs from 'fs'import * as path from 'path'import * as os from 'os'import { Unzip, UnzipInflate } from 'fflate'-import { parse } from 'csv-parse'+import { randomUUID } from 'crypto'+import { readCsvRows } from './csv.utils'import {ImportMapper,@@ -139,7 +140,7 @@ export class UmamiMapper implements ImportMapper {readonly expectedFileExtension = '.zip'private async extractCsvFromZip(zipPath: string): Promise<string> {- const tempCsv = path.join(os.tmpdir(), `swetrix-umami-${Date.now()}.csv`)+ const tempCsv = path.join(os.tmpdir(), `swetrix-umami-${randomUUID()}.csv`)return new Promise((resolve, reject) => {const zipStream = fs.createReadStream(zipPath)@@ -200,7 +201,25 @@ export class UmamiMapper implements ImportMapper {}unzipper.onfile = (file) => {- if (path.basename(file.name) !== WEBSITE_EVENT_CSV || foundEntry) return+ if (path.basename(file.name) !== WEBSITE_EVENT_CSV || foundEntry) {+ let ignoredBytes = 0+ file.ondata = (error, chunk) => {+ if (error) {+ fail(error)+ return+ }+ ignoredBytes += chunk.length+ if (ignoredBytes > MAX_UMAMI_CSV_BYTES) {+ fail(+ new ImportError(+ 'Umami ZIP contains an entry above the 512 MiB decompression limit.',+ ),+ )+ }+ }+ file.start()+ return+ }foundEntry = true@@ -318,15 +337,13 @@ export class UmamiMapper implements ImportMapper {}try {- const parser = fs.createReadStream(csvPath).pipe(- parse({- columns: true,- skip_empty_lines: true,- trim: true,- relax_quotes: true,- relax_column_count: true,- }),- )+ const parser = readCsvRows(csvPath, {+ columns: true,+ skip_empty_lines: true,+ trim: true,+ relax_quotes: true,+ relax_column_count: true,+ })for await (const row of parser) {const sessionId = normalizeNull(row.session_id)diff --git a/backend/jest.data-import.config.js b/backend/jest.data-import.config.jsnew file mode 100644index 000000000..5f9545091--- /dev/null+++ b/backend/jest.data-import.config.js@@ -0,0 +1,7 @@+module.exports = {+ preset: 'ts-jest',+ testEnvironment: 'node',+ roots: ['<rootDir>/tests'],+ testMatch: ['**/data-import*.spec.ts'],+ testTimeout: 60000,+}diff --git a/backend/tests/data-import-ga4.spec.ts b/backend/tests/data-import-ga4.spec.tsnew file mode 100644index 000000000..acbe1c5ff--- /dev/null+++ b/backend/tests/data-import-ga4.spec.ts@@ -0,0 +1,79 @@+import * as crypto from 'crypto'++const runReport = jest.fn()+jest.mock('@google-analytics/data', () => ({+ BetaAnalyticsDataClient: jest.fn(() => ({ runReport })),+}))+jest.mock('google-auth-library', () => ({+ OAuth2Client: jest.fn(() => ({ setCredentials: jest.fn() })),+}))++for (const edition of ['cloud', 'community']) {+ describe(`${edition} GA4 import`, () => {+ jest.doMock(`../apps/${edition}/src/common/utils`, () => ({+ deriveKey: () => '00'.repeat(32),+ }))+ const { Ga4Mapper } = require(+ `../apps/${edition}/src/data-import/mappers/ga4.mapper`,+ )+ it('maps paged API reports and preserves pageview and custom-event counts', async () => {+ runReport.mockReset()+ runReport.mockImplementation(async ({ dimensions, metrics }) => {+ const values: Record<string, string> = {+ dateHour: '2024010112',+ hostName: 'example.com',+ pagePath: '/',+ deviceCategory: 'desktop',+ browser: 'Chrome',+ operatingSystem: 'Linux',+ countryId: 'GB',+ eventName: 'Signup',+ sessionSource: 'google',+ sessionMedium: 'organic',+ }+ return [+ {+ rows: [+ {+ dimensionValues: dimensions.map(({ name }) => ({+ value: values[name] || '(not set)',+ })),+ metricValues: [+ { value: metrics[0].name === 'eventCount' ? '2' : '3' },+ ],+ },+ ],+ },+ ]+ })+ const iv = Buffer.alloc(12)+ const cipher = crypto.createCipheriv('aes-256-gcm', Buffer.alloc(32), iv)+ const encrypted = Buffer.concat([+ cipher.update('refresh-token'),+ cipher.final(),+ ])+ const token = `${iv.toString('hex')}:${encrypted.toString('hex')}:${cipher.getAuthTag().toString('hex')}`+ const rows = []+ for await (const row of new Ga4Mapper().createRowStream(+ null,+ 'testproject1',+ 1,+ {+ encryptedRefreshToken: token,+ ga4PropertyId: '123',+ ga4ClientId: 'client',+ ga4ClientSecret: 'secret',+ startDate: '2024-01-01',+ endDate: '2024-01-31',+ },+ ))+ rows.push(row)+ expect(rows.filter((row) => row.type === 'pageview')).toHaveLength(3)+ expect(rows.filter((row) => row.type === 'custom_event')).toHaveLength(2)+ expect(+ rows.every((row) => row.data.created === '2024-01-01 12:00:00'),+ ).toBe(true)+ expect(runReport).toHaveBeenCalledTimes(3)+ })+ })+}diff --git a/backend/tests/data-import-mappers.spec.ts b/backend/tests/data-import-mappers.spec.tsnew file mode 100644index 000000000..1fd7a841b--- /dev/null+++ b/backend/tests/data-import-mappers.spec.ts@@ -0,0 +1,243 @@+import * as fs from 'fs'+import * as os from 'os'+import * as path from 'path'+import { zipSync, strToU8 } from 'fflate'+import { PlausibleMapper as CloudPlausible } from '../apps/cloud/src/data-import/mappers/plausible.mapper'+import { PlausibleMapper as CommunityPlausible } from '../apps/community/src/data-import/mappers/plausible.mapper'+import { FathomMapper as CloudFathom } from '../apps/cloud/src/data-import/mappers/fathom.mapper'+import { FathomMapper as CommunityFathom } from '../apps/community/src/data-import/mappers/fathom.mapper'+import { SimpleAnalyticsMapper as CloudSimple } from '../apps/cloud/src/data-import/mappers/simple-analytics.mapper'+import { SimpleAnalyticsMapper as CommunitySimple } from '../apps/community/src/data-import/mappers/simple-analytics.mapper'+import { UmamiMapper as CloudUmami } from '../apps/cloud/src/data-import/mappers/umami.mapper'+import { UmamiMapper as CommunityUmami } from '../apps/community/src/data-import/mappers/umami.mapper'++const visitors =+ 'date,visitors,pageviews,bounces,visits,visit_duration\n2024-01-01,2,5,0,2,30\n'+const collect = async (stream: AsyncIterable<any>) => {+ const rows = []+ for await (const row of stream) rows.push(row)+ return rows+}+let directory: string+beforeEach(() => {+ directory = fs.mkdtempSync(path.join(os.tmpdir(), 'import-test-'))+})+afterEach(() => {+ fs.rmSync(directory, { recursive: true, force: true })+})+function archive(files: Record<string, string>, level: 0 | 6 = 6) {+ const file = path.join(directory, 'export.zip')+ fs.writeFileSync(+ file,+ zipSync(+ Object.fromEntries(+ Object.entries(files).map(([name, data]) => [name, strToU8(data)]),+ ),+ { level },+ ),+ )+ return file+}++describe.each([+ ['cloud', CloudPlausible, CloudFathom, CloudSimple, CloudUmami],+ [+ 'community',+ CommunityPlausible,+ CommunityFathom,+ CommunitySimple,+ CommunityUmami,+ ],+] as const)('%s imports', (_edition, Plausible, Fathom, Simple, Umami) => {+ it('imports all Plausible chunks, pageviews, dimensions and custom events', async () => {+ const file = archive({+ 'export/imported_visitors_20240101_20240101.csv': visitors,+ 'export/imported_visitors_20240102_20240102.csv': visitors.replaceAll(+ '2024-01-01',+ '2024-01-02',+ ),+ 'imported_pages.csv':+ 'date,hostname,page,pageviews\n2024-01-01,example.com,/a,5\n2024-01-02,example.com,/b,5\n',+ 'imported_browsers.csv':+ 'date,browser,browser_version,visits\n2024-01-01,Chrome,120,2\n',+ 'imported_devices.csv': 'date,device,visits\n2024-01-01,Mobile,2\n',+ 'imported_custom_events.csv': 'date,name,events\n2024-01-01,Signup,3\n',+ })+ const rows = await collect(+ new Plausible().createRowStream(file, 'testproject1', 7),+ )+ expect(rows.filter((row) => row.type === 'pageview')).toHaveLength(10)+ expect(rows.filter((row) => row.type === 'custom_event')).toHaveLength(3)+ expect(rows.find((row) => row.data.pg === '/a').data.br).toBe(+ 'Mobile Chrome',+ )+ expect(rows.some((row) => row.data.pg === '/b')).toBe(true)+ expect(rows.every((row) => row.data.importID === 7)).toBe(true)+ })++ it('handles a 57 MiB ZIP containing a CSV above the former 50 MiB limit', async () => {+ const padding = 'x'.repeat(2000)+ const record = `2024-01-01,example.com,/large,1,${padding}\n`+ const count = Math.ceil((57 * 1024 * 1024) / Buffer.byteLength(record))+ const file = archive(+ {+ 'imported_visitors.csv': visitors,+ 'imported_pages.csv': `date,hostname,page,pageviews,unused\n${record.repeat(count)}`,+ },+ 0,+ )+ expect(fs.statSync(file).size).toBeGreaterThan(57 * 1024 * 1024)+ let timerRan = false+ const timer = setTimeout(() => {+ timerRan = true+ }, 0)+ try {+ const rows = await collect(+ new Plausible().createRowStream(file, 'testproject1', 1),+ )+ expect(rows).toHaveLength(5)+ expect(rows.every((row) => row.data.pg === '/large')).toBe(true)+ expect(timerRan).toBe(true)+ } finally {+ clearTimeout(timer)+ }+ })++ it('rejects unsupported ZIP contents and malformed CSV headers', async () => {+ await expect(+ collect(+ new Plausible().createRowStream(+ archive({ 'visitors.csv': visitors }),+ 'testproject1',+ 1,+ ),+ ),+ ).rejects.toThrow('imported_visitors')+ await expect(+ collect(+ new Plausible().createRowStream(+ archive({ 'imported_visitors.csv': 'date,wrong\n2024-01-01,1\n' }),+ 'testproject1',+ 1,+ ),+ ),+ ).rejects.toThrow('missing columns')+ })++ it('rejects truncated archives, excessive declared expansion, and invalid counts', async () => {+ const file = archive({ 'imported_visitors.csv': visitors })+ const bytes = fs.readFileSync(file)+ fs.writeFileSync(file, bytes.subarray(0, 60))+ await expect(+ collect(new Plausible().createRowStream(file, 'testproject1', 1)),+ ).rejects.toThrow()+ bytes.writeUInt32LE(2 * 1024 * 1024 * 1024 + 1, 22)+ fs.writeFileSync(file, bytes)+ await expect(+ collect(new Plausible().createRowStream(file, 'testproject1', 1)),+ ).rejects.toThrow('2 GiB')+ archive({+ 'imported_visitors.csv': visitors.replace(',2,5,0,2,30', ',2,5.5,0,2,30'),+ })+ await expect(+ collect(new Plausible().createRowStream(file, 'testproject1', 1)),+ ).rejects.toThrow('invalid numeric')+ })++ it('rejects daily counts over the limits instead of silently truncating', async () => {+ const file = archive({+ 'imported_visitors.csv': visitors.replace(+ ',2,5,0,2,30',+ ',2,5,0,1000001,30',+ ),+ })+ await expect(+ collect(new Plausible().createRowStream(file, 'testproject1', 1)),+ ).rejects.toThrow('daily event processing limits')+ })++ it('preserves days with custom events but no pageviews or visits', async () => {+ const file = archive({+ 'imported_visitors.csv': visitors.replace(',2,5,0,2,30', ',1,0,0,0,0'),+ 'imported_custom_events.csv': 'date,name,events\n2024-01-01,Signup,3\n',+ })+ const rows = await collect(+ new Plausible().createRowStream(file, 'testproject1', 1),+ )+ expect(rows).toHaveLength(3)+ expect(rows.every((row) => row.type === 'custom_event')).toBe(true)+ })++ it('cleans Plausible temporary files when the consumer stops or parsing fails', async () => {+ const cleanup = jest.spyOn(fs.promises, 'rm')+ const file = archive({ 'imported_visitors.csv': visitors })+ const rows = new Plausible().createRowStream(file, 'testproject1', 1)+ const stream = rows[Symbol.asyncIterator]()+ await stream.next()+ await stream.return!()+ expect(cleanup).toHaveBeenCalledWith(+ expect.stringContaining('swetrix-plausible-'),+ { recursive: true, force: true },+ )+ cleanup.mockClear()+ await expect(+ collect(+ new Plausible().createRowStream(+ archive({ 'bad.csv': 'invalid' }),+ 'testproject1',+ 1,+ ),+ ),+ ).rejects.toThrow()+ expect(cleanup).toHaveBeenCalled()+ cleanup.mockRestore()+ })++ it('reports missing CSV files without an unhandled stream error', async () => {+ for (const Mapper of [Fathom, Simple]) {+ await expect(+ collect(+ new Mapper().createRowStream(+ path.join(directory, 'missing.csv'),+ 'testproject1',+ 1,+ ),+ ),+ ).rejects.toThrow('Could not read')+ }+ })++ it('streams Fathom counts and Simple Analytics raw events', async () => {+ const file = path.join(directory, 'export.csv')+ fs.writeFileSync(+ file,+ 'datetime,hostname,pathname,pageviews\n2024-01-01 00:00:00,example.com,/,3\n',+ )+ expect(+ await collect(new Fathom().createRowStream(file, 'testproject1', 1)),+ ).toHaveLength(3)+ fs.writeFileSync(+ file,+ 'added_iso,datapoint,session_id,path\n2024-01-01T00:00:00Z,pageview,s1,/\n2024-01-01T00:01:00Z,Signup,s1,/\n',+ )+ const rows = await collect(+ new Simple().createRowStream(file, 'testproject1', 1),+ )+ expect(rows.map((row) => row.type)).toEqual(['pageview', 'custom_event'])+ })++ it('imports Umami BOM CSV and reports invalid ZIPs', async () => {+ const file = archive({+ 'session.csv': 'ignored\n'.repeat(10000),+ 'website_event.csv':+ '\uFEFFsession_id,created_at,event_type,url_path\ns1,2024-01-01 00:00:00,1,/\n',+ })+ expect(+ await collect(new Umami().createRowStream(file, 'testproject1', 1)),+ ).toHaveLength(1)+ fs.writeFileSync(file, 'invalid')+ await expect(+ collect(new Umami().createRowStream(file, 'testproject1', 1)),+ ).rejects.toThrow()+ })+})diff --git a/backend/tests/data-import-processor.spec.ts b/backend/tests/data-import-processor.spec.tsnew file mode 100644index 000000000..a5e301cce--- /dev/null+++ b/backend/tests/data-import-processor.spec.ts@@ -0,0 +1,110 @@+import * as fs from 'fs'+import * as os from 'os'+import * as path from 'path'+import { randomUUID } from 'crypto'++for (const edition of ['cloud', 'community']) {+ describe(`${edition} import processor`, () => {+ const root = `../apps/${edition}/src`+ const insert = jest.fn()+ const getMapper = jest.fn()+ jest.doMock(`${root}/common/integrations/clickhouse`, () => ({+ clickhouse: { insert },+ }))+ jest.doMock(`${root}/data-import/mappers`, () => ({ getMapper }))+ jest.doMock(`${root}/data-import/data-import.service`, () => ({+ DataImportService: class {},+ }))+ jest.doMock(`${root}/data-import/entity/data-import.entity`, () => ({+ DataImportStatus: { COMPLETED: 'completed', PROCESSING: 'processing' },+ }))+ if (edition === 'cloud')+ jest.doMock(`${root}/common/analytics`, () => ({+ trackCustom: jest.fn(),+ }))+ const { DataImportProcessor } = require(+ `${root}/data-import/data-import.processor`,+ )+ const service = {+ findById: jest.fn(),+ findOne: jest.fn(),+ markProcessing: jest.fn(),+ markCompleted: jest.fn(),+ markFailed: jest.fn(),+ cleanupImportedRows: jest.fn(),+ }+ let fileName: string+ let filePath: string+ let job: any+ beforeEach(() => {+ jest.clearAllMocks()+ insert.mockResolvedValue({})+ service.findById.mockResolvedValue({ status: 'pending' })+ service.findOne.mockResolvedValue({ status: 'pending' })+ fileName = `test-${randomUUID()}.csv`+ filePath = path.join(os.tmpdir(), 'swetrix-imports', fileName)+ fs.mkdirSync(path.dirname(filePath), { recursive: true })+ fs.writeFileSync(filePath, '')+ job = {+ data: {+ id: 10,+ importId: 2,+ projectId: 'testproject1',+ provider: 'simple-analytics',+ fileName,+ },+ updateProgress: jest.fn(),+ }+ })+ afterEach(() => {+ fs.rmSync(filePath, { force: true })+ })+ function rows(count: number) {+ getMapper.mockReturnValue({+ createRowStream: async function* () {+ for (let i = 0; i < count; i++)+ yield {+ type: 'pageview',+ data: { created: '2024-01-01 00:00:00', importID: 2 },+ }+ },+ })+ }+ it('writes batches of 5000, flushes the remainder, and cleans the upload', async () => {+ rows(5001)+ const sizes: number[] = []+ insert.mockImplementation(async ({ values }) => {+ sizes.push(values.length)+ })+ await new DataImportProcessor(service).process(job)+ expect(sizes).toEqual([5000, 1])+ expect(service.markCompleted).toHaveBeenCalledWith(+ ...(edition === 'cloud' ? [10] : [2, 'testproject1']),+ expect.objectContaining({ importedRows: 5001, totalRows: 5001 }),+ )+ expect(service.markFailed).not.toHaveBeenCalled()+ expect(fs.existsSync(filePath)).toBe(false)+ })+ it('rolls back partial data and reports a failed insert', async () => {+ rows(5001)+ insert.mockRejectedValueOnce(new Error('database unavailable'))+ await new DataImportProcessor(service).process(job)+ expect(service.cleanupImportedRows).toHaveBeenCalledWith(+ 'testproject1',+ 2,+ )+ expect(service.markFailed).toHaveBeenCalled()+ expect(service.markCompleted).not.toHaveBeenCalled()+ expect(fs.existsSync(filePath)).toBe(false)+ })+ it('reports an empty or incompatible export instead of successful zero-row import', async () => {+ rows(0)+ await new DataImportProcessor(service).process(job)+ expect(service.markFailed).toHaveBeenCalledWith(+ ...(edition === 'cloud' ? [10] : [2, 'testproject1']),+ expect.stringContaining('no importable events'),+ )+ expect(service.markCompleted).not.toHaveBeenCalled()+ })+ })+}diff --git a/backend/tests/data-import-upload.spec.ts b/backend/tests/data-import-upload.spec.tsnew file mode 100644index 000000000..986fea4ad--- /dev/null+++ b/backend/tests/data-import-upload.spec.ts@@ -0,0 +1,119 @@+import * as fs from 'fs'+import { PassThrough, Readable } from 'stream'+import multer from 'multer'++for (const edition of ['cloud', 'community']) {+ describe(`${edition} multipart upload limit`, () => {+ const root = `../apps/${edition}/src`+ let options: multer.Options+ jest.resetModules()+ jest.doMock('@nestjs/platform-express', () => ({+ FileInterceptor: (_field, config) => {+ options = config+ return class {}+ },+ }))+ jest.doMock(`${root}/project/project.service`, () => ({+ ProjectService: class {},+ }))+ jest.doMock(`${root}/data-import/data-import.service`, () => ({+ DataImportService: class {},+ }))+ jest.doMock(`${root}/data-import/ga4-import.service`, () => ({+ Ga4ImportService: class {},+ }))+ jest.doMock(`${root}/data-import/data-import.processor`, () => ({+ DATA_IMPORT_QUEUE: 'data-import',+ }))+ jest.doMock(`${root}/data-import/mappers`, () => ({+ SUPPORTED_PROVIDERS: ['plausible'],+ getMapper: jest.fn(),+ }))+ jest.doMock(`${root}/auth/decorators`, () => ({ Auth: () => () => {} }))+ jest.doMock(`${root}/common/utils`, () => ({ getIPFromHeaders: jest.fn() }))+ if (edition === 'cloud') {+ jest.doMock(`${root}/auth/guards/authentication.guard`, () => ({+ AuthenticationGuard: class {},+ }))+ jest.doMock(`${root}/api-key/api-key-access.decorator`, () => ({+ ApiKeyAccess: () => () => {},+ }))+ jest.doMock(`${root}/common/analytics`, () => ({+ trackCustom: jest.fn(),+ }))+ }+ const { DataImportController } = require(+ `${root}/data-import/data-import.controller`,+ )+ it('removes the pending GA4 record when the connection token has expired', async () => {+ const error = new Error('Expired connection token')+ const imports = {+ create: jest.fn().mockResolvedValue({ id: 10 }),+ deleteImportRecord: jest.fn(),+ }+ const projects = { getFullProject: jest.fn(), allowedToManage: jest.fn() }+ const ga4 = { consumeTokenForImport: jest.fn().mockRejectedValue(error) }+ const queue = { add: jest.fn() }+ const controller = new DataImportController(imports, projects, ga4, queue)+ await expect(+ controller.ga4Start(+ 'testproject1',+ 'user',+ { propertyId: '123' },+ {},+ '127.0.0.1',+ ),+ ).rejects.toThrow(error)+ expect(imports.deleteImportRecord).toHaveBeenCalledWith(+ ...(edition === 'cloud' ? [10] : ['testproject1', 10]),+ )+ expect(queue.add).not.toHaveBeenCalled()+ })+ it.each([57 * 1024 * 1024, 100 * 1024 * 1024, 100 * 1024 * 1024 + 1])(+ 'handles a %i-byte file through the configured Multer middleware',+ async (size) => {+ const boundary = 'swetrix-import-test-boundary'+ const prefix = Buffer.from(+ `--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="export.zip"\r\nContent-Type: application/zip\r\n\r\n`,+ )+ const suffix = Buffer.from(`\r\n--${boundary}--\r\n`)+ const request = new PassThrough() as any+ request.headers = {+ 'content-type': `multipart/form-data; boundary=${boundary}`,+ 'content-length': String(prefix.length + size + suffix.length),+ }+ request.method = 'POST'+ const finished = new Promise<Error | undefined>((resolve) => {+ multer(options).single('file')(request, {} as any, (error) =>+ resolve(error),+ )+ })+ const chunk = Buffer.alloc(1024 * 1024)+ const source = Readable.from(+ (function* () {+ yield prefix+ for (let remaining = size; remaining > 0; remaining -= chunk.length)+ yield chunk.subarray(0, Math.min(chunk.length, remaining))+ yield suffix+ })(),+ )+ source.pipe(request)+ const error = await finished+ try {+ if (size <= 100 * 1024 * 1024) {+ expect(error).toBeUndefined()+ expect(request.file.size).toBe(size)+ expect(fs.statSync(request.file.path).size).toBe(size)+ } else {+ expect(error).toMatchObject({ code: 'LIMIT_FILE_SIZE' })+ expect(request.file).toBeUndefined()+ }+ } finally {+ if (request.file) fs.rmSync(request.file.path, { force: true })+ source.destroy()+ request.destroy()+ }+ },+ )+ })+}diff --git a/docs/content/docs/data-import.mdx b/docs/content/docs/data-import.mdxindex 0752874d1..882119c28 100644--- a/docs/content/docs/data-import.mdx+++ b/docs/content/docs/data-import.mdx@@ -279,13 +279,13 @@ The page auto-refreshes while an import is processing. You can navigate away and<TabsContent value="plausible"><Callout type="warn">- Plausible only allows exporting daily aggregated data — there is no raw event export. Swetrix- reconstructs synthetic per-event rows from your aggregates so you can browse the data in- dashboards. Because the mapper samples each dimension's daily distribution independently with- replacement, single-dimension breakdowns (e.g. top browsers or top pages) are deterministic- approximations rather than guaranteed exact reproductions of Plausible's report. Only per-day- totals and the top-level generated counts (sessions, pageviews, custom events) are preserved- exactly.+ Plausible's full CSV export contains daily aggregated data. Swetrix reconstructs synthetic+ per-event rows from your aggregates so you can browse the data in dashboards. Because the mapper+ samples each dimension's daily distribution independently with replacement, single-dimension+ breakdowns (e.g. top browsers or top pages) are deterministic approximations rather than+ guaranteed exact reproductions of Plausible's report. Only per-day pageview and custom-event+ totals are preserved for supported exports. Unique visitor counts, session duration, and bounce+ rate may differ.</Callout><Steps>@@ -340,7 +340,7 @@ For each day in the export, Swetrix:4. Distributes the day's `pageviews` across sessions (first page = a sampled entry page, last page = a sampled exit page, middle pages sampled from the pages distribution)5. Spreads session start times evenly across the 24h window and pageview gaps within a session based on the average `visit_duration` per session-This is deterministic — re-importing the same export produces identical rows.+The generated rows are deterministic for the same export and import ID.<h3>What's not imported?</h3>@@ -375,6 +375,10 @@ This permanently removes all analytics rows associated with that import. Your li## Limitations- **File size**: Maximum 100 MB per upload (for file-based imports)+- **Plausible archive size**: Maximum 2 GiB after decompression. CSVs are processed one day at a time; a single day's intermediate data is limited to 128 MiB. Archives above these limits need a shorter export range or help from support.+- **Plausible daily counts**: Up to 1 million sessions and 1 million custom events per day, with up to 1,000 pageviews per generated session. Imports exceeding these limits fail with an error rather than silently dropping events.+- **Event count**: Maximum 100 million generated events per import+- **Umami archive size**: The extracted `website_event.csv` is limited to 512 MiB- **One at a time**: Only one import can be active (pending or processing) per project at a time- **Timestamps**: Events with invalid timestamps are skipped during import- **GA4 dimensions**: Google Analytics 4 imports are subject to API limitations — see the "What's not imported?" section under the Google Analytics 4 tab for details