Files
baserow/web-frontend/modules/database/mixins/buttonField.js
alamin-br 2dd4defb3b feat(database): run a button click with external actions as a job (#6164)
* fix: keep every button action card in place after a save

A retyped action can keep its id, and an action created by an earlier
save still carries its client id, so the refetched list must keep the
client id of every buffered action rather than only the created ones.

* feat(jobs): let a job type choose its Celery queue

* test: assert the job enqueue through apply_async

* refactor(database): expose the button click pre-checks on the service

* refactor(database): share the button click payload and outcome mapping

* feat(database): run a button click with external actions as a job

* fix(database): map click races on the job and assert the audit entry

* feat(database): answer a click with external actions with a job

The request returns 202 and the job runs the sequence, so a slow endpoint
holds a Celery worker instead of a WSGI one.

* fix(database): give a capped click its slots back and cover the denied job

* refactor(database): raise a plain exception for a denied click job

* chore: consume the button_dispatch queue on the default worker

* chore: add the button_dispatch queue to the Zed worker launch config

* feat(database): wait on the job of an accepted button click

* fix(database): stop waiting on a button click job after a deadline

* test(e2e): a slow endpoint no longer blocks the grid during a click

* test(e2e): name the second-button test for what a single worker can prove

* test: assert the airtable import job enqueue through apply_async

* chore: changelog for the button dispatch job

* fix(database): keep the clicker's IP and session on a button click job

The audit log and analytics read both from the user, which the job only restores through these mixins.

* fix(database): fail a button click job whose field or table was trashed

* fix(database): serialize the busy check of a click with its job creation

Two racing requests could both see the cell free and each start a job, so a single worker sent every request twice.

Also drops the budget bookkeeping from the inline path, which no longer reaches outside Baserow.

* test: assert a refused dispatch check records no audit entry

* docs: say a button click job shares the default worker with realtime updates

Also adds the automation_workflow and button_dispatch queues to the example supervisor config.

* fix(database): check a button click job once more at the deadline

The job store stops polling before the deadline, so a job that finished unseen was reported as still running.

* test: cover an accepted click in the row modal and on a card

* refactor(database): ask the service whether a cell has a click in flight

The view queried the job table itself; the check belongs beside the
other dispatch rules in the service.

* fix(database): run only the action list a click was accepted with

The request checks and charges one list; the job re-read the field's
current one, so an action added while the job waited ran unchecked and
an added external one sent without a rate-limit slot.

* fix(database): keep queued button clicks sane across crashes, retypes and trash

A dead worker's job no longer blocks its cell until cleanup, a retype no longer deletes a queued job, and a trashed database refuses the click.
Core permission refusals use the API's wording. The cell lock is shared and the unused refund plumbing is gone.

* fix(database): stop a queued button click from sending twice or unchecked

A late or replica-blind click no longer repeats its requests, a retype to external is caught, and a quota refusal answers in the request.
Slots come back when no job row was written, and the stored answer is safe for jsonb.

* fix: keep polling a button click job after one failed poll

A click waits on the job store, which stopped for good after a single failed poll. A settled click's job is dropped so the store stops polling it.

* fix(database): stop a cancelled button click between actions

The owner can cancel a running job, and later actions still ran. The last job check at the deadline is bounded too, so a hung request cannot keep the button spinning.

* test: cover a job's answer reaching Open URL and a click edited while queued

* fix(database): let a click job finish when its button is retyped mid-run

The worker's save wrote the old field id back and failed. Timeouts and unmapped failures no longer name the job type, and a job that is already final leaves the store.

* fix(database): run button click jobs on the export queue

Review feedback: the celery queue is for fast tasks, and a new queue needs every self-hosted worker changed.
Also strips lone surrogates from the stored answer, moves the enqueue rules into the service and drops the unused websocket id.

* fix(database): drop a waiting button click on logout or table switch

A job can end minutes after the click, when its toast or Open URL no longer belongs to the page.

* chore: drop the changelog entry for #6134

The button field has not shipped yet, so there is no fix to announce.

* fix(database): point a click job at the base field

A retype deletes the button row, so a job pointing at it had to be
nulled first, and a click landing meanwhile failed the retype.

* fix(database): keep a button spinning for its job after a reload

The spinner only knew about clicks made in this page, so a reload
dropped it while the job ran and a second click got the 409 toast.

* fix(database): ignore a late job_started for a settled button click

On a single worker the broadcast reaches the clicking tab after the job
ended, and its started copy spun the button again until the next poll.

* docs(database): correct the dispatch signal and e2e comments

The signal's first send for a job click happens before the enqueue lock.
2026-09-28 11:13:42 +02:00

388 lines
14 KiB
JavaScript

import { reactive } from 'vue'
import WorkflowActionService from '@baserow/modules/database/services/workflowAction'
import { notifyIf } from '@baserow/modules/core/utils/error'
import { clone } from '@baserow/modules/core/utils/object'
import {
ButtonFieldDispatchJobDropped,
ButtonFieldDispatchJobType,
DISPATCH_JOB_DEADLINE_MS,
} from '@baserow/modules/database/jobTypes'
import JobService from '@baserow/modules/core/services/job'
// Keyed by field and row rather than kept per component. The grid swaps an
// unselected cell for its own component on the first click, and that remount
// would drop a flag held in `data`, taking the loading state and the double
// click guard with it. The flag also spans a click whose actions run behind
// a job: it stays set while that job is polled to its end.
const dispatchesInFlight = reactive(new Set())
const DISPATCH_OPERATION = 'database.table.field.workflow_action.dispatch'
export { DISPATCH_JOB_DEADLINE_MS }
export const DISPATCH_JOB_LAST_CHECK_MS = 10 * 1000
/**
* Dispatches a cell's actions on click and runs the ones the backend hands
* back. Falls back to the field store where the render context provides no
* `allFieldsInTable` (functional grid cells, cards).
*/
export default {
computed: {
hasWorkflowActions() {
return this.field.has_workflow_actions === true
},
/**
* An action writes to a field or table that is in the trash or gone, so
* the click is sure to fail. Worked out server side, where the trash is.
*/
requiresReconfiguration() {
return this.field.requires_reconfiguration === true
},
/**
* The row select modal's grid is the one place that hands no workspace,
* so there it is found through the field's table. A miss gives `null`,
* which the permission check answers with `false`: a disabled button
* saying the user may not click.
*/
fieldWorkspaceId() {
if (this.workspaceId != null) {
return this.workspaceId
}
const database = this.$store.getters['application/getAll'].find(
(application) =>
application.tables?.some((table) => table.id === this.field.table_id)
)
return database?.workspace?.id ?? null
},
/**
* Whether this user may click at all, which is a lower bar than editing
* the row and a higher one than reading it. The backend refuses the click
* either way, so this only stops the button offering one.
*/
canDispatch() {
return this.$hasPermission(
DISPATCH_OPERATION,
this.field,
this.fieldWorkspaceId
)
},
canClick() {
return this.hasWorkflowActions && this.canDispatch
},
/** A disabled button fires no mouse events, so its wrapper shows this. */
disabledReason() {
return this.hasWorkflowActions && !this.canDispatch
? this.$t('buttonField.noPermission')
: null
},
dispatchKey() {
return `${this.field.id}:${this.row.id}`
},
/**
* Also true for a click's job still running from before a page reload, so
* the button keeps spinning until that job ends.
*/
dispatching() {
return (
dispatchesInFlight.has(this.dispatchKey) ||
this.$store.getters['job/getAll'].some((job) =>
ButtonFieldDispatchJobType.isRunningOn(
job,
this.field.id,
this.row.id
)
)
)
},
},
methods: {
/**
* Runs the field's actions against this row. The backend rejects a
* concurrent click for the same field and row, so the local guard only
* avoids an obvious double fire.
*/
async dispatchWorkflowActions() {
if (dispatchesInFlight.has(this.dispatchKey)) {
return
}
// Captured up front so the release below cannot miss it if the cell is
// handed a different row while the request is in flight.
const key = this.dispatchKey
dispatchesInFlight.add(key)
const newTab = this.openNewTab()
try {
// The dispatch takes its own broadcast, so `this.row` can change
// mid-request. Client actions get the row as it was at click time.
const clickedRow = clone(this.row)
const openTableId = this.$store.getters['table/getSelectedId']
const response = await WorkflowActionService(this.$client).dispatch(
this.field.id,
this.row.id
)
// A click with an action that reaches outside Baserow runs behind
// the request; the job carries the same body once it has run.
const queued = response.status === 202
const outcome = queued
? await this.awaitDispatchJob(response.data)
: response.data
// A job can end minutes later, after the user opened another table.
// An Open URL then would navigate them away from it.
if (
queued &&
this.$store.getters['table/getSelectedId'] !== openTableId
) {
return
}
await this.runClientActions(
outcome?.client_actions || [],
clickedRow,
this.previousActionResults(outcome),
newTab
)
} catch (error) {
if (error instanceof ButtonFieldDispatchJobDropped) {
// Logged out while the job ran: nothing is left to tell.
return
}
// The shared handler stays quiet on a 429, so a refused click would
// otherwise look like a click that did nothing.
if (error.handler?.isTooManyRequests?.()) {
this.$store.dispatch('toast/error', {
title: this.$t('buttonField.rateLimitedTitle'),
message: this.$t('buttonField.rateLimitedMessage'),
})
} else if (error.handler) {
// A handled error already carries its own message. Anything else, a
// network failure for instance, still needs a toast of its own.
notifyIf(error, 'workflowAction')
} else {
this.$store.dispatch('toast/error', {
title: this.$t('buttonField.dispatchErrorTitle'),
message: this.$t('buttonField.dispatchErrorMessage'),
})
}
} finally {
dispatchesInFlight.delete(key)
// Still here when the dispatch failed or no action navigated it.
newTab?.discard()
}
},
/**
* Opens the tab a new tab action will navigate, while the click still
* counts as one. Safari blocks a `window.open` made once the dispatch
* request has returned, and says nothing about it.
*
* @returns {Object|null} `take()` hands the tab to the one action that
* navigates it, `discard()` closes it if none did.
*/
openNewTab() {
if (this.field.opens_new_tab !== true) {
return null
}
// Not `noopener`: that makes `window.open` return null, leaving nothing
// to navigate. Cut the link by hand instead.
let tab = window.open('', '_blank')
if (!tab) {
return null
}
tab.opener = null
return {
take() {
// Closed by the user while the dispatch ran: nothing to navigate.
const taken = tab?.closed ? null : tab
tab = null
return taken
},
discard() {
tab?.close()
tab = null
},
}
},
/**
* Waits for the job store to poll the click's job to its end. A failed
* job is raised the way a failed inline click is, with its own message,
* so the catch above shows it.
*/
async awaitDispatchJob(job) {
const tracked = await this.$store.dispatch('job/create', job)
try {
return await this.settleDispatchJob(tracked)
} finally {
// Settled or given up on either way, so the store stops polling it.
this.$store.dispatch('job/forceDelete', tracked)
}
},
async settleDispatchJob(tracked) {
const waiting = ButtonFieldDispatchJobType.waitFor(tracked)
let deadlineTimer
const deadline = new Promise((resolve, reject) => {
deadlineTimer = setTimeout(async () => {
ButtonFieldDispatchJobType.forget(tracked)
// A poll may have been missed, so the job may have ended unseen.
// Asked once more before giving up on it.
let job = null
try {
// Bounded, so a request that never answers cannot keep the
// button spinning past its deadline.
const { data } = await Promise.race([
JobService(this.$client).get(tracked.id),
new Promise((resolve, reject) =>
setTimeout(
() => reject(new Error('Timed out')),
DISPATCH_JOB_LAST_CHECK_MS
)
),
])
job = data
} catch {
// Treated as still running: the message says as much.
}
if (job?.state === 'finished') {
resolve(job)
} else if (job?.state === 'failed' || job?.state === 'cancelled') {
reject(this.dispatchJobError(job))
} else {
reject(this.dispatchJobStillRunningError())
}
}, DISPATCH_JOB_DEADLINE_MS)
})
try {
return await Promise.race([waiting, deadline])
} catch (failed) {
// The deadline already threw a fully formed error; a rejection from
// `waiting` is the failed job's data and still needs wrapping.
throw failed instanceof Error ? failed : this.dispatchJobError(failed)
} finally {
clearTimeout(deadlineTimer)
}
},
dispatchJobError(failed) {
// A failure the job type did not map carries no error code, and the
// framework's own wording for it, which names the job type.
const message = failed.error_code ? failed.human_readable_error : ''
const error = new Error(message || 'Button click failed')
error.handler = {
notifyIf: () => {
this.$store.dispatch('toast/error', {
title: this.$t('buttonField.dispatchErrorTitle'),
message: message || this.$t('buttonField.dispatchErrorMessage'),
})
},
}
return error
},
/**
* A job that never reached a final state before the deadline. The
* click's actions may still finish server side; this only stops the
* button waiting on them forever.
*/
dispatchJobStillRunningError() {
const error = new Error('Button click job still running')
error.handler = {
notifyIf: () => {
this.$store.dispatch('toast/error', {
title: this.$t('buttonField.stillRunningTitle'),
message: this.$t('buttonField.stillRunningMessage'),
})
},
}
return error
},
/**
* What the server side actions returned, for a client action to reference.
* The result is keyed by field name, so the ids it came with travel with
* it: the browser has no other way to map a `field_<id>` in a formula onto
* a row of a table that is not this one.
*/
previousActionResults(data) {
return Object.fromEntries(
(data?.results || []).map((result) => [
String(result.workflow_action_id),
{
data: result.data,
fieldNames: result.field_names || {},
order: result.order,
position: result.position,
},
])
)
},
/**
* The results of the actions that ran before this one. Client actions run
* last whatever their place in the list, so without this a reference to an
* action ordered after them would resolve here while the dispatch would
* have refused it.
*/
resultsBefore(previousActionResults, workflowAction) {
// Two actions can carry the same `order`, which the dispatch then breaks
// by id, so `position` is what really says which ran first. `order` is
// the fallback for a backend that sends no position.
const byPosition =
workflowAction.position !== undefined &&
workflowAction.position !== null
const place = byPosition ? workflowAction.position : workflowAction.order
if (place === undefined || place === null) {
return previousActionResults
}
return Object.fromEntries(
Object.entries(previousActionResults).filter(([, result]) => {
const resultPlace = byPosition ? result.position : result.order
return resultPlace === undefined || resultPlace === null
? true
: resultPlace < place
})
)
},
/**
* Runs the actions the backend hands back for the browser, in the order it
* returned them. It only sends them when every server side action
* succeeded, so a failed row action never navigates away.
*/
async runClientActions(
clientActions,
row,
previousActionResults = {},
newTab = null
) {
const fields =
this.allFieldsInTable?.length > 0
? this.allFieldsInTable
: this.$store.getters['field/getAll']
for (const workflowAction of clientActions) {
const ran = await this.$registry
.get('databaseWorkflowActionType', workflowAction.type)
.execute({
workflowAction,
applicationContext: {
row,
fields,
previousActionResults: this.resultsBefore(
previousActionResults,
workflowAction
),
newTab,
},
})
// The server cannot tell whether the browser opened the URL, so this
// is the one button event sent from the client.
try {
this.$posthog?.capture('button_field_client_action', {
field_id: this.field.id,
workflow_action_type: workflowAction.type,
ran: ran !== false,
})
} catch {
// Analytics must never stop the actions after this one.
}
// An action that could not run stops the ones after it, the way a
// failed server action stops the sequence. Carrying on would navigate
// away from the message this one just raised.
if (ran === false) {
break
}
}
},
},
}