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.

feat(data-warehouse): show upload progress for file sources (#95080)

posthog[bot]d1326b66ea63
diff --git a/frontend/src/lib/api.test.ts b/frontend/src/lib/api.test.ts
index 05112a8f483c..a1f357c855a5 100644
--- a/frontend/src/lib/api.test.ts
+++ b/frontend/src/lib/api.test.ts
@@ -486,6 +486,86 @@ describe('API helper', () => {
})
})
+ describe('uploads reporting progress', () => {
+ class FakeXMLHttpRequest {
+ static last: FakeXMLHttpRequest
+ upload: { onprogress?: (event: { loaded: number; total: number; lengthComputable: boolean }) => void } = {}
+ onload?: () => void
+ onerror?: () => void
+ onabort?: () => void
+ status = 200
+ statusText = 'OK'
+ responseText = '{"upload_id":"abc"}'
+
+ constructor() {
+ FakeXMLHttpRequest.last = this
+ }
+ open(): void {}
+ setRequestHeader(): void {}
+ getAllResponseHeaders(): string {
+ return 'content-type: application/json'
+ }
+ send(): void {}
+ abort(): void {}
+ }
+
+ const realXMLHttpRequest = window.XMLHttpRequest
+
+ beforeEach(() => {
+ window.XMLHttpRequest = FakeXMLHttpRequest as unknown as typeof XMLHttpRequest
+ })
+
+ afterEach(() => {
+ window.XMLHttpRequest = realXMLHttpRequest
+ })
+
+ it('reports how much of the body has been sent and resolves with the parsed response', async () => {
+ const onUploadProgress = jest.fn()
+ const result = api.dataWarehouseTables.uploadFile(new FormData(), { onUploadProgress })
+
+ const xhr = FakeXMLHttpRequest.last
+ xhr.upload.onprogress?.({ loaded: 512, total: 1024, lengthComputable: true })
+ xhr.onload?.()
+
+ await expect(result).resolves.toEqual({ upload_id: 'abc' })
+ expect(onUploadProgress).toHaveBeenCalledWith({ loaded: 512, total: 1024 })
+ })
+
+ it('reports an unmeasurable body as a null total', async () => {
+ const onUploadProgress = jest.fn()
+ const result = api.dataWarehouseTables.uploadFile(new FormData(), { onUploadProgress })
+
+ const xhr = FakeXMLHttpRequest.last
+ xhr.upload.onprogress?.({ loaded: 512, total: 0, lengthComputable: false })
+ xhr.onload?.()
+ await result
+
+ expect(onUploadProgress).toHaveBeenCalledWith({ loaded: 512, total: null })
+ })
+
+ it('raises the server message on a rejected upload instead of resolving', async () => {
+ const result = api.dataWarehouseTables.uploadFile(new FormData())
+
+ const xhr = FakeXMLHttpRequest.last
+ xhr.status = 400
+ xhr.statusText = 'Bad Request'
+ xhr.responseText = '{"message":"File is too large"}'
+ xhr.onload?.()
+
+ const error = await result.catch((e) => e)
+ expect(error).toBeInstanceOf(ApiError)
+ expect(error.data.message).toBe('File is too large')
+ })
+
+ it('classifies a request that never reached the server as a network failure', async () => {
+ const result = api.dataWarehouseTables.uploadFile(new FormData())
+
+ FakeXMLHttpRequest.last.onerror?.()
+
+ await expect(result).rejects.toBeInstanceOf(NetworkError)
+ })
+ })
+
describe('organizationFeatureFlags', () => {
it('builds correct URL for organization feature flags', () => {
const apiRequest = new ApiRequest()
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 7bbd4d521c8c..47cb7026ce49 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -315,6 +315,16 @@ export interface ApiMethodOptions {
headers?: Record<string, any>
}
+export interface ApiUploadProgress {
+ loaded: number
+ /** Null when the browser can't measure the body, so only `loaded` is meaningful. */
+ total: number | null
+}
+
+export interface ApiUploadOptions extends ApiMethodOptions {
+ onUploadProgress?: (progress: ApiUploadProgress) => void
+}
+
export { ApiError, NetworkError }
export class RateLimitError extends Error {
@@ -5619,10 +5629,15 @@ const api = {
async refreshSchema(tableId: DataWarehouseTable['id']): Promise<void> {
await new ApiRequest().dataWarehouseTable(tableId).withAction('refresh_schema').create()
},
- // FormData, not JSON — the browser sets the multipart boundary itself, so don't add a
- // Content-Type header here (`api.createResponse` already skips it for FormData bodies).
- async uploadFile(data: FormData): Promise<WarehouseTableFileUpload> {
- return await new ApiRequest().dataWarehouseTables().withAction('upload_file').create({ data })
+ // Goes over XHR rather than fetch so the caller can follow how much of a large file has
+ // gone up. FormData, not JSON — the browser sets the multipart boundary itself, so neither
+ // this call nor the transport adds a Content-Type header.
+ async uploadFile(data: FormData, options?: ApiUploadOptions): Promise<WarehouseTableFileUpload> {
+ return await api.createWithUploadProgress(
+ new ApiRequest().dataWarehouseTables().withAction('upload_file').assembleFullUrl(),
+ data,
+ options
+ )
},
async createFromUpload(data: {
upload_id: string
@@ -7149,6 +7164,21 @@ const api = {
)
},
+ /**
+ * POST a body and report how much of it has been sent.
+ *
+ * `fetch` exposes no upload progress at all, so a caller uploading a large file can only show
+ * an indeterminate spinner. This sends over XMLHttpRequest instead and wraps the result in a
+ * `Response`, so the call still goes through the same error, retry, and telemetry path as
+ * every other request.
+ */
+ async createWithUploadProgress<T = any>(url: string, data: FormData, options?: ApiUploadOptions): Promise<T> {
+ url = prepareUrl(url)
+ ensureProjectIdNotInvalid(url)
+ const response = await handleFetch(url, 'POST', () => xhrPost(url, data, options))
+ return await getJSONFromSuccessResponse(response, 'POST', url)
+ },
+
async delete(url: string): Promise<any> {
url = prepareUrl(url)
ensureProjectIdNotInvalid(url)
@@ -7457,6 +7487,59 @@ function captureClientRequestFailure(properties: {
}
}
+// The `Response` constructor rejects a body on these statuses, so they resolve with a null body.
+const NULL_BODY_STATUSES = new Set([204, 205, 304])
+
+function parseXhrHeaders(rawHeaders: string): Headers {
+ const headers = new Headers()
+ for (const line of rawHeaders.trim().split(/[\r\n]+/)) {
+ const separator = line.indexOf(':')
+ if (separator > 0) {
+ headers.append(line.slice(0, separator), line.slice(separator + 1).trim())
+ }
+ }
+ return headers
+}
+
+function xhrPost(url: string, data: FormData, options?: ApiUploadOptions): Promise<Response> {
+ return new Promise<Response>((resolve, reject) => {
+ const xhr = new XMLHttpRequest()
+ xhr.open('POST', url, true)
+ // No Content-Type: the body is always FormData, which carries its own multipart boundary.
+ const headers = {
+ ...objectClean(options?.headers ?? {}),
+ 'X-CSRFToken': getCookie(CSRF_COOKIE_NAME) || '',
+ ...tracingHeaders(),
+ ...oauthAuthHeaders(url),
+ }
+ for (const [name, value] of Object.entries(headers)) {
+ xhr.setRequestHeader(name, value)
+ }
+
+ const onUploadProgress = options?.onUploadProgress
+ if (onUploadProgress) {
+ xhr.upload.onprogress = (event) =>
+ onUploadProgress({ loaded: event.loaded, total: event.lengthComputable ? event.total : null })
+ }
+
+ // `fetch` rejects with a TypeError when the request never reached the server, and aborts
+ // surface as an AbortError. Match both so handleFetch classifies XHR failures the same way.
+ xhr.onerror = () => reject(new TypeError('Failed to fetch'))
+ xhr.onabort = () => reject(new DOMException('The user aborted a request.', 'AbortError'))
+ xhr.onload = () =>
+ resolve(
+ new Response(NULL_BODY_STATUSES.has(xhr.status) ? null : xhr.responseText, {
+ status: xhr.status,
+ statusText: xhr.statusText,
+ headers: parseXhrHeaders(xhr.getAllResponseHeaders()),
+ })
+ )
+
+ options?.signal?.addEventListener('abort', () => xhr.abort())
+ xhr.send(data)
+ })
+}
+
async function handleFetch(
url: string,
method: string,
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/components/FileUploadSourceForm.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/components/FileUploadSourceForm.tsx
index d796ac2c0a51..916543f54094 100644
--- a/products/data_warehouse/frontend/scenes/NewSourceScene/components/FileUploadSourceForm.tsx
+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/components/FileUploadSourceForm.tsx
@@ -1,17 +1,25 @@
import { useActions, useValues } from 'kea'
import { Form } from 'kea-forms'
-import { LemonButton, LemonInput, LemonSelect } from '@posthog/lemon-ui'
+import { LemonButton, LemonInput, LemonSelect, Spinner } from '@posthog/lemon-ui'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonFileInput } from 'lib/lemon-ui/LemonFileInput/LemonFileInput'
+import { LemonProgress } from 'lib/lemon-ui/LemonProgress'
+import { humanizeBytes } from 'lib/utils/numbers'
import { FILE_UPLOAD_ACCEPT, fileUploadSourceLogic } from '../fileUploadSourceLogic'
export function FileUploadSourceForm(): JSX.Element {
- const { fileUpload, isFileUploadSubmitting } = useValues(fileUploadSourceLogic)
+ const { fileUpload, isFileUploadSubmitting, uploadStage, uploadPercent } = useValues(fileUploadSourceLogic)
const { selectFiles, setTableName, setFileFormat } = useActions(fileUploadSourceLogic)
+ const busyReason = !isFileUploadSubmitting
+ ? undefined
+ : uploadStage === 'create_table'
+ ? 'Creating your table'
+ : 'Uploading your file'
+
return (
<Form
formKey="fileUpload"
@@ -32,7 +40,7 @@ export function FileUploadSourceForm(): JSX.Element {
]}
value={value}
onChange={setFileFormat}
- disabledReason={isFileUploadSubmitting ? 'Uploading your file' : undefined}
+ disabledReason={busyReason}
/>
)}
</LemonField>
@@ -44,7 +52,7 @@ export function FileUploadSourceForm(): JSX.Element {
accept={FILE_UPLOAD_ACCEPT[fileUpload.file_format]}
value={value}
onChange={selectFiles}
- disabledReason={isFileUploadSubmitting ? 'Uploading your file' : undefined}
+ disabledReason={busyReason}
/>
)}
</LemonField>
@@ -72,12 +80,26 @@ export function FileUploadSourceForm(): JSX.Element {
</div>
</div>
+ {uploadStage === 'upload' ? (
+ <div className="flex flex-col gap-1" data-attr="file-upload-progress">
+ <LemonProgress percent={uploadPercent} />
+ <div className="text-xs text-secondary">
+ Uploading file: {uploadPercent}% of {humanizeBytes(fileUpload.files[0]?.size ?? null)}
+ </div>
+ </div>
+ ) : uploadStage === 'create_table' ? (
+ <div className="flex items-center gap-2 text-xs text-secondary" data-attr="file-upload-progress">
+ <Spinner />
+ File uploaded. Creating the table.
+ </div>
+ ) : null}
+
<div className="flex justify-end">
<LemonButton
type="primary"
htmlType="submit"
loading={isFileUploadSubmitting}
- disabledReason={isFileUploadSubmitting ? 'Uploading your file' : undefined}
+ disabledReason={busyReason}
data-attr="file-upload-submit"
>
Upload and create table
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/fileUploadSourceLogic.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/fileUploadSourceLogic.tsx
index 71665774d363..1e95fab5dd76 100644
--- a/products/data_warehouse/frontend/scenes/NewSourceScene/fileUploadSourceLogic.tsx
+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/fileUploadSourceLogic.tsx
@@ -1,4 +1,4 @@
-import { MakeLogicType, actions, connect, kea, listeners, path, reducers } from 'kea'
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { router, urlToAction } from 'kea-router'
@@ -41,8 +41,8 @@ const EXTENSION_FORMATS: Record<string, FileUploadFormat> = {
const SPREADSHEET_EXTENSIONS = new Set(['xlsx', 'xls', 'xlsm', 'xlsb', 'ods', 'numbers'])
-/** Which step of the two-request upload failed. */
-type FileUploadStage = 'upload' | 'create_table'
+/** Which of the two requests the submission is on. */
+export type FileUploadStage = 'upload' | 'create_table'
function captureFileUploadFailed(format: FileUploadFormat, stage: FileUploadStage, error: any): void {
posthog.capture('warehouse file upload failed', {
@@ -140,6 +140,9 @@ export interface fileUploadSourceLogicValues {
isFileUploadValid: boolean
showFileUploadErrors: boolean
tableNameEdited: boolean
+ uploadPercent: number
+ uploadStage: FileUploadStage | null
+ uploadedBytes: number
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -180,6 +183,12 @@ export interface fileUploadSourceLogicActions {
setTableName: (tableName: string) => {
tableName: string
}
+ setUploadStage: (stage: FileUploadStage) => {
+ stage: FileUploadStage
+ }
+ setUploadedBytes: (uploadedBytes: number) => {
+ uploadedBytes: number
+ }
submitFileUpload: () => {
value: boolean
}
@@ -201,7 +210,19 @@ export interface fileUploadSourceLogicActions {
}
}
-export type fileUploadSourceLogicType = MakeLogicType<fileUploadSourceLogicValues, fileUploadSourceLogicActions>
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface fileUploadSourceLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ uploadPercent: (uploadedBytes: number, fileUpload: FileUploadForm) => number
+ }
+}
+
+export type fileUploadSourceLogicType = MakeLogicType<
+ fileUploadSourceLogicValues,
+ fileUploadSourceLogicActions,
+ Record<string, any>,
+ fileUploadSourceLogicMeta
+>
export const fileUploadSourceLogic = kea<fileUploadSourceLogicType>([
path(['products', 'dataWarehouse', 'fileUploadSourceLogic']),
@@ -212,10 +233,28 @@ export const fileUploadSourceLogic = kea<fileUploadSourceLogicType>([
selectFiles: (files: File[]) => ({ files }),
setTableName: (tableName: string) => ({ tableName }),
setFileFormat: (fileFormat: FileUploadFormat) => ({ fileFormat }),
+ setUploadStage: (stage: FileUploadStage) => ({ stage }),
+ setUploadedBytes: (uploadedBytes: number) => ({ uploadedBytes }),
}),
reducers({
// Once the user types their own table name we stop overwriting it when they swap the file.
tableNameEdited: [false, { setTableName: () => true }],
+ uploadStage: [
+ null as FileUploadStage | null,
+ {
+ submitFileUploadRequest: () => 'upload',
+ setUploadStage: (_, { stage }) => stage,
+ submitFileUploadSuccess: () => null,
+ submitFileUploadFailure: () => null,
+ },
+ ],
+ uploadedBytes: [
+ 0,
+ {
+ submitFileUploadRequest: () => 0,
+ setUploadedBytes: (_, { uploadedBytes }) => uploadedBytes,
+ },
+ ],
}),
forms(({ actions }) => ({
fileUpload: {
@@ -249,13 +288,16 @@ export const fileUploadSourceLogic = kea<fileUploadSourceLogicType>([
let upload
try {
- upload = await api.dataWarehouseTables.uploadFile(formData)
+ upload = await api.dataWarehouseTables.uploadFile(formData, {
+ onUploadProgress: ({ loaded }) => actions.setUploadedBytes(loaded),
+ })
} catch (e: any) {
captureFileUploadFailed(file_format, 'upload', e)
lemonToast.error(e.data?.message ?? e.message ?? 'Could not upload the file.')
return
}
+ actions.setUploadStage('create_table')
try {
await api.dataWarehouseTables.createFromUpload({
upload_id: upload.upload_id,
@@ -276,6 +318,19 @@ export const fileUploadSourceLogic = kea<fileUploadSourceLogicType>([
},
},
})),
+ selectors({
+ uploadPercent: [
+ (s) => [s.uploadedBytes, s.fileUpload],
+ (uploadedBytes: number, fileUpload: FileUploadForm): number => {
+ const size = fileUpload.files[0]?.size
+ if (!size) {
+ return 0
+ }
+ // Multipart framing makes the sent byte count overshoot the file size at the end.
+ return Math.min(100, Math.round((uploadedBytes / size) * 100))
+ },
+ ],
+ }),
listeners(({ actions, values }) => ({
selectFiles: ({ files }) => {
actions.setFileUploadValue('files', files)