Run Deck as the workflow owner, and drop the job interval
Build package / php-lint (8.2) (push) Successful in 49s
Build package / php-lint (8.3) (push) Successful in 42s
Build package / php-lint (8.4) (push) Successful in 37s
Build package / xml-lint (push) Successful in 13s
Build package / unit-tests (push) Successful in 44s
Build package / package (push) Successful in 59s
Build package / php-lint (8.2) (push) Successful in 49s
Build package / php-lint (8.3) (push) Successful in 42s
Build package / php-lint (8.4) (push) Successful in 37s
Build package / xml-lint (push) Successful in 13s
Build package / unit-tests (push) Successful in 44s
Build package / package (push) Successful in 59s
Workflows were being switched off with "its board no longer exists or is
no longer available to you" for boards that were perfectly intact.
Deck does not read the session for permissions. PermissionService -- the
class behind every check, including the ones inside CardService::reorder()
-- takes the current user as a plain `private ?string $userId`, filled
from the app container's `userId` service (ISession::get('user_id'),
registered shared). Pimple resolves that once per process and caches it,
and ServerContainer caches Deck's app container just as long. In cron the
value is null whenever a Deck-owned job ran earlier in the same pass, and
otherwise the first workflow owner touched -- never the user being
impersonated. null fails every check, so Deck answered NoPermissionException
for an untouched board and findStackIds() read that as "the board is gone".
IUserSession::setUser() never had any effect on this path.
- DeckIntegrationService::beginUserContext()/endUserContext() pin
PermissionService (mandatory), CardService, BoardService and
ActivityManager (best effort) to the workflow owner, and restore them
afterwards. If PermissionService cannot be pinned, the runner skips that
user instead of acting under someone else's permissions.
- findStackIds() now takes the uid as an argument and is assembled from
pieces that cannot answer for the wrong user: BoardMapper and StackMapper
carry no user state, and getPermissions() is handed the uid explicitly.
It no longer goes through StackService::findAll().
- NoPermissionException is no longer treated as "board missing". Unknown
failures throw, which leaves the workflow enabled.
This also fixes the second half of the same defect: card moves silently
failed for every user except the first one processed in a cron pass.
Separately, RunWorkflowsJob is now a plain Job instead of a TimedJob and
runs on every cron pass. The workflow_deck_automation.interval config key
is gone. Time sensitivity is no longer merely declared but structurally
unreachable: JobList::add() leaves the column at its TIME_SENSITIVE
default, and the ratchet in setLastRun() only fires for TimedJob.
This commit is contained in:
@@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
|
||||
|
||||
## What this is
|
||||
|
||||
A Nextcloud app (`workflow_deck_automation`, namespace `WorkflowDeckAutomation`) targeting **Nextcloud Hub 26 Spring (server 34.x)**. It lets each user configure, from their personal settings, automation "workflows" that move overdue [Deck](https://github.com/nextcloud/deck) cards from one stack to another, with optional assigned-user/label filters and an email notification. A background `TimedJob` evaluates all enabled workflows every 5 minutes.
|
||||
A Nextcloud app (`workflow_deck_automation`, namespace `WorkflowDeckAutomation`) targeting **Nextcloud Hub 26 Spring (server 34.x)**. It lets each user configure, from their personal settings, automation "workflows" that move overdue [Deck](https://github.com/nextcloud/deck) cards from one stack to another, with optional assigned-user/label filters and an email notification. A background `Job` evaluates all enabled workflows on every cron pass.
|
||||
|
||||
## Non-negotiable architectural constraint
|
||||
|
||||
@@ -14,28 +14,39 @@ All Deck access is funneled through `lib/Service/DeckIntegrationService.php` —
|
||||
|
||||
## Per-user impersonation in the background job
|
||||
|
||||
Deck's ACL/permission checks read the *live* `IUserSession`, not a value frozen at construction. `RunWorkflowsJob` (a `TimedJob`) has no logged-in user by default and must evaluate workflows belonging to many different users within one PHP process. `lib/Service/WorkflowRunner.php` therefore groups workflows by owner and, per owner, temporarily impersonates them (`IUserSession::setUser()`, restored in a `finally`) before touching Deck. Don't remove this — without it, Deck's permission checks inside the cron run would be evaluated against no user (or the wrong user).
|
||||
`RunWorkflowsJob` has no logged-in user by default and must evaluate workflows belonging to many different users within one PHP process. `lib/Service/WorkflowRunner.php` therefore groups workflows by owner and impersonates each owner in turn. **Impersonation here is two steps, and `IUserSession::setUser()` is the one that barely matters:**
|
||||
|
||||
1. `IUserSession::setUser()` — for the handful of Nextcloud services that do read the live session, plus `IRootFolder::getUserFolder()` for Deck helpers that expect an initialised user FS.
|
||||
2. `DeckIntegrationService::beginUserContext()` — pins **Deck itself** to that user. This is the load-bearing half.
|
||||
|
||||
Both are undone in a `finally` (`WorkflowRunner::clearImpersonation()`).
|
||||
|
||||
**Deck does not read the session for permissions. At all.** `PermissionService` — the class behind every permission check, including the ones inside `CardService::reorder()` — takes the current user as `private ?string $userId`, and so do `CardService`, `BoardService` and `ActivityManager`. That string comes from the app container's `userId` service, which is `ISession::get('user_id')` registered via `registerService()`, i.e. **shared**: Pimple resolves it once and caches it for the whole process, and `ServerContainer` caches Deck's app container just as long. Whoever was active when Deck's container first built `PermissionService` is who every later check is evaluated against.
|
||||
|
||||
In cron that is *never* the user being impersonated: `null` if any Deck-owned background job ran earlier in the same `cron.php` pass, otherwise the first workflow owner touched. `null` fails every check, so Deck answers `NoPermissionException` for perfectly intact boards. This produced a real bug — see the next section. `beginUserContext()` therefore swaps that private field directly (there is no API), records the old value, and `endUserContext()` puts it back. `PermissionService` is mandatory: if it can't be pinned, `beginUserContext()` throws and the runner **skips that user entirely** rather than acting under someone else's permissions. The other three are best-effort (they only affect activity attribution and unread counts).
|
||||
|
||||
Consequence for `getUserBoards()`: `listBoardsForCurrentUser()` stays **request-only** anyway — Deck may already have cached board lists behind that field, and the job has no use for a board *list*; it asks `findStackIds()` about one known board id. Before using any other `OCA\Deck\*` service from the runner, check whether it carries a frozen `$userId` — the failure mode is silent and user-crossing, not an error.
|
||||
|
||||
The filter-matching logic (`WorkflowRunner::cardMatchesFilters()`, `::isOverdue()`) is deliberately `static` and side-effect-free so it's unit-testable without a real Deck installation — see `tests/Unit/Service/WorkflowRunnerFilterTest.php`.
|
||||
|
||||
**Not everything in Deck reads the live session, though.** `BoardService` takes the current user as `private ?string $userId` — a plain string frozen when the container builds it. `getUserBoards()` uses exactly that, so in the background job (one process, many users, a container-cached `BoardService`) it answers for whoever happened to be impersonated at first resolution, or for `null`. `listBoardsForCurrentUser()` is therefore **request-only**; the job asks `findStackIds()` instead, which goes through `StackService::findAll()` → `PermissionService` → live session. Before using any other `OCA\Deck\*` service from the runner, check which of the two kinds it is — the failure mode is silent and user-crossing, not an error.
|
||||
|
||||
## Workflows are auto-disabled when their Deck targets vanish
|
||||
|
||||
`WorkflowRunner::findBrokenTarget()` checks board and stacks before every run and, if something is gone, switches the workflow off (`enabled = false`) and sends a one-off mail. Two invariants hold this together and must survive refactors:
|
||||
|
||||
- **Only positive knowledge disables.** `DeckIntegrationService::findStackIds()` returns `null` only for "board missing/not readable" (`DoesNotExistException`, Deck's `NoPermissionException`/`NotFoundException`) and *throws* for everything else. The runner skips the workflow on a throw. If you make that method degrade to `[]`/`null` on generic errors, a Deck outage will disable every workflow on the instance and mail every user about it.
|
||||
- **Only positive knowledge disables.** `DeckIntegrationService::findStackIds()` returns `null` only for "board row gone" (`DoesNotExistException`, Deck's `NotFoundException`), "board in the trash" (`deleted_at > 0`), or "this uid has no read permission" — and *throws* for everything else. The runner skips the workflow on a throw. If you make that method degrade to `[]`/`null` on generic errors, a Deck outage will disable every workflow on the instance and mail every user about it.
|
||||
- **`findStackIds()` must never ask a Deck service to figure out *who* is asking.** It takes the uid as an argument and is assembled from pieces that cannot answer for the wrong user: `BoardMapper`/`StackMapper` are plain QBMappers with no user state, and `PermissionService::getPermissions($boardId, $userId)` is handed the uid explicitly instead of falling back to the frozen field. Do not "simplify" it back to a single `StackService::findAll($boardId)` — that is precisely what broke. `StackService::findAll()` runs `checkPermission()` with no uid, which falls through to the construction-time `$userId`; with that frozen to `null` in cron, Deck threw `NoPermissionException` for an untouched board, the old code read that as "board is gone", and users got "your workflow was deactivated" mails for boards sitting right in front of them. This layer stays correct even if `beginUserContext()` silently degrades.
|
||||
- **`NoPermissionException` is not evidence of anything.** It is deliberately *not* in `isMissing()`. Deck raises it for every failed check regardless of cause.
|
||||
- **The mail ignores the `notifyEmail` flag** — that flag is about moved cards; this is a notice that the user's configuration stopped working. It stays a one-off simply because a disabled workflow is not picked up by `findAllEnabled()` again.
|
||||
|
||||
Archived boards deliberately do *not* trigger this (they stay readable, so `findStackIds()` succeeds), even though they're filtered out of the settings dropdowns.
|
||||
|
||||
## Job interval comes from config.php
|
||||
## The job has no interval — one run per cron pass
|
||||
|
||||
`RunWorkflowsJob` reads `workflow_deck_automation.interval` (seconds, default 300, clamped to a 60s minimum) via `IConfig::getSystemValueInt()` in its constructor. That works *because* `TimedJob` re-reads `$this->interval` on every cron pass from the freshly constructed job — so editing `config.php` takes effect immediately, with no `occ` command and no re-registration. Don't move this into `appinfo/info.xml` or a stored app config; the constants (`INTERVAL_CONFIG_KEY`, `DEFAULT_INTERVAL`, `MINIMUM_INTERVAL`) on the job are the single source of truth and are referenced from the README.
|
||||
`RunWorkflowsJob` extends `OCP\BackgroundJob\Job`, **not** `TimedJob`, so it runs every time cron picks it up. There is no interval and no knob: the cadence *is* the instance's cron cadence. Don't reintroduce one — an earlier version read `workflow_deck_automation.interval` from `config.php` (default 300, 60s floor), and that config key is gone as of v0.2.0. `TimedJob` with `setInterval(0)` would behave nearly identically but keeps an interval concept nothing uses.
|
||||
|
||||
**The job must stay `IJob::TIME_SENSITIVE`.** It was `TIME_INSENSITIVE` at first, which looked harmless and was not: `OC\Core\Service\CronService::runCli()` reads `maintenance_window_start` (default `100`, i.e. unset) and, whenever the current UTC hour is outside `[start, start+4]`, calls `jobList->getNext($onlyTimeSensitive = true)` — time-insensitive jobs are then skipped for the other 20 hours of the day. On an instance with a maintenance window configured (Nextcloud's admin overview nags admins into setting one) the job simply never ran, showing `last_run = 1970-01-01` in `occ background-job:list` indefinitely. Note this gate only exists in `runCli()`, so it doesn't apply to ajax/webcron mode, and passing job classes explicitly (`occ background-job:worker '<class>'`) bypasses it — which is exactly why manual testing can look fine while cron does nothing.
|
||||
**Time sensitivity is what actually decides whether the job runs at all.** `OC\Core\Service\CronService::runCli()` reads `maintenance_window_start` (default `100`, i.e. unset) and, whenever the current UTC hour is outside `[start, start+4]`, calls `jobList->getNext($onlyTimeSensitive = true)` — time-insensitive jobs are then skipped for the other 20 hours of the day. This app shipped `TIME_INSENSITIVE` once: on an instance with a maintenance window configured (Nextcloud's admin overview nags admins into setting one) the job simply never ran, showing `last_run = 1970-01-01` in `occ background-job:list` indefinitely. Note this gate only exists in `runCli()`, so it doesn't apply to ajax/webcron mode, and passing job classes explicitly (`occ background-job:worker '<class>'`) bypasses it — which is exactly why manual testing can look fine while cron does nothing.
|
||||
|
||||
**Changing the sensitivity in code does not fix an already-registered job.** `getNext()` filters on the `time_sensitive` *column* of `oc_jobs`, and `JobList::setLastRun()` is a one-way ratchet:
|
||||
Being a plain `Job` makes that unreachable rather than merely declared. `getNext()` filters on the `time_sensitive` *column* of `oc_jobs`; `JobList::add()` doesn't write the column at all (it takes the `TIME_SENSITIVE` default), and the only place that ever lowers it is a one-way ratchet in `JobList::setLastRun()`:
|
||||
|
||||
```php
|
||||
if ($job instanceof TimedJob && !$job->isTimeSensitive()) {
|
||||
@@ -43,7 +54,9 @@ if ($job instanceof TimedJob && !$job->isTimeSensitive()) {
|
||||
}
|
||||
```
|
||||
|
||||
There is no `else`. Once a job has run while declaring itself insensitive, the row is stamped `TIME_INSENSITIVE` for good — and nothing resets it: `JobList::add()` only writes the column in its *insert* branch, and re-registering an existing job (app update, `app:enable`) takes the *update* branch, which leaves it alone. So after deploying the `TIME_SENSITIVE` change, an existing instance still needs its row fixed once:
|
||||
There is no `else`, and a non-`TimedJob` never enters it. Note `setTimeSensitivity()`/`isTimeSensitive()` live on `TimedJob`, not on `Job` — so there is nothing to declare here, and nothing that can go wrong.
|
||||
|
||||
**Rows written by an older version keep their stamp.** Once stamped `TIME_INSENSITIVE` it stays that way: re-registering an existing job (app update, `app:enable`) takes `add()`'s update branch, which leaves the column alone. An instance that ran the pre-v0.1.0-fix build still needs its row fixed once:
|
||||
|
||||
```sql
|
||||
UPDATE oc_jobs SET time_sensitive = 0
|
||||
@@ -52,7 +65,7 @@ UPDATE oc_jobs SET time_sensitive = 0
|
||||
|
||||
or, without DB access, `occ background-job:delete <id>` followed by `occ app:disable workflow_deck_automation && occ app:enable workflow_deck_automation` to get a freshly inserted row. Fresh installs are unaffected.
|
||||
|
||||
To debug this job on a server: `occ background-job:list --class '<class>'` for its id and last run, then `occ background-job:execute <id> --force-execute` to run it right now regardless of the interval. `occ background-job:worker` takes **job classes**, not an app id.
|
||||
To debug this job on a server: `occ background-job:list --class '<class>'` for its id and last run, then `occ background-job:execute <id> --force-execute` to run it right now without waiting for cron. `occ background-job:worker` takes **job classes**, not an app id.
|
||||
|
||||
## Registration is declarative, not Bootstrap-based
|
||||
|
||||
@@ -116,7 +129,7 @@ This replaced an earlier hand-made `RELEASE_TOKEN` repo secret. If the publish s
|
||||
|
||||
- **UI**: `src/PersonalSettings.vue` (Vue 3, mounted from `templates/settings/personal.php` into the section registered by `lib/Settings/PersonalSection.php` + `lib/Settings/Personal.php`) talks to `lib/Controller/WorkflowController.php` (an `OCSController`) via `src/api.js`, hitting OCS routes declared in `appinfo/routes.php` (`/ocs/v2.php/apps/workflow_deck_automation/api/v1/...`).
|
||||
- **Storage**: `lib/Db/Workflow.php` (Entity) / `lib/Db/WorkflowMapper.php` (QBMapper) over the `wfda_workflows` table, created in `lib/Migration/Version1000Date20260813120000.php`. Filter fields (`filter_user_ids`, `filter_label_ids`) are stored as JSON-encoded arrays in text columns, not join tables.
|
||||
- **Automation**: `lib/BackgroundJob/RunWorkflowsJob.php` (5 min `TimedJob`) → `lib/Service/WorkflowRunner.php` (per-user impersonation + filtering, both filters OR-within-themselves and AND-between-each-other) → `lib/Service/DeckIntegrationService.php` (all actual Deck class calls) and `lib/Service/NotificationMailer.php` (email via `OCP\Mail\IMailer` to the workflow owner's account address, never a manually-entered address).
|
||||
- **Automation**: `lib/BackgroundJob/RunWorkflowsJob.php` (plain `Job`, one run per cron pass) → `lib/Service/WorkflowRunner.php` (per-user impersonation + filtering, both filters OR-within-themselves and AND-between-each-other) → `lib/Service/DeckIntegrationService.php` (all actual Deck class calls) and `lib/Service/NotificationMailer.php` (email via `OCP\Mail\IMailer` to the workflow owner's account address, never a manually-entered address).
|
||||
- Both the controller's board/stack/label/participant lookups (for populating the settings UI dropdowns) and the runner's card reads/moves go through the same `DeckIntegrationService` — there is no separate read path.
|
||||
|
||||
## Composer/npm lockfiles are intentionally not committed
|
||||
|
||||
Reference in New Issue
Block a user