Files
Davide Silvestri 03ffed6dba refactor: migrate table import to centralized job store with reload restore (#5264)
* feat: add dynamic concurrency limit for file import jobs

Override can_schedule_or_raise() on FileImportJobType to enforce:
- max 1 running import per table (existing table imports)
- max 1 running new-table-creation per database
- global max_count cap

Follows the same pattern as GenerateAIValuesJobType.

* refactor: migrate table import and data sync to centralized job store

Replace the deprecated jobProgress mixin with the job mixin in
ImportFileModal, CreateTable, CreateDataSync, and the shared dataSync
mixin. This enables:

- Restore running jobs after page refresh via loadRunningJob()
- Cancel support via the job mixin's cancelJob()
- Centralized polling through the Vuex job store

Also enriches FileImportJobType with lifecycle callbacks, disables type
selectors during import/sync, and exposes table_id in DataSyncSerializer
for job matching.

* feat: store importer metadata on FileImportJob for UI restore

Add importer_type and original_file_name fields to FileImportJob so the
frontend can show which importer and file were used when restoring a
running job after page reload. Both fields are passed through from the
table create and import API endpoints.

* test: add e2e test for CSV import restore after page reload

Uploads a large CSV, starts the import, reloads the page, reopens the
modal, and verifies the file name and cancel button are visible.

* fix: defensive handling when backend job data is missing new fields (pre-deploy jobs)

* test: verify cancel button stops the running import job

* test: add e2e test for CSV import into existing table restore after reload

* fix: address PR review — filter data sync jobs by database, restore importer type, prevent chooser click during import

* fix: reset importer selection after cancelling an import job

* address copilot feedback; fix tests

* fix: address review — database=table.database, opaque importer_type docs, avoid double goto for Firefox

* fix: stabilize e2e tests for Firefox — wait for job in store, use larger CSV

* feat: add on_cancelled hook and data sync cancellation support

Add on_cancelled lifecycle hook to the job system, invoked after a job
is cancelled. The data sync job type uses it to trash the table when a
first sync is cancelled before completing. Bump max_count to 3 and add
can_schedule_or_raise for per-data-sync concurrency. Frontend gets a
cancel button, optimistic table cleanup, and store lifecycle hooks.
Rework importer metadata migration to use ZDM-safe TextField(null=True).

* address copilot feedback

* address feedback
2026-05-12 17:29:25 +02:00

439 lines
12 KiB
Vue

<template>
<div>
<template v-if="restoredFromStore">
<div class="margin-top-3 margin-bottom-2">
<label v-if="job.name" class="control__label control__label--small">
{{ $t('createTable.importingTable', { name: job.name }) }}
</label>
<div v-if="job.importer_type" class="margin-bottom-1">
<span class="import-modal__restored-badge">
{{ restoredImporterName }}
</span>
<span v-if="job.original_file_name" class="margin-left-1">
{{ job.original_file_name }}
</span>
</div>
</div>
</template>
<template v-else>
<TableForm
ref="tableForm"
class="margin-top-3 margin-bottom-2"
:default-name="getDefaultName()"
@submitted="submitted"
>
<component
:is="importerComponent"
:key="importerKey"
ref="importerRef"
:disabled="importInProgress"
@changed="reset()"
@header="onHeader($event)"
@data="onData($event)"
@get-data="onGetData($event)"
/>
</TableForm>
<SimpleGrid
v-if="dataLoaded"
class="import-modal__preview margin-bottom-2"
:rows="previewFileData"
:fields="fileFields"
/>
</template>
<ImportErrorReport :job="job" :error="error"></ImportErrorReport>
<SimpleGrid
v-if="dataLoaded"
class="import-modal__preview margin-bottom-2"
:rows="previewFileData"
:fields="fileFields"
:field-options="fileFieldOptions"
/>
<div v-if="!hasErrors" class="modal-progress__actions">
<ProgressBar
v-if="(importInProgress || jobIsFinished) && showProgressBar"
:value="progressPercentage"
:status="humanReadableState"
/>
<ButtonText
v-if="jobIsRunning || cancelLoading"
tag="a"
type="secondary"
class="modal-progress__cancel-button"
:loading="cancelLoading"
@click="cancelJob"
>
{{ $t('action.cancel') }}
</ButtonText>
<Button
v-if="!restoredFromStore"
type="primary"
size="large"
full-width
class="modal-progress__primary-button"
:loading="importInProgress || jobIsFinished"
:disabled="importInProgress || jobIsFinished"
@click="$refs.tableForm.submit()"
>
{{ $t('createTable.addButton') }}
</Button>
</div>
<div v-else class="align-right">
<Button
type="primary"
size="large"
:loading="!isTableCreated"
@click="openTable()"
>
{{ $t('createTable.showTable') }}
</Button>
</div>
</div>
</template>
<script>
import error from '@baserow/modules/core/mixins/error'
import job from '@baserow/modules/core/mixins/job'
import TableService from '@baserow/modules/database/services/table'
import {
uuid,
getNextAvailableNameInSequence,
} from '@baserow/modules/core/utils/string'
import SimpleGrid from '@baserow/modules/database/components/view/grid/SimpleGrid'
import TableForm from '@baserow/modules/database/components/table/TableForm'
import { ResponseErrorMessage } from '@baserow/modules/core/plugins/clientHandler'
import ImportErrorReport from '@baserow/modules/database/components/table/ImportErrorReport'
import { FileImportJobType } from '@baserow/modules/database/jobTypes'
import { pageFinished } from '@baserow/modules/core/utils/routing'
import { nextTick, useNuxtApp } from '#imports'
export default {
name: 'CreateTable',
components: { ImportErrorReport, TableForm, SimpleGrid },
mixins: [error, job],
props: {
database: {
type: Object,
required: true,
},
chosenType: {
type: String,
required: true,
},
},
emits: ['hide', 'import-in-progress', 'uploading-before-job-created'],
setup() {
const nuxtApp = useNuxtApp()
return { nuxtApp }
},
data() {
return {
restoredFromStore: false,
uploadProgressPercentage: 0,
importState: null,
showProgressBar: false,
header: [],
mapping: {},
getData: null,
previewData: [],
dataLoaded: false,
importerKey: 0,
}
},
computed: {
restoredImporterName() {
if (!this.job?.importer_type) return ''
try {
return this.$registry.get('importer', this.job.importer_type).getName()
} catch {
return this.job.importer_type
}
},
isTableCreated() {
if (!this.job?.table_id) {
return false
}
return this.database.tables.some(({ id }) => id === this.job.table_id)
},
fileFields() {
return this.header.map((header, index) => ({
type: 'text',
name: header,
id: uuid(),
order: index,
}))
},
fileFieldOptions() {
return Object.fromEntries(
this.fileFields.map((field) => [field.id, { hidden: false }])
)
},
previewFileData() {
return this.previewData.map((row) => {
const newRow = Object.fromEntries(
this.fileFields.map((field, index) => [
`field_${field.id}`,
`${row[index]}`,
])
)
newRow.id = uuid()
return newRow
})
},
/**
* Fields that are mapped to a column
*/
selectedFields() {
return Object.values(this.mapping)
},
progressPercentage() {
switch (this.state) {
case null:
return 0
case 'preparingData':
return 1
case 'uploading':
// 10% -> 50%
return (this.uploadProgressPercentage / 100) * 40 + 10
default:
// 50% -> 100%
return 50 + this.job.progress_percentage / 2
}
},
state() {
if (this.job === null) {
return this.importState
} else {
return this.job.state
}
},
importInProgress() {
return (
this.state !== null &&
!this.jobIsFinished &&
!this.jobHasFailed &&
!this.error.visible
)
},
// True only while uploading the file before the backend job exists.
// Once the job is created the user can close the modal — the running job
// is in the store and will be restored on reopen.
uploadingBeforeJobCreated() {
return this.job === null && this.importInProgress
},
importerComponent() {
if (this.chosenType === '') return null
try {
return this.$registry
.get('importer', this.chosenType)
.getFormComponent()
} catch {
return null
}
},
humanReadableState() {
switch (this.state) {
case null:
return ''
case 'preparingData':
return this.$t('createTable.preparing')
case 'uploading':
if (this.uploadProgressPercentage === 100) {
return this.$t('job.statePending')
} else {
return this.$t('createTable.uploading')
}
default:
return this.jobHumanReadableState
}
},
hasErrors() {
return this.job && Object.keys(this.job.report.failing_rows).length > 0
},
},
watch: {
importInProgress: {
handler(value) {
this.$emit('import-in-progress', value)
},
immediate: true,
},
uploadingBeforeJobCreated: {
handler(value) {
this.$emit('uploading-before-job-created', value)
},
immediate: true,
},
},
mounted() {
this.loadRunningJob()
},
methods: {
hide() {
// Called by CreateTableModal when the modal is hidden.
},
getDefaultName() {
const excludeNames = this.database.tables.map((table) => table.name)
const baseName = this.$t('createTableModal.defaultName')
return getNextAvailableNameInSequence(baseName, excludeNames)
},
reset(full = true) {
this.job = null
this.restoredFromStore = false
this.uploadProgressPercentage = 0
if (full) {
this.header = []
this.importState = null
this.mapping = {}
this.getData = null
this.previewData = []
this.dataLoaded = false
}
this.hideError()
},
onData({ header, previewData }) {
this.header = header
this.previewData = previewData
this.mapping = Object.fromEntries(
header.map((name, index) => {
return [index, 0]
})
)
this.dataLoaded = header.length > 0 || previewData.length > 0
},
onGetData(getData) {
this.getData = getData
},
onHeader(header) {
this.header = header
this.mapping = Object.fromEntries(
header.map((name, index) => {
return [index, 0]
})
)
},
/**
* When the form is submitted we try to extract the initial data and first row
* header setting from the values. An importer could have added those, but they
* need to be removed from the values.
*/
async submitted(formValues) {
this.showProgressBar = false
this.reset(false)
let data = null
const values = { ...formValues }
if (typeof this.getData === 'function') {
try {
this.showProgressBar = true
this.importState = 'preparingData'
await this.$ensureRender()
data = await this.getData()
data = [this.header, ...data]
} catch (error) {
this.reset()
this.handleError(error, 'application')
}
}
this.importState = 'uploading'
values.importer_type = this.chosenType
values.original_file_name = this.$refs.importerRef?.values?.filename || ''
const onUploadProgress = ({ loaded, total }) =>
(this.uploadProgressPercentage = (loaded / total) * 100)
try {
if (data && data.length > 0) {
this.showProgressBar = true
}
const { data: job } = await TableService(this.$client).create(
this.database.id,
values,
data,
true,
{
onUploadProgress,
}
)
await this.createAndMonitorJob(job)
} catch (error) {
this.handleError(error, 'application', {
ERROR_MAX_JOB_COUNT_EXCEEDED: new ResponseErrorMessage(
this.$t('job.errorJobAlreadyRunningTitle'),
this.$t('job.errorJobAlreadyRunningDescription')
),
})
}
},
getCustomHumanReadableJobState(jobState) {
const translations = {
'row-import-creation': this.$t('createTable.stateRowCreation'),
'row-import-validation': this.$t('createTable.statePreValidation'),
'import-create-table': this.$t('createTable.stateCreateTable'),
}
return translations[jobState]
},
async openTable() {
await this.$router.push({
name: 'database-table',
params: {
databaseId: this.database.id,
tableId: this.job.table_id,
},
})
await pageFinished(this.nuxtApp)
await nextTick()
this.$emit('hide')
},
async onJobFinished() {
// Let's add the table to the store...
const { data: table } = await TableService(this.$client).get(
this.job.table_id
)
await this.$store.dispatch('table/forceUpsert', {
database: this.database,
data: table,
})
if (!this.hasErrors) {
await this.openTable()
}
},
onJobFailed() {
this.showError(
new ResponseErrorMessage(
this.$t('createTable.importError'),
this.job.human_readable_error
)
)
},
onJobCancelled() {
this.reset()
// Force to recreate the importer component for a new import
this.importerKey++
},
loadRunningJob() {
const runningJob = this.$store.getters['job/getUnfinishedJobs'].find(
(j) =>
j.type === FileImportJobType.getType() &&
j.table_id === null &&
j.database_id === this.database.id
)
if (runningJob) {
this.job = runningJob
this.restoredFromStore = true
this.showProgressBar = true
}
},
},
}
</script>