Record a swap of the active site as one act of two requests, and start the wait only when a change succeeds
A lifecycle request now covers exactly one instance. A swap of a
member's active FedWiki site records two requests, one for each site,
and groups them in one act whose cause is instances_swapped. The
member's request makes the chosen site active, and the console's request
makes the other site read-only. The console's request names no person.
Only core.record_lifecycle_act writes the link between a request and its
act, and it links only requests its own transaction inserted.
core_writer's table-wide INSERT and UPDATE on core.lifecycle_requests
become grants on the columns the request writers name. The act only ties
the requests together: the console undoes the others itself when one
fails, and a connector applies each request on its own. The two
swap_park_site_id and swap_activate_site_id parameters are gone. The
notices, dismissal and boot settle now find a swap through its act. A
failed swap shows one notice, and dismissing it dismisses both requests.
When a swap is declined because its parked site was deleted, the notice
names the parked site. Settle finishes an act's requests together.
A swap and a return (Keep active on a site a downgrade or an earlier swap
made read-only) both change which site is active. Each takes the
workspace lock at intake. Each is refused with "A change to your active
site is already in progress" while another change of that workspace's
active site is open, whether or not the wait between changes is
configured. A repeat click, or a stale tab posting a stored address, is
answered from the stored request before anything is recorded.
The wait between changes of the active site now starts when a change
succeeds, in the worker step that records the success. Intake no longer
starts it. A change that is declined, fails or never starts leaves the
wait as it was. Before this, such a change locked the member out for the
whole window.
The farm sync keeps a site's downgrade mark only on a row it writes
read-only. Restore of an archived site never counts as a change of the
active site, and the sites card shows Restore on every archived row. A
Restore posted for a row that is no longer archived answers "This site
changed since the list loaded."
Deploy notes. Every step runs against the console database.
1. Before stopping the old release, count the open swaps and the open
returns, read-only (console_reader can run it):
SELECT 'swap' AS kind, count(*) FROM core.lifecycle_requests lr
WHERE lr.status = 'accepted'
AND (lr.workflow_id LIKE 'swap-fedwiki-site-%'
OR lr.parameters ?| ARRAY['swap_park_site_id','swap_activate_site_id'])
UNION ALL
SELECT 'return', count(*) FROM core.lifecycle_requests lr
JOIN fedwiki.sites s ON s.site_id = lr.instance_id
WHERE lr.status = 'accepted' AND lr.operation = 'set_status'
AND lr.parameters->>'status' = 'active'
AND s.force_reduced_at IS NOT NULL
AND lr.workflow_id NOT LIKE 'swap-fedwiki-site-%';
Deploy only when both counts are 0. Then count the marked rows that
are not read-only:
SELECT count(*) FROM fedwiki.sites
WHERE force_reduced_at IS NOT NULL AND status <> 'readonly';
2. Stop every process of the old release. Migration 00040's change of
lock keys needs this step too, if the deployment has not run it yet.
3. Run both counts again, because the old release may have written more
rows before it stopped. In the stop window, as the runtime user, clear
the marks the second count finds:
UPDATE fedwiki.sites SET force_reduced_at = NULL
WHERE force_reduced_at IS NOT NULL AND status <> 'readonly';
4. List the stored parked-site requests that ended declined or failed and
are not dismissed. Then acknowledge them as the runtime user:
SELECT request_id, workspace_id, instance_id, status, reason_code, finished_at
FROM core.lifecycle_requests
WHERE parameters ? 'swap_activate_site_id'
AND status IN ('declined','failed') AND acknowledged_at IS NULL
ORDER BY finished_at;
UPDATE core.lifecycle_requests SET acknowledged_at = NOW()
WHERE parameters ? 'swap_activate_site_id'
AND status IN ('declined','failed') AND acknowledged_at IS NULL;
5. Migrate to 00041 and start the new release.
6. Once every change counted in step 3 has finished, run step 4's
listing again and acknowledge what it finds. A stored swap whose farm
cannot answer keeps retrying, so its parked request can end long after
the start. If a swap counted in step 3 fails, its workspace keeps the
wait the old intake started. Delete that workspace's
fedwiki.site_swap_policy row by hand to let the member change the
active site at once. The delete also erases any earlier wait.
7. Run scripts/db-reader-role.sql again. Until it runs, console_reader
cannot read the three new columns.
Rollback is the previous image on the 00041 schema, once no lifecycle
request is open. Under it, a failed or declined swap recorded by the new
release shows two notices that dismissal does not pair. A new swap
declined because its parked site was deleted reads "<chosen> was
deleted.", which names a site that still exists. After a rollback,
acknowledge two kinds of row by hand, in both cases while
acknowledged_at is NULL:
- rows with act_role = 'consequent' that ended declined or failed;
- rows with act_role = 'asked' and reason_code = 'site_missing' whose own
fedwiki.sites row still exists.
Rolling forward again repeats every step. The migration's Down refuses
once a lifecycle act exists.
Closes #184. Closes #328. Closes #329.
This commit is contained in:
@@ -595,6 +595,23 @@ Use this decision rule when designing a new integration's mutating verbs:
|
||||
FedWiki does: the handler then answers when the workflow starts, and a
|
||||
repeated submission is answered from the request's record.
|
||||
|
||||
A request covers one instance. An action that changes several instances
|
||||
(FedWiki's swap of a workspace's active site changes two) records one
|
||||
request per instance in one transaction, and groups them with
|
||||
`RecordLifecycleAct`, called in that transaction after the inserts, which
|
||||
names the act's `asked` request and its `consequent` requests. The act ties
|
||||
the requests together and nothing more, so a connector applies each request
|
||||
on its own. When the workflow start is refused as not found, delete the
|
||||
requests with `DeleteUnstartedLifecycleAct`, not one by one, so a retry is a
|
||||
fresh recording. When one request of the action fails, the console undoes
|
||||
a request that succeeded; the act does not do it.
|
||||
|
||||
A new lifecycle cause is provider-neutral. One core migration adds it to
|
||||
`chk_acts_cause` and to `chk_lifecycle_requests_act_cause`, with its own
|
||||
branch in `core.record_lifecycle_act` that holds the cause's rules for its
|
||||
requests, and its constant joins `acts.LifecycleCauses`. The test that
|
||||
compares the Go lists with the constraints fails when one side is missing.
|
||||
|
||||
Forcing every integration onto one shape buys uniformity at the cost of the
|
||||
worse fit for whichever shape doesn't match: pure-Temporal dispatch for
|
||||
Stripe's shape would mean either a dual-write window patched by
|
||||
|
||||
+45
-18
@@ -29,7 +29,7 @@ creators lock exactly one site `FOR SHARE` (see Registry below).
|
||||
| Subscription | `hashtextextended('stripe-subscription:<Stripe subscription id>', 0)` | exclusive | `fulfillment.ReconcileSubscription` | Two reconciles of one subscription (the checkout return and a webhook), so they converge instead of racing the exclusion constraint on subscription periods. |
|
||||
| Invoice | `hashtextextended('stripe-invoice:<Stripe invoice id>', 0)` | exclusive | `invoiceReconcile.converge` in `internal/integrations/stripe/workflows` | Two reconciles of one invoice (two events, or an event and the sweep), so the second finds what the first wrote. |
|
||||
| Product sync | `hashtextextended('stripe-product-sync:<product id>', 0)` | exclusive | `catalogsync.Sync` in `internal/integrations/stripe/catalogsync` | Two sync clicks for one product, so the mapping writes and the outbox enqueue happen once. |
|
||||
| FedWiki workspace | `hashtextextended('fedwiki-workspace:<workspace id>', 0)` | exclusive | `withWorkspaceTx` in `internal/integrations/fedwiki/web`, for the status-change and swap handlers | One workspace's rotations of its active site, so two tabs cannot interleave the cooldown check and stamp or the choice of the site to park. |
|
||||
| FedWiki workspace | `hashtextextended('fedwiki-workspace:<workspace id>', 0)` | exclusive | `withWorkspaceTx` in `internal/integrations/fedwiki/web`, for the swap handler and for a status change that is a rotation | One workspace's rotations of its active site (a swap, and a return of a downgrade-parked site), so two tabs cannot interleave the open-rotation check, the cooldown read or the choice of the site to park. |
|
||||
| Lifecycle instance | `hashtextextended('lifecycle:<instance id>', 0)` | exclusive | `db.Lock` on the lifecycle family, run by `integration.RecordLifecycleRequestInTx` and `RecordFirstLifecycleRequestInTx`, FedWiki's `RecordSiteRequestInTx` and `CheckSwapRequestSites`, `usage.Hold`, and the activity helpers `finishAllWith` and `purgeArchivedSite` | One instance's requests: the latest-generation check and the insert are one step, and an outcome is recorded against a request that is still accepted; and retention's check that no request is open, held through its farm delete and local deletion. |
|
||||
| Desired-state address | `hashtextextended('desired-state:<connection id>:<recipient kind>:<recipient id>', 0)` | exclusive | `lockAddress` in `internal/workflows/desiredstate` | Every write to the content or generation of the record at one (connection, recipient) address, and to its projection, including an address that has no record yet. |
|
||||
| Domains registry | `hashtextextended('domains-registry:', 0)` | exclusive | `registryKind`, the kind of `domains.Registry.WithLock` | Every mutating allocation in the registry, one lock for the whole namespace, because the disjointness rules span rows no database constraint can compare. |
|
||||
@@ -51,8 +51,9 @@ flag-only writes change neither claims nor allocation counts.
|
||||
| Org type row | `core.org_types` row of one type | `FOR NO KEY UPDATE` | the `LockOrgType` query, run by the default change's T0 | The T0 against the demonstration seed and an edit of the type's other columns, which write the row without the rendezvous. Every other writer of the default already waits on the exclusive rendezvous. `FOR NO KEY UPDATE` does not conflict with the `FOR KEY SHARE` an organization insert takes on its type's row. |
|
||||
| Plan ladder rows | every `core.plan_ladders` row | `FOR NO KEY UPDATE`, ascending `plan_ladder_id` | the `LockPlanLadderOrder` query, run by the topology reorder (`ReorderPlanLadders`) first in its transaction | Two reorders, so the later one waits and writes against the order the earlier committed. It does not conflict with the `FOR KEY SHARE` a tier, a position or an org type's default takes through its foreign key. |
|
||||
| Grant lineage head | the `core.grants` row no other grant extends | `FOR UPDATE OF g` | the `GetGrantLineageHeadForUpdate` query, run by `RevokeGrantTx`, `ExtendWaitingGrantTx` and `ManageGrantTx` | Acts on one lineage, so an extension that committed while another act waited is visible to it. |
|
||||
| FedWiki swap policy row | `fedwiki.site_swap_policy` row of one workspace | upsert (the row lock of the `INSERT ... ON CONFLICT DO UPDATE`) | the `UpsertSiteSwapPolicy` query, run by `RecordSwapActivity` and `RecordSiteStatusActivity` in the success transaction of a rotation, after the site and placement rows and before the usage row; intake reads the row without a lock (`GetSiteSwapPolicy`), under the workspace lock | Two success transactions of one workspace's rotations stamping the cooldown, so the later stamp waits for the earlier commit. Nothing at intake writes the row. |
|
||||
| Usage row | `core.numeric_entitlement_usage` row of one (pool, resource key) | `FOR UPDATE` | the `LockNumericUsage` query, run by `usage.Recount` and by the slot gate, after the site rows the transaction writes and before the request rows it finishes (the hold rows have no place in the order, see rule 5); the count is a statement of its own after the lock | Two recounts of one pool, so each count reads every change committed before its lock was granted; two slot gates for one pool, so the second counts the first's hold and two creates cannot both take the last slot. |
|
||||
| FedWiki site row | `fedwiki.sites` row of one domain or one site id | `FOR UPDATE`; `FOR SHARE` by `GetSiteForPlacement` | the `LockSiteStatusByDomain` query, run by `sweepLocally` and the sync's status write (`writeStatus`), and the `LockSiteStatusByID` query, run by the slot gate and by `RecordSiteStatusActivity` and `RecordSwapActivity` (which check the recorded workspace and domain under it), and `LockArchivedSiteForPurge`, run by retention; `GetSiteForPlacement`, run by `reconcileSite` and `syncPlacement` inside `Registry.WithLock` immediately before the first claim or placement write | Paths that move one site (a member's request, the downgrade sweep and the farm sync), so each writes the status it finds under the lock and the recount that follows counts the row as it ended; the sync's reading of the site's requests, which therefore reflects every request that committed before the lock was granted; the gate's reading of an activation whose row the sweep already made active; retention's eligibility check through deletion; and a status write or deletion against creation of that site's placement, so the writer's trigger sees the placement. |
|
||||
| FedWiki site row | `fedwiki.sites` row of one domain or one site id | `FOR UPDATE`; `FOR SHARE` by `GetSiteForPlacement` | the `LockSiteStatusByDomain` query, run by `sweepLocally` and the sync's status write (`writeStatus`), and the `LockSiteStatusByID` query, run by the slot gate, by a return's intake in the handler, and by `RecordSiteStatusActivity` and `RecordSwapActivity` (which check the recorded workspace and domain under it), and `LockArchivedSiteForPurge`, run by retention; `GetSiteForPlacement`, run by `reconcileSite` and `syncPlacement` inside `Registry.WithLock` immediately before the first claim or placement write | Paths that move one site (a member's request, the downgrade sweep and the farm sync), so each writes the status it finds under the lock and the recount that follows counts the row as it ended; the sync's reading of the site's requests, which therefore reflects every request that committed before the lock was granted; the gate's reading of an activation whose row the sweep already made active; retention's eligibility check through deletion; and a status write or deletion against creation of that site's placement, so the writer's trigger sees the placement. |
|
||||
| FedWiki placement row | `domains.placements` rows with provider `fedwiki` and the site's id | Row lock of the trigger's UPDATE, only where the flag changes | `fedwiki.set_site_placement_servability`, after the site row and before usage | Nothing beyond the site row; flag-only, outside the registry lock. |
|
||||
| Desired-state record | `core.desired_state_records` row | `FOR UPDATE` | the `LockDesiredStateRecord` query (after the address lock); `StampDesiredStateRecordsDispatched`, which locks the records in identifier order | The record's content and generation within one recompute; the dispatch stamp against another stamp. |
|
||||
| Desired-state notice | `core.desired_state_outbox` rows | `FOR UPDATE SKIP LOCKED` | the `ClaimDesiredStateOutbox` query | Two relay passes, so each claims different rows; a pass skips rows another still holds. Triggers write the rows through `core.insert_desired_state_notice` inside the transaction that changed the source, and they take no lock beyond the insert. |
|
||||
@@ -79,7 +80,7 @@ A change to a family's name or to the shape of its id changes its keys. Two proc
|
||||
|
||||
1. A transaction that takes the materialization rendezvous takes it as its first statement. No other advisory lock comes before it.
|
||||
2. The advisory families the transaction needs, in the order of the table above. Several locks of one family follow the order this page gives for that family: lifecycle instances in the order their requests were recorded.
|
||||
3. Rows, by the rules below: a rule change's set and rule rows before pool rows; pool rows in ascending `pool_id`, before a grant's lineage head, obligation rows and a tier's product row; FedWiki's site rows, then their placement rows through the trigger, then the usage row, then request rows; a desired-state record after its address.
|
||||
3. Rows, by the rules below: a rule change's set and rule rows before pool rows; pool rows in ascending `pool_id`, before a grant's lineage head, obligation rows and a tier's product row; FedWiki's site rows, then their placement rows through the trigger, then the swap policy row, then the usage row, then request rows; a desired-state record after its address.
|
||||
|
||||
No path waits on an advisory lock after it takes a row lock: a recording that takes an instance lock its transaction already holds, as the swap's second recording does, takes it without waiting. The sections below list each path's locks in this order.
|
||||
|
||||
@@ -390,13 +391,26 @@ lock is held until then.
|
||||
### FedWiki at the handler
|
||||
|
||||
`withWorkspaceTx` takes the workspace advisory lock, then runs the handler's
|
||||
statements. A swap (`swapActiveSite`) and a rotation with a cooldown
|
||||
(`changeStatus`) then record a lifecycle request, which takes the lifecycle
|
||||
instance lock of the activated site. A swap records a second request for the
|
||||
parked site, which takes that instance's lock after the first. The swap policy
|
||||
row is upserted last. The handler takes no usage-row lock and no site-row
|
||||
lock. A status change without a cooldown skips the workspace lock and records
|
||||
its request in a transaction of its own, taking only the instance lock.
|
||||
statements. Every rotation takes it, with the cooldown on or off: a swap
|
||||
(`swapActiveSite`) and a return of a downgrade-parked site
|
||||
(`changeStatus` with `rotation` true, through `recordRotation`). Under the lock
|
||||
the intake looks the address up again for a repeat, checks whether another
|
||||
rotation of the workspace is open (`WorkspaceHasOpenRotation`), then, when the
|
||||
cooldown is on, reads the swap policy row without a lock; either refusal
|
||||
rolls the transaction back before anything is recorded. It then records a
|
||||
lifecycle request, which takes the lifecycle instance lock of the activated
|
||||
site. A swap records a second request for the parked site, which takes that
|
||||
instance's lock after the first, then `RecordLifecycleAct` links the two. The
|
||||
intake writes no swap policy row: the record step of a rotation that succeeded
|
||||
does. A return, after the instance lock and before it records, takes its site
|
||||
row (`LockSiteStatusByID`) and checks under it that the row is still the
|
||||
member's, with the posted domain, read-only and marked; a missing or foreign
|
||||
row records nothing and answers that the site was not found, and a row no
|
||||
longer read-only and marked records nothing and answers that the site changed. The handler takes no usage-row lock
|
||||
and no other site-row lock. A status
|
||||
change that is not a rotation (a free fill, an archive, a Restore of an
|
||||
archived site, a delete) skips the workspace lock and records its request in
|
||||
a transaction of its own, taking only the instance lock.
|
||||
Both intake transaction openers use READ COMMITTED. Status intake reads the
|
||||
original site by ID after acquiring its instance lock, so it sees a purge
|
||||
that committed before that lock was granted. A swap takes both instance
|
||||
@@ -422,17 +436,25 @@ The workflow activities that finish a lifecycle request, and settle, run
|
||||
locks, in the order the handler recorded the requests (the activated site
|
||||
first, then the parked site); then the activity's own site-row writes
|
||||
(status and swap records lock and validate the original IDs, park then
|
||||
activate for a swap); then
|
||||
activate for a swap); then the swap policy row, in a rotation that succeeded
|
||||
(`UpsertSiteSwapPolicy`, which stamps the cooldown); then
|
||||
the requests' holds are deleted (`DeleteSlotHolds`); then the usage row
|
||||
(`usage.Recount`: `LockNumericUsage`, the count, the write); then the swap's
|
||||
guard; then the request rows (`FinishLifecycleRequest`).
|
||||
|
||||
Settle groups the requests it ends by act (a request with no act is a group of
|
||||
one) and runs one `finishAllWith` for each group, so an act's requests end in
|
||||
one transaction. Settle writes no swap policy row; the status reconcile that
|
||||
records a return's success does.
|
||||
|
||||
- `RecordCreatedSiteActivity`: the site row insert.
|
||||
- `RecordSiteStatusActivity`: the site row by id (`LockSiteStatusByID`),
|
||||
checked against the recorded workspace and domain.
|
||||
checked against the recorded workspace and domain; the swap policy row when
|
||||
the row was a return (`isReturn`: parked, not active, target active).
|
||||
- `RecordSwapActivity`: the site row of the parked site, then the site row of
|
||||
the activated site, both by id (`LockSiteStatusByID`) and checked against
|
||||
the recorded workspace and domain; the guard reads the pool's limit after
|
||||
the recorded workspace and domain; the swap policy row, unless the
|
||||
activated site was already active; the guard reads the pool's limit after
|
||||
the recount.
|
||||
- `RecordSiteDeletedActivity` and `FinishLifecycleRequestsActivity` (every
|
||||
declined or failed outcome): no site row.
|
||||
@@ -526,7 +548,9 @@ lifecycle instance lock or a workspace lock.
|
||||
status and recounts the pool. A record step that writes a status takes the
|
||||
same site row, so a request either committed before the sync's lock, and
|
||||
the two reads see it, or takes the row after the sync's commit and writes its
|
||||
own status last.
|
||||
own status last. A return's intake takes the same site row, after the
|
||||
instance lock, so it either committed before the sync's lock, and the reads
|
||||
see its accepted request, or waits and finds the row as the sync left it.
|
||||
- **A farm-absent row of the System workspace**: one transaction at READ
|
||||
COMMITTED that deletes the row and recounts the pool. The name is released
|
||||
after the commit.
|
||||
@@ -548,8 +572,10 @@ pinned connection; `RecordLifecycleRequestInTx` and
|
||||
`RecordFirstLifecycleRequestInTx` run in the caller's, which is how the handler
|
||||
records under the workspace lock.
|
||||
`DeleteUnstartedLifecycleRequest`, which removes a request whose workflow never
|
||||
started, takes no instance lock, so a repeat that races it may be answered from
|
||||
either side of the delete.
|
||||
started, and `DeleteUnstartedLifecycleAct`, which removes all of an act's
|
||||
accepted requests in one statement, take no instance lock, so a repeat that
|
||||
races either may be answered from either side of the delete. The act's header
|
||||
stays.
|
||||
|
||||
### Desired-state relay
|
||||
|
||||
@@ -620,8 +646,9 @@ transactions, apart from the transaction that allocates or releases the name.
|
||||
4. The grant lineage head row is locked after the pool row, never before.
|
||||
5. A FedWiki transaction takes its locks in this order, skipping those it
|
||||
does not need: the lifecycle instance locks, all site rows, their placement
|
||||
rows (through the site trigger), the usage row,
|
||||
then the lifecycle request rows. Hold rows have no place in the order,
|
||||
rows (through the site trigger), the swap policy row, the usage row,
|
||||
then the lifecycle request rows. Intake reads the swap policy row without a
|
||||
lock, under the workspace lock. Hold rows have no place in the order,
|
||||
because only the holder of their request's instance lock writes them. The
|
||||
count under the usage row is a statement of its own after the lock, so it
|
||||
reads every commit that preceded the lock's grant.
|
||||
|
||||
@@ -16,7 +16,7 @@ The catalog was motivated by a 2026-07 inventory of the console's domain models,
|
||||
- [Payments and Billing](payments-billing.md) — billing accounts, subscriptions, invoices and payments projected from Stripe, scheduled changes as intent, and the reconciler.
|
||||
- [Plan Ladders and Transitions](plan-ladders-transitions.md) — ranked tiers, who occupies which rung, the append-only audit, and the conferral functions as sole writers.
|
||||
- [Entitlements](entitlements.md) — resource keys, sets and rules, grants as decrees, provisions as delivery, and the materializer.
|
||||
- [Acts](acts.md) — the act record for actions that write several rows, the plan acts' details, the obligations a default change or reorder owes its organizations, and the functions that are the only writers of its tables.
|
||||
- [Acts](acts.md) — the act record for actions that write several rows, the plan acts' details, the lifecycle acts that group a person's requests for several instances, the obligations a default change or reorder owes its organizations, and the functions that are the only writers of its tables.
|
||||
- [Resource Pools](resource-pools.md) — the per-organization container: workspace assignments, the two resolution directions, and pool-grain usage.
|
||||
- [Providers and Integrations](provider-integration.md) — the registry and its connections, boot-time manifests, resource-key ownership, desired-state delivery, and the shared substrate.
|
||||
- [Domains Registry](domains-registry.md) — claims as subtree ownership, placements as the only thing that serves, and the anti-abuse ledger.
|
||||
|
||||
+14
-10
@@ -1,7 +1,7 @@
|
||||
---
|
||||
title: "Acts"
|
||||
audience: [developer]
|
||||
summary: "The act record: one header row per action that writes several rows, the plan acts' detail tables, the obligations a plan act owes its organizations, and the functions that are the only writers of its tables."
|
||||
summary: "The act record: one header row per action that writes several rows, the plan acts' detail tables, the lifecycle acts that group an action's lifecycle requests, the obligations a plan act owes its organizations, and the functions that are the only writers of its tables."
|
||||
---
|
||||
|
||||
# Acts
|
||||
@@ -10,7 +10,7 @@ summary: "The act record: one header row per action that writes several rows, th
|
||||
|
||||
An **act** is one action by one actor that writes several rows at once, such as an operator reordering a ladder's tiers. The act record answers "who did this, when, and why" once, in a header row, so that every table the action wrote can point at the same row instead of repeating the answer. The header is `core.acts`: a **cause** from a closed list, the **actor**, an optional **note**, the request id, and two times.
|
||||
|
||||
Only plan acts exist today. A **plan act** changes what the plan ladders mean: it adds a tier, removes a tier, reorders a ladder's tiers, changes the default ladder of an organization type, or retries the unfinished work of one of those. What a plan act did goes in `core.plan_act_details`, one row per act, naming the ladder, product and organization type involved by id and by the name each had when the act committed. A later kind of act adds its own causes and its own detail table beside this one, and shares the header.
|
||||
Two kinds of act exist today. A **plan act** changes what the plan ladders mean: it adds a tier, removes a tier, reorders a ladder's tiers, changes the default ladder of an organization type, or retries the unfinished work of one of those. What a plan act did goes in `core.plan_act_details`, one row per act, naming the ladder, product and organization type involved by id and by the name each had when the act committed. A **lifecycle act** groups the lifecycle requests that one action of a person records for several instances, such as swapping a workspace's active site (cause `instances_swapped`). It has no detail table: its requests, which carry the act's id, cause and their role in it, are what it did. A later kind of act adds its own causes and, when it has something to record beyond rows that already name the act, its own detail table beside these, and shares the header.
|
||||
|
||||
A default change, and a reorder that gives a default ladder a new rank-0 product, change the plan that every organization of one or more **organization types** (the `core.org_types` rows, one per kind of organization) should hold. The act commits first, together with the org types it **reaches**, in one short transaction. The organizations are moved afterwards, each in its own transaction under the shared materialization rendezvous (the lock described in `docs/database-locks.md`), so the exclusive rendezvous is held only while the act commits and not while every organization of the type is moved. The work left over is recorded as **obligations**: one row for each pool the act still owes a move. A **listing** writes the obligations in batches, and a **move** carries out one obligation in its own transaction. The request that made the act performs the first batch and the first moves; a background **drain** performs the rest.
|
||||
|
||||
@@ -24,7 +24,9 @@ Database objects sit in the `core` schema.
|
||||
|---|---|---|
|
||||
| `core.acts` | The header: `cause`, the actor triple (`actor_type` with `actor_person_id` or `actor_service_account_id`), `note`, `request_id`, `effective_at` (when the act took effect) and `created_at` (when the row was written) | `00027_acts.sql` |
|
||||
| `core.plan_act_details` | The plan act's detail, keyed by the act and tied to it by a composite foreign key on `(act_id, cause)`: ladder, product, previous product, org type, previous ladder (each id with its name), `disposition`, and `retried_act_id` for a Retry | `00027_acts.sql` |
|
||||
| `core.record_plan_act` | The only writer of the two tables above and of the reached-types table; it returns the act's id | `00027_acts.sql`; replaced in `00028_plan_act_obligations.sql` to write the reached types |
|
||||
| `core.record_plan_act` | The only writer of a plan act's header, its detail and the reached-types table; it returns the act's id | `00027_acts.sql`; replaced in `00028_plan_act_obligations.sql` to write the reached types |
|
||||
| `core.lifecycle_requests.act_id`, `act_cause`, `act_role` | Nullable columns that point a lifecycle request at its act, name the act's cause and say whether the request is `asked` or `consequent`; a composite foreign key on `(act_id, act_cause)` and `lifecycle_request_act_shape` tie them together | `00041_lifecycle_request_acts.sql` |
|
||||
| `core.record_lifecycle_act` | The only writer of a lifecycle act's header and of the act columns; it takes the ids of requests the calling transaction inserted and returns the act's id | `00041_lifecycle_request_acts.sql` |
|
||||
| `core.plan_act_reached_org_types` | One row per org type an act reaches: the type's name, the greatest organization id of the type when the act committed (`last_org_id`), and `reached_seq`, an identity value that orders the acts reaching one type | `00028_plan_act_obligations.sql` |
|
||||
| `core.plan_act_orgs_without_pool` | The organizations of a reached type that had no active default pool when the listing reached them; an obligation is keyed by a pool, so these cannot have one | `00028_plan_act_obligations.sql` |
|
||||
| `core.plan_act_obligations` | One row per (act, pool): `status` (`pending`, `settled`, `failed`, `superseded`), `outcome`, the attempt count, the step and text of the last error, and the acts that superseded or requeued it | `00028_plan_act_obligations.sql` |
|
||||
@@ -34,7 +36,8 @@ Database objects sit in the `core` schema.
|
||||
| `core.write_plan_act_obligations`, `core.settle_plan_act_obligation`, `core.record_plan_act_obligation_failure`, `core.requeue_plan_act_obligations` | The only writers of the obligation tables: a listing batch, a settlement, a failed attempt, and a Retry's requeue | `00028_plan_act_obligations.sql` |
|
||||
| `core.plan_position_is_outgoing`, `core.plan_pool_bucket` | The rule for an outgoing default and the class of one pool (`would_fail`, `outgoing_default`, `already_at_default`, `other_source`, `would_initiate`) that a move reads | `00026_outgoing_default_rule.sql` |
|
||||
| Plan act runner | `runPlanAct` opens an act's transaction, locks the pools the act names in ascending order, then runs the act; `writePlanAct` calls `core.record_plan_act`; `PlanActReason` builds the transition reason | `internal/entitlements/plan_act_runner.go` |
|
||||
| Causes and obligation vocabularies | `ActCause`, `ObligationStep`, `ObligationOutcome`, mirrored from the constraints and compared with them by tests | `internal/entitlements/act_cause.go`, `internal/entitlements/plan_act_obligation.go` |
|
||||
| Causes and obligation vocabularies | `acts.Cause` with the lists `acts.PlanCauses` and `acts.LifecycleCauses`, and `ObligationStep` and `ObligationOutcome`, mirrored from the constraints and compared with them by tests | `internal/acts/`, `internal/entitlements/plan_act_obligation.go` |
|
||||
| Lifecycle act writer | `RecordLifecycleAct` calls `core.record_lifecycle_act` in the transaction that inserted the requests; `DeleteUnstartedLifecycleAct` deletes an act's accepted requests, not its header | `internal/integration/lifecycle.go` |
|
||||
| The plan acts | `AddTier`, `DeleteTier`, `RemoveTier`, `ReorderTiers`, `ChangeOrgTypeDefault`, `RetryPlanAct` | `internal/entitlements/ladder_acts.go`, `tier_reorder.go`, `default_change.go`, `plan_act_retry.go` |
|
||||
| Listing, moves and drain | `ListPlanActBatch` lists; `EnactObligation` moves one pool; `DrainPlanAct` is one pass of both, as the request and the drain run it | `internal/entitlements/plan_act_drain.go`, `plan_act_move.go` |
|
||||
| Drain workflow and poller | `PlanActDrainWorkflow` repeats passes for one act; `PollPlanActs` finds every act that still owes work and starts its drain | `internal/workflows/entitlements/plan_act_drain_workflow.go` |
|
||||
@@ -46,11 +49,11 @@ Database objects sit in the `core` schema.
|
||||
An invariant is a rule the model guarantees everywhere; code that would break one is wrong even if it works locally. Tags mark the enforcement mechanism: **[db]** means a schema constraint, trigger or privilege rejects violations; **[db-code]** means database-side code upholds it; **[app]** means only Go code upholds it, so every new code path must too.
|
||||
|
||||
1. **[db]** An act's actor is coherent. A `person` actor has a person id and no service account id; a `service_account` actor has the reverse; a `system` actor has neither (`act_actor_coherent`). Only a person's act carries a note (`act_note_by_a_person`). The person id is a foreign key to `core.persons`; the service account id has no foreign key because no service account table exists.
|
||||
2. **[db]** An act's cause is one of a closed list (`chk_acts_cause`, repeated on the detail by `chk_plan_act_details_cause`), and a detail row belongs only to an act of its own cause (`plan_act_detail_is_its_act`). `plan_act_detail_shape` fixes which detail columns each cause fills and leaves empty. A later kind of act adds its causes by replacing `chk_acts_cause`; when it has its own detail table, that table carries its own cause constraint, so `chk_plan_act_details_cause` stays as it is.
|
||||
2. **[db]** An act's cause is one of a closed list (`chk_acts_cause`, repeated on the detail by `chk_plan_act_details_cause`), and a detail row belongs only to an act of its own cause (`plan_act_detail_is_its_act`). `plan_act_detail_shape` fixes which detail columns each cause fills and leaves empty. A lifecycle act's requests carry the cause on their own side: `chk_lifecycle_requests_act_cause` lists the lifecycle causes, and `lifecycle_request_in_its_act` holds a request to an act of the cause it states. A later kind of act adds its causes by replacing `chk_acts_cause`, and a later lifecycle cause enters `chk_lifecycle_requests_act_cause` as well; when a kind has its own detail table, that table carries its own cause constraint, so `chk_plan_act_details_cause` stays as it is.
|
||||
3. **[db]** A detail names what it identifies. Each id column and its name column are both set or both empty (`plan_act_detail_names_what_it_ids`). The ids carry no foreign key to the catalog, so the record outlives a deleted ladder, product or org type, and the name keeps the row readable.
|
||||
4. **[db]** `core.record_plan_act` is the only writer of `core.acts`, `core.plan_act_details` and `core.plan_act_reached_org_types`. It runs as `core_owner`; `core_writer` keeps SELECT and holds no insert, update or delete on them, and EXECUTE is granted to `core_writer` alone. Nothing updates or deletes a row after the function wrote it.
|
||||
5. **[db-code]** `core.record_plan_act` refuses an act written without the materialization rendezvous: the exclusive rendezvous for a tier add, a tier removal, a reorder and a default change, because they change what the tiers and defaults mean, and the rendezvous in either mode for a Retry. A reorder that names a new rank-0 product must name the product the ladder holds at rank 0 when the function runs (the caller renumbers first), and a Retry must name a default change or a reorder.
|
||||
6. **[db]** The note is the one column of the act record that `core_reader` and `console_reader` cannot read. It holds a person's own words, so `core_reader` receives a column-level SELECT on every other column of `core.acts`, and `scripts/db-reader-role.sql` lists `core.acts.note` among the columns the read-only role withholds. `core_owner` and `core_writer` read it. No plan act writes a note today.
|
||||
4. **[db]** `core.record_plan_act` is the only writer of a plan act's rows in `core.acts` and of `core.plan_act_details` and `core.plan_act_reached_org_types`, and `core.record_lifecycle_act` is the only writer of a lifecycle act's row in `core.acts`. Each runs as `core_owner`; `core_writer` keeps SELECT and holds no insert, update or delete on those tables, and EXECUTE is granted to `core_writer` alone. Nothing updates or deletes a row after its function wrote it.
|
||||
5. **[db-code]** `core.record_plan_act` refuses a plan act written without the materialization rendezvous: the exclusive rendezvous for a tier add, a tier removal, a reorder and a default change, because they change what the tiers and defaults mean, and the rendezvous in either mode for a Retry. A reorder that names a new rank-0 product must name the product the ladder holds at rank 0 when the function runs (the caller renumbers first), and a Retry must name a default change or a reorder. `core.record_lifecycle_act` asserts no rendezvous, because a lifecycle act changes no entitlement.
|
||||
6. **[db]** The note is the one column of the act record that `core_reader` and `console_reader` cannot read. It holds a person's own words, so `core_reader` receives a column-level SELECT on every other column of `core.acts`, and `scripts/db-reader-role.sql` lists `core.acts.note` among the columns the read-only role withholds. `core_owner` and `core_writer` read it. No act writes a note today.
|
||||
7. **[db-code]** A request id longer than the column (100 characters) is not stored, because the client chose it and it exists only for correlating the act with log lines. It is never a key.
|
||||
8. **[db-code]** The org types an act reaches are derived inside `core.record_plan_act` from the detail, so a caller cannot pass reached types that disagree with the detail. A default change reaches its org type. A reorder that gives the ladder a new rank-0 product reaches every org type whose `default_plan_ladder_id` is that ladder. Each reached row carries the type's name and the greatest organization id of the type at that moment (`NULL` for a type with no organization). A reorder that leaves rank 0 unchanged, a tier add, a tier removal and a Retry reach none.
|
||||
9. **[db-code]** At most one act owns an org type. The owner is the act whose reached-types row for that type has the greatest `reached_seq` (`core.plan_act_owns_org_type`). Ownership changes only when a commit under the exclusive rendezvous adds a reached-types row, so every reader that holds the rendezvous or reads committed rows sees one owner. Each statement that lists, moves or counts obligations calls this function, and the listing, the moves and the counts treat an obligation on a type the act no longer owns as not the act's. `reached_seq` orders correctly only while its sequence keeps `CACHE 1`, its default.
|
||||
@@ -61,7 +64,8 @@ An invariant is a rule the model guarantees everywhere; code that would break on
|
||||
14. **[app]** A move runs in one transaction. It locks the pool row, then the obligation row, and skips the obligation unless it is `pending` and its act still owns the type. It reads the org type's current default and the pool's class from `core.plan_pool_bucket`, applies the disposition, and settles the obligation in the same transaction, so a pool is either moved and settled or unchanged. The outcome is `already_at`, `untouched`, `initiated`, `left`, `grandfathered` or `migrated`. `left` means the pool had no position and no default was conferred. A pool that holds the outgoing default under an act with no disposition settles as `untouched` and logs a warning, because the disposition gate (invariant 15) should have refused the act.
|
||||
15. **[app]** A default change or a reorder that reaches an org type and was given no disposition is refused, and writes nothing, when any organization of a reached type holds the outgoing default. The gate reads at most two entries of a partial index for each type, so its cost does not grow with the number of organizations.
|
||||
16. **[app]** Everything a move writes is attributed to the act that put the obligation in motion: the act itself, or the Retry that requeued the obligation. Every grant the move creates carries that act's id in `core.grants.act_id`, and its transitions carry the operator of that act and the reason built from the original act's detail row. A move settled by a drain minutes later is still the operator's act.
|
||||
17. **[db]** The record is never purged. No role the application uses holds DELETE on any table of the act record, and no function deletes from them. Because no obligation is deleted, `fk_plan_act_obligations_pool_id` keeps every pool an obligation names, and `fk_resource_pools_org_id` keeps its organization. `fk_grants_act_id` keeps an act while a grant points at it. The guard trigger on `core.organizations.org_type` (migration `00026`, shown on the Entitlements card) keeps an organization on the type its obligations name, because an obligation records the organization's type when the listing reached it and a changed type would make that record wrong.
|
||||
17. **[db]** The record is never purged. No role the application uses holds DELETE on any table of the act record, and no function deletes from them. `core.lifecycle_requests` is outside the record: its rows are deleted when a workflow start is refused as not found, and the act's header stays, so an unstarted act's header outlives its requests. Because no obligation is deleted, `fk_plan_act_obligations_pool_id` keeps every pool an obligation names, and `fk_resource_pools_org_id` keeps its organization. `fk_grants_act_id` keeps an act while a grant points at it. The guard trigger on `core.organizations.org_type` (migration `00026`, shown on the Entitlements card) keeps an organization on the type its obligations name, because an obligation records the organization's type when the listing reached it and a changed type would make that record wrong.
|
||||
18. **[db-code]** `core.record_lifecycle_act` refuses, with SQLSTATE `22023`, a call whose cause is not a lifecycle cause or whose arguments do not fit it (`lifecycle_act_not_a_lifecycle_cause`, `lifecycle_act_swap_shape`); a request named twice or not found; a request that is not `accepted`, that already belongs to an act, or that this transaction did not insert (its `xmin` and `created_at` are checked); requests of more than one workspace or connection; a swap whose requests are not all `set_status`; an asked request that does not name the actor as its person, or a consequent request that names one; and a link that changes fewer rows than it named. Every refusal but the incomplete link raises before the header is written; the incomplete link raises after it, and the failed call's statement rolls the header back, so a refused call writes nothing.
|
||||
|
||||
## Dimensions
|
||||
|
||||
@@ -72,5 +76,5 @@ These axes are independent; hold them separately:
|
||||
- **Cause vs disposition vs outcome**: the cause says which kind of plan act it was; the disposition (`grandfather`, `migrate`, `keep`) is the operator's choice for positions held through the outgoing default, stored on the detail; the outcome is what happened to one pool and is stored on its obligation. A tier removal uses `keep` and `migrate`; a reorder and a default change use `grandfather` and `migrate`.
|
||||
- **Status vs ownership**: an obligation's `status` is its own row's state. Whether the row is still its act's to move is a separate fact, derived from `core.plan_act_owns_org_type`, because a newer act that reaches the type takes ownership without changing the older rows. A `superseded` status records that a newer act listed the same pool and owes the move instead; losing ownership alone leaves the status unchanged.
|
||||
- **Request vs drain**: the same pass (`DrainPlanAct`) runs in the request that made the act and in the drain. The request gives up sooner: it lists one batch, tries at most 50 obligations whether or not each settles, stops once 2 seconds have passed since the request began, waits 500 ms for a lock, and ends 5 seconds after it began (`internal/entitlements/constants.go`). The drain waits 5 seconds for a lock and has no transaction timeout. A lock wait that ends a request's pass records no attempt on the obligation, because it says nothing about the organization.
|
||||
- **Business time vs wall clock**: `effective_at` is when the act took effect, taken by the Go caller when it records the act; `created_at` is when the database wrote the row.
|
||||
- **Business time vs wall clock**: `effective_at` is when the act took effect, taken by the Go caller when it records a plan act; `created_at` is when the database wrote the row. A lifecycle act's `effective_at` is its asked request's `created_at`.
|
||||
- **Id vs name**: an id in a detail identifies the catalog row the act touched; the name beside it is what that row was called at commit and is never rewritten. Display reads the name, and navigation reads the id.
|
||||
|
||||
@@ -28,7 +28,8 @@ The delivery vocabulary, used the same way in code, specs and the other cards:
|
||||
- **Observed projection**: what an application reports holding for one recipient, with the generation it applied.
|
||||
- **Read-back**: the console asking a connection what its application holds, page by page.
|
||||
- **Lag**: a record whose generation the application has not applied, measured from when that generation was raised.
|
||||
- **Lifecycle request**: one request a person made for one instance (create, change status, delete), recorded under the console's identifier for the instance and a generation.
|
||||
- **Lifecycle request**: one request for one instance (create, change status, delete), recorded under the console's identifier for the instance and a generation. It names the person whose action caused it, or no one when the console added it to a person's action.
|
||||
- **Lifecycle act**: one action of a person that changes several instances, such as swapping a workspace's active site, grouped as one header row in `core.acts` that its requests point at. The request the person asked for is its `asked` request; one the console added as the consequence is `consequent`. The act only ties its requests together.
|
||||
- **Target mapping**: an operator's row that delivers one resource key through one group or role inside one application.
|
||||
- **Cut off everywhere**: the recorded fact that a person's records at every connection carry no entitlements.
|
||||
|
||||
@@ -50,11 +51,13 @@ Registry, delivery and substrate tables sit in the `core` schema (`internal/db/m
|
||||
| `core.observed_projections` | One row per (connection, recipient) for what the application last reported: the applied generation and hash, the observed entitlements, the last push answer, and a marker for a reported generation above the console's | `00024_integration_delivery_core.sql` |
|
||||
| `core.desired_state_outbox` | Change notices: each row names a subject (a pool, an organization, a person or a connection) and optionally a key, and carries a status, an attempt count, a claim lease and a paging cursor. No foreign keys | `00024_integration_delivery_core.sql` |
|
||||
| `core.person_cut_offs` | One open row per person who is cut off everywhere, closed rather than deleted when the cut-off is lifted, with who acted and when. Written only through `core.set_person_cut_off`, which no production code calls yet | `00024_integration_delivery_core.sql` |
|
||||
| `core.lifecycle_requests` | One row per request a person made for one instance, addressed by (instance, generation): the operation, the workspace, identifier-only parameters, the outcome (`accepted`, `succeeded`, `declined` or `failed`) with a reason code, the workflow id, and when the member dismissed the outcome. A partial unique index allows one `accepted` request per instance | `00024_integration_delivery_core.sql` |
|
||||
| `core.lifecycle_requests` | One row per request for one instance, addressed by (instance, generation): the operation, the workspace, identifier-only parameters, the outcome (`accepted`, `succeeded`, `declined` or `failed`) with a reason code, the workflow id, the person whose action caused it (none for a consequent request), the act columns (`act_id`, `act_cause`, `act_role`, all set or all empty) and when the member dismissed the outcome. A partial unique index allows one `accepted` request per instance | `00024_integration_delivery_core.sql`, `00041_lifecycle_request_acts.sql` (the act columns and the column grants) |
|
||||
| `core.acts`, cause `instances_swapped` | The header of a lifecycle act: the actor (the person of the asked request), no note, `effective_at` equal to the asked request's `created_at`. It has no detail table; its requests, tied by `(act_id, act_cause)`, are what it did | `00041_lifecycle_request_acts.sql` |
|
||||
| `core.record_lifecycle_act` | The only writer of the act columns and of a lifecycle act's header; it takes the ids of requests the calling transaction inserted and returns the act's id | `00041_lifecycle_request_acts.sql` |
|
||||
| Delivery functions | `core.desired_state_content` computes a record's content from the materialized entitlements under the recipient rules; `core.next_generation` and `core.generation_ceiling` raise and bound generations; `core.guard_desired_state_generation` refuses a falling generation or a content change without a rise; `core.requeue_desired_state` gives one failed recipient a retry row; one trigger function per trigger table writes notices through `core.insert_desired_state_notice` | `00024_integration_delivery_core.sql` |
|
||||
| The desired-state relay | `ProcessDesiredStateOutbox` claims notices, expands them into the records they can affect, and recomputes each record once under a per-address advisory lock, within one record budget per tick across every row it claimed; the relay workflow runs it every tick, push workflows send one record at a time and end, leaving the record as lag, after two consecutive stale or conflict answers, and the read-back workflow and its per-connection schedule are registered and started only for a connection a transport serves, each page ending the run once the connection is no longer approved and active | `internal/workflows/desiredstate/` |
|
||||
| The transport interface | `Transport` (`Apply` one record, `List` one page of what an application holds) and the lookup the relay asks for a connection's transport, which answers none for every connection today | `internal/integration/transport.go` |
|
||||
| Lifecycle request writers | The only writers of `core.lifecycle_requests`: minting an instance identifier, recording a request and answering a repeat from its record, deleting an accepted request whose workflow start was refused, finishing, listing open and unacknowledged requests, and recording a dismissal | `internal/integration/lifecycle.go` |
|
||||
| Lifecycle request writers | The only writers of `core.lifecycle_requests`: minting an instance identifier, recording a request and answering a repeat from its record, `RecordLifecycleAct` (which groups requests through `core.record_lifecycle_act`), deleting an accepted request or an act's accepted requests whose workflow start was refused, finishing, listing open and unacknowledged requests, and recording a dismissal | `internal/integration/lifecycle.go` |
|
||||
| Discourse convergence | The set-shaped delivery in action: a sweep recomputes each managed forum group's desired member set from boolean entitlements and pushes adds/removes, refreshing an observed projection | `internal/integrations/discourse/workflows/`; `discourse.observed_group_members` |
|
||||
| `core.webhook_events`, `core.outbox` | The shared inbound and outbound substrate (described in the Payments and Billing card); both deliberately carry no foreign keys, staying provider-generic | `00001_init.sql` |
|
||||
| `core.integration_config_overrides` | Operator-set values for non-secret config keys, overlaid at boot over environment and defaults | `00009_integration_config_overrides.sql` |
|
||||
@@ -104,6 +107,10 @@ An invariant is a rule the model guarantees everywhere; code that would break on
|
||||
16. **[db]** A key's `recipient` is a person, an organization or empty; a platform key carries none; and a key delivered to a person must be boolean, because a person's record takes the union of what their organizations hold and a union of numeric limits has no single meaning. Boot registration additionally refuses (app-side) a manifest that leaves an owned key without a recipient or names a key the provider does not own.
|
||||
17. **[db]** One connection exists per provider, retired connections included, so boot registration never creates a second connection beside one an operator retired. A target mapping can name only a key its connection's provider owns.
|
||||
18. **[db-code]** A record's generation never falls, and its content never changes without its generation rising: a trigger on `core.desired_state_records` refuses either update. Every raise goes through `core.next_generation`, which takes the largest of the current generation plus one, a reported generation plus one, and the clock in microseconds, and refuses a reported generation more than one day ahead of the clock.
|
||||
19. **[db]** A request covers one instance. Its act columns are all set or all empty (`lifecycle_request_act_shape`), and `(act_id, act_cause)` is a foreign key to the act's header (`lifecycle_request_in_its_act`), so a request points only at an act of the cause it states. An act has at most one `asked` request (`uq_lifecycle_requests_one_asked`), and a `consequent` request names no person (`lifecycle_request_consequent_names_no_person`).
|
||||
20. **[db-code]** Only `core.record_lifecycle_act` writes the act columns, and only on requests its own transaction inserted, so a request joins an act when it is recorded and never moves to another. For `instances_swapped` the asked request names the act's actor as its person. `core_writer` holds INSERT and UPDATE only on the columns the request writers name: nine to insert, four to update, and none of the act columns.
|
||||
21. **[app]** An action that changes several instances records one request for each in one transaction and groups them under one lifecycle act. Nothing else groups requests: no reader parses a workflow id or reads another request's identity from a request's parameters.
|
||||
22. **[app]** An act only ties its requests together. When one request of an action fails, the console undoes the others itself, so a connector applies each request on its own.
|
||||
|
||||
## Dimensions
|
||||
|
||||
@@ -116,7 +123,8 @@ An invariant is a rule the model guarantees everywhere; code that would break on
|
||||
- **Key ownership × shape × metering** — ownership (the `provider` column) and metering (whether usage of the key is measured, via the usage rows in the entitlements model) are independent: a platform-owned key may be metered. Shape is not fully independent — as built, only numeric keys have usage machinery, so a boolean key cannot be metered.
|
||||
- **The three roles of a key** — the bare stored id (`fedwiki_sites`), the grouping attribute (the `provider` column), and the display name shown to humans. A dotted `provider.key` form does not exist in storage and must never be parsed out of a key string.
|
||||
- **Config key classes** — secret vs overridable; boot-required vs runtime-managed; enum-closed vs free. Orthogonal, all declared in the spec.
|
||||
- **Per-instance lifecycle vs converged-set delivery** — FedWiki's resource is instance-shaped (create / set_status / delete per site, each a lifecycle request a person makes); Discourse's is set-shaped (a member set converged by reconciliation, manifest declaring only the read verbs). The registry expresses both. Instance-shaped work is recorded as lifecycle requests, addressed by an instance identifier the console chooses and a generation. Set-shaped delivery is a person-recipient key delivered through the connection's target mappings: a group's member set is the set of person records that hold the key, so it needs no verb of its own.
|
||||
- **Per-instance lifecycle vs converged-set delivery** — FedWiki's resource is instance-shaped (create / set_status / delete per site, each a lifecycle request recorded for a person's action); Discourse's is set-shaped (a member set converged by reconciliation, manifest declaring only the read verbs). The registry expresses both. Instance-shaped work is recorded as lifecycle requests, addressed by an instance identifier the console chooses and a generation; an action that changes several instances records one request for each and groups them under a lifecycle act. Set-shaped delivery is a person-recipient key delivered through the connection's target mappings: a group's member set is the set of person records that hold the key, so it needs no verb of its own.
|
||||
- **Request vs act** — a lifecycle request is the record for one instance and is what a connector applies; a lifecycle act is the header that says one action of a person caused several requests, and carries no instruction. The person on a request is whose action caused it, which is none for a consequent request; the actor of the act is always the person who asked.
|
||||
- **Schema per provider vs generic delivery tables** — an in-tree integration keeps its own state in its own schema; what the console keeps per connection, for any provider, lives in the core delivery tables keyed by connection (invariant 12).
|
||||
- **Desired vs observed** — a desired-state record is what the console wants an application to hold; an observed projection is what the application last reported holding. They have different writers and sit in different tables, and a record is delivered when the projection's applied generation has reached the record's generation and, when the application reported a content hash, that hash equals the record's.
|
||||
- **Registry status vs configuration readiness** — the operator-managed `core.providers.status` (a stored lifecycle value, changed only by an operator) vs whether the declared required config actually resolves (a read-time computation, `config.RequiredKeysUnresolved`). Independent facts, both shown, neither one a health check (invariant 15).
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
||||
// SPDX-FileCopyrightText: 2025-2026 Christian Galo
|
||||
|
||||
// Package acts holds the vocabulary of the act record that every kind of act
|
||||
// shares (docs/models/acts.md). It imports nothing of the console, so any
|
||||
// package that records or reads an act can name a cause.
|
||||
package acts
|
||||
|
||||
// Cause is why an act was recorded: the closed list core.acts.cause holds.
|
||||
// The constants mirror chk_acts_cause, chk_plan_act_details_cause and
|
||||
// chk_lifecycle_requests_act_cause, and a test compares them with the
|
||||
// constraints' definitions.
|
||||
type Cause string
|
||||
|
||||
// The causes of the plan acts. A tier delete and a tier removal are both
|
||||
// TierRemoved; the detail's disposition is NULL when no organization held
|
||||
// the tier.
|
||||
const (
|
||||
TierAdded Cause = "tier_added"
|
||||
TierRemoved Cause = "tier_removed"
|
||||
TiersReordered Cause = "tiers_reordered"
|
||||
OrgTypeDefaultChanged Cause = "org_type_default_changed"
|
||||
PlanActRetried Cause = "plan_act_retried"
|
||||
)
|
||||
|
||||
// The causes of the lifecycle acts.
|
||||
const (
|
||||
InstancesSwapped Cause = "instances_swapped"
|
||||
)
|
||||
|
||||
// PlanCauses lists the causes of the plan acts, the ones a plan act detail
|
||||
// row may carry.
|
||||
var PlanCauses = []Cause{
|
||||
TierAdded,
|
||||
TierRemoved,
|
||||
TiersReordered,
|
||||
OrgTypeDefaultChanged,
|
||||
PlanActRetried,
|
||||
}
|
||||
|
||||
// LifecycleCauses lists the causes of the lifecycle acts, the ones a
|
||||
// lifecycle request may link to.
|
||||
var LifecycleCauses = []Cause{
|
||||
InstancesSwapped,
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
||||
// SPDX-FileCopyrightText: 2025-2026 Christian Galo
|
||||
|
||||
package acts_test
|
||||
|
||||
// The Go causes mirror the constraints that list them (openspec changes
|
||||
// plan-act-obligations design D26 and lifecycle-request-acts design D5): a
|
||||
// cause added on one side only fails here.
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"regexp"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/acts"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/testkit/dbtest"
|
||||
)
|
||||
|
||||
var quoted = regexp.MustCompile(`'([^']*)'`)
|
||||
|
||||
func names(causes []acts.Cause) []string {
|
||||
var out []string
|
||||
for _, c := range causes {
|
||||
out = append(out, string(c))
|
||||
}
|
||||
slices.Sort(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// TestActCausesMirrorTheConstraints reads each constraint's definition from a
|
||||
// migrated database and requires it to list exactly the Go causes it should.
|
||||
func TestActCausesMirrorTheConstraints(t *testing.T) {
|
||||
q := dbtest.On(t, dbtest.Open(t))
|
||||
all := slices.Concat(acts.PlanCauses, acts.LifecycleCauses)
|
||||
for _, c := range []struct {
|
||||
table, constraint string
|
||||
want []acts.Cause
|
||||
}{
|
||||
{"acts", "chk_acts_cause", all},
|
||||
{"plan_act_details", "chk_plan_act_details_cause", acts.PlanCauses},
|
||||
{"lifecycle_requests", "chk_lifecycle_requests_act_cause", acts.LifecycleCauses},
|
||||
} {
|
||||
t.Run(c.constraint, func(t *testing.T) {
|
||||
def := q.String(`SELECT pg_get_constraintdef(con.oid) FROM pg_constraint con
|
||||
WHERE con.conrelid = ('core.' || $1)::regclass AND con.conname = $2`, c.table, c.constraint)
|
||||
var got []string
|
||||
for _, m := range quoted.FindAllStringSubmatch(def, -1) {
|
||||
got = append(got, m[1])
|
||||
}
|
||||
slices.Sort(got)
|
||||
if want := names(c.want); !slices.Equal(got, want) {
|
||||
t.Errorf("%s lists %v, the Go causes are %v\n%s", c.constraint, got, want, def)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestLifecycleActWriterRefusesEveryPlanCause calls core.record_lifecycle_act
|
||||
// with each plan cause: its CASE refuses before it reads a row, so the
|
||||
// function and chk_lifecycle_requests_act_cause cannot drift apart.
|
||||
func TestLifecycleActWriterRefusesEveryPlanCause(t *testing.T) {
|
||||
q := dbtest.Tx(t, dbtest.Open(t))
|
||||
for _, cause := range acts.PlanCauses {
|
||||
err := q.Attempt(`SELECT core.record_lifecycle_act($1, 'person', NULL, NULL, NULL, NULL, NULL::uuid[])`, string(cause))
|
||||
dbtest.WantPgError(t, err, dbtest.SQLStateInvalidParameter, "")
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Message != "lifecycle_act_not_a_lifecycle_cause" {
|
||||
t.Errorf("%s refused with %q, want lifecycle_act_not_a_lifecycle_cause", cause, pgErr.Message)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -228,6 +228,36 @@ func TestRecordPlanActIgnoresACallersTemporaryTables(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
// core.record_lifecycle_act reads and writes the real core tables through its
|
||||
// pinned search_path: a temporary table named lifecycle_requests or acts that
|
||||
// shadows the real one is not written.
|
||||
func TestRecordLifecycleActIgnoresACallersTemporaryTables(t *testing.T) {
|
||||
q := dbtest.Tx(t, dbtest.Open(t))
|
||||
tx := q.Tx()
|
||||
f := newLifecycleActFixture(t, q)
|
||||
asked, consequent := f.pair(q)
|
||||
|
||||
asRole(t, tx, db.RuntimeGroupRole, func() {
|
||||
q.Exec(`CREATE TEMPORARY TABLE lifecycle_requests (LIKE core.lifecycle_requests INCLUDING DEFAULTS) ON COMMIT DROP`)
|
||||
q.Exec(`CREATE TEMPORARY TABLE acts (LIKE core.acts INCLUDING DEFAULTS) ON COMMIT DROP`)
|
||||
q.Exec(`GRANT ALL ON pg_temp.lifecycle_requests, pg_temp.acts TO PUBLIC`)
|
||||
q.Exec(`SET LOCAL search_path = pg_temp, core`)
|
||||
actID := q.String(recordSwap, f.person, nil, asked, arrayLiteral(consequent))
|
||||
|
||||
var shadowRequests, shadowActs, realLinked, realActs int
|
||||
q.Scan([]any{&shadowRequests}, `SELECT COUNT(*) FROM pg_temp.lifecycle_requests`)
|
||||
q.Scan([]any{&shadowActs}, `SELECT COUNT(*) FROM pg_temp.acts`)
|
||||
q.Scan([]any{&realLinked}, `SELECT COUNT(*) FROM core.lifecycle_requests WHERE act_id = $1`, actID)
|
||||
q.Scan([]any{&realActs}, `SELECT COUNT(*) FROM core.acts WHERE act_id = $1`, actID)
|
||||
if shadowRequests != 0 || shadowActs != 0 {
|
||||
t.Errorf("the caller's temporary tables captured %d requests and %d acts, want none", shadowRequests, shadowActs)
|
||||
}
|
||||
if realLinked != 2 || realActs != 1 {
|
||||
t.Errorf("core holds %d linked requests and %d acts of the call, want 2 and 1", realLinked, realActs)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// core_reader, which every integration's writer role holds, reads every
|
||||
// column of the act record but the note.
|
||||
func TestCoreReaderCannotReadAnActsNote(t *testing.T) {
|
||||
@@ -283,6 +313,8 @@ func TestActConstraints(t *testing.T) {
|
||||
// A person's act may carry a note, and a system act none.
|
||||
q.Exec(insert, "tier_added", "person", f.person, nil, "a note")
|
||||
q.Exec(insert, "tier_added", "system", nil, nil, nil)
|
||||
// A lifecycle cause is a cause of the header.
|
||||
q.Exec(insert, "instances_swapped", "person", f.person, nil, nil)
|
||||
}
|
||||
|
||||
func TestPlanActDetailConstraints(t *testing.T) {
|
||||
@@ -301,6 +333,9 @@ func TestPlanActDetailConstraints(t *testing.T) {
|
||||
added, "tier_removed", ladder, "Main", product, "Basic", nil, nil, nil, nil, nil, nil, nil, nil)
|
||||
q.Refuse(dbtest.SQLStateCheck, "chk_plan_act_details_cause", insert,
|
||||
added, "tier_painted", ladder, "Main", product, "Basic", nil, nil, nil, nil, nil, nil, nil, nil)
|
||||
// A lifecycle act has no detail row.
|
||||
q.Refuse(dbtest.SQLStateCheck, "chk_plan_act_details_cause", insert,
|
||||
insertAct(q, "instances_swapped"), "instances_swapped", ladder, "Main", product, "Basic", nil, nil, nil, nil, nil, nil, nil, nil)
|
||||
q.Refuse(dbtest.SQLStateForeignKey, "plan_act_detail_is_its_act", insert,
|
||||
uuid.NewString(), "tier_added", ladder, "Main", product, "Basic", nil, nil, nil, nil, nil, nil, nil, nil)
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ package db_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
@@ -216,9 +217,10 @@ func TestDeliveryTablePrivileges(t *testing.T) {
|
||||
person := fxPerson(t, tx)
|
||||
workspace := fxWorkspace(t, tx, fxOrg(t, tx, person))
|
||||
|
||||
// core_writer holds every write on the five ordinary delivery tables;
|
||||
// the outbox and the cut-offs are enclosures, tested above.
|
||||
for _, table := range []string{"desired_state_records", "lifecycle_requests", "observed_projections",
|
||||
// core_writer holds every write on four of the ordinary delivery tables;
|
||||
// the outbox and the cut-offs are enclosures, tested above, and
|
||||
// core.lifecycle_requests is enclosed by column below.
|
||||
for _, table := range []string{"desired_state_records", "observed_projections",
|
||||
"provider_connections", "target_mappings"} {
|
||||
for _, privilege := range []string{"SELECT", "INSERT", "UPDATE", "DELETE"} {
|
||||
var held bool
|
||||
@@ -229,6 +231,30 @@ func TestDeliveryTablePrivileges(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// core_writer keeps SELECT and DELETE on the lifecycle requests and holds
|
||||
// INSERT and UPDATE by column: the nine columns the recording names and
|
||||
// the four the outcome and the dismissal set. No grant names an act
|
||||
// column, updated_at or an identity of the request.
|
||||
for _, privilege := range []string{"SELECT", "DELETE"} {
|
||||
if !queryBool(q, `SELECT has_table_privilege('core_writer', 'core.lifecycle_requests', $1)`, privilege) {
|
||||
t.Errorf("core_writer lacks %s on core.lifecycle_requests", privilege)
|
||||
}
|
||||
}
|
||||
for _, privilege := range []string{"INSERT", "UPDATE"} {
|
||||
if queryBool(q, `SELECT has_table_privilege('core_writer', 'core.lifecycle_requests', $1)`, privilege) {
|
||||
t.Errorf("core_writer holds %s on the whole of core.lifecycle_requests, want columns only", privilege)
|
||||
}
|
||||
}
|
||||
for _, column := range q.Strings(`SELECT attname::text FROM pg_attribute
|
||||
WHERE attrelid = 'core.lifecycle_requests'::regclass AND attnum > 0 AND NOT attisdropped ORDER BY attnum`) {
|
||||
for privilege, columns := range map[string][]string{"INSERT": lifecycleInsertColumns, "UPDATE": lifecycleUpdateColumns} {
|
||||
got := queryBool(q, `SELECT has_column_privilege('core_writer', 'core.lifecycle_requests', $1, $2)`, column, privilege)
|
||||
if want := slices.Contains(columns, column); got != want {
|
||||
t.Errorf("core_writer holds %s on core.lifecycle_requests.%s = %v, want %v", privilege, column, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The runtime group role writes the ordinary delivery tables.
|
||||
asRole(t, tx, db.RuntimeGroupRole, func() {
|
||||
var requestID string
|
||||
@@ -239,6 +265,18 @@ func TestDeliveryTablePrivileges(t *testing.T) {
|
||||
q.Exec(
|
||||
`UPDATE core.lifecycle_requests SET status = 'succeeded', finished_at = NOW() WHERE request_id = $1`, requestID)
|
||||
q.Exec(`DELETE FROM core.lifecycle_requests WHERE request_id = $1`, requestID)
|
||||
|
||||
// An act column is written by core.record_lifecycle_act alone, and
|
||||
// the identity of a request is never updated.
|
||||
for _, column := range []string{"act_id", "act_cause", "act_role"} {
|
||||
q.Refuse(dbtest.SQLStatePrivilege, "",
|
||||
`INSERT INTO core.lifecycle_requests (instance_id, generation, connection_id, resource_key, workspace_id, operation, workflow_id, `+column+`)
|
||||
VALUES (uuidv7(), 1, $1, $2, $3, 'create', 'wf', NULL)`, connectionID, key, workspace)
|
||||
q.Refuse(dbtest.SQLStatePrivilege, "", `UPDATE core.lifecycle_requests SET `+column+` = NULL WHERE FALSE`)
|
||||
}
|
||||
for _, column := range []string{"workspace_id", "connection_id", "operation", "requested_by_person_id", "updated_at"} {
|
||||
q.Refuse(dbtest.SQLStatePrivilege, "", `UPDATE core.lifecycle_requests SET `+column+` = `+column+` WHERE FALSE`)
|
||||
}
|
||||
for _, table := range deliveryTables {
|
||||
q.Exec(`SELECT * FROM core.` + table + ` LIMIT 1`)
|
||||
}
|
||||
@@ -260,6 +298,22 @@ func TestDeliveryTablePrivileges(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func queryBool(q *dbtest.Q, query string, args ...any) bool {
|
||||
var b bool
|
||||
q.Scan([]any{&b}, query, args...)
|
||||
return b
|
||||
}
|
||||
|
||||
// lifecycleInsertColumns are the columns of core.lifecycle_requests the
|
||||
// writer inserts, the ones InsertLifecycleRequest names, and
|
||||
// lifecycleUpdateColumns the ones it updates, the ones FinishLifecycleRequest
|
||||
// and AcknowledgeLifecycleRequest set.
|
||||
var (
|
||||
lifecycleInsertColumns = []string{"instance_id", "generation", "connection_id", "resource_key", "workspace_id",
|
||||
"operation", "parameters", "workflow_id", "requested_by_person_id"}
|
||||
lifecycleUpdateColumns = []string{"status", "reason_code", "finished_at", "acknowledged_at"}
|
||||
)
|
||||
|
||||
// deliveryKeys names each delivery table's primary key column.
|
||||
var deliveryKeys = map[string]string{
|
||||
"desired_state_outbox": "id",
|
||||
|
||||
@@ -218,7 +218,17 @@ func commentByName(t *testing.T, ctx context.Context, database *sql.DB, line str
|
||||
if err := database.QueryRowContext(ctx, `SELECT $1::oid::regclass::text`, parts[2]).Scan(&name); err != nil {
|
||||
t.Fatalf("name the commented relation %s: %v", parts[2], err)
|
||||
}
|
||||
return "comment " + name + " " + parts[3] + " " + parts[4]
|
||||
// A column's comment is keyed by its number, which a dropped and
|
||||
// re-added column does not keep; name the column instead.
|
||||
column := parts[3]
|
||||
if column != "0" {
|
||||
if err := database.QueryRowContext(ctx,
|
||||
`SELECT attname::text FROM pg_attribute WHERE attrelid = $1::oid AND attnum = $2::int`,
|
||||
parts[2], parts[3]).Scan(&column); err != nil {
|
||||
t.Fatalf("name the commented column %s of %s: %v", parts[3], name, err)
|
||||
}
|
||||
}
|
||||
return "comment " + name + " " + column + " " + parts[4]
|
||||
}
|
||||
|
||||
// snapshotDiff names the lines only one of two snapshots holds.
|
||||
|
||||
@@ -0,0 +1,391 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
||||
// SPDX-FileCopyrightText: 2025-2026 Christian Galo
|
||||
|
||||
package db_test
|
||||
|
||||
// Migration 00041 (openspec change lifecycle-request-acts, tasks 1.2 to 1.9):
|
||||
// the three act columns of core.lifecycle_requests, the cause of a lifecycle
|
||||
// act in core.acts, core.record_lifecycle_act and the Down that refuses once
|
||||
// an act exists. The constraint tests write the rows directly, as the
|
||||
// superuser would: the constraints are the subject, and the function that
|
||||
// links the rows would refuse some of these shapes before a constraint saw
|
||||
// them. The function's tests insert their requests at the top level of the
|
||||
// test transaction, because the function reads the transaction's id, and call
|
||||
// it under Refuse, whose savepoint ends only the call.
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io/fs"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/db"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/testkit/dbtest"
|
||||
)
|
||||
|
||||
const (
|
||||
lifecycleActsVersion = 41
|
||||
lifecycleActsPrevious = 40
|
||||
|
||||
// recordSwap calls core.record_lifecycle_act for a swap: $1 the actor,
|
||||
// $2 the correlation id, $3 the asked request, $4 the consequent
|
||||
// requests as an array literal.
|
||||
recordSwap = `SELECT core.record_lifecycle_act('instances_swapped', 'person', $1, NULL, $2, $3, $4::uuid[])`
|
||||
)
|
||||
|
||||
// lifecycleActFixture is the rows a request needs: two workspaces and two
|
||||
// connections, one to each of two providers, and two people.
|
||||
type lifecycleActFixture struct {
|
||||
person, stranger, workspace, otherWorkspace, connection, otherConnection, key string
|
||||
}
|
||||
|
||||
func newLifecycleActFixture(t *testing.T, q *dbtest.Q) lifecycleActFixture {
|
||||
t.Helper()
|
||||
tx := q.Tx()
|
||||
person := fxPerson(t, tx)
|
||||
org := fxOrg(t, tx, person)
|
||||
provider := fxProvider(t, tx)
|
||||
otherProvider := fxProvider(t, tx)
|
||||
return lifecycleActFixture{
|
||||
person: person,
|
||||
stranger: fxPerson(t, tx),
|
||||
workspace: fxWorkspace(t, tx, org),
|
||||
otherWorkspace: fxWorkspace(t, tx, org),
|
||||
connection: fxConnection(t, tx, provider, true),
|
||||
otherConnection: fxConnection(t, tx, otherProvider, true),
|
||||
key: fxKey(t, tx, provider, "numeric", "organization"),
|
||||
}
|
||||
}
|
||||
|
||||
// requestSpec is one request; an empty field takes its default.
|
||||
type requestSpec struct {
|
||||
workspace, connection, operation string
|
||||
person string // empty: names no one
|
||||
actID, actCause, actRole string // empty: NULL
|
||||
}
|
||||
|
||||
func orNull(s string) any {
|
||||
if s == "" {
|
||||
return nil
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// request inserts one accepted request on a new instance and returns its id.
|
||||
func (f lifecycleActFixture) request(q *dbtest.Q, s requestSpec) string {
|
||||
q.Tx() // fails the test when q does not run on a transaction
|
||||
if s.workspace == "" {
|
||||
s.workspace = f.workspace
|
||||
}
|
||||
if s.connection == "" {
|
||||
s.connection = f.connection
|
||||
}
|
||||
if s.operation == "" {
|
||||
s.operation = "set_status"
|
||||
}
|
||||
return q.ID(`INSERT INTO core.lifecycle_requests
|
||||
(instance_id, generation, connection_id, resource_key, workspace_id, operation, workflow_id,
|
||||
requested_by_person_id, act_id, act_cause, act_role)
|
||||
VALUES (uuidv7(), 1, $1, $2, $3, $4, 'wf', $5, $6, $7, $8) RETURNING request_id`,
|
||||
s.connection, f.key, s.workspace, s.operation, orNull(s.person),
|
||||
orNull(s.actID), orNull(s.actCause), orNull(s.actRole))
|
||||
}
|
||||
|
||||
// pair inserts the asked request of the member and the consequent request of
|
||||
// the console that a swap records.
|
||||
func (f lifecycleActFixture) pair(q *dbtest.Q) (asked, consequent string) {
|
||||
return f.request(q, requestSpec{person: f.person}), f.request(q, requestSpec{})
|
||||
}
|
||||
|
||||
func arrayLiteral(ids ...string) string { return "{" + strings.Join(ids, ",") + "}" }
|
||||
|
||||
// requireRefusal requires the statement to fail with the function's own
|
||||
// message, which names the rule it broke.
|
||||
func requireRefusal(t *testing.T, q *dbtest.Q, message, query string, args ...any) {
|
||||
t.Helper()
|
||||
err := q.Attempt(query, args...)
|
||||
dbtest.WantPgError(t, err, dbtest.SQLStateInvalidParameter, "")
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Message != message {
|
||||
t.Errorf("refused with %q, want %q", pgErr.Message, message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLifecycleRequestActConstraints(t *testing.T) {
|
||||
q := dbtest.Tx(t, dbtest.Open(t))
|
||||
f := newLifecycleActFixture(t, q)
|
||||
swap := insertAct(q, "instances_swapped")
|
||||
plan := insertAct(q, "tier_added")
|
||||
|
||||
// A row that breaks exactly one rule is refused with that rule's name.
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
spec requestSpec
|
||||
sqlstate string
|
||||
constraint string
|
||||
}{
|
||||
{"an act id with no cause and no role", requestSpec{actID: swap},
|
||||
dbtest.SQLStateCheck, "lifecycle_request_act_shape"},
|
||||
{"an act id with a cause and no role", requestSpec{actID: swap, actCause: "instances_swapped"},
|
||||
dbtest.SQLStateCheck, "lifecycle_request_act_shape"},
|
||||
{"a role with no act", requestSpec{actRole: "asked"},
|
||||
dbtest.SQLStateCheck, "lifecycle_request_act_shape"},
|
||||
{"a plan cause with a real plan act's id, which the foreign key alone accepts",
|
||||
requestSpec{actID: plan, actCause: "tier_added", actRole: "asked"},
|
||||
dbtest.SQLStateCheck, "chk_lifecycle_requests_act_cause"},
|
||||
{"a cause that does not match the act's",
|
||||
requestSpec{actID: plan, actCause: "instances_swapped", actRole: "asked"},
|
||||
dbtest.SQLStateForeignKey, "lifecycle_request_in_its_act"},
|
||||
{"a role outside the two",
|
||||
requestSpec{actID: swap, actCause: "instances_swapped", actRole: "bystander"},
|
||||
dbtest.SQLStateCheck, "chk_lifecycle_requests_act_role"},
|
||||
{"a consequent request that names a person",
|
||||
requestSpec{person: f.person, actID: swap, actCause: "instances_swapped", actRole: "consequent"},
|
||||
dbtest.SQLStateCheck, "lifecycle_request_consequent_names_no_person"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
q := dbtest.On(t, q.Tx())
|
||||
spec := tc.spec
|
||||
spec.workspace, spec.connection, spec.operation = f.workspace, f.connection, "set_status"
|
||||
q.Refuse(tc.sqlstate, tc.constraint, `INSERT INTO core.lifecycle_requests
|
||||
(instance_id, generation, connection_id, resource_key, workspace_id, operation, workflow_id,
|
||||
requested_by_person_id, act_id, act_cause, act_role)
|
||||
VALUES (uuidv7(), 1, $1, $2, $3, $4, 'wf', $5, $6, $7, $8)`,
|
||||
spec.connection, f.key, spec.workspace, spec.operation, orNull(spec.person),
|
||||
orNull(spec.actID), orNull(spec.actCause), orNull(spec.actRole))
|
||||
})
|
||||
}
|
||||
|
||||
// The rows it accepts: no link at all, and an asked and a consequent
|
||||
// request of one swap header.
|
||||
f.request(q, requestSpec{})
|
||||
f.request(q, requestSpec{person: f.person})
|
||||
f.request(q, requestSpec{person: f.person, actID: swap, actCause: "instances_swapped", actRole: "asked"})
|
||||
f.request(q, requestSpec{actID: swap, actCause: "instances_swapped", actRole: "consequent"})
|
||||
|
||||
// Two asked requests in one act.
|
||||
q.Refuse(dbtest.SQLStateUnique, "uq_lifecycle_requests_one_asked",
|
||||
`INSERT INTO core.lifecycle_requests
|
||||
(instance_id, generation, connection_id, resource_key, workspace_id, operation, workflow_id, act_id, act_cause, act_role)
|
||||
VALUES (uuidv7(), 1, $1, $2, $3, 'set_status', 'wf', $4, 'instances_swapped', 'asked')`,
|
||||
f.connection, f.key, f.workspace, swap)
|
||||
}
|
||||
|
||||
func TestRecordLifecycleActLinksItsOwnRows(t *testing.T) {
|
||||
q := dbtest.Tx(t, dbtest.Open(t))
|
||||
f := newLifecycleActFixture(t, q)
|
||||
asked, consequent := f.pair(q)
|
||||
|
||||
actID := q.String(recordSwap, f.person, "req-1", asked, arrayLiteral(consequent))
|
||||
|
||||
for id, role := range map[string]string{asked: "asked", consequent: "consequent"} {
|
||||
var gotAct, gotCause, gotRole string
|
||||
q.Scan([]any{&gotAct, &gotCause, &gotRole},
|
||||
`SELECT act_id::text, act_cause, act_role FROM core.lifecycle_requests WHERE request_id = $1`, id)
|
||||
if gotAct != actID || gotCause != "instances_swapped" || gotRole != role {
|
||||
t.Errorf("request %s carries act %s, cause %s, role %s; want %s, instances_swapped, %s",
|
||||
id, gotAct, gotCause, gotRole, actID, role)
|
||||
}
|
||||
}
|
||||
|
||||
var cause, actorType, actor, requestID string
|
||||
var noNote, atAsked bool
|
||||
q.Scan([]any{&cause, &actorType, &actor, &requestID, &noNote, &atAsked},
|
||||
`SELECT a.cause, a.actor_type, a.actor_person_id::text, a.request_id, a.note IS NULL,
|
||||
a.effective_at = (SELECT created_at FROM core.lifecycle_requests WHERE request_id = $2)
|
||||
FROM core.acts a WHERE a.act_id = $1`, actID, asked)
|
||||
if cause != "instances_swapped" || actorType != "person" || actor != f.person || requestID != "req-1" || !noNote || !atAsked {
|
||||
t.Errorf("the header is cause %s, actor %s %s, request id %s, note NULL %v, effective at the asked request %v; want instances_swapped, person %s, req-1, true, true",
|
||||
cause, actorType, actor, requestID, noNote, atAsked, f.person)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordLifecycleActStoresARequestIDOnlyWhenItFits(t *testing.T) {
|
||||
q := dbtest.Tx(t, dbtest.Open(t))
|
||||
f := newLifecycleActFixture(t, q)
|
||||
|
||||
for _, tc := range []struct{ name, id, want string }{
|
||||
{"short", "req-short", "req-short"},
|
||||
{"at the limit", strings.Repeat("a", 100), strings.Repeat("a", 100)},
|
||||
{"one over", strings.Repeat("a", 101), ""},
|
||||
{"none", "", ""},
|
||||
} {
|
||||
asked, consequent := f.pair(q)
|
||||
actID := q.String(recordSwap, f.person, orNull(tc.id), asked, arrayLiteral(consequent))
|
||||
if got := q.String(`SELECT coalesce(request_id, '') FROM core.acts WHERE act_id = $1`, actID); got != tc.want {
|
||||
t.Errorf("%s: stored request id %q, want %q", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordLifecycleActRefusals(t *testing.T) {
|
||||
q := dbtest.Tx(t, dbtest.Open(t))
|
||||
f := newLifecycleActFixture(t, q)
|
||||
other := insertAct(q, "instances_swapped")
|
||||
|
||||
// Every row is inserted before the first refusal: Attempt leaves its
|
||||
// savepoint open, and a row inserted under one carries the
|
||||
// subtransaction's id, which the function's step 3 would refuse first.
|
||||
type refusal struct {
|
||||
name, message, cause string
|
||||
asked string
|
||||
consequent any
|
||||
}
|
||||
var cases []refusal
|
||||
add := func(name, message, asked string, consequent any) {
|
||||
cases = append(cases, refusal{name, message, "instances_swapped", asked, consequent})
|
||||
}
|
||||
|
||||
// Every plan cause: the CASE's ELSE.
|
||||
for _, cause := range []string{"tier_added", "tier_removed", "tiers_reordered", "org_type_default_changed", "plan_act_retried"} {
|
||||
asked, consequent := f.pair(q)
|
||||
cases = append(cases, refusal{"the plan cause " + cause, "lifecycle_act_not_a_lifecycle_cause", cause, asked, arrayLiteral(consequent)})
|
||||
}
|
||||
|
||||
asked, consequent := f.pair(q)
|
||||
add("no consequent request", "lifecycle_act_swap_shape", asked, "{}")
|
||||
add("a NULL consequent array", "lifecycle_act_swap_shape", asked, nil)
|
||||
add("two consequent requests", "lifecycle_act_swap_shape", asked, arrayLiteral(consequent, f.request(q, requestSpec{})))
|
||||
|
||||
add("a consequent request whose operation is not set_status", "lifecycle_act_request_not_set_status",
|
||||
f.request(q, requestSpec{person: f.person}), arrayLiteral(f.request(q, requestSpec{operation: "delete"})))
|
||||
add("an asked request whose operation is not set_status", "lifecycle_act_request_not_set_status",
|
||||
f.request(q, requestSpec{operation: "create", person: f.person}), arrayLiteral(f.request(q, requestSpec{})))
|
||||
|
||||
add("an asked request that names no person", "lifecycle_act_asked_person",
|
||||
f.request(q, requestSpec{}), arrayLiteral(f.request(q, requestSpec{})))
|
||||
add("an asked request that names another person", "lifecycle_act_asked_person",
|
||||
f.request(q, requestSpec{person: f.stranger}), arrayLiteral(f.request(q, requestSpec{})))
|
||||
add("a consequent request that names a person", "lifecycle_act_consequent_names_a_person",
|
||||
f.request(q, requestSpec{person: f.person}), arrayLiteral(f.request(q, requestSpec{person: f.stranger})))
|
||||
|
||||
repeated := f.request(q, requestSpec{person: f.person})
|
||||
add("a repeated id", "lifecycle_act_request_repeated", repeated, arrayLiteral(repeated))
|
||||
add("an id with no row", "lifecycle_act_request_missing",
|
||||
f.request(q, requestSpec{person: f.person}), arrayLiteral(uuid.NewString()))
|
||||
|
||||
asked, consequent = f.pair(q)
|
||||
q.Exec(`UPDATE core.lifecycle_requests SET status = 'declined', finished_at = NOW() WHERE request_id = $1`, consequent)
|
||||
add("a request that is not accepted", "lifecycle_act_request_not_accepted", asked, arrayLiteral(consequent))
|
||||
|
||||
add("a request that already carries a link", "lifecycle_act_request_linked",
|
||||
f.request(q, requestSpec{person: f.person}),
|
||||
arrayLiteral(f.request(q, requestSpec{actID: other, actCause: "instances_swapped", actRole: "consequent"})))
|
||||
|
||||
add("two requests of different workspaces", "lifecycle_act_requests_differ",
|
||||
f.request(q, requestSpec{person: f.person}), arrayLiteral(f.request(q, requestSpec{workspace: f.otherWorkspace})))
|
||||
add("two requests of different connections", "lifecycle_act_requests_differ",
|
||||
f.request(q, requestSpec{person: f.person}), arrayLiteral(f.request(q, requestSpec{connection: f.otherConnection})))
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
q := dbtest.On(t, q.Tx())
|
||||
requireRefusal(t, q, tc.message,
|
||||
`SELECT core.record_lifecycle_act($1, 'person', $2, NULL, NULL, $3, $4::uuid[])`,
|
||||
tc.cause, f.person, tc.asked, tc.consequent)
|
||||
})
|
||||
}
|
||||
|
||||
if n := q.Int(`SELECT count(*) FROM core.acts WHERE actor_person_id = $1`, f.person); n != 0 {
|
||||
t.Errorf("%d acts of the member were recorded by refused calls, want none", n)
|
||||
}
|
||||
}
|
||||
|
||||
// A request that an earlier transaction inserted is refused, and so is one an
|
||||
// earlier transaction inserted and this one only updated, whose xmin passes
|
||||
// the first half of the test and whose created_at does not (design D2 step 3).
|
||||
func TestRecordLifecycleActRefusesRequestsOfAnEarlierTransaction(t *testing.T) {
|
||||
scratch := dbtest.Connect(t, dbtest.Scratch(t))
|
||||
dbtest.UpTo(t, scratch, db.BaseSources()[0], lifecycleActsVersion)
|
||||
|
||||
tx, err := scratch.BeginTx(t.Context(), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
seed := dbtest.On(t, tx)
|
||||
f := newLifecycleActFixture(t, seed)
|
||||
asked, consequent := f.pair(seed)
|
||||
if err := tx.Commit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// The rows come from a committed transaction: their xmin differs.
|
||||
requireRefusal(t, dbtest.Tx(t, scratch), "lifecycle_act_request_not_current", recordSwap, f.person, nil, asked, arrayLiteral(consequent))
|
||||
|
||||
// Updated here first, so the call is the first savepoint of its
|
||||
// transaction and the update ran at the top level.
|
||||
q := dbtest.Tx(t, scratch)
|
||||
q.Exec(`UPDATE core.lifecycle_requests SET parameters = '{"touched": true}' WHERE request_id IN ($1, $2)`, asked, consequent)
|
||||
if q.String(`SELECT bool_and(xmin = pg_current_xact_id()::xid)::text FROM core.lifecycle_requests WHERE request_id IN ($1, $2)`, asked, consequent) != "true" {
|
||||
t.Fatal("the update did not give the rows this transaction's xmin")
|
||||
}
|
||||
requireRefusal(t, q, "lifecycle_act_request_not_current", recordSwap, f.person, nil, asked, arrayLiteral(consequent))
|
||||
}
|
||||
|
||||
// A request inserted under a savepoint has this transaction's created_at and
|
||||
// a subtransaction's xmin: only the first half of step 3 refuses it.
|
||||
func TestRecordLifecycleActRefusesRequestsInsertedUnderASavepoint(t *testing.T) {
|
||||
q := dbtest.Tx(t, dbtest.Open(t))
|
||||
f := newLifecycleActFixture(t, q)
|
||||
q.Exec(`SAVEPOINT lifecycle_rows`)
|
||||
asked, consequent := f.pair(q)
|
||||
q.Exec(`RELEASE SAVEPOINT lifecycle_rows`)
|
||||
requireRefusal(t, q, "lifecycle_act_request_not_current", recordSwap, f.person, nil, asked, arrayLiteral(consequent))
|
||||
}
|
||||
|
||||
func TestLifecycleRequestActsMigrationUpDownUp(t *testing.T) {
|
||||
requireMigrationUpDownUp(t, lifecycleActsPrevious, lifecycleActsVersion)
|
||||
}
|
||||
|
||||
// The Down refuses once a lifecycle act exists, names how many, and changes
|
||||
// nothing.
|
||||
func TestLifecycleRequestActsDownRefusesAnExistingAct(t *testing.T) {
|
||||
dsn := dbtest.Scratch(t)
|
||||
scratch := dbtest.Connect(t, dsn)
|
||||
core := db.BaseSources()[0]
|
||||
dbtest.UpTo(t, scratch, core, lifecycleActsVersion)
|
||||
|
||||
tx, err := scratch.BeginTx(t.Context(), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
seed := dbtest.On(t, tx)
|
||||
f := newLifecycleActFixture(t, seed)
|
||||
asked, consequent := f.pair(seed)
|
||||
seed.String(recordSwap, f.person, "req-1", asked, arrayLiteral(consequent))
|
||||
if err := tx.Commit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before := schemaSnapshot(t, t.Context(), scratch)
|
||||
|
||||
raw, err := fs.ReadFile(core.Migrations, core.Dir+"/00041_lifecycle_request_acts.sql")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, down, _ := strings.Cut(string(raw), "-- +goose Down")
|
||||
simple := dbtest.Connect(t, dbtest.SimpleProtocol(dsn))
|
||||
_, err = simple.ExecContext(t.Context(), down)
|
||||
dbtest.WantPgError(t, err, "55000", "")
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && (pgErr.Message != "lifecycle_acts_exist" || !strings.HasPrefix(pgErr.Detail, "1 ")) {
|
||||
t.Errorf("refused with %q (%s), want lifecycle_acts_exist naming 1 act", pgErr.Message, pgErr.Detail)
|
||||
}
|
||||
|
||||
if after := schemaSnapshot(t, t.Context(), scratch); !slices.Equal(before, after) {
|
||||
t.Errorf("the refused Down changed the schema:\n%s", snapshotDiff(before, after))
|
||||
}
|
||||
q := dbtest.On(t, scratch)
|
||||
if n := q.Int(`SELECT count(*) FROM information_schema.columns
|
||||
WHERE table_schema = 'core' AND table_name = 'lifecycle_requests' AND column_name IN ('act_id', 'act_cause', 'act_role')`); n != 3 {
|
||||
t.Errorf("%d act columns remain, want 3", n)
|
||||
}
|
||||
if n := q.Int(`SELECT count(*) FROM pg_constraint WHERE conrelid = 'core.lifecycle_requests'::regclass
|
||||
AND conname IN ('lifecycle_request_in_its_act', 'lifecycle_request_act_shape', 'chk_lifecycle_requests_act_cause',
|
||||
'chk_lifecycle_requests_act_role', 'lifecycle_request_consequent_names_no_person')`); n != 5 {
|
||||
t.Errorf("%d act constraints remain, want 5", n)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
-- SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
||||
-- SPDX-FileCopyrightText: 2025-2026 Christian Galo
|
||||
|
||||
-- +goose Up
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- A lifecycle act (openspec change lifecycle-request-acts, design D1-D4).
|
||||
-- The swap of a workspace's active site records two lifecycle requests, the
|
||||
-- one the member asked for and the one the console added as its consequence.
|
||||
-- core.acts gains the cause instances_swapped for the pair, and each request
|
||||
-- carries three nullable columns that tie it to its act: the act, the cause
|
||||
-- it states and its role. A composite foreign key on (act_id, cause) lets a
|
||||
-- request point only at an act of the cause it states, as 00027's detail
|
||||
-- table does, and a shape check keeps the three columns together, because
|
||||
-- MATCH SIMPLE skips a row with any NULL referencing column.
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
ALTER TABLE core.lifecycle_requests
|
||||
ADD COLUMN act_id UUID,
|
||||
ADD COLUMN act_cause VARCHAR(50),
|
||||
ADD COLUMN act_role VARCHAR(20);
|
||||
|
||||
ALTER TABLE core.lifecycle_requests
|
||||
ADD CONSTRAINT lifecycle_request_in_its_act FOREIGN KEY (act_id, act_cause) REFERENCES core.acts (act_id, cause),
|
||||
ADD CONSTRAINT lifecycle_request_act_shape CHECK (
|
||||
(act_id IS NULL) = (act_cause IS NULL) AND (act_id IS NULL) = (act_role IS NULL)),
|
||||
ADD CONSTRAINT chk_lifecycle_requests_act_cause CHECK (act_cause IN ('instances_swapped')),
|
||||
ADD CONSTRAINT chk_lifecycle_requests_act_role CHECK (act_role IN ('asked', 'consequent')),
|
||||
ADD CONSTRAINT lifecycle_request_consequent_names_no_person CHECK (
|
||||
act_role IS DISTINCT FROM 'consequent' OR requested_by_person_id IS NULL);
|
||||
|
||||
CREATE UNIQUE INDEX uq_lifecycle_requests_one_asked ON core.lifecycle_requests (act_id) WHERE act_role = 'asked';
|
||||
CREATE INDEX idx_lifecycle_requests_act_id ON core.lifecycle_requests (act_id) WHERE act_id IS NOT NULL;
|
||||
|
||||
COMMENT ON COLUMN core.lifecycle_requests.act_id IS
|
||||
'The act this request belongs to; NULL for a request that belongs to none.';
|
||||
COMMENT ON COLUMN core.lifecycle_requests.act_cause IS
|
||||
'The cause of the act, stated so the foreign key to core.acts holds the request to an act of that cause.';
|
||||
COMMENT ON COLUMN core.lifecycle_requests.act_role IS
|
||||
'asked for the request the person made, consequent for one the console added because of it.';
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- core.acts takes the lifecycle cause. core.plan_act_details keeps the five
|
||||
-- plan causes, because a lifecycle act has no detail row.
|
||||
-- ---------------------------------------------------------------------------
|
||||
ALTER TABLE core.acts
|
||||
DROP CONSTRAINT chk_acts_cause,
|
||||
ADD CONSTRAINT chk_acts_cause CHECK (cause IN (
|
||||
'tier_added', 'tier_removed', 'tiers_reordered', 'org_type_default_changed', 'plan_act_retried',
|
||||
'instances_swapped'));
|
||||
|
||||
COMMENT ON TABLE core.acts IS
|
||||
'One row per act: who acted, when, and why, from a closed list of causes. Written once by core.record_plan_act or core.record_lifecycle_act; nothing updates or deletes a row.';
|
||||
COMMENT ON TABLE core.lifecycle_requests IS
|
||||
'One request for one instance (create, change status, delete), addressed by the console''s instance identifier and a generation. It names the person whose action caused it, or no one for a consequent request.';
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- core.record_lifecycle_act: the only writer of a lifecycle act. The caller
|
||||
-- inserts the act's requests first and names them here; the function inserts
|
||||
-- the header and links the rows, so no caller holds INSERT or UPDATE on the
|
||||
-- act columns. It runs five steps:
|
||||
-- 1. the cause: a CASE holds each lifecycle cause's argument rules and its
|
||||
-- ELSE refuses, so a plan cause cannot get a header without its detail
|
||||
-- row or the rendezvous;
|
||||
-- 2. the rows: one read of the named rows, without a row lock, then the
|
||||
-- cause's rules for them (the operation, the person of each role);
|
||||
-- 3. inserted by this transaction: each row's xmin equals the
|
||||
-- transaction's id, as in core.requeue_plan_act_obligations, and its
|
||||
-- created_at equals transaction_timestamp(). The xmin alone is not
|
||||
-- exact for a request, because an UPDATE gives a row a new xmin; the
|
||||
-- column comes from its default, because core_writer holds no INSERT or
|
||||
-- UPDATE on it, so no older row passes both;
|
||||
-- 4. the header, with a NULL note, the request id kept only when it fits
|
||||
-- the column, and effective_at equal to the asked request's created_at;
|
||||
-- 5. the link: one UPDATE that sets the three columns WHERE act_id IS NULL,
|
||||
-- which raises when it changed fewer rows than the call named.
|
||||
-- No lifecycle recording runs inside a savepoint: a request inserted under
|
||||
-- one carries the subtransaction's id in its xmin, and pg_current_xact_id()
|
||||
-- returns the top-level transaction's, so the step 3 test would refuse it.
|
||||
-- The function takes no lock: the intake that calls it already holds the
|
||||
-- workspace lock, and no lifecycle act changes an entitlement, so it asserts
|
||||
-- no rendezvous.
|
||||
-- The table names are unqualified on purpose: the pinned search_path, core
|
||||
-- first and pg_temp last, keeps a caller's temporary table from shadowing
|
||||
-- them.
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION core.record_lifecycle_act(
|
||||
p_cause VARCHAR,
|
||||
p_actor_type VARCHAR,
|
||||
p_actor_person_id UUID,
|
||||
p_actor_service_account_id UUID,
|
||||
p_request_id VARCHAR,
|
||||
p_asked_lifecycle_request UUID,
|
||||
p_consequent_lifecycle_requests UUID[]
|
||||
) RETURNS UUID
|
||||
LANGUAGE plpgsql
|
||||
SECURITY DEFINER
|
||||
SET search_path = core, pg_temp
|
||||
AS $$
|
||||
DECLARE
|
||||
v_ids UUID[];
|
||||
v_named INTEGER;
|
||||
v_found INTEGER;
|
||||
v_workspaces INTEGER;
|
||||
v_connections INTEGER;
|
||||
v_not_accepted INTEGER;
|
||||
v_linked INTEGER;
|
||||
v_not_current INTEGER;
|
||||
v_not_status INTEGER;
|
||||
v_asked_ok BOOLEAN;
|
||||
v_consequent_named INTEGER;
|
||||
v_asked_at TIMESTAMPTZ;
|
||||
v_act_id UUID;
|
||||
v_linked_now INTEGER;
|
||||
BEGIN
|
||||
-- 1. The cause.
|
||||
CASE p_cause
|
||||
WHEN 'instances_swapped' THEN
|
||||
IF p_asked_lifecycle_request IS NULL
|
||||
OR p_consequent_lifecycle_requests IS NULL
|
||||
OR cardinality(p_consequent_lifecycle_requests) <> 1
|
||||
OR p_consequent_lifecycle_requests[1] IS NULL THEN
|
||||
RAISE EXCEPTION 'lifecycle_act_swap_shape'
|
||||
USING ERRCODE = '22023',
|
||||
DETAIL = 'a swap names one asked request and one consequent request';
|
||||
END IF;
|
||||
v_ids := array_prepend(p_asked_lifecycle_request, p_consequent_lifecycle_requests);
|
||||
ELSE
|
||||
RAISE EXCEPTION 'lifecycle_act_not_a_lifecycle_cause'
|
||||
USING ERRCODE = '22023',
|
||||
DETAIL = 'the cause is not one that records lifecycle requests';
|
||||
END CASE;
|
||||
|
||||
-- 2. The rows, read once.
|
||||
v_named := cardinality(v_ids);
|
||||
IF (SELECT count(DISTINCT i) FROM unnest(v_ids) AS i) <> v_named THEN
|
||||
RAISE EXCEPTION 'lifecycle_act_request_repeated'
|
||||
USING ERRCODE = '22023',
|
||||
DETAIL = 'a request is named twice';
|
||||
END IF;
|
||||
|
||||
SELECT count(*),
|
||||
count(DISTINCT r.workspace_id),
|
||||
count(DISTINCT r.connection_id),
|
||||
count(*) FILTER (WHERE r.status <> 'accepted'),
|
||||
count(*) FILTER (WHERE r.act_id IS NOT NULL),
|
||||
count(*) FILTER (WHERE r.xmin <> pg_current_xact_id()::xid OR r.created_at <> transaction_timestamp()),
|
||||
count(*) FILTER (WHERE r.operation <> 'set_status'),
|
||||
coalesce(bool_and(r.requested_by_person_id IS NOT DISTINCT FROM p_actor_person_id)
|
||||
FILTER (WHERE r.request_id = p_asked_lifecycle_request), FALSE),
|
||||
count(*) FILTER (WHERE r.request_id <> p_asked_lifecycle_request AND r.requested_by_person_id IS NOT NULL),
|
||||
max(r.created_at) FILTER (WHERE r.request_id = p_asked_lifecycle_request)
|
||||
INTO v_found, v_workspaces, v_connections, v_not_accepted, v_linked, v_not_current,
|
||||
v_not_status, v_asked_ok, v_consequent_named, v_asked_at
|
||||
FROM lifecycle_requests r
|
||||
WHERE r.request_id = ANY (v_ids);
|
||||
|
||||
IF v_found <> v_named THEN
|
||||
RAISE EXCEPTION 'lifecycle_act_request_missing'
|
||||
USING ERRCODE = '22023',
|
||||
DETAIL = 'a named request does not exist';
|
||||
END IF;
|
||||
IF v_not_accepted <> 0 THEN
|
||||
RAISE EXCEPTION 'lifecycle_act_request_not_accepted'
|
||||
USING ERRCODE = '22023',
|
||||
DETAIL = 'a named request is not accepted';
|
||||
END IF;
|
||||
IF v_linked <> 0 THEN
|
||||
RAISE EXCEPTION 'lifecycle_act_request_linked'
|
||||
USING ERRCODE = '22023',
|
||||
DETAIL = 'a named request already belongs to an act';
|
||||
END IF;
|
||||
IF v_workspaces <> 1 OR v_connections <> 1 THEN
|
||||
RAISE EXCEPTION 'lifecycle_act_requests_differ'
|
||||
USING ERRCODE = '22023',
|
||||
DETAIL = 'the named requests belong to more than one workspace or connection';
|
||||
END IF;
|
||||
|
||||
-- The cause's rules for the rows.
|
||||
CASE p_cause
|
||||
WHEN 'instances_swapped' THEN
|
||||
IF v_not_status <> 0 THEN
|
||||
RAISE EXCEPTION 'lifecycle_act_request_not_set_status'
|
||||
USING ERRCODE = '22023',
|
||||
DETAIL = 'a swap''s requests are all set_status';
|
||||
END IF;
|
||||
IF p_actor_person_id IS NULL OR NOT v_asked_ok THEN
|
||||
RAISE EXCEPTION 'lifecycle_act_asked_person'
|
||||
USING ERRCODE = '22023',
|
||||
DETAIL = 'the asked request names the actor as its person';
|
||||
END IF;
|
||||
IF v_consequent_named <> 0 THEN
|
||||
RAISE EXCEPTION 'lifecycle_act_consequent_names_a_person'
|
||||
USING ERRCODE = '22023',
|
||||
DETAIL = 'a consequent request names no person';
|
||||
END IF;
|
||||
END CASE;
|
||||
|
||||
-- 3. Inserted by this transaction.
|
||||
IF v_not_current <> 0 THEN
|
||||
RAISE EXCEPTION 'lifecycle_act_request_not_current'
|
||||
USING ERRCODE = '22023',
|
||||
DETAIL = 'a named request was not inserted by this transaction';
|
||||
END IF;
|
||||
|
||||
-- 4. The header.
|
||||
INSERT INTO acts (cause, actor_type, actor_person_id, actor_service_account_id, note, request_id, effective_at)
|
||||
VALUES (p_cause, p_actor_type, p_actor_person_id, p_actor_service_account_id, NULL,
|
||||
CASE WHEN char_length(p_request_id) <= 100 THEN p_request_id END, v_asked_at)
|
||||
RETURNING act_id INTO v_act_id;
|
||||
|
||||
-- 5. The link.
|
||||
UPDATE lifecycle_requests u
|
||||
SET act_id = v_act_id,
|
||||
act_cause = p_cause,
|
||||
act_role = CASE WHEN u.request_id = p_asked_lifecycle_request THEN 'asked' ELSE 'consequent' END
|
||||
WHERE u.request_id = ANY (v_ids) AND u.act_id IS NULL;
|
||||
GET DIAGNOSTICS v_linked_now = ROW_COUNT;
|
||||
IF v_linked_now <> v_named THEN
|
||||
RAISE EXCEPTION 'lifecycle_act_link_incomplete'
|
||||
USING ERRCODE = '22023',
|
||||
DETAIL = 'fewer requests were linked than were named';
|
||||
END IF;
|
||||
RETURN v_act_id;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
ALTER FUNCTION core.record_lifecycle_act(VARCHAR, VARCHAR, UUID, UUID, VARCHAR, UUID, UUID[]) OWNER TO core_owner;
|
||||
REVOKE EXECUTE ON FUNCTION core.record_lifecycle_act(VARCHAR, VARCHAR, UUID, UUID, VARCHAR, UUID, UUID[]) FROM PUBLIC;
|
||||
GRANT EXECUTE ON FUNCTION core.record_lifecycle_act(VARCHAR, VARCHAR, UUID, UUID, VARCHAR, UUID, UUID[]) TO core_writer;
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- The enclosure of the act columns (design D4). core_writer loses the table
|
||||
-- INSERT and UPDATE on core.lifecycle_requests and holds them by column: the
|
||||
-- nine columns the recording inserts, and the four the outcome and the
|
||||
-- dismissal set. SELECT and DELETE stay. No grant names updated_at, which the
|
||||
-- trigger sets, or an act column, which only core.record_lifecycle_act
|
||||
-- writes.
|
||||
-- ---------------------------------------------------------------------------
|
||||
REVOKE INSERT, UPDATE ON core.lifecycle_requests FROM core_writer;
|
||||
GRANT INSERT (instance_id, generation, connection_id, resource_key, workspace_id, operation, parameters,
|
||||
workflow_id, requested_by_person_id)
|
||||
ON core.lifecycle_requests TO core_writer;
|
||||
GRANT UPDATE (status, reason_code, finished_at, acknowledged_at)
|
||||
ON core.lifecycle_requests TO core_writer;
|
||||
|
||||
-- +goose Down
|
||||
-- A lifecycle act cannot be reversed: the five-cause constraint would refuse
|
||||
-- its header, and dropping the columns would lose the tie to its requests.
|
||||
-- +goose StatementBegin
|
||||
DO $$
|
||||
DECLARE
|
||||
v_acts BIGINT;
|
||||
BEGIN
|
||||
SELECT count(*) INTO v_acts FROM core.acts WHERE cause IN ('instances_swapped');
|
||||
IF v_acts <> 0 THEN
|
||||
RAISE EXCEPTION 'lifecycle_acts_exist'
|
||||
USING ERRCODE = '55000',
|
||||
DETAIL = format('%s lifecycle acts exist', v_acts);
|
||||
END IF;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
REVOKE INSERT (instance_id, generation, connection_id, resource_key, workspace_id, operation, parameters,
|
||||
workflow_id, requested_by_person_id)
|
||||
ON core.lifecycle_requests FROM core_writer;
|
||||
REVOKE UPDATE (status, reason_code, finished_at, acknowledged_at)
|
||||
ON core.lifecycle_requests FROM core_writer;
|
||||
GRANT INSERT, UPDATE ON core.lifecycle_requests TO core_writer;
|
||||
|
||||
DROP FUNCTION core.record_lifecycle_act(VARCHAR, VARCHAR, UUID, UUID, VARCHAR, UUID, UUID[]);
|
||||
|
||||
DROP INDEX core.idx_lifecycle_requests_act_id;
|
||||
DROP INDEX core.uq_lifecycle_requests_one_asked;
|
||||
ALTER TABLE core.lifecycle_requests
|
||||
DROP CONSTRAINT lifecycle_request_consequent_names_no_person,
|
||||
DROP CONSTRAINT chk_lifecycle_requests_act_role,
|
||||
DROP CONSTRAINT chk_lifecycle_requests_act_cause,
|
||||
DROP CONSTRAINT lifecycle_request_act_shape,
|
||||
DROP CONSTRAINT lifecycle_request_in_its_act;
|
||||
ALTER TABLE core.lifecycle_requests
|
||||
DROP COLUMN act_role,
|
||||
DROP COLUMN act_cause,
|
||||
DROP COLUMN act_id;
|
||||
|
||||
ALTER TABLE core.acts
|
||||
DROP CONSTRAINT chk_acts_cause,
|
||||
ADD CONSTRAINT chk_acts_cause CHECK (cause IN (
|
||||
'tier_added', 'tier_removed', 'tiers_reordered', 'org_type_default_changed', 'plan_act_retried'));
|
||||
|
||||
COMMENT ON TABLE core.acts IS
|
||||
'One row per act: who acted, when, and why, from a closed list of causes. Written once by core.record_plan_act; nothing updates or deletes a row.';
|
||||
COMMENT ON TABLE core.lifecycle_requests IS
|
||||
'One request a person made for one instance (create, change status, delete), addressed by the console''s instance identifier and a generation.';
|
||||
@@ -272,7 +272,7 @@ func TestPlanActObligationTablesAreEnclosed(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
// PUBLIC calls none of the five, and each is a SECURITY DEFINER function owned
|
||||
// PUBLIC calls none of the writers, and each is a SECURITY DEFINER function owned
|
||||
// by core_owner with the search path pinned and pg_temp last.
|
||||
func TestPlanActWritersAreEnclosedInTheCatalog(t *testing.T) {
|
||||
q := dbtest.Tx(t, dbtest.Open(t))
|
||||
@@ -284,7 +284,7 @@ func TestPlanActWritersAreEnclosedInTheCatalog(t *testing.T) {
|
||||
f.obligation(act, pool, orgType, org)
|
||||
|
||||
writers := []string{"record_plan_act", "write_plan_act_obligations", "settle_plan_act_obligation",
|
||||
"record_plan_act_obligation_failure", "requeue_plan_act_obligations", "lock_plan_act_obligation"}
|
||||
"record_plan_act_obligation_failure", "requeue_plan_act_obligations", "lock_plan_act_obligation", "record_lifecycle_act"}
|
||||
for _, name := range writers {
|
||||
var secdef bool
|
||||
var owner, config string
|
||||
@@ -315,8 +315,17 @@ func TestPlanActWritersAreEnclosedInTheCatalog(t *testing.T) {
|
||||
q.Refuse(dbtest.SQLStatePrivilege, "", requeuePlanActObligates, act)
|
||||
q.Refuse(dbtest.SQLStatePrivilege, "", recordTierRemoved, f.person, f.ladder, f.product)
|
||||
q.Refuse(dbtest.SQLStatePrivilege, "", lockPlanActObligation, act, pool)
|
||||
q.Refuse(dbtest.SQLStatePrivilege, "", recordSwap, f.person, nil, uuid.NewString(), arrayLiteral(uuid.NewString()))
|
||||
})
|
||||
}
|
||||
// The read-only role is made by a script, and a database that has not
|
||||
// run it has none; internal/migrate's console_reader tests cover the
|
||||
// stack where it exists, and here it is checked when present.
|
||||
if q.Int(`SELECT count(*) FROM pg_roles WHERE rolname = 'console_reader'`) == 1 {
|
||||
if q.String(`SELECT has_function_privilege('console_reader', 'core.record_lifecycle_act(varchar, varchar, uuid, uuid, varchar, uuid, uuid[])'::regprocedure, 'EXECUTE')::text`) != "false" {
|
||||
t.Errorf("console_reader can execute core.record_lifecycle_act")
|
||||
}
|
||||
}
|
||||
// The ownership rule runs with the caller's rights: a reader reads it.
|
||||
asRole(t, tx, "core_reader", func() {
|
||||
q.Exec(`SELECT core.plan_act_owns_org_type($1::uuid, $2)`, act, orgType)
|
||||
|
||||
@@ -21,37 +21,36 @@ import (
|
||||
)
|
||||
|
||||
// lockedTable is a table whose enclosure withholds some of INSERT, UPDATE and
|
||||
// DELETE from the writer. holds lists the ones among the three it keeps; every
|
||||
// locked table is also readable.
|
||||
// DELETE from the writer. holds lists the ones among the three it keeps whole;
|
||||
// every locked table is also readable. columns names, for INSERT or UPDATE,
|
||||
// the columns the writer holds that privilege on when it holds it by column
|
||||
// alone; a privilege in neither holds nor columns is held on no column.
|
||||
type lockedTable struct {
|
||||
name string
|
||||
holds []string
|
||||
name string
|
||||
holds []string
|
||||
columns map[string][]string
|
||||
}
|
||||
|
||||
var lockedTables = []lockedTable{
|
||||
{"core.pool_provisions", nil},
|
||||
{"core.pool_provision_ladders", nil},
|
||||
{"core.pool_provision_transitions", nil},
|
||||
{"core.entitlement_set_rules", nil},
|
||||
{"core.entitlement_set_changes", nil},
|
||||
{"core.entitlement_set_change_effects", nil},
|
||||
{"core.entitlement_set_change_obligations", []string{"UPDATE"}},
|
||||
{"core.acts", nil},
|
||||
{"core.plan_act_details", nil},
|
||||
{"core.plan_act_obligations", nil},
|
||||
{"core.plan_act_reached_org_types", nil},
|
||||
{"core.plan_act_orgs_without_pool", nil},
|
||||
{"core.desired_state_outbox", []string{"DELETE"}},
|
||||
{"core.person_cut_offs", nil},
|
||||
}
|
||||
|
||||
const outboxTable = "core.desired_state_outbox"
|
||||
|
||||
// outboxUpdatableColumns are the columns of core.desired_state_outbox the
|
||||
// writer may update; the relay claims and completes a row and never retargets
|
||||
// it.
|
||||
var outboxUpdatableColumns = []string{
|
||||
"status", "attempts", "claimed_until", "expansion_cursor", "last_error", "completed_at",
|
||||
{"core.pool_provisions", nil, nil},
|
||||
{"core.pool_provision_ladders", nil, nil},
|
||||
{"core.pool_provision_transitions", nil, nil},
|
||||
{"core.entitlement_set_rules", nil, nil},
|
||||
{"core.entitlement_set_changes", nil, nil},
|
||||
{"core.entitlement_set_change_effects", nil, nil},
|
||||
{"core.entitlement_set_change_obligations", []string{"UPDATE"}, nil},
|
||||
{"core.acts", nil, nil},
|
||||
{"core.plan_act_details", nil, nil},
|
||||
{"core.plan_act_obligations", nil, nil},
|
||||
{"core.plan_act_reached_org_types", nil, nil},
|
||||
{"core.plan_act_orgs_without_pool", nil, nil},
|
||||
{"core.desired_state_outbox", []string{"DELETE"}, map[string][]string{"UPDATE": {"status", "attempts", "claimed_until", "expansion_cursor", "last_error", "completed_at"}}},
|
||||
{"core.person_cut_offs", nil, nil},
|
||||
{"core.lifecycle_requests", []string{"DELETE"}, map[string][]string{
|
||||
"INSERT": {"instance_id", "generation", "connection_id", "resource_key", "workspace_id", "operation",
|
||||
"parameters", "workflow_id", "requested_by_person_id"},
|
||||
"UPDATE": {"status", "reason_code", "finished_at", "acknowledged_at"},
|
||||
}},
|
||||
}
|
||||
|
||||
// streamNames are the registered migration streams, which are also their
|
||||
@@ -128,9 +127,9 @@ func checkWritePrivileges(q *dbtest.Q, t *testing.T, rels []relation) {
|
||||
for _, privilege := range []string{"INSERT", "UPDATE", "DELETE"} {
|
||||
want := !isLocked || slices.Contains(locked.holds, privilege)
|
||||
got := groupRoleHolds(q, r.name, privilege)
|
||||
// A column grant also reopens a write; the outbox's updatable
|
||||
// columns are checked one by one in checkOutboxColumns.
|
||||
if !want && !got && privilege != "DELETE" && (r.name != outboxTable || privilege != "UPDATE") {
|
||||
// A column grant also reopens a write; the columns a locked table
|
||||
// names are checked one by one in checkLockedColumns.
|
||||
if !want && !got && privilege != "DELETE" && len(locked.columns[privilege]) == 0 {
|
||||
got = groupRoleHoldsAnyColumn(q, r.name, privilege)
|
||||
}
|
||||
if got != want {
|
||||
@@ -152,16 +151,20 @@ func checkLockedEntriesExist(t *testing.T, rels []relation) {
|
||||
}
|
||||
}
|
||||
|
||||
func checkOutboxColumns(q *dbtest.Q, t *testing.T) {
|
||||
// checkLockedColumns checks, for every locked table that names columns for a
|
||||
// privilege, that the group role holds the privilege on exactly those columns.
|
||||
func checkLockedColumns(q *dbtest.Q, t *testing.T) {
|
||||
t.Helper()
|
||||
columns := q.Strings(`SELECT attname::text FROM pg_attribute
|
||||
WHERE attrelid = 'core.desired_state_outbox'::regclass AND attnum > 0 AND NOT attisdropped
|
||||
ORDER BY attnum`)
|
||||
for _, column := range columns {
|
||||
got := q.String(`SELECT has_column_privilege($1, 'core.desired_state_outbox'::regclass, $2, 'UPDATE')::text`,
|
||||
db.RuntimeGroupRole, column) == "true"
|
||||
if want := slices.Contains(outboxUpdatableColumns, column); got != want {
|
||||
t.Errorf("%s holds UPDATE on core.desired_state_outbox.%s = %v, want %v", db.RuntimeGroupRole, column, got, want)
|
||||
for _, l := range lockedTables {
|
||||
for privilege, want := range l.columns {
|
||||
for _, column := range q.Strings(`SELECT attname::text FROM pg_attribute
|
||||
WHERE attrelid = $1::regclass AND attnum > 0 AND NOT attisdropped ORDER BY attnum`, l.name) {
|
||||
got := q.String(`SELECT has_column_privilege($1, $2::regclass, $3, $4)::text`,
|
||||
db.RuntimeGroupRole, l.name, column, privilege) == "true"
|
||||
if wantHeld := slices.Contains(want, column); got != wantHeld {
|
||||
t.Errorf("%s holds %s on %s.%s = %v, want %v", db.RuntimeGroupRole, privilege, l.name, column, got, wantHeld)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -241,7 +244,7 @@ func TestRuntimeRolePrivileges(t *testing.T) {
|
||||
checkReadable(q, t, rels)
|
||||
checkWritePrivileges(q, t, rels)
|
||||
checkLockedEntriesExist(t, rels)
|
||||
checkOutboxColumns(q, t)
|
||||
checkLockedColumns(q, t)
|
||||
checkNoExtraPrivileges(q, t, rels)
|
||||
checkLedgersReadable(q, t)
|
||||
checkFunctionsExecutable(q, t)
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
||||
// SPDX-FileCopyrightText: 2025-2026 Christian Galo
|
||||
|
||||
package entitlements
|
||||
|
||||
// ActCause is why an act was recorded: the closed list core.acts.cause
|
||||
// holds. The constants mirror chk_acts_cause and chk_plan_act_details_cause,
|
||||
// and a test compares them with the constraints' definitions. A later act
|
||||
// kind adds its causes in its own migration, replacing both constraints.
|
||||
// The list lives here until the first act outside this package adopts the
|
||||
// record.
|
||||
type ActCause string
|
||||
|
||||
// The causes of the plan acts. A tier delete and a tier removal are both
|
||||
// ActTierRemoved; the detail's disposition is NULL when no organization held
|
||||
// the tier.
|
||||
const (
|
||||
ActTierAdded ActCause = "tier_added"
|
||||
ActTierRemoved ActCause = "tier_removed"
|
||||
ActTiersReordered ActCause = "tiers_reordered"
|
||||
ActOrgTypeDefaultChanged ActCause = "org_type_default_changed"
|
||||
ActPlanActRetried ActCause = "plan_act_retried"
|
||||
)
|
||||
@@ -1,56 +0,0 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
||||
// SPDX-FileCopyrightText: 2025-2026 Christian Galo
|
||||
|
||||
package entitlements_test
|
||||
|
||||
// The Go causes mirror the two constraints that list them (openspec change
|
||||
// plan-act-obligations, task 4.2, design D26): a cause added on one side only
|
||||
// fails here. The list lands whole, so four of the causes have no caller
|
||||
// until the tasks that add their acts.
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/entitlements"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/testkit/dbtest"
|
||||
)
|
||||
|
||||
// The causes, as the Go constants name them.
|
||||
var actCauses = []entitlements.ActCause{
|
||||
entitlements.ActTierAdded,
|
||||
entitlements.ActTierRemoved,
|
||||
entitlements.ActTiersReordered,
|
||||
entitlements.ActOrgTypeDefaultChanged,
|
||||
entitlements.ActPlanActRetried,
|
||||
}
|
||||
|
||||
var quoted = regexp.MustCompile(`'([^']*)'`)
|
||||
|
||||
// TestActCausesMirrorTheConstraints reads the definition of chk_acts_cause and
|
||||
// of chk_plan_act_details_cause from a migrated database and requires each to
|
||||
// list exactly the Go causes.
|
||||
func TestActCausesMirrorTheConstraints(t *testing.T) {
|
||||
q := dbtest.On(t, dbtest.Open(t))
|
||||
var want []string
|
||||
for _, cause := range actCauses {
|
||||
want = append(want, string(cause))
|
||||
}
|
||||
slices.Sort(want)
|
||||
for _, c := range []struct{ table, constraint string }{
|
||||
{"acts", "chk_acts_cause"},
|
||||
{"plan_act_details", "chk_plan_act_details_cause"},
|
||||
} {
|
||||
def := q.String(`SELECT pg_get_constraintdef(con.oid) FROM pg_constraint con
|
||||
WHERE con.conrelid = ('core.' || $1)::regclass AND con.conname = $2`, c.table, c.constraint)
|
||||
var got []string
|
||||
for _, m := range quoted.FindAllStringSubmatch(def, -1) {
|
||||
got = append(got, m[1])
|
||||
}
|
||||
slices.Sort(got)
|
||||
if !slices.Equal(got, want) {
|
||||
t.Errorf("%s lists %v, the Go causes are %v\n%s", c.constraint, got, want, def)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/acts"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/billing"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/organization"
|
||||
)
|
||||
@@ -186,7 +187,7 @@ func (t *defaultChange) act(ctx context.Context, q planActQueriers) error {
|
||||
}
|
||||
|
||||
record := planActRecord{
|
||||
Cause: ActOrgTypeDefaultChanged,
|
||||
Cause: acts.OrgTypeDefaultChanged,
|
||||
ActorPersonID: in.OperatorPersonID,
|
||||
RequestID: in.RequestID,
|
||||
EffectiveAt: time.Now(),
|
||||
|
||||
@@ -6,6 +6,8 @@ package entitlements
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/acts"
|
||||
)
|
||||
|
||||
// FoldKey is one numeric key's folded state on a pool: the effective limit and
|
||||
@@ -75,6 +77,6 @@ func PlanActLimitsOf(c PlanActConfig) (PlanActLimits, error) { return c.limits()
|
||||
|
||||
// PlanActReasonFor is PlanActReason of the detail row a plan act of cause
|
||||
// records with these names.
|
||||
func PlanActReasonFor(cause ActCause, ladderName, productName, orgType string) string {
|
||||
func PlanActReasonFor(cause acts.Cause, ladderName, productName, orgType string) string {
|
||||
return PlanActReason(planActRecord{Cause: cause, PlanLadderName: ladderName, ProductName: productName, OrgType: orgType})
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/acts"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/billing"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/db"
|
||||
)
|
||||
@@ -223,7 +224,7 @@ type tierHolders struct {
|
||||
// then locks the holders' pools in ascending order and reads the holders again
|
||||
// under the locks; the first read only names them. Default-sourced holders
|
||||
// with no disposition refuse the removal with a DispositionRequiredError.
|
||||
// Then it records the act (cause ActTierRemoved, the disposition when one was
|
||||
// Then it records the act (cause acts.TierRemoved, the disposition when one was
|
||||
// asked for), deletes the tier and renumbers the ladder, and reconciles each
|
||||
// pool in ascending pool order. Other-source positions align-shrink (the
|
||||
// junction ends, delivery continues). Default-sourced positions follow the
|
||||
@@ -355,7 +356,7 @@ func (t *tierRemoval) act(ctx context.Context, q planActQueriers) error {
|
||||
return nil
|
||||
}
|
||||
record := planActRecord{
|
||||
Cause: ActTierRemoved,
|
||||
Cause: acts.TierRemoved,
|
||||
ActorPersonID: in.OperatorPersonID,
|
||||
RequestID: in.RequestID,
|
||||
EffectiveAt: time.Now(),
|
||||
@@ -564,7 +565,7 @@ func (t *tierAdd) act(ctx context.Context, q planActQueriers) error {
|
||||
return &PlanActError{Step: StepReadNames, Err: err}
|
||||
}
|
||||
record := planActRecord{
|
||||
Cause: ActTierAdded,
|
||||
Cause: acts.TierAdded,
|
||||
ActorPersonID: t.in.OperatorPersonID,
|
||||
RequestID: t.in.RequestID,
|
||||
EffectiveAt: time.Now(),
|
||||
@@ -643,7 +644,7 @@ type DeleteTierInput struct {
|
||||
// remaining tiers to 0..N-1 in one transaction, so ranks never gap and the
|
||||
// ladder always has a rank-0 provisioning default (deleting the base tier
|
||||
// promotes the next tier). It is a removal with no holders: the same act
|
||||
// record (cause ActTierRemoved, no disposition), with the guards read inside
|
||||
// record (cause acts.TierRemoved, no disposition), with the guards read inside
|
||||
// the exclusive transaction that deletes. It counts the tier's live holders,
|
||||
// positions that are active or suspended (the population a removal
|
||||
// reconciles), and refuses with a *LiveHoldersError when there is one;
|
||||
@@ -700,7 +701,7 @@ func deleteTierAct(ctx context.Context, q planActQueriers, in DeleteTierInput) e
|
||||
return &PlanActError{Step: StepReadNames, Err: err}
|
||||
}
|
||||
if _, err := writePlanAct(ctx, q.Ent, planActRecord{
|
||||
Cause: ActTierRemoved,
|
||||
Cause: acts.TierRemoved,
|
||||
ActorPersonID: in.OperatorPersonID,
|
||||
RequestID: in.RequestID,
|
||||
EffectiveAt: time.Now(),
|
||||
|
||||
@@ -93,9 +93,9 @@ func (h hookedQ) GetOutgoingDefaultExists(ctx context.Context, arg entitlements.
|
||||
return h.Querier.GetOutgoingDefaultExists(ctx, arg)
|
||||
}
|
||||
|
||||
// acts is the plan act configuration whose entitlements querier is hooked by
|
||||
// actConfig is the plan act configuration whose entitlements querier is hooked by
|
||||
// set, under limits.
|
||||
func acts(limits entitlements.PlanActLimits, set func(*hookedQ)) entitlements.PlanActConfig {
|
||||
func actConfig(limits entitlements.PlanActLimits, set func(*hookedQ)) entitlements.PlanActConfig {
|
||||
cfg := entitlements.PlanActConfig{Limits: limits}
|
||||
if set != nil {
|
||||
cfg.Entitlements = func(d entitlements.DBTX) entitlements.Querier {
|
||||
@@ -177,7 +177,7 @@ func (f *drainFixture) change(disposition string, cfg entitlements.PlanActConfig
|
||||
// the listing runs here in one batch.
|
||||
func (f *drainFixture) begin(disposition string) string {
|
||||
f.t.Helper()
|
||||
res, err := f.change(disposition, acts(limitsOf(func(l *entitlements.PlanActLimits) { l.Budget = time.Nanosecond }), nil))
|
||||
res, err := f.change(disposition, actConfig(limitsOf(func(l *entitlements.PlanActLimits) { l.Budget = time.Nanosecond }), nil))
|
||||
if err != nil {
|
||||
f.t.Fatalf("commit the default change: %v", err)
|
||||
}
|
||||
@@ -337,7 +337,7 @@ func TestChangeOrgTypeDefaultDeadlineEndsAWaitingT0(t *testing.T) {
|
||||
defer rc.Rollback()
|
||||
|
||||
began := time.Now()
|
||||
_, err = f.change("migrate", acts(limitsOf(func(l *entitlements.PlanActLimits) { l.Deadline = 300 * time.Millisecond }), nil))
|
||||
_, err = f.change("migrate", actConfig(limitsOf(func(l *entitlements.PlanActLimits) { l.Deadline = 300 * time.Millisecond }), nil))
|
||||
if !errors.Is(err, entitlements.ErrPlanActDeadline) {
|
||||
t.Fatalf("T0 past the deadline returned %T %v, want ErrPlanActDeadline", err, err)
|
||||
}
|
||||
@@ -357,7 +357,7 @@ func TestChangeOrgTypeDefaultDeadlineEndsAWaitingT0(t *testing.T) {
|
||||
// the act done.
|
||||
func TestDrainPlanActFollowsTheCursorAcrossPasses(t *testing.T) {
|
||||
f := newDrainFixture(t, 3)
|
||||
one := acts(limitsOf(func(l *entitlements.PlanActLimits) { l.Cap = 1 }), nil)
|
||||
one := actConfig(limitsOf(func(l *entitlements.PlanActLimits) { l.Cap = 1 }), nil)
|
||||
res, err := f.change("grandfather", one)
|
||||
if err != nil {
|
||||
t.Fatalf("ChangeOrgTypeDefault: %v", err)
|
||||
@@ -394,7 +394,7 @@ func TestDrainPlanActFollowsTheCursorAcrossPasses(t *testing.T) {
|
||||
func TestDrainPlanActRecordsFailedMovesAndWrapsToThem(t *testing.T) {
|
||||
f := newDrainFixture(t, 3)
|
||||
broken := f.orgs[0].PoolID
|
||||
cfg := acts(limitsOf(nil), func(h *hookedQ) {
|
||||
cfg := actConfig(limitsOf(nil), func(h *hookedQ) {
|
||||
h.beforeDefault = func(_ context.Context, _ entitlements.DBTX, poolID string) error {
|
||||
if poolID == broken {
|
||||
return errors.New("boom")
|
||||
@@ -449,7 +449,7 @@ func TestDrainPlanActRecordsFailedMovesAndWrapsToThem(t *testing.T) {
|
||||
func TestDrainPlanActARecordingThatFailsDoesNotHoldBackTheRest(t *testing.T) {
|
||||
f := newDrainFixture(t, 3)
|
||||
broken := f.orgs[0].PoolID
|
||||
cfg := acts(limitsOf(func(l *entitlements.PlanActLimits) { l.Cap = 1 }), func(h *hookedQ) {
|
||||
cfg := actConfig(limitsOf(func(l *entitlements.PlanActLimits) { l.Cap = 1 }), func(h *hookedQ) {
|
||||
h.beforeDefault = func(_ context.Context, _ entitlements.DBTX, poolID string) error {
|
||||
if poolID == broken {
|
||||
return errors.New("move boom")
|
||||
@@ -486,7 +486,7 @@ func TestDrainPlanActStopsWhenItsContextEndsAndRecordsNoAttempt(t *testing.T) {
|
||||
actID := f.begin("grandfather")
|
||||
ctx, cancel := context.WithCancel(f.ctx)
|
||||
defer cancel()
|
||||
cfg := acts(limitsOf(nil), func(h *hookedQ) {
|
||||
cfg := actConfig(limitsOf(nil), func(h *hookedQ) {
|
||||
h.beforeDefault = func(ctx context.Context, _ entitlements.DBTX, _ string) error {
|
||||
cancel()
|
||||
return ctx.Err()
|
||||
@@ -522,7 +522,7 @@ func TestDrainPlanActInARequestStopsAtALockWaitPastTheShorterTimeout(t *testing.
|
||||
}
|
||||
|
||||
began := time.Now()
|
||||
request := acts(limitsOf(func(l *entitlements.PlanActLimits) { l.LockTimeout = 150 * time.Millisecond }), nil)
|
||||
request := actConfig(limitsOf(func(l *entitlements.PlanActLimits) { l.LockTimeout = 150 * time.Millisecond }), nil)
|
||||
pass := f.drain(actID, request, entitlements.DrainPlanActInput{Mode: entitlements.DrainInRequest, Started: time.Now()})
|
||||
if elapsed := time.Since(began); elapsed > 3*time.Second {
|
||||
t.Errorf("the request waited %v, want its 150 ms lock timeout to end the wait", elapsed)
|
||||
@@ -548,7 +548,7 @@ func TestDrainPlanActInTheDrainRecordsALockWaitAsInProgress(t *testing.T) {
|
||||
f := newDrainFixture(t, 1)
|
||||
actID := f.begin("migrate")
|
||||
contended := &pgconn.PgError{Code: "55P03", Message: "canceling statement due to lock timeout"}
|
||||
cfg := acts(limitsOf(nil), func(h *hookedQ) {
|
||||
cfg := actConfig(limitsOf(nil), func(h *hookedQ) {
|
||||
h.beforeDefault = func(context.Context, entitlements.DBTX, string) error { return contended }
|
||||
})
|
||||
pass := f.drain(actID, cfg, entitlements.DrainPlanActInput{Mode: entitlements.DrainInBackground})
|
||||
@@ -590,7 +590,7 @@ func TestDrainPlanActInARequestStopsWhenTheTransactionTimeoutFires(t *testing.T)
|
||||
f := newDrainFixture(t, 2)
|
||||
actID := f.begin("migrate")
|
||||
var seen []error
|
||||
cfg := acts(limitsOf(func(l *entitlements.PlanActLimits) { l.TxTimeout = timeout }), func(h *hookedQ) {
|
||||
cfg := actConfig(limitsOf(func(l *entitlements.PlanActLimits) { l.TxTimeout = timeout }), func(h *hookedQ) {
|
||||
h.beforeDefault = tc.before
|
||||
h.seen = func(err error) { seen = append(seen, err) }
|
||||
})
|
||||
@@ -630,7 +630,7 @@ func TestDrainPlanActTransactionTimeoutBoundsTheRendezvousWait(t *testing.T) {
|
||||
defer rc.Rollback()
|
||||
|
||||
began := time.Now()
|
||||
cfg := acts(limitsOf(func(l *entitlements.PlanActLimits) { l.TxTimeout = 300 * time.Millisecond }), nil)
|
||||
cfg := actConfig(limitsOf(func(l *entitlements.PlanActLimits) { l.TxTimeout = 300 * time.Millisecond }), nil)
|
||||
pass := f.drain(actID, cfg, entitlements.DrainPlanActInput{Mode: entitlements.DrainInRequest, Started: time.Now()})
|
||||
if elapsed := time.Since(began); elapsed > 3*time.Second {
|
||||
t.Errorf("the request waited %v for the rendezvous, want the 300 ms transaction timeout to end it, not the 5 s lock timeout", elapsed)
|
||||
@@ -666,7 +666,7 @@ func TestDrainPlanActRunsTheLastProbeOnceAfterAnOutgoingMove(t *testing.T) {
|
||||
t.Run(disposition+" over two passes", func(t *testing.T) {
|
||||
f := newDrainFixture(t, 2)
|
||||
var p probes
|
||||
cfg := acts(limitsOf(func(l *entitlements.PlanActLimits) { l.ListBatch = 1 }), hook(&p))
|
||||
cfg := actConfig(limitsOf(func(l *entitlements.PlanActLimits) { l.ListBatch = 1 }), hook(&p))
|
||||
res, err := f.change(disposition, cfg)
|
||||
if err != nil {
|
||||
t.Fatalf("ChangeOrgTypeDefault: %v", err)
|
||||
@@ -699,7 +699,7 @@ func TestDrainPlanActRunsTheLastProbeOnceAfterAnOutgoingMove(t *testing.T) {
|
||||
var p probes
|
||||
res, err := entitlements.ChangeOrgTypeDefault(w.Ctx, w.DB, entitlements.DefaultChangeInput{
|
||||
OrgType: orgType, Ladder: uuid.NullUUID{UUID: uuid.MustParse(next.ID), Valid: true}, Disposition: "migrate",
|
||||
OperatorPersonID: operator.ID, Acts: acts(limitsOf(nil), hook(&p)),
|
||||
OperatorPersonID: operator.ID, Acts: actConfig(limitsOf(nil), hook(&p)),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("ChangeOrgTypeDefault: %v", err)
|
||||
@@ -717,7 +717,7 @@ func TestDrainPlanActRunsTheLastProbeOnceAfterAnOutgoingMove(t *testing.T) {
|
||||
// still found done.
|
||||
func TestDrainPlanActALastProbeThatFailsKeepsTheActDone(t *testing.T) {
|
||||
f := newDrainFixture(t, 1)
|
||||
cfg := acts(limitsOf(nil), func(h *hookedQ) {
|
||||
cfg := actConfig(limitsOf(nil), func(h *hookedQ) {
|
||||
h.probe = func(context.Context, entitlements.DBTX) error { return errors.New("probe boom") }
|
||||
})
|
||||
res, err := f.change("migrate", cfg)
|
||||
@@ -772,7 +772,7 @@ func TestAnOlderActDoesNotMoveAPoolANewerActReaches(t *testing.T) {
|
||||
// A newer act takes the type back to Main; its listing has not run.
|
||||
newer, err := entitlements.ChangeOrgTypeDefault(f.ctx, f.w.DB, entitlements.DefaultChangeInput{
|
||||
OrgType: f.orgType, Ladder: uuid.NullUUID{UUID: uuid.MustParse(f.main.ID), Valid: true}, Disposition: "migrate",
|
||||
OperatorPersonID: f.operator.ID, Acts: acts(limitsOf(func(l *entitlements.PlanActLimits) { l.Budget = time.Nanosecond }), nil),
|
||||
OperatorPersonID: f.operator.ID, Acts: actConfig(limitsOf(func(l *entitlements.PlanActLimits) { l.Budget = time.Nanosecond }), nil),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("the newer default change: %v", err)
|
||||
@@ -832,7 +832,7 @@ func TestDefaultChangeWaitsForAMoveInFlight(t *testing.T) {
|
||||
go func() {
|
||||
_, err := entitlements.ChangeOrgTypeDefault(f.ctx, f.w.DB, entitlements.DefaultChangeInput{
|
||||
OrgType: f.orgType, Ladder: uuid.NullUUID{UUID: uuid.MustParse(f.main.ID), Valid: true}, Disposition: "migrate",
|
||||
OperatorPersonID: f.operator.ID, Acts: acts(limitsOf(func(l *entitlements.PlanActLimits) { l.Budget = time.Nanosecond }), nil),
|
||||
OperatorPersonID: f.operator.ID, Acts: actConfig(limitsOf(func(l *entitlements.PlanActLimits) { l.Budget = time.Nanosecond }), nil),
|
||||
})
|
||||
changed <- err
|
||||
}()
|
||||
@@ -861,7 +861,7 @@ func TestDefaultChangeWaitsForAMoveInFlight(t *testing.T) {
|
||||
// reads, and gets the new default at signup.
|
||||
func TestOrganizationCreatedAfterTheCommitIsNotListed(t *testing.T) {
|
||||
f := newDrainFixture(t, 2)
|
||||
res, err := f.change("grandfather", acts(limitsOf(func(l *entitlements.PlanActLimits) { l.Budget = time.Nanosecond }), nil))
|
||||
res, err := f.change("grandfather", actConfig(limitsOf(func(l *entitlements.PlanActLimits) { l.Budget = time.Nanosecond }), nil))
|
||||
if err != nil {
|
||||
t.Fatalf("ChangeOrgTypeDefault: %v", err)
|
||||
}
|
||||
@@ -970,7 +970,7 @@ func newRetryListingFixture(t *testing.T) retryListingFixture {
|
||||
// A default change of the first type takes it over; its listing has not run.
|
||||
f.change, err = entitlements.ChangeOrgTypeDefault(ctx, w.DB, entitlements.DefaultChangeInput{
|
||||
OrgType: first, Ladder: uuid.NullUUID{UUID: uuid.MustParse(next.ID), Valid: true}, Disposition: "migrate",
|
||||
OperatorPersonID: f.operator.ID, Acts: acts(limitsOf(func(l *entitlements.PlanActLimits) { l.Budget = time.Nanosecond }), nil),
|
||||
OperatorPersonID: f.operator.ID, Acts: actConfig(limitsOf(func(l *entitlements.PlanActLimits) { l.Budget = time.Nanosecond }), nil),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("the default change: %v", err)
|
||||
@@ -1038,7 +1038,7 @@ func TestRetryAndASupersedingListingTouchDisjointRows(t *testing.T) {
|
||||
var listed int
|
||||
var listErr error
|
||||
var requeuedInTx int32
|
||||
cfg := acts(limitsOf(func(l *entitlements.PlanActLimits) { l.Budget = time.Nanosecond }), func(h *hookedQ) {
|
||||
cfg := actConfig(limitsOf(func(l *entitlements.PlanActLimits) { l.Budget = time.Nanosecond }), func(h *hookedQ) {
|
||||
h.afterRequeue = func(n int32) {
|
||||
requeuedInTx = n
|
||||
listing, cancel := context.WithTimeout(f.w.Ctx, 5*time.Second)
|
||||
@@ -1073,7 +1073,7 @@ func TestRetryAndASupersedingListingTouchDisjointRows(t *testing.T) {
|
||||
func TestDrainPlanActAFailedMoveOnAnObligationSettledMeanwhileRecordsNothing(t *testing.T) {
|
||||
f := newDrainFixture(t, 1)
|
||||
actID := f.begin("migrate")
|
||||
cfg := acts(limitsOf(nil), func(h *hookedQ) {
|
||||
cfg := actConfig(limitsOf(nil), func(h *hookedQ) {
|
||||
h.beforeDefault = func(context.Context, entitlements.DBTX, string) error { return errors.New("move boom") }
|
||||
h.failure = func(arg entitlements.RecordPlanActObligationFailureParams) error {
|
||||
f.q.Exec(`UPDATE core.plan_act_obligations SET status = 'settled', outcome = 'migrated', settled_at = NOW()
|
||||
@@ -1101,7 +1101,7 @@ func TestDrainPlanActAFailedMoveOnAnObligationSettledMeanwhileRecordsNothing(t *
|
||||
// timeout, lists it once the lock is gone.
|
||||
func TestDrainPlanActInARequestStopsWhenItsListingBatchIsCut(t *testing.T) {
|
||||
f := newDrainFixture(t, 2)
|
||||
res, err := f.change("migrate", acts(limitsOf(func(l *entitlements.PlanActLimits) { l.Budget = time.Nanosecond }), nil))
|
||||
res, err := f.change("migrate", actConfig(limitsOf(func(l *entitlements.PlanActLimits) { l.Budget = time.Nanosecond }), nil))
|
||||
if err != nil {
|
||||
t.Fatalf("commit the default change: %v", err)
|
||||
}
|
||||
@@ -1114,7 +1114,7 @@ func TestDrainPlanActInARequestStopsWhenItsListingBatchIsCut(t *testing.T) {
|
||||
t.Fatalf("hold the pool: %v", err)
|
||||
}
|
||||
|
||||
request := acts(limitsOf(func(l *entitlements.PlanActLimits) { l.LockTimeout = 150 * time.Millisecond }), nil)
|
||||
request := actConfig(limitsOf(func(l *entitlements.PlanActLimits) { l.LockTimeout = 150 * time.Millisecond }), nil)
|
||||
pass := f.drain(res.ActID, request, entitlements.DrainPlanActInput{Mode: entitlements.DrainInRequest, Started: time.Now()})
|
||||
if pass.Listed != 0 || pass.Moves.Total() != 0 || pass.Recorded != 0 || pass.Done || pass.ReadFailed {
|
||||
t.Errorf("the pass is %+v, want it stopped with nothing listed, moved or recorded", pass)
|
||||
@@ -1168,7 +1168,7 @@ func TestDrainPlanActALastProbeEndedByTheContextLogsNoError(t *testing.T) {
|
||||
actID := f.begin("migrate")
|
||||
ctx, cancel := context.WithCancel(f.ctx)
|
||||
defer cancel()
|
||||
cfg := acts(limitsOf(nil), func(h *hookedQ) {
|
||||
cfg := actConfig(limitsOf(nil), func(h *hookedQ) {
|
||||
h.probe = func(ctx context.Context, _ entitlements.DBTX) error {
|
||||
cancel()
|
||||
return ctx.Err()
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/acts"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/db"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/logging"
|
||||
)
|
||||
@@ -107,7 +108,7 @@ func (m *obligationEnactment) act(ctx context.Context, q planActQueriers) error
|
||||
return failAt(ObligationReadObligation, err)
|
||||
}
|
||||
reason := PlanActReason(planActRecord{
|
||||
Cause: ActCause(motion.Cause),
|
||||
Cause: acts.Cause(motion.Cause),
|
||||
PlanLadderName: motion.PlanLadderName.String,
|
||||
ProductName: motion.ProductName.String,
|
||||
OrgType: motion.DetailOrgType.String,
|
||||
|
||||
@@ -20,11 +20,14 @@ import (
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/acts"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/db"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/entitlements"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/testkit/dbtest"
|
||||
)
|
||||
|
||||
var quoted = regexp.MustCompile(`'([^']*)'`)
|
||||
|
||||
// constraintValues is the quoted values of a constraint's definition, sorted.
|
||||
func constraintValues(q *dbtest.Q, table, constraint string) []string {
|
||||
def := q.String(`SELECT pg_get_constraintdef(con.oid) FROM pg_constraint con
|
||||
@@ -113,14 +116,14 @@ func TestObligationDefaultReadStep(t *testing.T) {
|
||||
// holds the same strings).
|
||||
func TestPlanActReasons(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
cause entitlements.ActCause
|
||||
cause acts.Cause
|
||||
want string
|
||||
}{
|
||||
{entitlements.ActTierAdded, "tier added to ladder Main"},
|
||||
{entitlements.ActTierRemoved, "tier removal (Basic from Main)"},
|
||||
{entitlements.ActTiersReordered, "plan-ladder tier reorder (Main)"},
|
||||
{entitlements.ActOrgTypeDefaultChanged, "org-type default change (personal)"},
|
||||
{entitlements.ActPlanActRetried, ""},
|
||||
{acts.TierAdded, "tier added to ladder Main"},
|
||||
{acts.TierRemoved, "tier removal (Basic from Main)"},
|
||||
{acts.TiersReordered, "plan-ladder tier reorder (Main)"},
|
||||
{acts.OrgTypeDefaultChanged, "org-type default change (personal)"},
|
||||
{acts.PlanActRetried, ""},
|
||||
} {
|
||||
reason := entitlements.PlanActReasonFor(c.cause, "Main", "Basic", "personal")
|
||||
if reason != c.want {
|
||||
|
||||
@@ -9,6 +9,8 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/acts"
|
||||
)
|
||||
|
||||
// StepRequeue is the Retry's own step, which the plan-wide acts' lists do not
|
||||
@@ -96,7 +98,7 @@ func (r *planActRetry) act(ctx context.Context, q planActQueriers) error {
|
||||
in := r.in
|
||||
var err error
|
||||
r.retryActID, err = writePlanAct(ctx, q.Ent, planActRecord{
|
||||
Cause: ActPlanActRetried,
|
||||
Cause: acts.PlanActRetried,
|
||||
ActorPersonID: in.OperatorPersonID,
|
||||
RequestID: in.RequestID,
|
||||
EffectiveAt: time.Now(),
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/acts"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/billing"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/db"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/organization"
|
||||
@@ -173,7 +174,7 @@ func runPlanAct(ctx context.Context, b db.Beginner, a planAct) error {
|
||||
// planActRecord is the act row and the detail row a plan act records. An
|
||||
// empty string stands for NULL.
|
||||
type planActRecord struct {
|
||||
Cause ActCause
|
||||
Cause acts.Cause
|
||||
ActorPersonID string
|
||||
Note string
|
||||
RequestID string
|
||||
@@ -356,13 +357,13 @@ func TierRemovalRefusal(tiers []billing.PlanLadderTier, productID string, defaul
|
||||
// position (a Retry) has none.
|
||||
func PlanActReason(detail planActRecord) string {
|
||||
switch detail.Cause {
|
||||
case ActTierAdded:
|
||||
case acts.TierAdded:
|
||||
return "tier added to ladder " + detail.PlanLadderName
|
||||
case ActTierRemoved:
|
||||
case acts.TierRemoved:
|
||||
return fmt.Sprintf("tier removal (%s from %s)", detail.ProductName, detail.PlanLadderName)
|
||||
case ActTiersReordered:
|
||||
case acts.TiersReordered:
|
||||
return fmt.Sprintf("plan-ladder tier reorder (%s)", detail.PlanLadderName)
|
||||
case ActOrgTypeDefaultChanged:
|
||||
case acts.OrgTypeDefaultChanged:
|
||||
return fmt.Sprintf("org-type default change (%s)", detail.OrgType)
|
||||
}
|
||||
return ""
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/acts"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/billing"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/testkit/dbtest"
|
||||
)
|
||||
@@ -287,11 +288,11 @@ func TestPlanActReason(t *testing.T) {
|
||||
detail planActRecord
|
||||
want string
|
||||
}{
|
||||
{planActRecord{Cause: ActTierAdded, PlanLadderName: "Main"}, "tier added to ladder Main"},
|
||||
{planActRecord{Cause: ActTierRemoved, PlanLadderName: "Main", ProductName: "Basic"}, "tier removal (Basic from Main)"},
|
||||
{planActRecord{Cause: ActTiersReordered, PlanLadderName: "Main"}, "plan-ladder tier reorder (Main)"},
|
||||
{planActRecord{Cause: ActOrgTypeDefaultChanged, OrgType: "team"}, "org-type default change (team)"},
|
||||
{planActRecord{Cause: ActPlanActRetried}, ""},
|
||||
{planActRecord{Cause: acts.TierAdded, PlanLadderName: "Main"}, "tier added to ladder Main"},
|
||||
{planActRecord{Cause: acts.TierRemoved, PlanLadderName: "Main", ProductName: "Basic"}, "tier removal (Basic from Main)"},
|
||||
{planActRecord{Cause: acts.TiersReordered, PlanLadderName: "Main"}, "plan-ladder tier reorder (Main)"},
|
||||
{planActRecord{Cause: acts.OrgTypeDefaultChanged, OrgType: "team"}, "org-type default change (team)"},
|
||||
{planActRecord{Cause: acts.PlanActRetried}, ""},
|
||||
} {
|
||||
if got := PlanActReason(tc.detail); got != tc.want {
|
||||
t.Errorf("%s: PlanActReason = %q, want %q", tc.detail.Cause, got, tc.want)
|
||||
|
||||
@@ -629,10 +629,11 @@ type RecordPlanActParams struct {
|
||||
RetriedActID uuid.NullUUID `json:"retried_act_id"`
|
||||
}
|
||||
|
||||
// The only writer of core.acts and core.plan_act_details: one act and its
|
||||
// detail row, returning the act's id. The calling transaction must hold the
|
||||
// materialization rendezvous (exclusive for every cause but a Retry), which
|
||||
// the function asserts. A request id longer than the column is not stored.
|
||||
// One of the two writers of core.acts (the other is core.record_lifecycle_act,
|
||||
// for the lifecycle causes) and the only writer of core.plan_act_details: one
|
||||
// plan act and its detail row, returning the act's id. The calling transaction
|
||||
// must hold the materialization rendezvous (exclusive for every cause but a
|
||||
// Retry), which the function asserts. A request id longer than the column is not stored.
|
||||
func (q *Queries) RecordPlanAct(ctx context.Context, arg RecordPlanActParams) (string, error) {
|
||||
row := q.db.QueryRowContext(ctx, recordPlanAct,
|
||||
arg.Cause,
|
||||
|
||||
@@ -726,10 +726,11 @@ type Querier interface {
|
||||
// ladders, with the current tier (none on a ladder the subscription does
|
||||
// not hold) and the tier that follows (none when nothing follows).
|
||||
PredictCancellationOutcome(ctx context.Context, arg PredictCancellationOutcomeParams) ([]PredictCancellationOutcomeRow, error)
|
||||
// The only writer of core.acts and core.plan_act_details: one act and its
|
||||
// detail row, returning the act's id. The calling transaction must hold the
|
||||
// materialization rendezvous (exclusive for every cause but a Retry), which
|
||||
// the function asserts. A request id longer than the column is not stored.
|
||||
// One of the two writers of core.acts (the other is core.record_lifecycle_act,
|
||||
// for the lifecycle causes) and the only writer of core.plan_act_details: one
|
||||
// plan act and its detail row, returning the act's id. The calling transaction
|
||||
// must hold the materialization rendezvous (exclusive for every cause but a
|
||||
// Retry), which the function asserts. A request id longer than the column is not stored.
|
||||
RecordPlanAct(ctx context.Context, arg RecordPlanActParams) (string, error)
|
||||
// Records one failed attempt on a pending obligation, in a plain transaction,
|
||||
// and returns its status after the update. No row when the obligation was no
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
-- name: RecordPlanAct :one
|
||||
-- The only writer of core.acts and core.plan_act_details: one act and its
|
||||
-- detail row, returning the act's id. The calling transaction must hold the
|
||||
-- materialization rendezvous (exclusive for every cause but a Retry), which
|
||||
-- the function asserts. A request id longer than the column is not stored.
|
||||
-- One of the two writers of core.acts (the other is core.record_lifecycle_act,
|
||||
-- for the lifecycle causes) and the only writer of core.plan_act_details: one
|
||||
-- plan act and its detail row, returning the act's id. The calling transaction
|
||||
-- must hold the materialization rendezvous (exclusive for every cause but a
|
||||
-- Retry), which the function asserts. A request id longer than the column is not stored.
|
||||
SELECT core.record_plan_act(
|
||||
sqlc.arg(cause)::varchar,
|
||||
sqlc.arg(actor_type)::varchar,
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/acts"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/billing"
|
||||
)
|
||||
|
||||
@@ -167,7 +168,7 @@ func (t *tierReorder) act(ctx context.Context, q planActQueriers) error {
|
||||
t.rankZeroChanged = final[0] != previousRankZero
|
||||
|
||||
record := planActRecord{
|
||||
Cause: ActTiersReordered,
|
||||
Cause: acts.TiersReordered,
|
||||
ActorPersonID: in.OperatorPersonID,
|
||||
RequestID: in.RequestID,
|
||||
EffectiveAt: time.Now(),
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/acts"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/db"
|
||||
)
|
||||
|
||||
@@ -30,6 +31,14 @@ const (
|
||||
LifecycleFailed = "failed"
|
||||
)
|
||||
|
||||
// Lifecycle request act roles (chk_lifecycle_requests_act_role): the request
|
||||
// the person made, and a request the console added because of it. A test
|
||||
// compares them with the constraint's definition.
|
||||
const (
|
||||
LifecycleActAsked = "asked"
|
||||
LifecycleActConsequent = "consequent"
|
||||
)
|
||||
|
||||
// Lifecycle request operations (chk_lifecycle_requests_operation): the three
|
||||
// mutating verbs of the five-verb set.
|
||||
const (
|
||||
@@ -93,9 +102,11 @@ const (
|
||||
|
||||
// LifecycleAnswer is RecordLifecycleRequest's answer. Status, ReasonCode
|
||||
// and WorkflowID describe the request at the address for a recorded
|
||||
// request or a repeat, and are empty otherwise.
|
||||
// request or a repeat, and are empty otherwise. RequestID is the id of the
|
||||
// request recorded or held at the address, empty otherwise.
|
||||
type LifecycleAnswer struct {
|
||||
Kind LifecycleAnswerKind
|
||||
RequestID string
|
||||
Status string
|
||||
ReasonCode string
|
||||
WorkflowID string
|
||||
@@ -281,7 +292,7 @@ func recordNew(ctx context.Context, q *Queries, spec LifecycleRequestSpec, c req
|
||||
if open != 0 {
|
||||
return LifecycleAnswer{Kind: LifecycleBusy}, nil
|
||||
}
|
||||
_, err = q.InsertLifecycleRequest(ctx, InsertLifecycleRequestParams{
|
||||
requestID, err := q.InsertLifecycleRequest(ctx, InsertLifecycleRequestParams{
|
||||
InstanceID: spec.InstanceID,
|
||||
Generation: spec.Generation,
|
||||
WorkspaceID: spec.WorkspaceID,
|
||||
@@ -301,7 +312,7 @@ func recordNew(ctx context.Context, q *Queries, spec LifecycleRequestSpec, c req
|
||||
if err != nil {
|
||||
return LifecycleAnswer{}, fmt.Errorf("insert lifecycle request: %w", err)
|
||||
}
|
||||
return LifecycleAnswer{Kind: LifecycleRecorded, Status: LifecycleAccepted, WorkflowID: spec.WorkflowID}, nil
|
||||
return LifecycleAnswer{Kind: LifecycleRecorded, RequestID: requestID, Status: LifecycleAccepted, WorkflowID: spec.WorkflowID}, nil
|
||||
}
|
||||
|
||||
// answerAddress answers a generation at or below the instance's latest from
|
||||
@@ -309,24 +320,57 @@ func recordNew(ctx context.Context, q *Queries, spec LifecycleRequestSpec, c req
|
||||
// another workspace's request does, and otherwise a repeat or a conflict by
|
||||
// the content rule.
|
||||
func answerAddress(ctx context.Context, q *Queries, spec LifecycleRequestSpec, c requestContent) (LifecycleAnswer, error) {
|
||||
held, holder, err := heldAt(ctx, q, spec.WorkspaceID, spec.InstanceID, spec.Generation)
|
||||
answer, _, err := repeatAt(ctx, q, spec, c)
|
||||
if err != nil {
|
||||
return LifecycleAnswer{}, err
|
||||
}
|
||||
if answer.Kind == 0 {
|
||||
return LifecycleAnswer{Kind: LifecycleConflict}, nil
|
||||
}
|
||||
return answer, nil
|
||||
}
|
||||
|
||||
// AnswerLifecycleRepeat answers a repeat from what holds spec's address,
|
||||
// without recording and without the instance's lock (design D7): a zero Kind
|
||||
// when nothing holds the address, LifecycleNotFound for another workspace's
|
||||
// request, LifecycleRepeatOpen or LifecycleRepeatFinished with the held
|
||||
// request when its content matches, and LifecycleConflict when it differs. A
|
||||
// generation that holds nothing is left to the recording, which reads under
|
||||
// the lock and alone can call it a conflict reliably. The request's act link
|
||||
// is not content, so a request that belongs to an act still matches.
|
||||
func AnswerLifecycleRepeat(ctx context.Context, db DBTX, spec LifecycleRequestSpec) (LifecycleAnswer, LifecycleRequest, error) {
|
||||
if err := spec.checkAddress("answer lifecycle repeat"); err != nil {
|
||||
return LifecycleAnswer{}, LifecycleRequest{}, err
|
||||
}
|
||||
content, err := spec.content()
|
||||
if err != nil {
|
||||
return LifecycleAnswer{}, LifecycleRequest{}, err
|
||||
}
|
||||
return repeatAt(ctx, New(db), spec, content)
|
||||
}
|
||||
|
||||
// repeatAt is the one copy of the repeat rule: the answer from what holds
|
||||
// spec's address, the held request with it, and a zero Kind when nothing
|
||||
// holds it.
|
||||
func repeatAt(ctx context.Context, q *Queries, spec LifecycleRequestSpec, c requestContent) (LifecycleAnswer, LifecycleRequest, error) {
|
||||
held, holder, err := heldAt(ctx, q, spec.WorkspaceID, spec.InstanceID, spec.Generation)
|
||||
if err != nil {
|
||||
return LifecycleAnswer{}, LifecycleRequest{}, err
|
||||
}
|
||||
switch holder {
|
||||
case heldByNobody:
|
||||
return LifecycleAnswer{Kind: LifecycleConflict}, nil
|
||||
return LifecycleAnswer{}, LifecycleRequest{}, nil
|
||||
case heldByOtherWorkspace:
|
||||
return LifecycleAnswer{Kind: LifecycleNotFound}, nil
|
||||
return LifecycleAnswer{Kind: LifecycleNotFound}, LifecycleRequest{}, nil
|
||||
}
|
||||
same, err := sameLifecycleContent(held, spec.Operation, c.person, c.params)
|
||||
if err != nil {
|
||||
return LifecycleAnswer{}, err
|
||||
return LifecycleAnswer{}, LifecycleRequest{}, err
|
||||
}
|
||||
if !same {
|
||||
return LifecycleAnswer{Kind: LifecycleConflict}, nil
|
||||
return LifecycleAnswer{Kind: LifecycleConflict}, LifecycleRequest{}, nil
|
||||
}
|
||||
return answerFromRow(held), nil
|
||||
return answerFromRow(held), held, nil
|
||||
}
|
||||
|
||||
// addressHolder is who holds a request's address, as a workspace sees it.
|
||||
@@ -391,7 +435,7 @@ func LookupLifecycleRequest(ctx context.Context, db DBTX, workspaceID, instanceI
|
||||
}
|
||||
|
||||
func answerFromRow(held LifecycleRequest) LifecycleAnswer {
|
||||
answer := LifecycleAnswer{Status: held.Status, ReasonCode: held.ReasonCode.String, WorkflowID: held.WorkflowID}
|
||||
answer := LifecycleAnswer{RequestID: held.RequestID, Status: held.Status, ReasonCode: held.ReasonCode.String, WorkflowID: held.WorkflowID}
|
||||
if held.Status == LifecycleAccepted {
|
||||
answer.Kind = LifecycleRepeatOpen
|
||||
} else {
|
||||
@@ -473,6 +517,58 @@ func DeleteUnstartedLifecycleRequest(ctx context.Context, db DBTX, workspaceID,
|
||||
return n > 0, nil
|
||||
}
|
||||
|
||||
// DeleteUnstartedLifecycleAct deletes the accepted requests of the act whose
|
||||
// workflow start was refused with NotFound, in one statement, so the member's
|
||||
// retry is a fresh recording (design D11). The act's header stays. It deletes
|
||||
// nothing that is finished or in another workspace, and reports how many
|
||||
// requests went.
|
||||
func DeleteUnstartedLifecycleAct(ctx context.Context, db DBTX, workspaceID, actID string) (int64, error) {
|
||||
n, err := New(db).DeleteUnstartedLifecycleAct(ctx, DeleteUnstartedLifecycleActParams{
|
||||
ActID: actID,
|
||||
WorkspaceID: workspaceID,
|
||||
})
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("delete unstarted lifecycle act: %w", err)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// LifecycleAct is one act that links lifecycle requests the caller's
|
||||
// transaction already inserted (design D5). CorrelationID is the header's
|
||||
// request_id, since RequestID already names a lifecycle request's id here.
|
||||
type LifecycleAct struct {
|
||||
Cause acts.Cause
|
||||
ActorPersonID string
|
||||
CorrelationID string
|
||||
Asked string // the asked request's id
|
||||
Consequent []string // the consequent requests' ids
|
||||
}
|
||||
|
||||
// RecordLifecycleAct writes the act's header and links its requests through
|
||||
// core.record_lifecycle_act, and returns the act's id. It takes the
|
||||
// transaction that inserted the requests, because a call from any other
|
||||
// transaction could only fail (the function refuses a request of an earlier
|
||||
// one). The database's refusal comes back wrapped; only a code defect reaches
|
||||
// it, because the caller's own inserts satisfy every rule.
|
||||
func RecordLifecycleAct(ctx context.Context, tx *sql.Tx, act LifecycleAct) (string, error) {
|
||||
person, err := uuid.Parse(act.ActorPersonID)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("record lifecycle act: actor person: %w", err)
|
||||
}
|
||||
id, err := New(tx).RecordLifecycleAct(ctx, RecordLifecycleActParams{
|
||||
Cause: string(act.Cause),
|
||||
ActorType: "person",
|
||||
ActorPersonID: uuid.NullUUID{UUID: person, Valid: true},
|
||||
CorrelationID: sql.NullString{String: act.CorrelationID, Valid: act.CorrelationID != ""},
|
||||
AskedRequest: act.Asked,
|
||||
ConsequentRequests: act.Consequent,
|
||||
})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("record lifecycle act %s: %w", act.Cause, err)
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// NextGenerations returns the generation each instance's next request
|
||||
// carries, core.next_generation over its latest generation: above every
|
||||
// generation recorded for it and at least the clock, so an instance with no
|
||||
@@ -509,6 +605,8 @@ func OpenRequestsByWorkspace(ctx context.Context, db DBTX, workspaceID, connecti
|
||||
|
||||
// AcknowledgeLifecycleRequest records that a member dismissed a declined or
|
||||
// failed outcome in their workspace, and reports whether one was dismissed.
|
||||
// It acknowledges every declined or failed request of the workspace at the
|
||||
// address and in the address's act (design D12).
|
||||
func AcknowledgeLifecycleRequest(ctx context.Context, db DBTX, workspaceID, instanceID string, generation int64) (bool, error) {
|
||||
n, err := New(db).AcknowledgeLifecycleRequest(ctx, AcknowledgeLifecycleRequestParams{
|
||||
InstanceID: instanceID,
|
||||
|
||||
@@ -15,12 +15,16 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"math"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/acts"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/db"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/integration"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/testkit"
|
||||
@@ -104,7 +108,17 @@ func TestRecordLifecycleRequestAnswers_DB(t *testing.T) {
|
||||
|
||||
var outboxBefore int
|
||||
d.Scan([]any{&outboxBefore}, `SELECT count(*) FROM core.desired_state_outbox`)
|
||||
d.record(f.spec(instance, gen, integration.LifecycleCreate, `{"domain": "one.example.test", "custom": false}`))
|
||||
recorded := d.record(f.spec(instance, gen, integration.LifecycleCreate, `{"domain": "one.example.test", "custom": false}`))
|
||||
// The answer carries the id of the request it recorded, and a repeat
|
||||
// carries the id of the request it found (design D5).
|
||||
var storedID string
|
||||
d.Scan([]any{&storedID}, `SELECT request_id FROM core.lifecycle_requests WHERE instance_id = $1 AND generation = $2`, instance, gen)
|
||||
if recorded.RequestID == "" || recorded.RequestID != storedID {
|
||||
t.Errorf("recorded answer carries request id %q, the stored request is %q", recorded.RequestID, storedID)
|
||||
}
|
||||
if repeat := d.record(f.spec(instance, gen, integration.LifecycleCreate, `{"domain": "one.example.test", "custom": false}`)); repeat.Kind != integration.LifecycleRepeatOpen || repeat.RequestID != storedID {
|
||||
t.Errorf("repeat = %+v, want RepeatOpen with request id %q", repeat, storedID)
|
||||
}
|
||||
|
||||
// Another workspace's request is not found by lookup.
|
||||
if _, _, found, err := integration.LookupLifecycleRequest(d.ctx, d.tx, f.ows, instance, gen); err != nil || found {
|
||||
@@ -264,6 +278,14 @@ func TestLifecycleRequestListAndCleanup_DB(t *testing.T) {
|
||||
t.Errorf("an acknowledged outcome is shown: %+v", rows)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// A declined outcome gives way to a later request, and an unstarted request
|
||||
// is deleted only in its own workspace.
|
||||
func TestLifecycleRequestSupersessionAndUnstartedDelete_DB(t *testing.T) {
|
||||
d := newDQ(t)
|
||||
f := newLifecycleFixture(d)
|
||||
|
||||
// A declined outcome is superseded by a later request on the instance.
|
||||
site := uuid.New().String()
|
||||
s1 := d.generation()
|
||||
@@ -301,6 +323,227 @@ func TestLifecycleRequestListAndCleanup_DB(t *testing.T) {
|
||||
if a := d.record(f.spec(site, s2, integration.LifecycleDelete, `{}`)); a.Kind != integration.LifecycleRecorded {
|
||||
t.Errorf("retry after the delete = %+v", a)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// The act delete removes the accepted requests of one act and nothing else.
|
||||
func TestLifecycleActDelete_DB(t *testing.T) {
|
||||
d := newDQ(t)
|
||||
f := newLifecycleFixture(d)
|
||||
|
||||
// An act's requests go together: the act delete removes both accepted
|
||||
// requests and leaves the header, and removes nothing for another
|
||||
// workspace.
|
||||
act := f.recordAct(d)
|
||||
if gone, err := integration.DeleteUnstartedLifecycleRequest(d.ctx, d.tx, f.ws, act.asked.InstanceID, act.asked.Generation); err != nil || gone {
|
||||
t.Errorf("per-address delete of an asked request that belongs to an act = %v, %v", gone, err)
|
||||
}
|
||||
if gone, err := integration.DeleteUnstartedLifecycleRequest(d.ctx, d.tx, f.ws, act.consequent.InstanceID, act.consequent.Generation); err != nil || gone {
|
||||
t.Errorf("per-address delete of a consequent request = %v, %v", gone, err)
|
||||
}
|
||||
if n, err := integration.DeleteUnstartedLifecycleAct(d.ctx, d.tx, f.ows, act.id); err != nil || n != 0 {
|
||||
t.Errorf("act delete from another workspace = %d, %v", n, err)
|
||||
}
|
||||
if n, err := integration.DeleteUnstartedLifecycleAct(d.ctx, d.tx, f.ws, uuid.New().String()); err != nil || n != 0 {
|
||||
t.Errorf("act delete of an unknown act = %d, %v", n, err)
|
||||
}
|
||||
if n, err := integration.DeleteUnstartedLifecycleAct(d.ctx, d.tx, f.ws, act.id); err != nil || n != 2 {
|
||||
t.Errorf("act delete = %d, %v; want both requests", n, err)
|
||||
}
|
||||
for _, spec := range []integration.LifecycleRequestSpec{act.asked, act.consequent} {
|
||||
if n := d.requestRows(spec.InstanceID); n != 0 {
|
||||
t.Errorf("%s left %d rows after the act delete", spec.InstanceID, n)
|
||||
}
|
||||
}
|
||||
if n := d.Int(`SELECT count(*) FROM core.acts WHERE act_id = $1`, act.id); n != 1 {
|
||||
t.Errorf("the act delete left %d headers, want the header kept", n)
|
||||
}
|
||||
|
||||
// A finished member of an act is not deleted.
|
||||
finishedAct := f.recordAct(d)
|
||||
d.finished(finishedAct.consequent.InstanceID, finishedAct.consequent.Generation, integration.LifecycleSucceeded, "")
|
||||
if n, err := integration.DeleteUnstartedLifecycleAct(d.ctx, d.tx, f.ws, finishedAct.id); err != nil || n != 1 {
|
||||
t.Errorf("act delete with a finished member = %d, %v; want only the accepted one", n, err)
|
||||
}
|
||||
if n := d.requestRows(finishedAct.consequent.InstanceID); n != 1 {
|
||||
t.Errorf("the finished member was deleted: %d rows", n)
|
||||
}
|
||||
|
||||
// A request that belongs to no act is still deleted by its address.
|
||||
loneInstance := uuid.New().String()
|
||||
lone := d.generation()
|
||||
d.record(f.spec(loneInstance, lone, integration.LifecycleDelete, `{}`))
|
||||
if gone, err := integration.DeleteUnstartedLifecycleRequest(d.ctx, d.tx, f.ws, loneInstance, lone); err != nil || !gone {
|
||||
t.Errorf("per-address delete of a request with no act = %v, %v", gone, err)
|
||||
}
|
||||
}
|
||||
|
||||
// lifecycleActRows is a swap's two requests and the act that links them.
|
||||
type lifecycleActRows struct {
|
||||
asked, consequent integration.LifecycleRequestSpec
|
||||
askedID, conseqID string
|
||||
id string
|
||||
}
|
||||
|
||||
// recordAct records an asked and a consequent set_status request on two new
|
||||
// instances, then the act that links them, in the test's transaction.
|
||||
func (f lifecycleFixture) recordAct(d *dq) lifecycleActRows {
|
||||
d.t.Helper()
|
||||
d.Exec(`INSERT INTO core.provider_operations (provider, operation) VALUES ($1, 'set_status') ON CONFLICT DO NOTHING`, f.r.provider)
|
||||
spec := func(domain, status, person string) integration.LifecycleRequestSpec {
|
||||
s := f.spec(uuid.New().String(), d.generation(), integration.LifecycleSetStatus,
|
||||
`{"domain": "`+domain+`", "status": "`+status+`"}`)
|
||||
s.RequestedByPersonID = person
|
||||
return s
|
||||
}
|
||||
rows := lifecycleActRows{asked: spec("chosen.example.test", "active", f.owner), consequent: spec("parked.example.test", "readonly", "")}
|
||||
asked := d.record(rows.asked)
|
||||
consequent := d.record(rows.consequent)
|
||||
if asked.Kind != integration.LifecycleRecorded || consequent.Kind != integration.LifecycleRecorded {
|
||||
d.t.Fatalf("recording the pair = %+v, %+v", asked, consequent)
|
||||
}
|
||||
rows.askedID, rows.conseqID = asked.RequestID, consequent.RequestID
|
||||
id, err := integration.RecordLifecycleAct(d.ctx, d.tx, integration.LifecycleAct{
|
||||
Cause: acts.InstancesSwapped, ActorPersonID: f.owner, CorrelationID: "corr-" + rows.askedID,
|
||||
Asked: rows.askedID, Consequent: []string{rows.conseqID},
|
||||
})
|
||||
if err != nil {
|
||||
d.t.Fatalf("record lifecycle act: %v", err)
|
||||
}
|
||||
rows.id = id
|
||||
return rows
|
||||
}
|
||||
|
||||
// TestLifecycleActRolesMirrorTheConstraint compares the Go roles with
|
||||
// chk_lifecycle_requests_act_role.
|
||||
func TestLifecycleActRolesMirrorTheConstraint(t *testing.T) {
|
||||
d := newDQ(t)
|
||||
def := d.String(`SELECT pg_get_constraintdef(con.oid) FROM pg_constraint con
|
||||
WHERE con.conrelid = 'core.lifecycle_requests'::regclass AND con.conname = 'chk_lifecycle_requests_act_role'`)
|
||||
var got []string
|
||||
for _, m := range regexp.MustCompile(`'([^']*)'`).FindAllStringSubmatch(def, -1) {
|
||||
got = append(got, m[1])
|
||||
}
|
||||
slices.Sort(got)
|
||||
want := []string{integration.LifecycleActAsked, integration.LifecycleActConsequent}
|
||||
slices.Sort(want)
|
||||
if !slices.Equal(got, want) {
|
||||
t.Errorf("chk_lifecycle_requests_act_role lists %v, the Go roles are %v\n%s", got, want, def)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRecordLifecycleAct_DB records two requests in one transaction, calls the
|
||||
// wrapper, and reads back both rows' act columns and the header; a consequent
|
||||
// request recorded in an earlier transaction comes back as the wrapped
|
||||
// refusal.
|
||||
func TestRecordLifecycleAct_DB(t *testing.T) {
|
||||
d := newDQ(t)
|
||||
f := newLifecycleFixture(d)
|
||||
act := f.recordAct(d)
|
||||
|
||||
for _, c := range []struct{ id, role string }{{act.askedID, integration.LifecycleActAsked}, {act.conseqID, integration.LifecycleActConsequent}} {
|
||||
var gotAct, cause, role string
|
||||
d.Scan([]any{&gotAct, &cause, &role}, `SELECT act_id::text, act_cause, act_role FROM core.lifecycle_requests WHERE request_id = $1`, c.id)
|
||||
if gotAct != act.id || cause != string(acts.InstancesSwapped) || role != c.role {
|
||||
t.Errorf("request %s carries act %s cause %s role %s, want %s %s %s", c.id, gotAct, cause, role, act.id, acts.InstancesSwapped, c.role)
|
||||
}
|
||||
}
|
||||
var cause, actorType, actor, correlation string
|
||||
d.Scan([]any{&cause, &actorType, &actor, &correlation}, `SELECT cause, actor_type, actor_person_id::text, request_id FROM core.acts WHERE act_id = $1`, act.id)
|
||||
if cause != string(acts.InstancesSwapped) || actorType != "person" || actor != f.owner || correlation != "corr-"+act.askedID {
|
||||
t.Errorf("header = %s %s %s %s", cause, actorType, actor, correlation)
|
||||
}
|
||||
|
||||
// A consequent request recorded in an earlier transaction is refused.
|
||||
database := dbtest.Open(t)
|
||||
fx := committedLifecycleFixture(t, database)
|
||||
ctx := context.Background()
|
||||
if _, err := database.ExecContext(ctx, `INSERT INTO core.provider_operations (provider, operation) VALUES ($1, 'set_status')`, fx.r.provider); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
earlier := fx.spec(uuid.New().String(), d.generation(), integration.LifecycleSetStatus, `{"domain": "parked.example.test", "status": "readonly"}`)
|
||||
earlier.RequestedByPersonID = ""
|
||||
earlierAnswer, err := integration.RecordLifecycleRequest(ctx, database, earlier)
|
||||
if err != nil || earlierAnswer.Kind != integration.LifecycleRecorded {
|
||||
t.Fatalf("earlier request = %+v, %v", earlierAnswer, err)
|
||||
}
|
||||
err = db.InTx(ctx, database, db.Plain, func(tx *sql.Tx) error {
|
||||
asked := fx.spec(uuid.New().String(), d.generation(), integration.LifecycleSetStatus, `{"domain": "chosen.example.test", "status": "active"}`)
|
||||
a, err := integration.RecordLifecycleRequestInTx(ctx, tx, asked)
|
||||
if err != nil || a.Kind != integration.LifecycleRecorded {
|
||||
t.Fatalf("asked request = %+v, %v", a, err)
|
||||
}
|
||||
_, err = integration.RecordLifecycleAct(ctx, tx, integration.LifecycleAct{
|
||||
Cause: acts.InstancesSwapped, ActorPersonID: fx.owner, Asked: a.RequestID, Consequent: []string{earlierAnswer.RequestID},
|
||||
})
|
||||
if err == nil {
|
||||
t.Error("a consequent request of an earlier transaction was linked")
|
||||
}
|
||||
var pgErr *pgconn.PgError
|
||||
if !errors.As(err, &pgErr) || pgErr.Message != "lifecycle_act_request_not_current" {
|
||||
t.Errorf("refusal = %v, want the wrapped lifecycle_act_request_not_current", err)
|
||||
}
|
||||
return errors.New("roll back")
|
||||
})
|
||||
if err == nil || err.Error() != "roll back" {
|
||||
t.Errorf("transaction ended with %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAnswerLifecycleRepeat_DB covers each answer of the lock-free lookup.
|
||||
func TestAnswerLifecycleRepeat_DB(t *testing.T) {
|
||||
d := newDQ(t)
|
||||
f := newLifecycleFixture(d)
|
||||
answer := func(spec integration.LifecycleRequestSpec) (integration.LifecycleAnswer, integration.LifecycleRequest) {
|
||||
t.Helper()
|
||||
a, row, err := integration.AnswerLifecycleRepeat(d.ctx, d.tx, spec)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return a, row
|
||||
}
|
||||
instance := uuid.New().String()
|
||||
g1 := d.generation()
|
||||
spec := f.spec(instance, g1, integration.LifecycleCreate, `{"domain": "repeat.example.test"}`)
|
||||
|
||||
if a, row := answer(spec); a.Kind != 0 || row.RequestID != "" {
|
||||
t.Errorf("nothing held = %+v, %+v; want a zero answer", a, row)
|
||||
}
|
||||
d.record(spec)
|
||||
if a, row := answer(spec); a.Kind != integration.LifecycleRepeatOpen || row.Generation != g1 || a.RequestID != row.RequestID || a.RequestID == "" {
|
||||
t.Errorf("open repeat = %+v, %+v", a, row)
|
||||
}
|
||||
other := spec
|
||||
other.WorkspaceID = f.ows
|
||||
if a, row := answer(other); a.Kind != integration.LifecycleNotFound || row.RequestID != "" {
|
||||
t.Errorf("another workspace's request = %+v, %+v", a, row)
|
||||
}
|
||||
conflict := spec
|
||||
conflict.Parameters = json.RawMessage(`{"domain": "other.example.test"}`)
|
||||
if a, _ := answer(conflict); a.Kind != integration.LifecycleConflict {
|
||||
t.Errorf("other content = %+v", a)
|
||||
}
|
||||
d.finished(instance, g1, integration.LifecycleFailed, "retries_exhausted")
|
||||
if a, row := answer(spec); a.Kind != integration.LifecycleRepeatFinished || a.Status != integration.LifecycleFailed || row.Status != integration.LifecycleFailed {
|
||||
t.Errorf("finished repeat = %+v, %+v", a, row)
|
||||
}
|
||||
|
||||
// An older tab's generation holds nothing: zero, left to the recording.
|
||||
older := spec
|
||||
older.Generation = g1 - 1000
|
||||
if a, _ := answer(older); a.Kind != 0 {
|
||||
t.Errorf("an address that holds nothing = %+v, want zero", a)
|
||||
}
|
||||
|
||||
// A request that carries an act link still matches: the link is not
|
||||
// content.
|
||||
act := f.recordAct(d)
|
||||
if a, row := answer(act.asked); a.Kind != integration.LifecycleRepeatOpen || !row.ActID.Valid || row.ActID.UUID.String() != act.id {
|
||||
t.Errorf("repeat of an asked request = %+v, %+v", a, row)
|
||||
}
|
||||
if a, row := answer(act.consequent); a.Kind != integration.LifecycleRepeatOpen || row.ActRole.String != integration.LifecycleActConsequent {
|
||||
t.Errorf("repeat of a consequent request = %+v, %+v", a, row)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRecordLifecycleRequestConcurrentOlderTab is the race the advisory lock
|
||||
@@ -548,6 +791,67 @@ func TestLifecycleAcknowledgeOnlyDeclinedOrFailed_DB(t *testing.T) {
|
||||
if ok, err := integration.AcknowledgeLifecycleRequest(d.ctx, d.tx, f.ws, other, g2); err != nil || !ok {
|
||||
t.Errorf("acknowledging a failed request = %v, %v", ok, err)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// A request in an act is acknowledged with the act, and one with no act alone.
|
||||
func TestLifecycleAcknowledgeAnAct_DB(t *testing.T) {
|
||||
d := newDQ(t)
|
||||
f := newLifecycleFixture(d)
|
||||
|
||||
// A request in an act: a call at either member's address acknowledges
|
||||
// every declined or failed row of the act, and leaves a succeeded member
|
||||
// and another workspace's rows alone.
|
||||
acked := func(spec integration.LifecycleRequestSpec) bool {
|
||||
return d.Int(`SELECT (acknowledged_at IS NOT NULL)::int FROM core.lifecycle_requests WHERE instance_id = $1 AND generation = $2`, spec.InstanceID, spec.Generation) == 1
|
||||
}
|
||||
for _, at := range []string{"asked", "consequent"} {
|
||||
act := f.recordAct(d)
|
||||
d.finished(act.asked.InstanceID, act.asked.Generation, integration.LifecycleFailed, "retries_exhausted")
|
||||
d.finished(act.consequent.InstanceID, act.consequent.Generation, integration.LifecycleDeclined, "site_missing")
|
||||
target := act.asked
|
||||
if at == "consequent" {
|
||||
target = act.consequent
|
||||
}
|
||||
if ok, err := integration.AcknowledgeLifecycleRequest(d.ctx, d.tx, f.ows, target.InstanceID, target.Generation); err != nil || ok {
|
||||
t.Errorf("%s: another workspace acknowledged = %v, %v", at, ok, err)
|
||||
}
|
||||
if acked(act.asked) || acked(act.consequent) {
|
||||
t.Fatalf("%s: another workspace's call acknowledged a row", at)
|
||||
}
|
||||
if ok, err := integration.AcknowledgeLifecycleRequest(d.ctx, d.tx, f.ws, target.InstanceID, target.Generation); err != nil || !ok {
|
||||
t.Errorf("%s: acknowledge = %v, %v", at, ok, err)
|
||||
}
|
||||
if !acked(act.asked) || !acked(act.consequent) {
|
||||
t.Errorf("%s: asked acknowledged %v, consequent acknowledged %v, want both", at, acked(act.asked), acked(act.consequent))
|
||||
}
|
||||
}
|
||||
succeeded := f.recordAct(d)
|
||||
d.finished(succeeded.asked.InstanceID, succeeded.asked.Generation, integration.LifecycleSucceeded, "")
|
||||
d.finished(succeeded.consequent.InstanceID, succeeded.consequent.Generation, integration.LifecycleFailed, "retries_exhausted")
|
||||
if ok, err := integration.AcknowledgeLifecycleRequest(d.ctx, d.tx, f.ws, succeeded.consequent.InstanceID, succeeded.consequent.Generation); err != nil || !ok {
|
||||
t.Errorf("acknowledge beside a succeeded member = %v, %v", ok, err)
|
||||
}
|
||||
if acked(succeeded.asked) || !acked(succeeded.consequent) {
|
||||
t.Errorf("a succeeded member acknowledged %v, the failed one %v", acked(succeeded.asked), acked(succeeded.consequent))
|
||||
}
|
||||
|
||||
// A request with no act acknowledges only itself, whatever else the
|
||||
// workspace holds that failed.
|
||||
loneA, loneB := uuid.New().String(), uuid.New().String()
|
||||
ga, gb := d.generation(), d.generation()
|
||||
specA := f.spec(loneA, ga, integration.LifecycleCreate, `{"domain": "lone-a.example.test"}`)
|
||||
specB := f.spec(loneB, gb, integration.LifecycleCreate, `{"domain": "lone-b.example.test"}`)
|
||||
d.record(specA)
|
||||
d.record(specB)
|
||||
d.finished(loneA, ga, integration.LifecycleFailed, "retries_exhausted")
|
||||
d.finished(loneB, gb, integration.LifecycleFailed, "retries_exhausted")
|
||||
if ok, err := integration.AcknowledgeLifecycleRequest(d.ctx, d.tx, f.ws, loneA, ga); err != nil || !ok {
|
||||
t.Errorf("acknowledge with no act = %v, %v", ok, err)
|
||||
}
|
||||
if !acked(specA) || acked(specB) {
|
||||
t.Errorf("a request with no act acknowledged itself %v and another %v", acked(specA), acked(specB))
|
||||
}
|
||||
}
|
||||
|
||||
// A first request repeated at its own address is a repeat, and the first
|
||||
@@ -649,3 +953,133 @@ func TestARecordingOnAConnectionHoldsTheInstanceLock(t *testing.T) {
|
||||
t.Errorf("a recording on a pinned connection left the instance lock free after taking it")
|
||||
}
|
||||
}
|
||||
|
||||
// TestLifecycleStatementsRunAsTheRuntimeRole_DB runs every statement of the
|
||||
// lifecycle path as console_runtime, the role the served console runs as, whose
|
||||
// column grants on core.lifecycle_requests the suite's superuser connection
|
||||
// cannot test: a statement naming a column the role lacks fails with 42501. The
|
||||
// fixture is built first, as the test user.
|
||||
func TestLifecycleStatementsRunAsTheRuntimeRole_DB(t *testing.T) {
|
||||
d := newDQ(t)
|
||||
f := newLifecycleFixture(d)
|
||||
d.Exec(`INSERT INTO core.provider_operations (provider, operation) VALUES ($1, 'set_status') ON CONFLICT DO NOTHING`, f.r.provider)
|
||||
d.Exec("SET LOCAL ROLE " + db.RuntimeGroupRole)
|
||||
|
||||
must := func(what string, err error) {
|
||||
t.Helper()
|
||||
if err != nil {
|
||||
t.Fatalf("%s as %s: %v", what, db.RuntimeGroupRole, err)
|
||||
}
|
||||
}
|
||||
setStatus := func(domain, status, person string) integration.LifecycleRequestSpec {
|
||||
s := f.spec(uuid.New().String(), d.generation(), integration.LifecycleSetStatus,
|
||||
`{"domain": "`+domain+`", "status": "`+status+`"}`)
|
||||
s.RequestedByPersonID = person
|
||||
return s
|
||||
}
|
||||
recorded := func(spec integration.LifecycleRequestSpec) string {
|
||||
t.Helper()
|
||||
a := d.record(spec)
|
||||
if a.Kind != integration.LifecycleRecorded {
|
||||
t.Fatalf("record = %+v, want recorded", a)
|
||||
}
|
||||
return a.RequestID
|
||||
}
|
||||
|
||||
// Record two requests and their act: the insert with its ON CONFLICT
|
||||
// clause, the generation and open-generation reads, and the act function.
|
||||
asked, consequent := setStatus("chosen.example.test", "active", f.owner), setStatus("parked.example.test", "readonly", "")
|
||||
askedID, conseqID := recorded(asked), recorded(consequent)
|
||||
_, err := integration.NewInstanceID(d.ctx, d.tx)
|
||||
must("NewInstanceID", err)
|
||||
_, err = integration.NextGenerations(d.ctx, d.tx, []string{asked.InstanceID})
|
||||
must("NextGenerations", err)
|
||||
actID, err := integration.RecordLifecycleAct(d.ctx, d.tx, integration.LifecycleAct{
|
||||
Cause: acts.InstancesSwapped, ActorPersonID: f.owner, CorrelationID: "corr-" + askedID,
|
||||
Asked: askedID, Consequent: []string{conseqID},
|
||||
})
|
||||
must("RecordLifecycleAct", err)
|
||||
|
||||
// The lookups.
|
||||
_, _, _, err = integration.LookupLifecycleRequest(d.ctx, d.tx, f.ws, asked.InstanceID, asked.Generation)
|
||||
must("LookupLifecycleRequest", err)
|
||||
_, _, _, err = integration.FirstLifecycleRequest(d.ctx, d.tx, f.ws, asked.InstanceID)
|
||||
must("FirstLifecycleRequest", err)
|
||||
_, _, err = integration.AnswerLifecycleRepeat(d.ctx, d.tx, asked)
|
||||
must("AnswerLifecycleRepeat", err)
|
||||
_, err = integration.OpenRequestsByWorkspace(d.ctx, d.tx, f.ws, f.r.conn)
|
||||
must("OpenRequestsByWorkspace", err)
|
||||
_, err = integration.AcceptedLifecycleRequestsOlderThan(d.ctx, d.tx, f.r.conn, time.Hour)
|
||||
must("AcceptedLifecycleRequestsOlderThan", err)
|
||||
_, err = integration.LifecycleRequesterSubject(d.ctx, d.tx, asked.InstanceID, asked.Generation)
|
||||
must("LifecycleRequesterSubject", err)
|
||||
|
||||
// The finish, and the updated_at trigger under column UPDATE: the row's
|
||||
// stamp is set back as the test user, and the runtime finish moves it.
|
||||
// The reset skips the trigger, or it would stamp NOW() over the old value.
|
||||
d.Exec("RESET ROLE")
|
||||
d.Exec("SET LOCAL session_replication_role = replica")
|
||||
d.Exec(`UPDATE core.lifecycle_requests SET updated_at = '2000-01-01T00:00:00Z' WHERE instance_id = $1`, asked.InstanceID)
|
||||
d.Exec("SET LOCAL session_replication_role = origin")
|
||||
if d.Int(`SELECT (updated_at < '2001-01-01T00:00:00Z')::int FROM core.lifecycle_requests WHERE instance_id = $1`, asked.InstanceID) != 1 {
|
||||
t.Fatal("the reset of updated_at did not hold")
|
||||
}
|
||||
d.Exec("SET LOCAL ROLE " + db.RuntimeGroupRole)
|
||||
must("FinishLifecycleRequest", d.finish(asked.InstanceID, asked.Generation, integration.LifecycleFailed, "retries_exhausted"))
|
||||
must("FinishLifecycleRequest", d.finish(consequent.InstanceID, consequent.Generation, integration.LifecycleDeclined, "site_missing"))
|
||||
if d.Int(`SELECT (updated_at > '2001-01-01T00:00:00Z')::int FROM core.lifecycle_requests WHERE instance_id = $1`, asked.InstanceID) != 1 {
|
||||
t.Errorf("updated_at did not move on a finish as %s: the trigger did not fire", db.RuntimeGroupRole)
|
||||
}
|
||||
|
||||
// Acknowledge by act (at the consequent's address) and by address (a
|
||||
// request with no act).
|
||||
ok, err := integration.AcknowledgeLifecycleRequest(d.ctx, d.tx, f.ws, consequent.InstanceID, consequent.Generation)
|
||||
must("AcknowledgeLifecycleRequest by act", err)
|
||||
if !ok || d.Int(`SELECT count(*) FROM core.lifecycle_requests WHERE act_id = $1 AND acknowledged_at IS NOT NULL`, actID) != 2 {
|
||||
t.Errorf("acknowledge by act = %v, want both of the act's requests acknowledged", ok)
|
||||
}
|
||||
lone := setStatus("lone.example.test", "active", f.owner)
|
||||
recorded(lone)
|
||||
d.finished(lone.InstanceID, lone.Generation, integration.LifecycleFailed, "retries_exhausted")
|
||||
ok, err = integration.AcknowledgeLifecycleRequest(d.ctx, d.tx, f.ws, lone.InstanceID, lone.Generation)
|
||||
must("AcknowledgeLifecycleRequest by address", err)
|
||||
if !ok {
|
||||
t.Error("acknowledge by address found nothing")
|
||||
}
|
||||
|
||||
// Both deletes.
|
||||
unstarted := setStatus("unstarted.example.test", "active", f.owner)
|
||||
recorded(unstarted)
|
||||
deleted, err := integration.DeleteUnstartedLifecycleRequest(d.ctx, d.tx, f.ws, unstarted.InstanceID, unstarted.Generation)
|
||||
must("DeleteUnstartedLifecycleRequest", err)
|
||||
if !deleted {
|
||||
t.Error("the unstarted request was not deleted")
|
||||
}
|
||||
a2, c2 := setStatus("chosen2.example.test", "active", f.owner), setStatus("parked2.example.test", "readonly", "")
|
||||
a2ID, c2ID := recorded(a2), recorded(c2)
|
||||
act2, err := integration.RecordLifecycleAct(d.ctx, d.tx, integration.LifecycleAct{
|
||||
Cause: acts.InstancesSwapped, ActorPersonID: f.owner, Asked: a2ID, Consequent: []string{c2ID},
|
||||
})
|
||||
must("RecordLifecycleAct", err)
|
||||
n, err := integration.DeleteUnstartedLifecycleAct(d.ctx, d.tx, f.ws, act2)
|
||||
must("DeleteUnstartedLifecycleAct", err)
|
||||
if n != 2 {
|
||||
t.Errorf("DeleteUnstartedLifecycleAct deleted %d requests, want 2", n)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRuntimeRoleCannotWriteTheActColumns_DB: the act columns are written only
|
||||
// by core.record_lifecycle_act, so console_runtime's INSERT and UPDATE naming
|
||||
// act_id are refused for want of a privilege.
|
||||
func TestRuntimeRoleCannotWriteTheActColumns_DB(t *testing.T) {
|
||||
d := newDQ(t)
|
||||
f := newLifecycleFixture(d)
|
||||
spec := f.spec(uuid.New().String(), d.generation(), integration.LifecycleCreate, `{}`)
|
||||
d.record(spec)
|
||||
d.Exec("SET LOCAL ROLE " + db.RuntimeGroupRole)
|
||||
d.Refuse(dbtest.SQLStatePrivilege, "", `INSERT INTO core.lifecycle_requests
|
||||
(instance_id, generation, connection_id, resource_key, workspace_id, operation, parameters, workflow_id, act_id)
|
||||
VALUES ($1, $2, $3, $4, $5, 'create', '{}', 'wf-x', $6)`,
|
||||
uuid.New().String(), spec.Generation+1, f.r.conn, f.r.sites, f.ws, uuid.New().String())
|
||||
d.Refuse(dbtest.SQLStatePrivilege, "", `UPDATE core.lifecycle_requests SET act_id = NULL WHERE instance_id = $1`, spec.InstanceID)
|
||||
}
|
||||
|
||||
@@ -21,22 +21,52 @@ import (
|
||||
const acknowledgeLifecycleRequest = `-- name: AcknowledgeLifecycleRequest :execrows
|
||||
UPDATE core.lifecycle_requests
|
||||
SET acknowledged_at = NOW()
|
||||
WHERE instance_id = $1::uuid
|
||||
AND generation = $2::bigint
|
||||
AND workspace_id = $3::uuid
|
||||
WHERE workspace_id = $1::uuid
|
||||
AND status IN ('declined', 'failed')
|
||||
AND acknowledged_at IS NULL
|
||||
AND ((instance_id = $2::uuid AND generation = $3::bigint)
|
||||
OR act_id = (SELECT at.act_id FROM core.lifecycle_requests at
|
||||
WHERE at.instance_id = $2::uuid
|
||||
AND at.generation = $3::bigint
|
||||
AND at.workspace_id = $1::uuid))
|
||||
`
|
||||
|
||||
type AcknowledgeLifecycleRequestParams struct {
|
||||
WorkspaceID string `json:"workspace_id"`
|
||||
InstanceID string `json:"instance_id"`
|
||||
Generation int64 `json:"generation"`
|
||||
}
|
||||
|
||||
// The member dismissed a declined or failed outcome in their workspace. It
|
||||
// acknowledges every declined or failed, unacknowledged request of the
|
||||
// workspace at the address or in the address's act, found by a subquery; a
|
||||
// request with no act has a NULL act_id, which matches nothing, so it
|
||||
// acknowledges only itself.
|
||||
func (q *Queries) AcknowledgeLifecycleRequest(ctx context.Context, arg AcknowledgeLifecycleRequestParams) (int64, error) {
|
||||
result, err := q.db.ExecContext(ctx, acknowledgeLifecycleRequest, arg.WorkspaceID, arg.InstanceID, arg.Generation)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected()
|
||||
}
|
||||
|
||||
const deleteUnstartedLifecycleAct = `-- name: DeleteUnstartedLifecycleAct :execrows
|
||||
DELETE FROM core.lifecycle_requests
|
||||
WHERE act_id = $1::uuid
|
||||
AND workspace_id = $2::uuid
|
||||
AND status = 'accepted'
|
||||
`
|
||||
|
||||
type DeleteUnstartedLifecycleActParams struct {
|
||||
ActID string `json:"act_id"`
|
||||
WorkspaceID string `json:"workspace_id"`
|
||||
}
|
||||
|
||||
// The member dismissed a declined or failed outcome in their workspace.
|
||||
func (q *Queries) AcknowledgeLifecycleRequest(ctx context.Context, arg AcknowledgeLifecycleRequestParams) (int64, error) {
|
||||
result, err := q.db.ExecContext(ctx, acknowledgeLifecycleRequest, arg.InstanceID, arg.Generation, arg.WorkspaceID)
|
||||
// A handler whose workflow start was refused with NotFound deletes the
|
||||
// accepted requests of the act it recorded in one statement. The act's header
|
||||
// stays. Only accepted requests in the caller's workspace are deleted.
|
||||
func (q *Queries) DeleteUnstartedLifecycleAct(ctx context.Context, arg DeleteUnstartedLifecycleActParams) (int64, error) {
|
||||
result, err := q.db.ExecContext(ctx, deleteUnstartedLifecycleAct, arg.ActID, arg.WorkspaceID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@@ -49,6 +79,7 @@ WHERE instance_id = $1::uuid
|
||||
AND generation = $2::bigint
|
||||
AND workspace_id = $3::uuid
|
||||
AND status = 'accepted'
|
||||
AND act_id IS NULL
|
||||
`
|
||||
|
||||
type DeleteUnstartedLifecycleRequestParams struct {
|
||||
@@ -59,7 +90,9 @@ type DeleteUnstartedLifecycleRequestParams struct {
|
||||
|
||||
// A handler whose workflow start was refused with NotFound deletes the row it
|
||||
// inserted, so the member's retry is a fresh insert. Only an accepted row in
|
||||
// the caller's workspace is deleted.
|
||||
// the caller's workspace is deleted, and never one that belongs to an act:
|
||||
// DeleteUnstartedLifecycleAct deletes an act's requests together, so no
|
||||
// per-address delete leaves half an act.
|
||||
func (q *Queries) DeleteUnstartedLifecycleRequest(ctx context.Context, arg DeleteUnstartedLifecycleRequestParams) (int64, error) {
|
||||
result, err := q.db.ExecContext(ctx, deleteUnstartedLifecycleRequest, arg.InstanceID, arg.Generation, arg.WorkspaceID)
|
||||
if err != nil {
|
||||
@@ -106,7 +139,7 @@ func (q *Queries) FinishLifecycleRequest(ctx context.Context, arg FinishLifecycl
|
||||
}
|
||||
|
||||
const getFirstLifecycleRequest = `-- name: GetFirstLifecycleRequest :one
|
||||
SELECT request_id, instance_id, generation, connection_id, resource_key, workspace_id, operation, parameters, status, reason_code, workflow_id, requested_by_person_id, created_at, updated_at, finished_at, acknowledged_at FROM core.lifecycle_requests
|
||||
SELECT request_id, instance_id, generation, connection_id, resource_key, workspace_id, operation, parameters, status, reason_code, workflow_id, requested_by_person_id, created_at, updated_at, finished_at, acknowledged_at, act_id, act_cause, act_role FROM core.lifecycle_requests
|
||||
WHERE instance_id = $1::uuid
|
||||
ORDER BY generation
|
||||
LIMIT 1
|
||||
@@ -134,12 +167,15 @@ func (q *Queries) GetFirstLifecycleRequest(ctx context.Context, instanceID strin
|
||||
&i.UpdatedAt,
|
||||
&i.FinishedAt,
|
||||
&i.AcknowledgedAt,
|
||||
&i.ActID,
|
||||
&i.ActCause,
|
||||
&i.ActRole,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getLifecycleRequestByAddress = `-- name: GetLifecycleRequestByAddress :one
|
||||
SELECT request_id, instance_id, generation, connection_id, resource_key, workspace_id, operation, parameters, status, reason_code, workflow_id, requested_by_person_id, created_at, updated_at, finished_at, acknowledged_at FROM core.lifecycle_requests
|
||||
SELECT request_id, instance_id, generation, connection_id, resource_key, workspace_id, operation, parameters, status, reason_code, workflow_id, requested_by_person_id, created_at, updated_at, finished_at, acknowledged_at, act_id, act_cause, act_role FROM core.lifecycle_requests
|
||||
WHERE instance_id = $1::uuid AND generation = $2::bigint
|
||||
`
|
||||
|
||||
@@ -168,6 +204,9 @@ func (q *Queries) GetLifecycleRequestByAddress(ctx context.Context, arg GetLifec
|
||||
&i.UpdatedAt,
|
||||
&i.FinishedAt,
|
||||
&i.AcknowledgedAt,
|
||||
&i.ActID,
|
||||
&i.ActCause,
|
||||
&i.ActRole,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -277,7 +316,7 @@ func (q *Queries) LatestLifecycleGeneration(ctx context.Context, instanceID stri
|
||||
}
|
||||
|
||||
const listAcceptedLifecycleRequestsOlderThan = `-- name: ListAcceptedLifecycleRequestsOlderThan :many
|
||||
SELECT request_id, instance_id, generation, connection_id, resource_key, workspace_id, operation, parameters, status, reason_code, workflow_id, requested_by_person_id, created_at, updated_at, finished_at, acknowledged_at FROM core.lifecycle_requests
|
||||
SELECT request_id, instance_id, generation, connection_id, resource_key, workspace_id, operation, parameters, status, reason_code, workflow_id, requested_by_person_id, created_at, updated_at, finished_at, acknowledged_at, act_id, act_cause, act_role FROM core.lifecycle_requests
|
||||
WHERE connection_id = $1::uuid
|
||||
AND status = 'accepted'
|
||||
AND created_at < NOW() - ($2::bigint * INTERVAL '1 second')
|
||||
@@ -318,6 +357,9 @@ func (q *Queries) ListAcceptedLifecycleRequestsOlderThan(ctx context.Context, ar
|
||||
&i.UpdatedAt,
|
||||
&i.FinishedAt,
|
||||
&i.AcknowledgedAt,
|
||||
&i.ActID,
|
||||
&i.ActCause,
|
||||
&i.ActRole,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -414,7 +456,7 @@ func (q *Queries) OpenLifecycleGeneration(ctx context.Context, instanceID string
|
||||
}
|
||||
|
||||
const openLifecycleRequestsByWorkspace = `-- name: OpenLifecycleRequestsByWorkspace :many
|
||||
SELECT lr.request_id, lr.instance_id, lr.generation, lr.connection_id, lr.resource_key, lr.workspace_id, lr.operation, lr.parameters, lr.status, lr.reason_code, lr.workflow_id, lr.requested_by_person_id, lr.created_at, lr.updated_at, lr.finished_at, lr.acknowledged_at FROM core.lifecycle_requests lr
|
||||
SELECT lr.request_id, lr.instance_id, lr.generation, lr.connection_id, lr.resource_key, lr.workspace_id, lr.operation, lr.parameters, lr.status, lr.reason_code, lr.workflow_id, lr.requested_by_person_id, lr.created_at, lr.updated_at, lr.finished_at, lr.acknowledged_at, lr.act_id, lr.act_cause, lr.act_role FROM core.lifecycle_requests lr
|
||||
WHERE lr.workspace_id = $1::uuid
|
||||
AND lr.connection_id = $2::uuid
|
||||
AND (lr.status = 'accepted'
|
||||
@@ -461,6 +503,9 @@ func (q *Queries) OpenLifecycleRequestsByWorkspace(ctx context.Context, arg Open
|
||||
&i.UpdatedAt,
|
||||
&i.FinishedAt,
|
||||
&i.AcknowledgedAt,
|
||||
&i.ActID,
|
||||
&i.ActCause,
|
||||
&i.ActRole,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -474,3 +519,43 @@ func (q *Queries) OpenLifecycleRequestsByWorkspace(ctx context.Context, arg Open
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const recordLifecycleAct = `-- name: RecordLifecycleAct :one
|
||||
SELECT core.record_lifecycle_act(
|
||||
$1::varchar,
|
||||
$2::varchar,
|
||||
$3::uuid,
|
||||
$4::uuid,
|
||||
$5::varchar,
|
||||
$6::uuid,
|
||||
$7::uuid[])::uuid AS act_id
|
||||
`
|
||||
|
||||
type RecordLifecycleActParams struct {
|
||||
Cause string `json:"cause"`
|
||||
ActorType string `json:"actor_type"`
|
||||
ActorPersonID uuid.NullUUID `json:"actor_person_id"`
|
||||
ActorServiceAccountID uuid.NullUUID `json:"actor_service_account_id"`
|
||||
CorrelationID sql.NullString `json:"correlation_id"`
|
||||
AskedRequest string `json:"asked_request"`
|
||||
ConsequentRequests []string `json:"consequent_requests"`
|
||||
}
|
||||
|
||||
// The only writer of a lifecycle act: core.record_lifecycle_act inserts the
|
||||
// header and links the named requests, which the calling transaction
|
||||
// inserted. The correlation id is the header's request_id; one longer than the
|
||||
// column is not stored.
|
||||
func (q *Queries) RecordLifecycleAct(ctx context.Context, arg RecordLifecycleActParams) (string, error) {
|
||||
row := q.db.QueryRowContext(ctx, recordLifecycleAct,
|
||||
arg.Cause,
|
||||
arg.ActorType,
|
||||
arg.ActorPersonID,
|
||||
arg.ActorServiceAccountID,
|
||||
arg.CorrelationID,
|
||||
arg.AskedRequest,
|
||||
pq.Array(arg.ConsequentRequests),
|
||||
)
|
||||
var act_id string
|
||||
err := row.Scan(&act_id)
|
||||
return act_id, err
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ type DesiredStateRecord struct {
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// One request a person made for one instance (create, change status, delete), addressed by the console's instance identifier and a generation.
|
||||
// One request for one instance (create, change status, delete), addressed by the console's instance identifier and a generation. It names the person whose action caused it, or no one for a consequent request.
|
||||
type LifecycleRequest struct {
|
||||
RequestID string `json:"request_id"`
|
||||
InstanceID string `json:"instance_id"`
|
||||
@@ -58,6 +58,12 @@ type LifecycleRequest struct {
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
FinishedAt sql.NullTime `json:"finished_at"`
|
||||
AcknowledgedAt sql.NullTime `json:"acknowledged_at"`
|
||||
// The act this request belongs to; NULL for a request that belongs to none.
|
||||
ActID uuid.NullUUID `json:"act_id"`
|
||||
// The cause of the act, stated so the foreign key to core.acts holds the request to an act of that cause.
|
||||
ActCause sql.NullString `json:"act_cause"`
|
||||
// asked for the request the person made, consequent for one the console added because of it.
|
||||
ActRole sql.NullString `json:"act_role"`
|
||||
}
|
||||
|
||||
// What an application last reported holding for one recipient at one connection, with the generation it applied. Not an instance list.
|
||||
|
||||
@@ -12,7 +12,11 @@ import (
|
||||
)
|
||||
|
||||
type Querier interface {
|
||||
// The member dismissed a declined or failed outcome in their workspace.
|
||||
// The member dismissed a declined or failed outcome in their workspace. It
|
||||
// acknowledges every declined or failed, unacknowledged request of the
|
||||
// workspace at the address or in the address's act, found by a subquery; a
|
||||
// request with no act has a NULL act_id, which matches nothing, so it
|
||||
// acknowledges only itself.
|
||||
AcknowledgeLifecycleRequest(ctx context.Context, arg AcknowledgeLifecycleRequestParams) (int64, error)
|
||||
AddProviderOperation(ctx context.Context, arg AddProviderOperationParams) error
|
||||
AddProviderState(ctx context.Context, arg AddProviderStateParams) error
|
||||
@@ -50,9 +54,15 @@ type Querier interface {
|
||||
DeleteProviderOperationsNotIn(ctx context.Context, arg DeleteProviderOperationsNotInParams) error
|
||||
// Boot reconciliation: drop states a provider no longer declares.
|
||||
DeleteProviderStatesNotIn(ctx context.Context, arg DeleteProviderStatesNotInParams) error
|
||||
// A handler whose workflow start was refused with NotFound deletes the
|
||||
// accepted requests of the act it recorded in one statement. The act's header
|
||||
// stays. Only accepted requests in the caller's workspace are deleted.
|
||||
DeleteUnstartedLifecycleAct(ctx context.Context, arg DeleteUnstartedLifecycleActParams) (int64, error)
|
||||
// A handler whose workflow start was refused with NotFound deletes the row it
|
||||
// inserted, so the member's retry is a fresh insert. Only an accepted row in
|
||||
// the caller's workspace is deleted.
|
||||
// the caller's workspace is deleted, and never one that belongs to an act:
|
||||
// DeleteUnstartedLifecycleAct deletes an act's requests together, so no
|
||||
// per-address delete leaves half an act.
|
||||
DeleteUnstartedLifecycleRequest(ctx context.Context, arg DeleteUnstartedLifecycleRequestParams) (int64, error)
|
||||
// A record's content under the recipient rules, its hash computed as the
|
||||
// stored column computes it, and how many entitlements it carries (0 is the
|
||||
@@ -240,6 +250,11 @@ type Querier interface {
|
||||
// the connection trigger, so the relay recomputes every record of the
|
||||
// connection. A pending connection is left pending.
|
||||
ReapproveConnection(ctx context.Context, provider string) (int64, error)
|
||||
// The only writer of a lifecycle act: core.record_lifecycle_act inserts the
|
||||
// header and links the named requests, which the calling transaction
|
||||
// inserted. The correlation id is the header's request_id; one longer than the
|
||||
// column is not stored.
|
||||
RecordLifecycleAct(ctx context.Context, arg RecordLifecycleActParams) (string, error)
|
||||
// A push answer for an organization; as the person form.
|
||||
RecordPushResultForOrganization(ctx context.Context, arg RecordPushResultForOrganizationParams) error
|
||||
// A push answer for a person: the result, the generation it was about and
|
||||
|
||||
@@ -62,13 +62,39 @@ RETURNING request_id;
|
||||
-- name: DeleteUnstartedLifecycleRequest :execrows
|
||||
-- A handler whose workflow start was refused with NotFound deletes the row it
|
||||
-- inserted, so the member's retry is a fresh insert. Only an accepted row in
|
||||
-- the caller's workspace is deleted.
|
||||
-- the caller's workspace is deleted, and never one that belongs to an act:
|
||||
-- DeleteUnstartedLifecycleAct deletes an act's requests together, so no
|
||||
-- per-address delete leaves half an act.
|
||||
DELETE FROM core.lifecycle_requests
|
||||
WHERE instance_id = sqlc.arg(instance_id)::uuid
|
||||
AND generation = sqlc.arg(generation)::bigint
|
||||
AND workspace_id = sqlc.arg(workspace_id)::uuid
|
||||
AND status = 'accepted'
|
||||
AND act_id IS NULL;
|
||||
|
||||
-- name: DeleteUnstartedLifecycleAct :execrows
|
||||
-- A handler whose workflow start was refused with NotFound deletes the
|
||||
-- accepted requests of the act it recorded in one statement. The act's header
|
||||
-- stays. Only accepted requests in the caller's workspace are deleted.
|
||||
DELETE FROM core.lifecycle_requests
|
||||
WHERE act_id = sqlc.arg(act_id)::uuid
|
||||
AND workspace_id = sqlc.arg(workspace_id)::uuid
|
||||
AND status = 'accepted';
|
||||
|
||||
-- name: RecordLifecycleAct :one
|
||||
-- The only writer of a lifecycle act: core.record_lifecycle_act inserts the
|
||||
-- header and links the named requests, which the calling transaction
|
||||
-- inserted. The correlation id is the header's request_id; one longer than the
|
||||
-- column is not stored.
|
||||
SELECT core.record_lifecycle_act(
|
||||
sqlc.arg(cause)::varchar,
|
||||
sqlc.arg(actor_type)::varchar,
|
||||
sqlc.narg(actor_person_id)::uuid,
|
||||
sqlc.narg(actor_service_account_id)::uuid,
|
||||
sqlc.narg(correlation_id)::varchar,
|
||||
sqlc.arg(asked_request)::uuid,
|
||||
sqlc.arg(consequent_requests)::uuid[])::uuid AS act_id;
|
||||
|
||||
-- name: OpenLifecycleRequestsByWorkspace :many
|
||||
-- What a workspace's list shows for one connection: every accepted request,
|
||||
-- and per instance the latest request when it is declined or failed and not
|
||||
@@ -86,14 +112,21 @@ WHERE lr.workspace_id = sqlc.arg(workspace_id)::uuid
|
||||
ORDER BY lr.created_at, lr.request_id;
|
||||
|
||||
-- name: AcknowledgeLifecycleRequest :execrows
|
||||
-- The member dismissed a declined or failed outcome in their workspace.
|
||||
-- The member dismissed a declined or failed outcome in their workspace. It
|
||||
-- acknowledges every declined or failed, unacknowledged request of the
|
||||
-- workspace at the address or in the address's act, found by a subquery; a
|
||||
-- request with no act has a NULL act_id, which matches nothing, so it
|
||||
-- acknowledges only itself.
|
||||
UPDATE core.lifecycle_requests
|
||||
SET acknowledged_at = NOW()
|
||||
WHERE instance_id = sqlc.arg(instance_id)::uuid
|
||||
AND generation = sqlc.arg(generation)::bigint
|
||||
AND workspace_id = sqlc.arg(workspace_id)::uuid
|
||||
WHERE workspace_id = sqlc.arg(workspace_id)::uuid
|
||||
AND status IN ('declined', 'failed')
|
||||
AND acknowledged_at IS NULL;
|
||||
AND acknowledged_at IS NULL
|
||||
AND ((instance_id = sqlc.arg(instance_id)::uuid AND generation = sqlc.arg(generation)::bigint)
|
||||
OR act_id = (SELECT at.act_id FROM core.lifecycle_requests at
|
||||
WHERE at.instance_id = sqlc.arg(instance_id)::uuid
|
||||
AND at.generation = sqlc.arg(generation)::bigint
|
||||
AND at.workspace_id = sqlc.arg(workspace_id)::uuid));
|
||||
|
||||
-- name: ListAcceptedLifecycleRequestsOlderThan :many
|
||||
-- The boot pass (design D27): accepted requests at one connection older than
|
||||
|
||||
@@ -278,3 +278,36 @@ func TestArchiveTimeMigration_DB(t *testing.T) {
|
||||
func sameStamp(first, second sql.NullTime) bool {
|
||||
return first.Valid == second.Valid && (!first.Valid || first.Time.Equal(second.Time))
|
||||
}
|
||||
|
||||
// TestUpsertSiteFromFarmKeepsTheMarkOnlyOnReadonly_DB proves the sync keeps a
|
||||
// row's downgrade mark only when the row it writes is read-only.
|
||||
func TestUpsertSiteFromFarmKeepsTheMarkOnlyOnReadonly_DB(t *testing.T) {
|
||||
database := archiveDatabase(t, math.MaxInt64)
|
||||
workspace := fedwikitest.New(t, database).Tenant("Mark").Workspace.ID
|
||||
query := fwmod.New(database)
|
||||
cases := []struct {
|
||||
name, initial, write string
|
||||
marked, wantMark bool
|
||||
}{
|
||||
{"a marked row written archived", "readonly", "archived", true, false},
|
||||
{"a marked row written active", "readonly", "active", true, false},
|
||||
{"a marked row written readonly", "readonly", "readonly", true, true},
|
||||
{"an unmarked row written readonly", "readonly", "readonly", false, false},
|
||||
}
|
||||
for _, row := range cases {
|
||||
t.Run(row.name, func(t *testing.T) {
|
||||
domain := dbtest.Name("mark") + ".test"
|
||||
fedwikitest.Site(t, database, workspace, domain, row.initial)
|
||||
if row.marked {
|
||||
fedwikitest.ForceReduce(t, database, domain)
|
||||
}
|
||||
site, err := query.UpsertSiteFromFarm(t.Context(), fwmod.UpsertSiteFromFarmParams{WorkspaceID: workspace, Domain: domain, Status: row.write})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if site.ForceReducedAt.Valid != row.wantMark {
|
||||
t.Errorf("mark after the sync wrote %s = %v, want %v", row.write, site.ForceReducedAt.Valid, row.wantMark)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
||||
// SPDX-FileCopyrightText: 2025-2026 Christian Galo
|
||||
|
||||
package fedwiki_test
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/acts"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/db"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/integration"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/fedwiki/fedwikitest"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/fedwiki/workflows"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/testkit/dbtest"
|
||||
)
|
||||
|
||||
// The statements below are the SQL of the migration plan of the change that
|
||||
// added lifecycle acts, copied unchanged: the two counts of its first step, the
|
||||
// count and the clearing of marks of its first and third steps, and the listing
|
||||
// and the acknowledgement of its fourth.
|
||||
const (
|
||||
planOpenCounts = `SELECT 'swap' AS kind, count(*) FROM core.lifecycle_requests lr
|
||||
WHERE lr.status = 'accepted'
|
||||
AND (lr.workflow_id LIKE 'swap-fedwiki-site-%'
|
||||
OR lr.parameters ?| ARRAY['swap_park_site_id','swap_activate_site_id'])
|
||||
UNION ALL
|
||||
SELECT 'return', count(*) FROM core.lifecycle_requests lr
|
||||
JOIN fedwiki.sites s ON s.site_id = lr.instance_id
|
||||
WHERE lr.status = 'accepted' AND lr.operation = 'set_status'
|
||||
AND lr.parameters->>'status' = 'active'
|
||||
AND s.force_reduced_at IS NOT NULL
|
||||
AND lr.workflow_id NOT LIKE 'swap-fedwiki-site-%'`
|
||||
planMarkedCount = `SELECT count(*) FROM fedwiki.sites
|
||||
WHERE force_reduced_at IS NOT NULL AND status <> 'readonly'`
|
||||
planClearMarks = `UPDATE fedwiki.sites SET force_reduced_at = NULL
|
||||
WHERE force_reduced_at IS NOT NULL AND status <> 'readonly'`
|
||||
planParkedListing = `SELECT request_id, workspace_id, instance_id, status, reason_code, finished_at
|
||||
FROM core.lifecycle_requests
|
||||
WHERE parameters ? 'swap_activate_site_id'
|
||||
AND status IN ('declined','failed') AND acknowledged_at IS NULL
|
||||
ORDER BY finished_at`
|
||||
planAcknowledge = `UPDATE core.lifecycle_requests SET acknowledged_at = NOW()
|
||||
WHERE parameters ? 'swap_activate_site_id'
|
||||
AND status IN ('declined','failed') AND acknowledged_at IS NULL`
|
||||
)
|
||||
|
||||
// planRows hand-builds stored requests in the old form and records new-form
|
||||
// ones as the handlers do.
|
||||
type planRows struct {
|
||||
database *sql.DB
|
||||
env *fedwikitest.Env
|
||||
ws string
|
||||
person string
|
||||
}
|
||||
|
||||
// newSwap records a swap as the new release does: the activation naming the
|
||||
// person, the park naming none, both under the swap workflow id, and their
|
||||
// act, in one transaction. It returns the two request ids.
|
||||
func (p planRows) newSwap(t *testing.T, activateID, parkID string) (asked, consequent string) {
|
||||
t.Helper()
|
||||
ctx := p.env.Ctx
|
||||
tx, err := p.database.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
gens, err := integration.NextGenerations(ctx, tx, []string{activateID, parkID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
workflowID := workflows.SwapRequestWorkflowID(activateID, gens[activateID])
|
||||
record := func(instance, status, person string) string {
|
||||
params, _ := json.Marshal(map[string]any{"domain": p.domain(t, instance), "status": status})
|
||||
answer, err := integration.RecordLifecycleRequestInTx(ctx, tx, integration.LifecycleRequestSpec{
|
||||
InstanceID: instance, Generation: gens[instance], ConnectionID: p.env.Conn, ResourceKey: "fedwiki_sites",
|
||||
WorkspaceID: p.ws, Operation: integration.LifecycleSetStatus, Parameters: params, WorkflowID: workflowID,
|
||||
RequestedByPersonID: person,
|
||||
})
|
||||
if err != nil || answer.Kind != integration.LifecycleRecorded {
|
||||
t.Fatalf("record on %s: %+v, %v", instance, answer, err)
|
||||
}
|
||||
return answer.RequestID
|
||||
}
|
||||
asked = record(activateID, "active", p.person)
|
||||
consequent = record(parkID, "readonly", "")
|
||||
if _, err := integration.RecordLifecycleAct(ctx, tx, integration.LifecycleAct{
|
||||
Cause: acts.InstancesSwapped, ActorPersonID: p.person, Asked: asked, Consequent: []string{consequent},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return asked, consequent
|
||||
}
|
||||
|
||||
// domain reads a site's domain, the value the handler writes into a request's
|
||||
// parameters.
|
||||
func (p planRows) domain(t *testing.T, siteID string) string {
|
||||
t.Helper()
|
||||
return dbtest.On(t, p.database).String(`SELECT domain FROM fedwiki.sites WHERE site_id = $1`, siteID)
|
||||
}
|
||||
|
||||
// decline ends a recorded request declined and unacknowledged.
|
||||
func (p planRows) decline(t *testing.T, requestID string) {
|
||||
t.Helper()
|
||||
dbtest.On(t, p.database).Exec(`UPDATE core.lifecycle_requests
|
||||
SET status = 'declined', reason_code = 'site_missing', finished_at = NOW() WHERE request_id = $1`, requestID)
|
||||
}
|
||||
|
||||
// request inserts one request as the test user and returns its request id.
|
||||
func (p planRows) request(t *testing.T, instance, status, params, workflow string, acknowledged bool) string {
|
||||
t.Helper()
|
||||
gen, err := integration.NewLifecycleGeneration(p.env.Ctx, p.database)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
finished := "NOW()"
|
||||
if status == "accepted" {
|
||||
finished = "NULL"
|
||||
}
|
||||
reason := "NULL"
|
||||
if status == "declined" {
|
||||
reason = "'site_missing'"
|
||||
}
|
||||
ack := "NULL"
|
||||
if acknowledged {
|
||||
ack = "'2020-01-01T00:00:00Z'"
|
||||
}
|
||||
return dbtest.On(t, p.database).ID(fmt.Sprintf(`INSERT INTO core.lifecycle_requests
|
||||
(instance_id, generation, connection_id, resource_key, workspace_id, operation, parameters, workflow_id,
|
||||
status, finished_at, reason_code, acknowledged_at)
|
||||
VALUES ($1, $2, $3, 'fedwiki_sites', $4, 'set_status', $5::jsonb, $6, $7, %s, %s, %s)
|
||||
RETURNING request_id`, finished, reason, ack),
|
||||
instance, gen, p.env.Conn, p.ws, params, workflow, status)
|
||||
}
|
||||
|
||||
// TestMigrationPlanStatementsRunAsTheirRoles_DB runs the plan's counts, listing
|
||||
// and two updates as console_runtime. Step 1 runs over rows of the old form
|
||||
// alone, as it does before the new release writes a request; the listing and
|
||||
// the two updates then run over those rows and rows of the new form, and must
|
||||
// find or change only the old ones.
|
||||
func TestMigrationPlanStatementsRunAsTheirRoles_DB(t *testing.T) {
|
||||
database := archiveDatabase(t, math.MaxInt64)
|
||||
env := fedwikitest.New(t, database)
|
||||
tenant := env.Tenant("Plan")
|
||||
p := planRows{database: database, env: env, ws: tenant.Workspace.ID, person: tenant.Person.ID}
|
||||
site := func(name, status string) string {
|
||||
return fedwikitest.Site(t, database, p.ws, name+"-"+env.Sfx+".localhost", status)
|
||||
}
|
||||
mark := func(id string) {
|
||||
dbtest.On(t, database).Exec(`UPDATE fedwiki.sites SET force_reduced_at = NOW() WHERE site_id = $1`, id)
|
||||
}
|
||||
|
||||
// Old form: an open swap, an open return on a marked read-only site, a
|
||||
// declined request of a parked site that no one acknowledged, a marked
|
||||
// archived row.
|
||||
swapSite, parkedSite, returnSite, archivedSite := site("swap", "active"), site("parked", "readonly"), site("return", "readonly"), site("marked", "archived")
|
||||
mark(returnSite)
|
||||
mark(archivedSite)
|
||||
p.request(t, swapSite, "accepted",
|
||||
fmt.Sprintf(`{"status":"active","swap_park_site_id":%q,"swap_activate_site_id":%q}`, parkedSite, swapSite),
|
||||
"swap-fedwiki-site-"+swapSite, false)
|
||||
p.request(t, returnSite, "accepted", `{"status":"active"}`, "return-"+returnSite, false)
|
||||
oldParked := p.request(t, parkedSite, "declined",
|
||||
fmt.Sprintf(`{"status":"readonly","swap_activate_site_id":%q}`, swapSite), "swap-fedwiki-site-"+parkedSite, false)
|
||||
|
||||
// Old-form rows the statements leave alone: a swap request without keys, a
|
||||
// keyed request already acknowledged, one that succeeded, and a declined
|
||||
// request without keys.
|
||||
doneSite, plainSite := site("done", "readonly"), site("plain", "readonly")
|
||||
ackedKeyed := p.request(t, doneSite, "declined", fmt.Sprintf(`{"swap_activate_site_id":%q}`, swapSite), "wf-"+doneSite, true)
|
||||
succeeded := p.request(t, site("ok", "readonly"), "succeeded", fmt.Sprintf(`{"swap_activate_site_id":%q}`, swapSite), "wf-ok", false)
|
||||
plain := p.request(t, plainSite, "declined", `{"status":"readonly"}`, "wf-"+plainSite, false)
|
||||
|
||||
q := dbtest.Tx(t, database)
|
||||
q.Exec("SET LOCAL ROLE " + db.RuntimeGroupRole)
|
||||
|
||||
// Step 1 runs before the new release writes any request, so it counts old
|
||||
// forms only.
|
||||
if counts, want := q.Rows(planOpenCounts), "kind | count\nswap | 1\nreturn | 1\n"; counts != want {
|
||||
t.Errorf("step 1 counts read\n%s\nwant\n%s", counts, want)
|
||||
}
|
||||
if n := q.Int(planMarkedCount); n != 1 {
|
||||
t.Errorf("the count of marked rows that are not read-only = %d, want 1", n)
|
||||
}
|
||||
|
||||
// New form, with the parameters the handler writes: a swap whose requests share the
|
||||
// swap workflow id and one act, a swap whose two requests were declined and
|
||||
// not acknowledged, and a return, a set_status to active on a marked
|
||||
// read-only site.
|
||||
newActivate, newPark := site("newact", "readonly"), site("newpark", "active")
|
||||
declinedActivate, declinedPark := site("decact", "readonly"), site("decpark", "active")
|
||||
newReturn := site("newret", "readonly")
|
||||
mark(newReturn)
|
||||
_, openConsequent := p.newSwap(t, newActivate, newPark)
|
||||
declinedAsked, declinedConsequent := p.newSwap(t, declinedActivate, declinedPark)
|
||||
p.decline(t, declinedAsked)
|
||||
p.decline(t, declinedConsequent)
|
||||
returnGen, err := integration.NewLifecycleGeneration(env.Ctx, database)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
returnRequest := dbtest.On(t, database).ID(`INSERT INTO core.lifecycle_requests
|
||||
(instance_id, generation, connection_id, resource_key, workspace_id, operation, parameters, workflow_id, status, requested_by_person_id)
|
||||
VALUES ($1, $2, $3, 'fedwiki_sites', $4, 'set_status', $5::jsonb, $6, 'accepted', $7)
|
||||
RETURNING request_id`,
|
||||
newReturn, returnGen, env.Conn, p.ws, fmt.Sprintf(`{"domain":%q,"status":"active"}`, p.domain(t, newReturn)),
|
||||
workflows.SetStatusRequestWorkflowID(newReturn, returnGen), p.person)
|
||||
|
||||
if listed := strings.Split(strings.TrimSpace(q.Rows(planParkedListing)), "\n"); len(listed) != 2 || !strings.HasPrefix(listed[1], oldParked+" | ") {
|
||||
t.Errorf("step 4 listing = %q, want only request %s", listed, oldParked)
|
||||
}
|
||||
|
||||
q.Exec(planClearMarks)
|
||||
marked := func(id string) bool {
|
||||
return q.Int(`SELECT (force_reduced_at IS NOT NULL)::int FROM fedwiki.sites WHERE site_id = $1`, id) == 1
|
||||
}
|
||||
if marked(archivedSite) || !marked(returnSite) || !marked(newReturn) {
|
||||
t.Errorf("step 3 left the archived row marked = %v, cleared the old return's mark = %v, cleared the new return's mark = %v",
|
||||
marked(archivedSite), !marked(returnSite), !marked(newReturn))
|
||||
}
|
||||
if n := q.Int(`SELECT count(*) FROM fedwiki.sites WHERE force_reduced_at IS NOT NULL`); n != 2 {
|
||||
t.Errorf("%d rows are marked after step 3, want the two read-only ones", n)
|
||||
}
|
||||
|
||||
q.Exec(planAcknowledge)
|
||||
acked := func(id string) bool {
|
||||
return q.Int(`SELECT (acknowledged_at IS NOT NULL)::int FROM core.lifecycle_requests WHERE request_id = $1`, id) == 1
|
||||
}
|
||||
if !acked(oldParked) || !acked(ackedKeyed) {
|
||||
t.Errorf("step 4 left the parked request acknowledged = %v (and the earlier acknowledgement kept = %v)", acked(oldParked), acked(ackedKeyed))
|
||||
}
|
||||
if acked(succeeded) || acked(plain) {
|
||||
t.Errorf("step 4 acknowledged a succeeded request (%v) or one without keys (%v)", acked(succeeded), acked(plain))
|
||||
}
|
||||
if acked(declinedAsked) || acked(declinedConsequent) || acked(openConsequent) || acked(returnRequest) {
|
||||
t.Errorf("step 4 acknowledged a new-form row: declined activation %v, declined park %v, open park %v, return %v",
|
||||
acked(declinedAsked), acked(declinedConsequent), acked(openConsequent), acked(returnRequest))
|
||||
}
|
||||
if n := q.Int(`SELECT count(*) FROM core.lifecycle_requests WHERE acknowledged_at IS NOT NULL`); n != 2 {
|
||||
t.Errorf("%d requests are acknowledged after step 4, want 2", n)
|
||||
}
|
||||
if got := strings.Split(strings.TrimSpace(q.Rows(planParkedListing)), "\n"); len(got) != 1 {
|
||||
t.Errorf("step 4 listing after the acknowledgement reads %q, want no rows", got)
|
||||
}
|
||||
}
|
||||
@@ -183,8 +183,12 @@ type Querier interface {
|
||||
// the observed status/storage/last-modified onto an existing row WITHOUT touching
|
||||
// its workspace_id (user-created sites keep their owner).
|
||||
UpsertSiteFromFarm(ctx context.Context, arg UpsertSiteFromFarmParams) (Site, error)
|
||||
// Records that a swap just happened (resets the cooldown clock for the workspace).
|
||||
// Records that a rotation succeeded (resets the cooldown clock for the workspace).
|
||||
UpsertSiteSwapPolicy(ctx context.Context, workspaceID string) error
|
||||
// Whether the workspace holds an open rotation on the connection: an accepted
|
||||
// request of a swap act, or an accepted set_status to active on a site a
|
||||
// downgrade or a swap parked (force_reduced_at set), which is a return.
|
||||
WorkspaceHasOpenRotation(ctx context.Context, arg WorkspaceHasOpenRotationParams) (bool, error)
|
||||
}
|
||||
|
||||
var _ Querier = (*Queries)(nil)
|
||||
|
||||
@@ -89,6 +89,7 @@ ON CONFLICT(domain) DO UPDATE SET
|
||||
status = excluded.status,
|
||||
storage_bytes = excluded.storage_bytes,
|
||||
last_modified_at = excluded.last_modified_at,
|
||||
force_reduced_at = CASE WHEN excluded.status = 'readonly' THEN fedwiki.sites.force_reduced_at END,
|
||||
updated_at = NOW()
|
||||
RETURNING *;
|
||||
|
||||
@@ -130,6 +131,23 @@ SELECT EXISTS (
|
||||
WHERE instance_id = $1 AND status = 'accepted'
|
||||
) AS open;
|
||||
|
||||
-- name: WorkspaceHasOpenRotation :one
|
||||
-- Whether the workspace holds an open rotation on the connection: an accepted
|
||||
-- request of a swap act, or an accepted set_status to active on a site a
|
||||
-- downgrade or a swap parked (force_reduced_at set), which is a return.
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM core.lifecycle_requests r
|
||||
LEFT JOIN fedwiki.sites s ON s.site_id = r.instance_id
|
||||
WHERE r.workspace_id = sqlc.arg(workspace_id)::uuid
|
||||
AND r.connection_id = sqlc.arg(connection_id)::uuid
|
||||
AND r.status = 'accepted'
|
||||
AND (r.act_cause = sqlc.arg(swap_cause)::text
|
||||
OR (r.operation = 'set_status'
|
||||
AND r.parameters->>'status' = 'active'
|
||||
AND s.force_reduced_at IS NOT NULL))
|
||||
) AS open;
|
||||
|
||||
-- name: SiteHasRequestUpdatedSince :one
|
||||
-- Whether any lifecycle request on the site, open or finished, was updated at
|
||||
-- or after the moment. The sync reads it under the site row's lock, against
|
||||
@@ -352,7 +370,7 @@ FOR UPDATE;
|
||||
SELECT last_swap_at FROM fedwiki.site_swap_policy WHERE workspace_id = $1;
|
||||
|
||||
-- name: UpsertSiteSwapPolicy :exec
|
||||
-- Records that a swap just happened (resets the cooldown clock for the workspace).
|
||||
-- Records that a rotation succeeded (resets the cooldown clock for the workspace).
|
||||
INSERT INTO fedwiki.site_swap_policy (workspace_id, last_swap_at)
|
||||
VALUES ($1, NOW())
|
||||
ON CONFLICT (workspace_id) DO UPDATE SET last_swap_at = NOW();
|
||||
|
||||
@@ -12,6 +12,9 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/acts"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/db"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/integration"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/fedwiki/fedwikitest"
|
||||
@@ -220,3 +223,169 @@ func recordIntakePair(ctx context.Context, database *sql.DB, spec integration.Li
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
// openRotationRig records requests at the top level of one transaction, so
|
||||
// the act writer accepts them, and asks the open-rotation query as the
|
||||
// runtime user.
|
||||
type openRotationRig struct {
|
||||
t *testing.T
|
||||
env *fedwikitest.Env
|
||||
db *sql.DB
|
||||
q *dbtest.Q
|
||||
conn string
|
||||
}
|
||||
|
||||
// in rebinds the rig to a subtest's t, on the same transaction.
|
||||
func (r openRotationRig) in(t *testing.T) openRotationRig {
|
||||
t.Helper()
|
||||
r.t = t
|
||||
r.q = dbtest.On(t, r.q.Tx())
|
||||
return r
|
||||
}
|
||||
|
||||
// site makes a site of the tenant, parked by a downgrade when marked.
|
||||
func (r openRotationRig) site(tenant fedwikitest.Tenant, status string, marked bool) string {
|
||||
r.t.Helper()
|
||||
id := fedwikitest.Site(r.t, r.db, tenant.Workspace.ID, dbtest.Name("rotation")+".localhost", status)
|
||||
if marked {
|
||||
dbtest.On(r.t, r.db).Exec("UPDATE fedwiki.sites SET force_reduced_at = NOW() WHERE site_id = $1", id)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// record inserts an accepted request on the site and returns its id.
|
||||
func (r openRotationRig) record(tenant fedwikitest.Tenant, site, status, person string) string {
|
||||
r.t.Helper()
|
||||
gens, err := integration.NextGenerations(r.env.Ctx, r.q.Tx(), []string{site})
|
||||
if err != nil {
|
||||
r.t.Fatal(err)
|
||||
}
|
||||
params := []byte(`{}`)
|
||||
if status != "" {
|
||||
params = []byte(`{"status":"` + status + `"}`)
|
||||
}
|
||||
answer, err := integration.RecordLifecycleRequestInTx(r.env.Ctx, r.q.Tx(), integration.LifecycleRequestSpec{
|
||||
InstanceID: site, Generation: gens[site], WorkspaceID: tenant.Workspace.ID, ConnectionID: r.conn,
|
||||
ResourceKey: "fedwiki_sites", Operation: integration.LifecycleSetStatus, Parameters: params,
|
||||
WorkflowID: dbtest.Name("wf"), RequestedByPersonID: person,
|
||||
})
|
||||
if err != nil || answer.Kind != integration.LifecycleRecorded {
|
||||
r.t.Fatalf("record on %s: %+v %v", site, answer, err)
|
||||
}
|
||||
return answer.RequestID
|
||||
}
|
||||
|
||||
// finish closes a request as succeeded.
|
||||
func (r openRotationRig) finish(id string) {
|
||||
r.t.Helper()
|
||||
r.q.Exec("UPDATE core.lifecycle_requests SET status = 'succeeded', finished_at = NOW() WHERE request_id = $1", id)
|
||||
}
|
||||
|
||||
// open runs the query as console_runtime.
|
||||
func (r openRotationRig) open(workspace, connection string) bool {
|
||||
r.t.Helper()
|
||||
r.q.Exec("SET LOCAL ROLE console_runtime")
|
||||
defer r.q.Exec("RESET ROLE")
|
||||
open, err := fwmod.New(r.q.Tx()).WorkspaceHasOpenRotation(r.env.Ctx, fwmod.WorkspaceHasOpenRotationParams{
|
||||
WorkspaceID: workspace, ConnectionID: connection, SwapCause: string(acts.InstancesSwapped),
|
||||
})
|
||||
if err != nil {
|
||||
r.t.Fatalf("WorkspaceHasOpenRotation: %v", err)
|
||||
}
|
||||
return open
|
||||
}
|
||||
|
||||
// TestWorkspaceHasOpenRotation_DB proves what counts as an open rotation
|
||||
// (design D8): a swap's accepted request, or an accepted return on a marked
|
||||
// site, and nothing else.
|
||||
func TestWorkspaceHasOpenRotation_DB(t *testing.T) {
|
||||
database := dbtest.Open(t)
|
||||
env := fedwikitest.New(t, database)
|
||||
rig := openRotationRig{t: t, env: env, db: database, q: dbtest.Tx(t, database), conn: env.Conn}
|
||||
person := func(tenant fedwikitest.Tenant) string { return tenant.Person.ID }
|
||||
|
||||
t.Run("nothing recorded", func(t *testing.T) {
|
||||
rig := rig.in(t)
|
||||
tenant := env.Tenant("RotNone")
|
||||
if rig.open(tenant.Workspace.ID, env.Conn) {
|
||||
t.Error("an empty workspace holds an open rotation")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("open swap, chosen site unmarked", func(t *testing.T) {
|
||||
rig := rig.in(t)
|
||||
tenant := env.Tenant("RotSwap")
|
||||
chosen := rig.site(tenant, "readonly", false)
|
||||
parked := rig.site(tenant, "active", false)
|
||||
asked := rig.record(tenant, chosen, "active", person(tenant))
|
||||
consequent := rig.record(tenant, parked, "readonly", "")
|
||||
if _, err := integration.RecordLifecycleAct(env.Ctx, rig.q.Tx(), integration.LifecycleAct{
|
||||
Cause: acts.InstancesSwapped, ActorPersonID: person(tenant), Asked: asked, Consequent: []string{consequent},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !rig.open(tenant.Workspace.ID, env.Conn) {
|
||||
t.Error("an open swap did not match")
|
||||
}
|
||||
if rig.open(tenant.Workspace.ID, uuid.NewString()) {
|
||||
t.Error("another connection's query matched")
|
||||
}
|
||||
rig.finish(asked)
|
||||
rig.finish(consequent)
|
||||
if rig.open(tenant.Workspace.ID, env.Conn) {
|
||||
t.Error("a finished swap matched")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("open return on a marked site", func(t *testing.T) {
|
||||
rig := rig.in(t)
|
||||
tenant := env.Tenant("RotReturn")
|
||||
other := env.Tenant("RotReturnOther")
|
||||
site := rig.site(tenant, "readonly", true)
|
||||
id := rig.record(tenant, site, "active", person(tenant))
|
||||
if !rig.open(tenant.Workspace.ID, env.Conn) {
|
||||
t.Error("an open return did not match")
|
||||
}
|
||||
if rig.open(other.Workspace.ID, env.Conn) {
|
||||
t.Error("another workspace's query matched")
|
||||
}
|
||||
rig.finish(id)
|
||||
if rig.open(tenant.Workspace.ID, env.Conn) {
|
||||
t.Error("a finished return matched")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("open free fill on an unmarked site", func(t *testing.T) {
|
||||
rig := rig.in(t)
|
||||
tenant := env.Tenant("RotFill")
|
||||
site := rig.site(tenant, "readonly", false)
|
||||
rig.record(tenant, site, "active", person(tenant))
|
||||
if rig.open(tenant.Workspace.ID, env.Conn) {
|
||||
t.Error("a free fill matched")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("accepted restore on an archived site", func(t *testing.T) {
|
||||
rig := rig.in(t)
|
||||
tenant := env.Tenant("RotRestore")
|
||||
site := rig.site(tenant, "archived", false)
|
||||
rig.record(tenant, site, "active", person(tenant))
|
||||
if rig.open(tenant.Workspace.ID, env.Conn) {
|
||||
t.Error("a restore matched")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("return whose mark the sweep cleared", func(t *testing.T) {
|
||||
rig := rig.in(t)
|
||||
tenant := env.Tenant("RotSwept")
|
||||
site := rig.site(tenant, "readonly", true)
|
||||
rig.record(tenant, site, "active", person(tenant))
|
||||
if !rig.open(tenant.Workspace.ID, env.Conn) {
|
||||
t.Fatal("an open return did not match")
|
||||
}
|
||||
rig.q.Exec("UPDATE fedwiki.sites SET force_reduced_at = NULL WHERE site_id = $1", site)
|
||||
if rig.open(tenant.Workspace.ID, env.Conn) {
|
||||
t.Error("a return whose mark was cleared still matched")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1241,6 +1241,7 @@ ON CONFLICT(domain) DO UPDATE SET
|
||||
status = excluded.status,
|
||||
storage_bytes = excluded.storage_bytes,
|
||||
last_modified_at = excluded.last_modified_at,
|
||||
force_reduced_at = CASE WHEN excluded.status = 'readonly' THEN fedwiki.sites.force_reduced_at END,
|
||||
updated_at = NOW()
|
||||
RETURNING site_id, workspace_id, domain, created_at, updated_at, status, storage_bytes, last_modified_at, force_reduced_at, archived_at
|
||||
`
|
||||
@@ -1286,8 +1287,39 @@ VALUES ($1, NOW())
|
||||
ON CONFLICT (workspace_id) DO UPDATE SET last_swap_at = NOW()
|
||||
`
|
||||
|
||||
// Records that a swap just happened (resets the cooldown clock for the workspace).
|
||||
// Records that a rotation succeeded (resets the cooldown clock for the workspace).
|
||||
func (q *Queries) UpsertSiteSwapPolicy(ctx context.Context, workspaceID string) error {
|
||||
_, err := q.db.ExecContext(ctx, upsertSiteSwapPolicy, workspaceID)
|
||||
return err
|
||||
}
|
||||
|
||||
const workspaceHasOpenRotation = `-- name: WorkspaceHasOpenRotation :one
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM core.lifecycle_requests r
|
||||
LEFT JOIN fedwiki.sites s ON s.site_id = r.instance_id
|
||||
WHERE r.workspace_id = $1::uuid
|
||||
AND r.connection_id = $2::uuid
|
||||
AND r.status = 'accepted'
|
||||
AND (r.act_cause = $3::text
|
||||
OR (r.operation = 'set_status'
|
||||
AND r.parameters->>'status' = 'active'
|
||||
AND s.force_reduced_at IS NOT NULL))
|
||||
) AS open
|
||||
`
|
||||
|
||||
type WorkspaceHasOpenRotationParams struct {
|
||||
WorkspaceID string `json:"workspace_id"`
|
||||
ConnectionID string `json:"connection_id"`
|
||||
SwapCause string `json:"swap_cause"`
|
||||
}
|
||||
|
||||
// Whether the workspace holds an open rotation on the connection: an accepted
|
||||
// request of a swap act, or an accepted set_status to active on a site a
|
||||
// downgrade or a swap parked (force_reduced_at set), which is a return.
|
||||
func (q *Queries) WorkspaceHasOpenRotation(ctx context.Context, arg WorkspaceHasOpenRotationParams) (bool, error) {
|
||||
row := q.db.QueryRowContext(ctx, workspaceHasOpenRotation, arg.WorkspaceID, arg.ConnectionID, arg.SwapCause)
|
||||
var open bool
|
||||
err := row.Scan(&open)
|
||||
return open, err
|
||||
}
|
||||
|
||||
@@ -163,9 +163,6 @@
|
||||
</td>
|
||||
<td class="text-end">
|
||||
{{ if not .Pending }}
|
||||
{{ if and .IsForceReduced $.CooldownMsg }}
|
||||
{{ template "disabledControl" (.RestoreControl $.CooldownMsg) }}
|
||||
{{ else }}
|
||||
<button class="btn btn-outline-primary btn-sm ms-1"
|
||||
hx-post="{{ routeURL "/partials/fedwiki/sites/{domain}/restore" .Domain }}"
|
||||
hx-vals='{"instance": "{{ .ID }}", "generation": "{{ .Generation }}"}'
|
||||
@@ -173,7 +170,6 @@
|
||||
hx-swap="innerHTML">
|
||||
Restore
|
||||
</button>
|
||||
{{ end }}
|
||||
<button class="btn btn-outline-danger btn-sm ms-1"
|
||||
data-bs-toggle="modal"
|
||||
data-bs-target="#confirmActionModal"
|
||||
|
||||
@@ -499,7 +499,7 @@ func (h *FedWikiHandler) CreateSite(w http.ResponseWriter, r *http.Request) {
|
||||
Domain: fqdn,
|
||||
OwnerName: session.Username,
|
||||
OwnerID: session.OIDCSubject,
|
||||
}, session.WorkspaceID, addr)
|
||||
}, session.WorkspaceID, atAddress(addr))
|
||||
if !started {
|
||||
respondError(w, http.StatusInternalServerError, "Failed to initiate site creation", h.SupportURL)
|
||||
return
|
||||
@@ -551,19 +551,20 @@ func (h *FedWikiHandler) DeleteSite(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
if withAddress {
|
||||
_, held, found, err := integration.LookupLifecycleRequest(r.Context(), h.Database, session.WorkspaceID, addr.Instance, addr.Generation)
|
||||
repeat := newRequestSpec(h.connectionID(), session.WorkspaceID, session.PersonID, integration.LifecycleDelete, addr, "", requestParams{Domain: domain})
|
||||
answer, held, err := integration.AnswerLifecycleRepeat(r.Context(), h.Database, repeat)
|
||||
if err != nil {
|
||||
h.Logger.Error("failed to look up a delete request", slog.Any("error", err))
|
||||
respondError(w, http.StatusInternalServerError, "Failed to initiate site deletion", h.SupportURL)
|
||||
return
|
||||
}
|
||||
if found {
|
||||
if !sameRowRequest(held, integration.LifecycleDelete, domain, "", session.PersonID) {
|
||||
respondError(w, http.StatusConflict, msgAPIConflict, "")
|
||||
return
|
||||
}
|
||||
switch answer.Kind {
|
||||
case integration.LifecycleRepeatOpen, integration.LifecycleRepeatFinished:
|
||||
respondRepeat(w, held, acceptedMessage)
|
||||
return
|
||||
case integration.LifecycleConflict:
|
||||
respondError(w, http.StatusConflict, msgAPIConflict, "")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -635,7 +636,7 @@ func (h *FedWikiHandler) DeleteSite(w http.ResponseWriter, r *http.Request) {
|
||||
Generation: addr.Generation,
|
||||
WorkspaceID: session.WorkspaceID,
|
||||
Domain: site.Domain,
|
||||
}, session.WorkspaceID, addr)
|
||||
}, session.WorkspaceID, atAddress(addr))
|
||||
if !started {
|
||||
respondError(w, http.StatusInternalServerError, "Failed to initiate site deletion", h.SupportURL)
|
||||
return
|
||||
|
||||
@@ -55,6 +55,10 @@ type FedWikiPartialsHandler struct {
|
||||
// FedWiki records names it.
|
||||
ConnectionID func() string
|
||||
Templates *server.SafeTemplates
|
||||
|
||||
// wrapTxQuerier lets a test observe the statements a workspace
|
||||
// transaction runs. Nil outside tests.
|
||||
wrapTxQuerier func(fwmod.Querier) fwmod.Querier
|
||||
}
|
||||
|
||||
// FedWikiPartialsConfig holds configuration for the FedWiki partials handler.
|
||||
@@ -144,7 +148,6 @@ type SiteViewModel struct {
|
||||
Status string // active | readonly | archived
|
||||
IsReadonly bool
|
||||
IsArchived bool
|
||||
IsForceReduced bool // parked by a downgrade/swap rotation, not archived by choice — Keep active/Restore on this site is cooldown-gated
|
||||
// Generation is the generation this site's next request carries: above
|
||||
// every request recorded for it, at least the clock (design D25). Each
|
||||
// row action posts it with the site id.
|
||||
@@ -187,10 +190,10 @@ type SitesData struct {
|
||||
// computed) when HasEntitlement is false.
|
||||
NoPublishedPlan bool
|
||||
// CooldownMsg, when non-empty, is the remaining-time message for the
|
||||
// workspace's active-site swap cooldown. Read-only display: the buttons
|
||||
// gated by it (readonly sites' Keep active, force-reduced archived sites'
|
||||
// Restore) are always the same rotation the server enforces on click —
|
||||
// see checkSwapCooldown and RestoreSite/KeepSiteActive's `rotation` gates.
|
||||
// workspace's active-site swap cooldown. Read-only display: the button
|
||||
// gated by it (readonly sites' Keep active) is always the same rotation
|
||||
// the server enforces on click — see checkSwapCooldown and
|
||||
// KeepSiteActive's `rotation` gate.
|
||||
CooldownMsg string
|
||||
// DomainsSurface is core's member domains surface, composed on the
|
||||
// server (page-anatomy "A page arrives complete").
|
||||
@@ -292,19 +295,6 @@ func (s SiteViewModel) KeepActiveControl(reason string) server.DisabledControl {
|
||||
)
|
||||
}
|
||||
|
||||
// RestoreControl builds the shared disabledControl part's data for a
|
||||
// force-reduced archived site's Restore button during the swap cooldown
|
||||
// (design D6), the same tooltip variant KeepActiveControl uses and for the
|
||||
// same reason.
|
||||
func (s SiteViewModel) RestoreControl(reason string) server.DisabledControl {
|
||||
return server.NewDisabledControl(
|
||||
"fedwiki-site-restore-reason-"+s.ID,
|
||||
"Restore",
|
||||
"btn btn-outline-primary btn-sm me-1",
|
||||
reason,
|
||||
)
|
||||
}
|
||||
|
||||
// GetSites handles GET /partials/fedwiki/sites
|
||||
func (h *FedWikiPartialsHandler) GetSites(w http.ResponseWriter, r *http.Request) {
|
||||
session := h.AuthConfig.GetUserSession(r.Context())
|
||||
@@ -349,7 +339,6 @@ func (h *FedWikiPartialsHandler) GetSites(w http.ResponseWriter, r *http.Request
|
||||
Status: site.Status,
|
||||
IsReadonly: site.Status == "readonly",
|
||||
IsArchived: site.Status == "archived",
|
||||
IsForceReduced: site.ForceReducedAt.Valid,
|
||||
Generation: nextGen[site.SiteID],
|
||||
}
|
||||
requests.apply(&vm)
|
||||
@@ -388,8 +377,8 @@ func (h *FedWikiPartialsHandler) GetSites(w http.ResponseWriter, r *http.Request
|
||||
count = q.Used
|
||||
}
|
||||
|
||||
// Read-only cooldown check for the Keep active/Restore hints below — the
|
||||
// authoritative gate is still re-checked server-side on click.
|
||||
// Read-only cooldown check for Keep active's disabled control below; the
|
||||
// authoritative read is still made server-side under the workspace lock.
|
||||
cooldownMsg := h.checkSwapCooldown(r.Context(), workspaceID)
|
||||
|
||||
// The "no plan includes this yet" branch only matters when the member
|
||||
@@ -638,14 +627,15 @@ func (h *FedWikiPartialsHandler) GetCreateForm(w http.ResponseWriter, r *http.Re
|
||||
// rotation is still within the configured cooldown window, or "" if it is
|
||||
// allowed (no prior rotation, the window elapsed, or the cooldown is disabled).
|
||||
// It reads through the handler's default querier; the swap path uses
|
||||
// cooldownMsgFor to re-check under the transaction that holds the advisory lock.
|
||||
// cooldownMsgFor to read the stamp under the transaction that holds the advisory lock.
|
||||
func (h *FedWikiPartialsHandler) checkSwapCooldown(ctx context.Context, workspaceID string) string {
|
||||
return h.cooldownMsgFor(ctx, h.SiteQ, workspaceID)
|
||||
}
|
||||
|
||||
// cooldownMsgFor is checkSwapCooldown against an explicit querier, so the cooldown
|
||||
// re-check can run through the same transaction that holds the per-workspace
|
||||
// advisory lock — making the check-and-stamp atomic.
|
||||
// read can run through the same transaction that holds the per-workspace
|
||||
// advisory lock, after the open-rotation check. Intake only reads the stamp;
|
||||
// a rotation's success writes it.
|
||||
func (h *FedWikiPartialsHandler) cooldownMsgFor(ctx context.Context, q fwmod.Querier, workspaceID string) string {
|
||||
window := h.SwapCooldown
|
||||
if window <= 0 {
|
||||
|
||||
@@ -187,8 +187,8 @@ func checkIntakeIdentity(t *testing.T, row intakeIdentityCase) {
|
||||
t.Errorf("%s: missing-site refresh = %v, want %v", row.name, refresh, row.wantRefresh)
|
||||
}
|
||||
count := dbtest.On(t, env.db).Int("SELECT count(*) FROM fedwiki.site_swap_policy WHERE workspace_id = $1", env.ws)
|
||||
if env.requestCount(instance) != 0 || len(env.temporal.starts()) != 0 || count != 0 {
|
||||
t.Errorf("%s: refused intake recorded work or stamped cooldown", row.name)
|
||||
if env.requestCount(instance) != 0 || len(env.temporal.starts()) != 0 || count != 0 || env.counts().headers != 0 {
|
||||
t.Errorf("%s: refused intake recorded work, wrote a header or stamped cooldown", row.name)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"go.temporal.io/api/serviceerror"
|
||||
"go.temporal.io/sdk/client"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/acts"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/integration"
|
||||
fwmod "git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/fedwiki/store"
|
||||
siteusage "git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/fedwiki/usage"
|
||||
@@ -82,10 +83,10 @@ func noticeSentence(domain, action, code string) string {
|
||||
// requestAction is the past participle a notice names a request by: the
|
||||
// action the member took. Restore and Keep active record the same status
|
||||
// change; a declined or failed one leaves the site where it was (design
|
||||
// D32), so a request to make an archived site active was a restore. A
|
||||
// swap is always a Keep active.
|
||||
func requestAction(operation string, p requestParams, siteStatus string) string {
|
||||
switch operation {
|
||||
// D32), so a request to make an archived site active was a restore, unless
|
||||
// its act is a swap, which is always a Keep active.
|
||||
func requestAction(row integration.LifecycleRequest, p requestParams, siteStatus string) string {
|
||||
switch row.Operation {
|
||||
case integration.LifecycleCreate:
|
||||
return "created"
|
||||
case integration.LifecycleDelete:
|
||||
@@ -94,7 +95,7 @@ func requestAction(operation string, p requestParams, siteStatus string) string
|
||||
switch {
|
||||
case p.Status == "archived":
|
||||
return "archived"
|
||||
case p.Status == "active" && p.SwapParkSiteID == "" && siteStatus == "archived":
|
||||
case p.Status == "active" && siteStatus == "archived" && row.ActCause.String != string(acts.InstancesSwapped):
|
||||
return "restored"
|
||||
case p.Status == "active":
|
||||
return "kept active"
|
||||
@@ -118,13 +119,11 @@ const (
|
||||
// DNS names only (the column comment on core.lifecycle_requests.parameters).
|
||||
// Domain is the fully resolved name, under the key the fedwiki.sites column
|
||||
// uses (design Open Questions 17); IsCustomDomain only on a create; Status is
|
||||
// a status change's target; the swap keys name the other site of a swap.
|
||||
// a status change's target.
|
||||
type requestParams struct {
|
||||
Domain string `json:"domain"`
|
||||
IsCustomDomain *bool `json:"is_custom_domain,omitempty"`
|
||||
Status string `json:"status,omitempty"`
|
||||
SwapParkSiteID string `json:"swap_park_site_id,omitempty"`
|
||||
SwapActivateSiteID string `json:"swap_activate_site_id,omitempty"`
|
||||
Domain string `json:"domain"`
|
||||
IsCustomDomain *bool `json:"is_custom_domain,omitempty"`
|
||||
Status string `json:"status,omitempty"`
|
||||
}
|
||||
|
||||
func (p requestParams) raw() json.RawMessage {
|
||||
@@ -168,25 +167,6 @@ func parseAddressValues(instanceRaw, generationRaw string) (requestAddress, bool
|
||||
return requestAddress{Instance: id.String(), Generation: gen}, true
|
||||
}
|
||||
|
||||
// sameRowRequest reports whether a recorded request is the one a row action
|
||||
// would record at its address: the same operation, site domain, target
|
||||
// status and requesting person (design D26's content; the workspace was
|
||||
// already matched by the lookup).
|
||||
func sameRowRequest(held integration.LifecycleRequest, operation, domain, status, personID string) bool {
|
||||
if held.Operation != operation {
|
||||
return false
|
||||
}
|
||||
heldPerson := ""
|
||||
if held.RequestedByPersonID.Valid {
|
||||
heldPerson = held.RequestedByPersonID.UUID.String()
|
||||
}
|
||||
if heldPerson != personID {
|
||||
return false
|
||||
}
|
||||
p := decodeParams(held.Parameters)
|
||||
return p.Domain == domain && p.Status == status
|
||||
}
|
||||
|
||||
// newRequestSpec builds the spec FedWiki records for one request.
|
||||
func newRequestSpec(connectionID, workspaceID, personID, operation string, addr requestAddress, workflowID string, params requestParams) integration.LifecycleRequestSpec {
|
||||
return integration.LifecycleRequestSpec{
|
||||
@@ -202,6 +182,20 @@ func newRequestSpec(connectionID, workspaceID, personID, operation string, addr
|
||||
}
|
||||
}
|
||||
|
||||
// unstartedRequests names what a failed start deletes: the request at an
|
||||
// address, or every accepted request of an act in one statement (design
|
||||
// D11). Exactly one of the two is set.
|
||||
type unstartedRequests struct {
|
||||
addr requestAddress
|
||||
actID string
|
||||
}
|
||||
|
||||
// atAddress names a single request.
|
||||
func atAddress(a requestAddress) unstartedRequests { return unstartedRequests{addr: a} }
|
||||
|
||||
// ofAct names an act's requests.
|
||||
func ofAct(id string) unstartedRequests { return unstartedRequests{actID: id} }
|
||||
|
||||
// workflowStartTimeout bounds a request's workflow start and the Describe
|
||||
// that disambiguates a failed one, once they no longer end with the member's
|
||||
// connection.
|
||||
@@ -211,7 +205,7 @@ const workflowStartTimeout = 10 * time.Second
|
||||
// the request committed (design D27). A start that succeeds, or that answers
|
||||
// that the workflow already started, is accepted. Any other start error is
|
||||
// ambiguous, so the workflow is described: only when Temporal answers that
|
||||
// it does not exist are the requests deleted and false returned, so the
|
||||
// it does not exist are the request or the act's requests deleted and false returned, so the
|
||||
// member's retry is a fresh request; on any other answer the requests stay
|
||||
// accepted for the workflow or the boot pass to settle.
|
||||
//
|
||||
@@ -219,7 +213,7 @@ const workflowStartTimeout = 10 * time.Second
|
||||
// context when the client goes away, which would fail both calls before
|
||||
// they reach Temporal and keep a request accepted that nothing started.
|
||||
func startRequestWorkflow(ctx context.Context, c client.Client, database *sql.DB, logger *slog.Logger,
|
||||
workflowID string, wf any, input any, workspaceID string, addrs ...requestAddress) bool {
|
||||
workflowID string, wf any, input any, workspaceID string, unstarted unstartedRequests) bool {
|
||||
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), workflowStartTimeout)
|
||||
defer cancel()
|
||||
_, err := c.ExecuteWorkflow(ctx, client.StartWorkflowOptions{ID: workflowID, TaskQueue: queues.Main}, wf, input)
|
||||
@@ -236,11 +230,17 @@ func startRequestWorkflow(ctx context.Context, c client.Client, database *sql.DB
|
||||
}
|
||||
return true
|
||||
}
|
||||
for _, a := range addrs {
|
||||
if _, err := integration.DeleteUnstartedLifecycleRequest(ctx, database, workspaceID, a.Instance, a.Generation); err != nil {
|
||||
logger.Error("failed to delete an unstarted lifecycle request",
|
||||
slog.String("instance", a.Instance), slog.Int64("generation", a.Generation), slog.Any("error", err))
|
||||
if unstarted.actID != "" {
|
||||
if _, err := integration.DeleteUnstartedLifecycleAct(ctx, database, workspaceID, unstarted.actID); err != nil {
|
||||
logger.Error("failed to delete an unstarted lifecycle act",
|
||||
slog.String("act", unstarted.actID), slog.Any("error", err))
|
||||
}
|
||||
return false
|
||||
}
|
||||
a := unstarted.addr
|
||||
if _, err := integration.DeleteUnstartedLifecycleRequest(ctx, database, workspaceID, a.Instance, a.Generation); err != nil {
|
||||
logger.Error("failed to delete an unstarted lifecycle request",
|
||||
slog.String("instance", a.Instance), slog.Int64("generation", a.Generation), slog.Any("error", err))
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -16,11 +16,14 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"html"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -31,6 +34,7 @@ import (
|
||||
"go.temporal.io/api/workflowservice/v1"
|
||||
"go.temporal.io/sdk/client"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/acts"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/auth"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/db"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/domains"
|
||||
@@ -60,6 +64,7 @@ type fakeTemporal struct {
|
||||
mu sync.Mutex
|
||||
started []string // workflow ids, in order
|
||||
inputs []any
|
||||
attempted []any // the first argument of every start, failed or not
|
||||
startErr error // returned by every ExecuteWorkflow when set
|
||||
describeErr error // returned by DescribeWorkflowExecution
|
||||
described int
|
||||
@@ -78,6 +83,9 @@ func (f *fakeTemporal) ExecuteWorkflow(ctx context.Context, opts client.StartWor
|
||||
if ctx.Err() != nil {
|
||||
return nil, serviceerror.NewCanceled(ctx.Err().Error())
|
||||
}
|
||||
if len(args) > 0 {
|
||||
f.attempted = append(f.attempted, args[0])
|
||||
}
|
||||
if f.startErr != nil {
|
||||
return nil, f.startErr
|
||||
}
|
||||
@@ -555,15 +563,117 @@ func TestStartFailure(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
// TestSwapStartFailureRetry: a swap whose start fails loses both requests and the retry records afresh (F11).
|
||||
func TestSwapStartFailureRetry(t *testing.T) {
|
||||
// F11: the act's requests go in one statement, the header stays,
|
||||
// and the retry records afresh with no cooldown refusal.
|
||||
e := newSiteEnv(t, 1)
|
||||
e.h.SwapCooldown = 24 * time.Hour
|
||||
r := newSwapRig(e)
|
||||
e.temporal.startErr = context.DeadlineExceeded
|
||||
e.temporal.describeErr = serviceerror.NewNotFound("no such workflow")
|
||||
firstGen := e.nextGen(r.chosenID)
|
||||
rec := e.rowAction(e.h.KeepSiteActive, "keep-active", r.chosenDomain, r.chosenID, firstGen)
|
||||
if !says(rec, "Couldn't change the active site. Try again.") || isRefresh(rec) {
|
||||
t.Fatalf("swap with no start = %d %q, want the swap's try-again sentence", rec.Code, rec.Body.String())
|
||||
}
|
||||
if got := e.counts(); got.requests != 0 || got.headers != 1 || got.stamps != 0 {
|
||||
t.Errorf("counts after the failed start = %+v, want no requests, the header kept and no stamp", got)
|
||||
}
|
||||
firstAct := e.id(`SELECT act_id::text FROM core.acts WHERE cause = 'instances_swapped' AND actor_person_id = $1`, e.person)
|
||||
failedPark := e.temporal.attempted[len(e.temporal.attempted)-1].(workflows.SwapSiteRequestInput)
|
||||
e.temporal.startErr, e.temporal.describeErr = nil, nil
|
||||
gen := firstGen
|
||||
if retry := e.rowAction(e.h.KeepSiteActive, "keep-active", r.chosenDomain, r.chosenID, gen); !accepted(retry) {
|
||||
t.Fatalf("retry = %d %q, want accepted", retry.Code, retry.Body.String())
|
||||
}
|
||||
asked, ok := e.request(r.chosenID, gen)
|
||||
in := e.temporal.inputs[len(e.temporal.inputs)-1].(workflows.SwapSiteRequestInput)
|
||||
park, parkOK := e.request(in.ParkInstanceID, in.ParkGeneration)
|
||||
if !ok || !parkOK || !asked.ActID.Valid || asked.ActID.UUID.String() == firstAct || asked.ActID != park.ActID {
|
||||
t.Errorf("retry's rows %+v and %+v, first act %s; want one new act", asked, park, firstAct)
|
||||
}
|
||||
if in.ParkInstanceID != r.parkID || in.ParkGeneration <= failedPark.ParkGeneration {
|
||||
t.Errorf("retry's park address %s/%d, want the park site at a generation after the failed attempt's %d", in.ParkInstanceID, in.ParkGeneration, failedPark.ParkGeneration)
|
||||
}
|
||||
if got := e.counts(); got.requests != 2 || got.headers != 2 {
|
||||
t.Errorf("counts after the retry = %+v, want two requests and two headers", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReturnStartFailureRetry: a return whose start fails loses its request and the retry is accepted (F11).
|
||||
func TestReturnStartFailureRetry(t *testing.T) {
|
||||
e := newSiteEnv(t, 3)
|
||||
e.h.SwapCooldown = 24 * time.Hour
|
||||
markedID, markedDomain := e.markedSite("marked")
|
||||
e.temporal.startErr = context.DeadlineExceeded
|
||||
e.temporal.describeErr = serviceerror.NewNotFound("no such workflow")
|
||||
gen := e.nextGen(markedID)
|
||||
rec := e.rowAction(e.h.KeepSiteActive, "keep-active", markedDomain, markedID, gen)
|
||||
if !says(rec, "Couldn't update the site. Try again.") || e.requestCount(markedID) != 0 {
|
||||
t.Fatalf("return with no start = %q with %d requests, want the try-again sentence and none", rec.Body.String(), e.requestCount(markedID))
|
||||
}
|
||||
e.temporal.startErr, e.temporal.describeErr = nil, nil
|
||||
if retry := e.rowAction(e.h.KeepSiteActive, "keep-active", markedDomain, markedID, gen); !accepted(retry) || e.requestCount(markedID) != 1 {
|
||||
t.Errorf("retry = %d %q with %d requests, want accepted and 1", retry.Code, retry.Body.String(), e.requestCount(markedID))
|
||||
}
|
||||
}
|
||||
|
||||
// TestSwapStartFailureDeleteFails: a swap whose delete fails keeps both requests accepted (F12).
|
||||
func TestSwapStartFailureDeleteFails(t *testing.T) {
|
||||
// F12: the retry is answered as a repeat, the list shows Pending,
|
||||
// and another rotation of the workspace is refused.
|
||||
e := newSiteEnv(t, 1)
|
||||
r := newSwapRig(e)
|
||||
otherID, otherDomain := e.site("other"+e.uniq, "readonly")
|
||||
e.failRequestDelete()
|
||||
e.temporal.startErr = context.DeadlineExceeded
|
||||
e.temporal.describeErr = serviceerror.NewNotFound("no such workflow")
|
||||
gen := e.nextGen(r.chosenID)
|
||||
rec := e.rowAction(e.h.KeepSiteActive, "keep-active", r.chosenDomain, r.chosenID, gen)
|
||||
if !says(rec, "Couldn't change the active site. Try again.") {
|
||||
t.Fatalf("swap with no start and no delete = %q, want the try-again sentence", rec.Body.String())
|
||||
}
|
||||
if got := e.counts(); got.requests != 2 {
|
||||
t.Fatalf("requests after a failed delete = %d, want both kept", got.requests)
|
||||
}
|
||||
e.temporal.startErr, e.temporal.describeErr = nil, nil
|
||||
if retry := e.rowAction(e.h.KeepSiteActive, "keep-active", r.chosenDomain, r.chosenID, gen); !accepted(retry) || len(e.temporal.starts()) != 0 {
|
||||
t.Errorf("retry = %d %q with %d starts, want a repeat answer and no start", retry.Code, retry.Body.String(), len(e.temporal.starts()))
|
||||
}
|
||||
if n := strings.Count(e.sitesList(), ">Pending<"); n != 2 {
|
||||
t.Errorf("the list shows %d Pending rows, want 2", n)
|
||||
}
|
||||
if busy := e.keepActive(otherDomain, otherID); !says(busy, msgActiveSiteBusy) {
|
||||
t.Errorf("another rotation = %q, want %q", busy.Body.String(), msgActiveSiteBusy)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSwapStartFailureAmbiguous: a swap whose describe does not answer NotFound keeps both requests (F12).
|
||||
func TestSwapStartFailureAmbiguous(t *testing.T) {
|
||||
e := newSiteEnv(t, 1)
|
||||
r := newSwapRig(e)
|
||||
e.temporal.startErr = context.DeadlineExceeded
|
||||
e.temporal.describeErr = errors.New("temporal unavailable")
|
||||
if rec := e.keepActive(r.chosenDomain, r.chosenID); !accepted(rec) {
|
||||
t.Fatalf("swap = %d %q, want accepted", rec.Code, rec.Body.String())
|
||||
}
|
||||
if got := e.counts(); got.requests != 2 || got.headers != 1 {
|
||||
t.Errorf("counts = %+v, want both requests kept under one header", got)
|
||||
}
|
||||
}
|
||||
|
||||
// repeatAction is one row action of TestRowActionRepeatTable.
|
||||
type repeatAction struct {
|
||||
name string
|
||||
status string // the site's status before
|
||||
send func(e *siteEnv, domain, id string, gen int64) *httptest.ResponseRecorder
|
||||
workflo func(id string, gen int64) string
|
||||
}
|
||||
|
||||
// TestRowActionRepeatTable covers the repeat table for each row action.
|
||||
func TestRowActionRepeatTable(t *testing.T) {
|
||||
type action struct {
|
||||
name string
|
||||
status string // the site's status before
|
||||
send func(e *siteEnv, domain, id string, gen int64) *httptest.ResponseRecorder
|
||||
workflo func(id string, gen int64) string
|
||||
}
|
||||
actions := []action{
|
||||
actions := []repeatAction{
|
||||
{"archive", "active", func(e *siteEnv, d, id string, g int64) *httptest.ResponseRecorder {
|
||||
return e.rowAction(e.h.ArchiveSite, "archive", d, id, g)
|
||||
}, workflows.SetStatusRequestWorkflowID},
|
||||
@@ -578,40 +688,50 @@ func TestRowActionRepeatTable(t *testing.T) {
|
||||
}, workflows.DeleteRequestWorkflowID},
|
||||
}
|
||||
for _, a := range actions {
|
||||
t.Run(a.name, func(t *testing.T) {
|
||||
e := newSiteEnv(t, 5)
|
||||
id, domain := e.site(strings.ReplaceAll(a.name, " ", "")+e.uniq, a.status)
|
||||
gen := e.nextGen(id)
|
||||
t.Run(a.name, func(t *testing.T) { checkRowActionRepeats(t, a) })
|
||||
}
|
||||
}
|
||||
|
||||
if rec := a.send(e, domain, id, gen); !accepted(rec) {
|
||||
t.Fatalf("new = %d %q, want accepted", rec.Code, rec.Body.String())
|
||||
}
|
||||
if got := e.temporal.starts(); len(got) != 1 || got[0] != a.workflo(id, gen) {
|
||||
t.Fatalf("starts = %v, want [%s]", got, a.workflo(id, gen))
|
||||
}
|
||||
if rec := a.send(e, domain, id, gen); !accepted(rec) || len(e.temporal.starts()) != 1 {
|
||||
t.Errorf("repeat while open = %d %q, starts %d; want accepted and no start", rec.Code, rec.Body.String(), len(e.temporal.starts()))
|
||||
}
|
||||
e.finish(id, gen, integration.LifecycleSucceeded, "")
|
||||
if a.name == "delete" {
|
||||
e.exec(`DELETE FROM fedwiki.sites WHERE site_id = $1`, id)
|
||||
}
|
||||
// Answered from the record, even after a permanent delete
|
||||
// removed the site the path names.
|
||||
if rec := a.send(e, domain, id, gen); !accepted(rec) || len(e.temporal.starts()) != 1 {
|
||||
t.Errorf("repeat after finish = %d %q, starts %d; want the stored outcome and no start", rec.Code, rec.Body.String(), len(e.temporal.starts()))
|
||||
}
|
||||
if a.name == "delete" {
|
||||
return
|
||||
}
|
||||
// An older tab: a generation below the latest that holds nothing.
|
||||
if rec := a.send(e, domain, id, gen-1); !conflicted(rec) {
|
||||
t.Errorf("older tab = %d %q, want the conflict sentence and a refresh", rec.Code, rec.Body.String())
|
||||
}
|
||||
if e.requestCount(id) != 1 || len(e.temporal.starts()) != 1 {
|
||||
t.Errorf("older tab recorded or started something")
|
||||
}
|
||||
})
|
||||
// checkRowActionRepeats runs one action through new, repeat while open,
|
||||
// repeat after finish, an older tab, and the site's deletion.
|
||||
func checkRowActionRepeats(t *testing.T, a repeatAction) {
|
||||
e := newSiteEnv(t, 5)
|
||||
id, domain := e.site(strings.ReplaceAll(a.name, " ", "")+e.uniq, a.status)
|
||||
gen := e.nextGen(id)
|
||||
|
||||
if rec := a.send(e, domain, id, gen); !accepted(rec) {
|
||||
t.Fatalf("new = %d %q, want accepted", rec.Code, rec.Body.String())
|
||||
}
|
||||
if got := e.temporal.starts(); len(got) != 1 || got[0] != a.workflo(id, gen) {
|
||||
t.Fatalf("starts = %v, want [%s]", got, a.workflo(id, gen))
|
||||
}
|
||||
if rec := a.send(e, domain, id, gen); !accepted(rec) || len(e.temporal.starts()) != 1 {
|
||||
t.Errorf("repeat while open = %d %q, starts %d; want accepted and no start", rec.Code, rec.Body.String(), len(e.temporal.starts()))
|
||||
}
|
||||
e.finish(id, gen, integration.LifecycleSucceeded, "")
|
||||
if a.name == "delete" {
|
||||
e.exec(`DELETE FROM fedwiki.sites WHERE site_id = $1`, id)
|
||||
}
|
||||
// Answered from the record, even after a permanent delete
|
||||
// removed the site the path names.
|
||||
if rec := a.send(e, domain, id, gen); !accepted(rec) || len(e.temporal.starts()) != 1 {
|
||||
t.Errorf("repeat after finish = %d %q, starts %d; want the stored outcome and no start", rec.Code, rec.Body.String(), len(e.temporal.starts()))
|
||||
}
|
||||
if a.name == "delete" {
|
||||
return
|
||||
}
|
||||
// An older tab: a generation below the latest that holds nothing.
|
||||
if rec := a.send(e, domain, id, gen-1); !conflicted(rec) {
|
||||
t.Errorf("older tab = %d %q, want the conflict sentence and a refresh", rec.Code, rec.Body.String())
|
||||
}
|
||||
if e.requestCount(id) != 1 || len(e.temporal.starts()) != 1 {
|
||||
t.Errorf("older tab recorded or started something")
|
||||
}
|
||||
// A permanent delete removing the site leaves the record: the
|
||||
// repeat is still answered from it (design D7).
|
||||
e.exec(`DELETE FROM fedwiki.sites WHERE site_id = $1`, id)
|
||||
if rec := a.send(e, domain, id, gen); !accepted(rec) || len(e.temporal.starts()) != 1 {
|
||||
t.Errorf("repeat after the site's deletion = %d %q, starts %d; want the stored outcome and no start", rec.Code, rec.Body.String(), len(e.temporal.starts()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -670,6 +790,29 @@ func TestOneOpenRequestPerSite(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// requireSwapAct requires the swap's two rows to carry the member only on the
|
||||
// asked row, no swap key, and one swap act with both roles.
|
||||
func requireSwapAct(t *testing.T, e *siteEnv, asked, park integration.LifecycleRequest) {
|
||||
t.Helper()
|
||||
if park.RequestedByPersonID.Valid || !asked.RequestedByPersonID.Valid {
|
||||
t.Errorf("person of the asked row %v, of the park row %v; want the member on the asked row only", asked.RequestedByPersonID, park.RequestedByPersonID)
|
||||
}
|
||||
for _, row := range []integration.LifecycleRequest{asked, park} {
|
||||
if strings.Contains(string(row.Parameters), "swap_") {
|
||||
t.Errorf("request %s carries a swap key: %s", row.InstanceID, row.Parameters)
|
||||
}
|
||||
}
|
||||
if !asked.ActID.Valid || asked.ActID != park.ActID ||
|
||||
asked.ActRole.String != integration.LifecycleActAsked || park.ActRole.String != integration.LifecycleActConsequent ||
|
||||
asked.ActCause.String != string(acts.InstancesSwapped) || park.ActCause.String != string(acts.InstancesSwapped) {
|
||||
t.Errorf("asked row act %v/%v/%v, park row act %v/%v/%v; want one swap act, asked and consequent",
|
||||
asked.ActID, asked.ActRole, asked.ActCause, park.ActID, park.ActRole, park.ActCause)
|
||||
}
|
||||
if n := e.id("SELECT count(*)::text FROM core.acts WHERE act_id = $1", asked.ActID.UUID); n != "1" {
|
||||
t.Errorf("acts for the swap = %s, want 1", n)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSwapHoldsBothSites: archiving the parked site during a swap is
|
||||
// refused, and a swap whose park target has an open request is refused.
|
||||
func TestSwapHoldsBothSites(t *testing.T) {
|
||||
@@ -689,6 +832,8 @@ func TestSwapHoldsBothSites(t *testing.T) {
|
||||
if in.ParkInstanceID != activeID || !ok || park.WorkflowID != workflows.SwapRequestWorkflowID(chosenID, gen) {
|
||||
t.Fatalf("park request = %+v (%v), input %+v", park, ok, in)
|
||||
}
|
||||
asked, _ := e.request(chosenID, gen)
|
||||
requireSwapAct(t, e, asked, park)
|
||||
rec := e.rowAction(e.h.ArchiveSite, "archive", activeDomain, activeID, e.nextGen(activeID))
|
||||
if !strings.Contains(rec.Body.String(), msgSiteBusy) || len(e.temporal.starts()) != 1 {
|
||||
t.Errorf("archive of the parked site = %q with %d starts, want %q and no start", rec.Body.String(), len(e.temporal.starts()), msgSiteBusy)
|
||||
@@ -1111,16 +1256,19 @@ func TestNoticeSentences(t *testing.T) {
|
||||
actions := []struct {
|
||||
name, operation, siteStatus, want string
|
||||
params requestParams
|
||||
actCause string
|
||||
}{
|
||||
{"create", integration.LifecycleCreate, "", "created", requestParams{}},
|
||||
{"archive", integration.LifecycleSetStatus, "active", "archived", requestParams{Status: "archived"}},
|
||||
{"restore", integration.LifecycleSetStatus, "archived", "restored", requestParams{Status: "active"}},
|
||||
{"keep active", integration.LifecycleSetStatus, "readonly", "kept active", requestParams{Status: "active"}},
|
||||
{"keep active by a swap", integration.LifecycleSetStatus, "readonly", "kept active", requestParams{Status: "active", SwapParkSiteID: "park"}},
|
||||
{"delete", integration.LifecycleDelete, "archived", "deleted", requestParams{}},
|
||||
{"create", integration.LifecycleCreate, "", "created", requestParams{}, ""},
|
||||
{"archive", integration.LifecycleSetStatus, "active", "archived", requestParams{Status: "archived"}, ""},
|
||||
{"restore", integration.LifecycleSetStatus, "archived", "restored", requestParams{Status: "active"}, ""},
|
||||
{"keep active", integration.LifecycleSetStatus, "readonly", "kept active", requestParams{Status: "active"}, ""},
|
||||
{"keep active by a swap", integration.LifecycleSetStatus, "archived", "kept active", requestParams{Status: "active"}, string(acts.InstancesSwapped)},
|
||||
{"keep active of a parked site that is not a swap", integration.LifecycleSetStatus, "readonly", "kept active", requestParams{Status: "active"}, ""},
|
||||
{"delete", integration.LifecycleDelete, "archived", "deleted", requestParams{}, ""},
|
||||
}
|
||||
for _, a := range actions {
|
||||
if got := requestAction(a.operation, a.params, a.siteStatus); got != a.want {
|
||||
row := integration.LifecycleRequest{Operation: a.operation, ActCause: sql.NullString{String: a.actCause, Valid: a.actCause != ""}}
|
||||
if got := requestAction(row, a.params, a.siteStatus); got != a.want {
|
||||
t.Errorf("%s: requestAction = %q, want %q", a.name, got, a.want)
|
||||
}
|
||||
}
|
||||
@@ -1206,6 +1354,24 @@ func TestSwapNoticeOnce(t *testing.T) {
|
||||
if strings.Contains(list, incumbentDomain+" wasn") {
|
||||
t.Errorf("the swap's parked site has a notice of its own")
|
||||
}
|
||||
cancelled, cancel := context.WithCancel(e.sctx)
|
||||
cancel()
|
||||
failed := httptest.NewRequest(http.MethodPost, "/partials/fedwiki/requests/x/y/dismiss", nil).WithContext(cancelled)
|
||||
failed.SetPathValue("instance", chosenID)
|
||||
failed.SetPathValue("generation", strconv.FormatInt(gen, 10))
|
||||
failedRec := httptest.NewRecorder()
|
||||
e.h.DismissRequest(failedRec, failed)
|
||||
if failedRec.Code != http.StatusInternalServerError {
|
||||
t.Errorf("failed dismissal = %d, want 500", failedRec.Code)
|
||||
}
|
||||
for _, a := range []requestAddress{{chosenID, gen}, {in.ParkInstanceID, in.ParkGeneration}} {
|
||||
if req, ok := e.request(a.Instance, a.Generation); !ok || req.AcknowledgedAt.Valid {
|
||||
t.Errorf("swap row %s/%d after a failed dismissal: %+v, want unacknowledged", a.Instance, a.Generation, req)
|
||||
}
|
||||
}
|
||||
if got := notices(t, e.sitesList()); len(got) != 1 {
|
||||
t.Errorf("notices after a failed dismissal = %q, want the swap's notice kept", got)
|
||||
}
|
||||
dismiss := e.post(e.h.DismissRequest, "/partials/fedwiki/requests/x/y/dismiss",
|
||||
map[string]string{"instance": chosenID, "generation": strconv.FormatInt(gen, 10)}, nil)
|
||||
if dismiss.Code != http.StatusOK {
|
||||
@@ -1221,6 +1387,58 @@ func TestSwapNoticeOnce(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// storedRow records a set_status request with no act, as a swap recorded
|
||||
// before acts left it: under the swap's shared workflow id, with the old
|
||||
// swap key in its parameters, and ends it.
|
||||
func (e *siteEnv) storedRow(instance, domain, status, workflowID, keyName, keyValue, outcome, reason string) int64 {
|
||||
e.t.Helper()
|
||||
addr := requestAddress{Instance: instance, Generation: e.nextGen(instance)}
|
||||
spec := newRequestSpec(e.h.connectionID(), e.ws, e.person, integration.LifecycleSetStatus, addr, workflowID, requestParams{Domain: domain, Status: status})
|
||||
raw, err := json.Marshal(map[string]string{"domain": domain, "status": status, keyName: keyValue})
|
||||
if err != nil {
|
||||
e.t.Fatal(err)
|
||||
}
|
||||
spec.Parameters = raw
|
||||
if a, err := integration.RecordLifecycleRequest(e.ctx, e.db, spec); err != nil || a.Kind != integration.LifecycleRecorded {
|
||||
e.t.Fatalf("record stored row: %v %+v", err, a)
|
||||
}
|
||||
e.finish(instance, addr.Generation, outcome, reason)
|
||||
return addr.Generation
|
||||
}
|
||||
|
||||
// TestStoredRowsHaveNoAct: a stored swap's activated row that ended
|
||||
// site_missing while its site exists reads the generic sentence, a stored
|
||||
// parked row shows its own notice, and dismissing one acknowledges that row
|
||||
// only.
|
||||
func TestStoredRowsHaveNoAct(t *testing.T) {
|
||||
e := newSiteEnv(t, 3)
|
||||
chosenID, chosenDomain := e.site("chosen"+e.uniq, "readonly")
|
||||
parkID, parkDomain := e.site("parked"+e.uniq, "readonly")
|
||||
// Both rows of one stored swap share the workflow id the first row's
|
||||
// address names, as the previous release wrote them.
|
||||
wf := workflows.SwapRequestWorkflowID(chosenID, e.nextGen(chosenID))
|
||||
chosenGen := e.storedRow(chosenID, chosenDomain, "active", wf, "swap_park_site_id", parkID, integration.LifecycleDeclined, workflows.ReasonSiteMissing)
|
||||
parkGen := e.storedRow(parkID, parkDomain, "readonly", wf, "swap_activate_site_id", chosenID, integration.LifecycleFailed, workflows.ReasonRetriesExhausted)
|
||||
|
||||
want := []string{parkDomain + " wasn't changed. Try again later.", chosenDomain + " wasn't kept active. Try again later."}
|
||||
got := notices(t, e.sitesList())
|
||||
slices.Sort(got)
|
||||
slices.Sort(want)
|
||||
if fmt.Sprint(got) != fmt.Sprint(want) {
|
||||
t.Fatalf("notices = %q, want %q", got, want)
|
||||
}
|
||||
if rec := e.post(e.h.DismissRequest, "/dismiss",
|
||||
map[string]string{"instance": parkID, "generation": strconv.FormatInt(parkGen, 10)}, nil); rec.Code != http.StatusOK {
|
||||
t.Fatalf("dismiss = %d %q", rec.Code, rec.Body.String())
|
||||
}
|
||||
if r, ok := e.request(parkID, parkGen); !ok || !r.AcknowledgedAt.Valid {
|
||||
t.Errorf("the dismissed stored row = %+v, want acknowledged", r)
|
||||
}
|
||||
if r, ok := e.request(chosenID, chosenGen); !ok || r.AcknowledgedAt.Valid {
|
||||
t.Errorf("the other stored row = %+v, want unacknowledged", r)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDismissFailureKeepsNotice: a dismissal that cannot be recorded
|
||||
// answers 500, which htmx-config leaves unswapped, so the notice stays.
|
||||
func TestDismissFailureKeepsNotice(t *testing.T) {
|
||||
@@ -1427,6 +1645,33 @@ func TestAPIDelete(t *testing.T) {
|
||||
t.Errorf("repeat after finish = %d %s, want the stored outcome", rec.Code, rec.Body.String())
|
||||
}
|
||||
})
|
||||
t.Run("with identifiers, repeated while open", func(t *testing.T) {
|
||||
e := newSiteEnv(t, 5)
|
||||
id, domain := e.site("apidelopen"+e.uniq, "archived")
|
||||
q := addressForm(id, e.nextGen(id))
|
||||
if rec := e.apiDelete(domain, q); rec.Code != http.StatusAccepted {
|
||||
t.Fatalf("delete = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec := e.apiDelete(domain, q); rec.Code != http.StatusAccepted || len(e.temporal.starts()) != 1 {
|
||||
t.Errorf("repeat while open = %d %s, starts %d; want 202 and no start", rec.Code, rec.Body.String(), len(e.temporal.starts()))
|
||||
}
|
||||
})
|
||||
t.Run("with identifiers, the address holds other content", func(t *testing.T) {
|
||||
e := newSiteEnv(t, 5)
|
||||
id, domain := e.site("apidelconf"+e.uniq, "active")
|
||||
gen := e.nextGen(id)
|
||||
if rec := e.rowAction(e.h.ArchiveSite, "archive", domain, id, gen); !accepted(rec) {
|
||||
t.Fatalf("archive = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
// Finished and its site gone: only the lookup at the address can
|
||||
// answer the conflict, before any site is resolved.
|
||||
e.finish(id, gen, integration.LifecycleSucceeded, "")
|
||||
e.exec(`DELETE FROM fedwiki.sites WHERE site_id = $1`, id)
|
||||
rec := e.apiDelete(domain, addressForm(id, gen))
|
||||
if rec.Code != http.StatusConflict || !strings.Contains(rec.Body.String(), msgAPIConflict) {
|
||||
t.Errorf("delete at an archive's address = %d %s, want 409 %q", rec.Code, rec.Body.String(), msgAPIConflict)
|
||||
}
|
||||
})
|
||||
t.Run("without identifiers", func(t *testing.T) {
|
||||
e := newSiteEnv(t, 5)
|
||||
id, domain := e.site("apidel2"+e.uniq, "archived")
|
||||
@@ -1721,3 +1966,355 @@ func TestKeepActiveUsesRecordedTimeOrCreation_DB(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// failRequestInsert is the seam that makes the insert of one instance's
|
||||
// lifecycle request fail or change: a BEFORE INSERT trigger on
|
||||
// core.lifecycle_requests for that instance, whose plpgsql body the test
|
||||
// names (it ends with RETURN NEW unless it raises). The trigger is dropped
|
||||
// when the test ends.
|
||||
func (e *siteEnv) failRequestInsert(instance, body string) {
|
||||
e.t.Helper()
|
||||
name := fmt.Sprintf("fedwiki_web_fail_%d", time.Now().UnixNano())
|
||||
e.exec(fmt.Sprintf(`
|
||||
CREATE FUNCTION public.%[1]s() RETURNS TRIGGER LANGUAGE plpgsql AS $$ BEGIN %[3]s END; $$;
|
||||
CREATE TRIGGER %[1]s BEFORE INSERT ON core.lifecycle_requests
|
||||
FOR EACH ROW WHEN (NEW.instance_id = '%[2]s') EXECUTE FUNCTION public.%[1]s();`, name, instance, body))
|
||||
e.t.Cleanup(func() {
|
||||
e.exec(fmt.Sprintf(`DROP TRIGGER IF EXISTS %[1]s ON core.lifecycle_requests; DROP FUNCTION IF EXISTS public.%[1]s();`, name))
|
||||
})
|
||||
}
|
||||
|
||||
// failRequestDelete makes every delete of the workspace's lifecycle requests
|
||||
// fail, as a database error on the statement that removes an unstarted
|
||||
// request would. The trigger is dropped when the test ends.
|
||||
func (e *siteEnv) failRequestDelete() {
|
||||
e.t.Helper()
|
||||
name := fmt.Sprintf("fedwiki_web_faildel_%d", time.Now().UnixNano())
|
||||
e.exec(fmt.Sprintf(`
|
||||
CREATE FUNCTION public.%[1]s() RETURNS TRIGGER LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected failure'; RETURN OLD; END; $$;
|
||||
CREATE TRIGGER %[1]s BEFORE DELETE ON core.lifecycle_requests
|
||||
FOR EACH ROW WHEN (OLD.workspace_id = '%[2]s') EXECUTE FUNCTION public.%[1]s();`, name, e.ws))
|
||||
e.t.Cleanup(func() {
|
||||
e.exec(fmt.Sprintf(`DROP TRIGGER IF EXISTS %[1]s ON core.lifecycle_requests; DROP FUNCTION IF EXISTS public.%[1]s();`, name))
|
||||
})
|
||||
}
|
||||
|
||||
// intakeCounts is what an intake may have written for the workspace.
|
||||
type intakeCounts struct{ requests, headers, starts, stamps int }
|
||||
|
||||
func (e *siteEnv) counts() intakeCounts {
|
||||
e.t.Helper()
|
||||
n := func(q string, arg any) int {
|
||||
var v int
|
||||
if err := e.db.QueryRowContext(e.ctx, q, arg).Scan(&v); err != nil {
|
||||
e.t.Fatal(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
return intakeCounts{
|
||||
requests: n(`SELECT count(*) FROM core.lifecycle_requests WHERE workspace_id = $1`, e.ws),
|
||||
headers: n(`SELECT count(*) FROM core.acts WHERE cause = 'instances_swapped' AND actor_person_id = $1`, e.person),
|
||||
starts: len(e.temporal.starts()),
|
||||
stamps: n(`SELECT count(*) FROM fedwiki.site_swap_policy WHERE workspace_id = $1`, e.ws),
|
||||
}
|
||||
}
|
||||
|
||||
// stamp writes the workspace's cooldown stamp as a rotation that succeeded
|
||||
// just now would.
|
||||
func (e *siteEnv) stamp() {
|
||||
e.t.Helper()
|
||||
e.exec(`INSERT INTO fedwiki.site_swap_policy (workspace_id, last_swap_at) VALUES ($1, NOW())`, e.ws)
|
||||
e.t.Cleanup(func() { e.exec(`DELETE FROM fedwiki.site_swap_policy WHERE workspace_id = $1`, e.ws) })
|
||||
}
|
||||
|
||||
// setUsage stores the pool's fedwiki_sites figure, as the count a writer of a
|
||||
// site row or a hold would have stored.
|
||||
func (e *siteEnv) setUsage(used int64) {
|
||||
e.t.Helper()
|
||||
if _, err := entitlements.New(e.db).SetNumericUsage(e.ctx, entitlements.SetNumericUsageParams{
|
||||
Usage: used, PoolID: e.pool, ResourceKey: siteusage.ResourceKey,
|
||||
}); err != nil {
|
||||
e.t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// keepActive posts Keep active on a site under its next generation.
|
||||
func (e *siteEnv) keepActive(domain, instance string) *httptest.ResponseRecorder {
|
||||
e.t.Helper()
|
||||
return e.rowAction(e.h.KeepSiteActive, "keep-active", domain, instance, e.nextGen(instance))
|
||||
}
|
||||
|
||||
// swapRig is a workspace at its limit of one: an active incumbent the swap
|
||||
// parks and a read-only site it activates.
|
||||
type swapRig struct {
|
||||
parkID, parkDomain, chosenID, chosenDomain string
|
||||
}
|
||||
|
||||
func newSwapRig(e *siteEnv) swapRig {
|
||||
var r swapRig
|
||||
r.parkID, r.parkDomain = e.site("incumbent"+e.uniq, "active")
|
||||
r.chosenID, r.chosenDomain = e.site("chosen"+e.uniq, "readonly")
|
||||
return r
|
||||
}
|
||||
|
||||
// TestSwapRepeatIsAnsweredFromItsRecord: a second click of an open swap and of
|
||||
// a finished one is answered from the record (F1); the same address with
|
||||
// other content, and a stored swap's park address posted from a stale tab,
|
||||
// answer the changed-site sentence and write no header (F2).
|
||||
func TestSwapRepeatIsAnsweredFromItsRecord(t *testing.T) {
|
||||
e := newSiteEnv(t, 1)
|
||||
r := newSwapRig(e)
|
||||
gen := e.nextGen(r.chosenID)
|
||||
if rec := e.rowAction(e.h.KeepSiteActive, "keep-active", r.chosenDomain, r.chosenID, gen); !accepted(rec) {
|
||||
t.Fatalf("swap = %d %q", rec.Code, rec.Body.String())
|
||||
}
|
||||
in := e.temporal.inputs[0].(workflows.SwapSiteRequestInput)
|
||||
want := e.counts()
|
||||
|
||||
t.Run("a second click of an open swap", func(t *testing.T) {
|
||||
if rec := e.rowAction(e.h.KeepSiteActive, "keep-active", r.chosenDomain, r.chosenID, gen); !accepted(rec) {
|
||||
t.Errorf("repeat of the open swap = %d %q, want accepted", rec.Code, rec.Body.String())
|
||||
}
|
||||
if got := e.counts(); got != want {
|
||||
t.Errorf("a repeat wrote: %+v, want %+v", got, want)
|
||||
}
|
||||
})
|
||||
t.Run("the same address with other content", func(t *testing.T) {
|
||||
rec := e.rowAction(e.h.ArchiveSite, "archive", r.chosenDomain, r.chosenID, gen)
|
||||
if !conflicted(rec) {
|
||||
t.Errorf("archive at the swap's address = %q, want %q and a refresh", rec.Body.String(), msgSiteChanged)
|
||||
}
|
||||
if got := e.counts(); got != want {
|
||||
t.Errorf("a conflict wrote: %+v, want %+v", got, want)
|
||||
}
|
||||
})
|
||||
t.Run("a stale tab posting the stored park address", func(t *testing.T) {
|
||||
rec := e.rowAction(e.h.KeepSiteActive, "keep-active", r.parkDomain, in.ParkInstanceID, in.ParkGeneration)
|
||||
if !conflicted(rec) {
|
||||
t.Errorf("keep active at the park row's address = %q, want %q and a refresh", rec.Body.String(), msgSiteChanged)
|
||||
}
|
||||
if got := e.counts(); got != want {
|
||||
t.Errorf("a conflict wrote: %+v, want %+v", got, want)
|
||||
}
|
||||
})
|
||||
t.Run("a second click of a finished swap", func(t *testing.T) {
|
||||
e.finish(r.chosenID, gen, integration.LifecycleSucceeded, "")
|
||||
e.finish(in.ParkInstanceID, in.ParkGeneration, integration.LifecycleSucceeded, "")
|
||||
if rec := e.rowAction(e.h.KeepSiteActive, "keep-active", r.chosenDomain, r.chosenID, gen); !accepted(rec) {
|
||||
t.Errorf("repeat of the finished swap = %d %q, want accepted", rec.Code, rec.Body.String())
|
||||
}
|
||||
if got := e.counts(); got != want {
|
||||
t.Errorf("a repeat wrote: %+v, want %+v", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestSwapIntakeRefusals: each refusal of the swap's intake answers its
|
||||
// sentence and leaves no request, no header and no stamp (F3, F4, F7).
|
||||
func TestSwapIntakeRefusals(t *testing.T) {
|
||||
refused := func(t *testing.T, e *siteEnv, rec *httptest.ResponseRecorder, want string, before intakeCounts) {
|
||||
t.Helper()
|
||||
if !strings.Contains(rec.Body.String(), want) {
|
||||
t.Errorf("answer = %d %q, want %q", rec.Code, rec.Body.String(), want)
|
||||
}
|
||||
if got := e.counts(); got != before {
|
||||
t.Errorf("a refused swap wrote: %+v, want %+v", got, before)
|
||||
}
|
||||
}
|
||||
for _, cooldown := range []time.Duration{0, 24 * time.Hour} {
|
||||
t.Run("another swap is open, cooldown "+cooldown.String(), func(t *testing.T) {
|
||||
e := newSiteEnv(t, 1)
|
||||
e.h.SwapCooldown = cooldown
|
||||
r := newSwapRig(e)
|
||||
if rec := e.keepActive(r.chosenDomain, r.chosenID); !accepted(rec) {
|
||||
t.Fatalf("first swap = %d %q", rec.Code, rec.Body.String())
|
||||
}
|
||||
otherID, otherDomain := e.site("second"+e.uniq, "readonly")
|
||||
before := e.counts()
|
||||
refused(t, e, e.keepActive(otherDomain, otherID), msgActiveSiteBusy, before)
|
||||
})
|
||||
}
|
||||
t.Run("inside the cooldown window", func(t *testing.T) {
|
||||
e := newSiteEnv(t, 1)
|
||||
e.h.SwapCooldown = 24 * time.Hour
|
||||
r := newSwapRig(e)
|
||||
e.stamp()
|
||||
before := e.counts()
|
||||
refused(t, e, e.keepActive(r.chosenDomain, r.chosenID), "try again in about", before)
|
||||
})
|
||||
t.Run("no active site of its own", func(t *testing.T) {
|
||||
e := newSiteEnv(t, 1)
|
||||
chosenID, chosenDomain := e.site("chosen"+e.uniq, "readonly")
|
||||
e.setUsage(1) // a sibling workspace of the pool holds its one slot
|
||||
before := e.counts()
|
||||
refused(t, e, e.keepActive(chosenDomain, chosenID), reasonSentence(workflows.ReasonActiveLimitReached), before)
|
||||
})
|
||||
t.Run("the chosen site is busy", func(t *testing.T) {
|
||||
e := newSiteEnv(t, 1)
|
||||
r := newSwapRig(e)
|
||||
if rec := e.rowAction(e.h.ArchiveSite, "archive", r.chosenDomain, r.chosenID, e.nextGen(r.chosenID)); !accepted(rec) {
|
||||
t.Fatalf("archive = %d %q", rec.Code, rec.Body.String())
|
||||
}
|
||||
before := e.counts()
|
||||
refused(t, e, e.keepActive(r.chosenDomain, r.chosenID), msgSiteBusy, before)
|
||||
})
|
||||
t.Run("the park site is busy", func(t *testing.T) {
|
||||
e := newSiteEnv(t, 1)
|
||||
r := newSwapRig(e)
|
||||
if rec := e.rowAction(e.h.ArchiveSite, "archive", r.parkDomain, r.parkID, e.nextGen(r.parkID)); !accepted(rec) {
|
||||
t.Fatalf("archive = %d %q", rec.Code, rec.Body.String())
|
||||
}
|
||||
before := e.counts()
|
||||
refused(t, e, e.keepActive(r.chosenDomain, r.chosenID), msgActiveSiteBusy, before)
|
||||
})
|
||||
}
|
||||
|
||||
// TestSwapIntakeFailureRollsBack: a database error and a writer refusal
|
||||
// answer one sentence with both requests and the header rolled back (F8). The
|
||||
// consequent request's insert is the statement that fails, or names the member
|
||||
// so the act's writer refuses it.
|
||||
func TestSwapIntakeFailureRollsBack(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name, body, logged string
|
||||
}{
|
||||
{"a database error", `RAISE EXCEPTION 'injected failure'; RETURN NEW;`, "injected failure"},
|
||||
{"a writer refusal", `NEW.requested_by_person_id := '%s'; RETURN NEW;`, "lifecycle_act_consequent_names_a_person"},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
e := newSiteEnv(t, 1)
|
||||
var logs bytes.Buffer
|
||||
e.h.Logger = slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelError}))
|
||||
r := newSwapRig(e)
|
||||
body := c.body
|
||||
if strings.Contains(body, "%s") {
|
||||
body = fmt.Sprintf(body, e.person)
|
||||
}
|
||||
e.failRequestInsert(r.parkID, body)
|
||||
before := e.counts()
|
||||
rec := e.keepActive(r.chosenDomain, r.chosenID)
|
||||
if !strings.Contains(html.UnescapeString(rec.Body.String()), "Couldn't change the active site. Try again.") || isRefresh(rec) {
|
||||
t.Errorf("answer = %d %q, want the swap's try-again sentence", rec.Code, rec.Body.String())
|
||||
}
|
||||
if got := e.counts(); got != before {
|
||||
t.Errorf("a failed intake wrote: %+v, want %+v", got, before)
|
||||
}
|
||||
if !strings.Contains(logs.String(), c.logged) {
|
||||
t.Errorf("the log does not name %q: %s", c.logged, logs.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestSwapIntakeRecordsTwoRequestsAndOneAct: a successful intake leaves two
|
||||
// accepted requests, one swap header whose actor is the member, and no stamp.
|
||||
func TestSwapIntakeRecordsTwoRequestsAndOneAct(t *testing.T) {
|
||||
e := newSiteEnv(t, 1)
|
||||
r := newSwapRig(e)
|
||||
gen := e.nextGen(r.chosenID)
|
||||
if rec := e.rowAction(e.h.KeepSiteActive, "keep-active", r.chosenDomain, r.chosenID, gen); !accepted(rec) {
|
||||
t.Fatalf("swap = %d %q", rec.Code, rec.Body.String())
|
||||
}
|
||||
in := e.temporal.inputs[0].(workflows.SwapSiteRequestInput)
|
||||
asked, _ := e.request(r.chosenID, gen)
|
||||
park, _ := e.request(in.ParkInstanceID, in.ParkGeneration)
|
||||
for _, row := range []integration.LifecycleRequest{asked, park} {
|
||||
if row.Status != integration.LifecycleAccepted {
|
||||
t.Errorf("request %s is %s, want accepted", row.InstanceID, row.Status)
|
||||
}
|
||||
}
|
||||
requireSwapAct(t, e, asked, park)
|
||||
if got, want := e.counts(), (intakeCounts{requests: 2, headers: 1, starts: 1, stamps: 0}); got != want {
|
||||
t.Errorf("counts = %+v, want %+v", got, want)
|
||||
}
|
||||
actor := e.id(`SELECT actor_person_id::text FROM core.acts WHERE act_id = $1`, asked.ActID.UUID)
|
||||
if actor != e.person {
|
||||
t.Errorf("the header's actor is %s, want the member %s", actor, e.person)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRestoreOfANonArchivedRow_DB: a Restore posted for a row that is not
|
||||
// archived records nothing, starts nothing and answers the conflict (F10a).
|
||||
func TestRestoreOfANonArchivedRow_DB(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
row func(e *siteEnv) (id, domain string)
|
||||
}{
|
||||
{"a marked read-only row", func(e *siteEnv) (string, string) { return e.markedSite("marked") }},
|
||||
{"an active row", func(e *siteEnv) (string, string) { return e.site("active"+e.uniq, "active") }},
|
||||
}
|
||||
for _, row := range cases {
|
||||
t.Run(row.name, func(t *testing.T) {
|
||||
e := newSiteEnv(t, 3)
|
||||
id, domain := row.row(e)
|
||||
before := e.counts()
|
||||
rec := e.rowAction(e.h.RestoreSite, "restore", domain, id, e.nextGen(id))
|
||||
if !conflicted(rec) {
|
||||
t.Errorf("restore = %d %q, want the conflict and a refresh", rec.Code, rec.Body.String())
|
||||
}
|
||||
if got := e.counts(); got != before {
|
||||
t.Errorf("counts = %+v, want %+v: nothing recorded", got, before)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestRestoreIsNeverARotation_DB: a Restore of an archived row is accepted
|
||||
// while a rotation is open and inside the cooldown window, takes no workspace
|
||||
// lock and writes no stamp at intake; a database error answers the single-site
|
||||
// sentence. The record step's success of a Restore stamping nothing is covered
|
||||
// in the workflows package ("a free fill and a Restore stamp nothing").
|
||||
func TestRestoreIsNeverARotation_DB(t *testing.T) {
|
||||
for _, cooldown := range cooldowns {
|
||||
t.Run("accepted, cooldown "+cooldown.String(), func(t *testing.T) {
|
||||
e := newSiteEnv(t, 4)
|
||||
e.h.SwapCooldown = cooldown
|
||||
markedID, markedDomain := e.markedSite("marked")
|
||||
archivedID, archivedDomain := e.site("archived"+e.uniq, "archived")
|
||||
if rec := e.keepActive(markedDomain, markedID); !accepted(rec) {
|
||||
t.Fatalf("return = %d %q", rec.Code, rec.Body.String())
|
||||
}
|
||||
e.stamp()
|
||||
var stamped time.Time
|
||||
stampRead := func() time.Time {
|
||||
if err := e.db.QueryRowContext(e.ctx, `SELECT last_swap_at FROM fedwiki.site_swap_policy WHERE workspace_id = $1`, e.ws).Scan(&stamped); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return stamped
|
||||
}
|
||||
want := stampRead()
|
||||
|
||||
side := dbtest.Tx(t, e.db)
|
||||
if err := db.Lock(e.ctx, side.Tx(), db.FedWikiWorkspace, e.ws); err != nil {
|
||||
t.Fatalf("take the workspace lock on the side: %v", err)
|
||||
}
|
||||
answer := make(chan *httptest.ResponseRecorder, 1)
|
||||
go func() {
|
||||
answer <- e.rowAction(e.h.RestoreSite, "restore", archivedDomain, archivedID, e.nextGen(archivedID))
|
||||
}()
|
||||
var rec *httptest.ResponseRecorder
|
||||
select {
|
||||
case rec = <-answer:
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("the Restore waited for the workspace lock")
|
||||
}
|
||||
if err := side.Tx().Rollback(); err != nil {
|
||||
t.Fatalf("release the workspace lock: %v", err)
|
||||
}
|
||||
if !accepted(rec) {
|
||||
t.Errorf("restore = %d %q, want accepted", rec.Code, rec.Body.String())
|
||||
}
|
||||
if got := stampRead(); !got.Equal(want) {
|
||||
t.Errorf("stamp = %v, want %v kept", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
t.Run("a database error", func(t *testing.T) {
|
||||
e := newSiteEnv(t, 3)
|
||||
id, domain := e.site("restore"+e.uniq, "archived")
|
||||
e.failRequestInsert(id, `RAISE EXCEPTION 'injected failure'; RETURN NEW;`)
|
||||
const single = "Couldn't update the site. Try again."
|
||||
if rec := e.rowAction(e.h.RestoreSite, "restore", domain, id, e.nextGen(id)); !says(rec, single) {
|
||||
t.Errorf("restore = %q, want %q", rec.Body.String(), single)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -7,12 +7,14 @@ import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/acts"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/auth"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/db"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/dnsname"
|
||||
@@ -21,6 +23,7 @@ import (
|
||||
fwmod "git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/fedwiki/store"
|
||||
siteusage "git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/fedwiki/usage"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/fedwiki/workflows"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/middleware"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/notice"
|
||||
coreweb "git.coopcloud.tech/wiki-cafe/member-console/internal/web"
|
||||
)
|
||||
@@ -223,7 +226,7 @@ func (h *FedWikiPartialsHandler) CreateSite(w http.ResponseWriter, r *http.Reque
|
||||
Domain: fqdn,
|
||||
OwnerName: session.Username,
|
||||
OwnerID: session.OIDCSubject,
|
||||
}, session.WorkspaceID, addr)
|
||||
}, session.WorkspaceID, atAddress(addr))
|
||||
if !started {
|
||||
errs.Form("Failed to initiate site creation")
|
||||
h.renderCreateFormRefusal(w, r, session.WorkspaceID, values, errs, false)
|
||||
@@ -349,20 +352,21 @@ func (h *FedWikiPartialsHandler) beginRowAction(w http.ResponseWriter, r *http.R
|
||||
return rowAction{}, false
|
||||
}
|
||||
|
||||
_, held, found, err := integration.LookupLifecycleRequest(ctx, h.Database, session.WorkspaceID, addr.Instance, addr.Generation)
|
||||
repeat := h.repeatSpec(session, addr, operation, domain, status)
|
||||
answer, _, err := integration.AnswerLifecycleRepeat(ctx, h.Database, repeat)
|
||||
if err != nil {
|
||||
h.Logger.Error("failed to look up a lifecycle request", slog.Any("error", err))
|
||||
h.siteActionResult(w, "Couldn't update the site. Try again.")
|
||||
return rowAction{}, false
|
||||
}
|
||||
if found {
|
||||
switch answer.Kind {
|
||||
case integration.LifecycleRepeatOpen, integration.LifecycleRepeatFinished:
|
||||
// A repeat is answered as the first submission was, whether the
|
||||
// request is still open or finished: the list shows its outcome.
|
||||
if sameRowRequest(held, operation, domain, status, session.PersonID) {
|
||||
h.siteActionResult(w, "")
|
||||
} else {
|
||||
h.siteActionConflict(w)
|
||||
}
|
||||
h.siteActionResult(w, "")
|
||||
return rowAction{}, false
|
||||
case integration.LifecycleConflict:
|
||||
h.siteActionConflict(w)
|
||||
return rowAction{}, false
|
||||
}
|
||||
|
||||
@@ -419,17 +423,21 @@ func (h *FedWikiPartialsHandler) ArchiveSite(w http.ResponseWriter, r *http.Requ
|
||||
}
|
||||
|
||||
// RestoreSite handles POST /partials/fedwiki/sites/{domain}/restore — returns an
|
||||
// archived site to active. Restoring a site that is NOT force-reduced (your own
|
||||
// active/archived site — your incumbent) is free. Restoring a force-reduced site
|
||||
// (one a downgrade parked) brings a reserve back into the active set, which is a
|
||||
// rotation gated by the swap cooldown. Quota-gated either way, inside the
|
||||
// workflow.
|
||||
// archived site to active. A row that is not archived changed since the list
|
||||
// loaded and is answered as a conflict before anything is recorded. An archived
|
||||
// row carries no downgrade mark, so a Restore is never a rotation: it takes no
|
||||
// workspace lock, is not refused by the cooldown or an open rotation, and
|
||||
// stamps nothing. It is quota-gated inside the workflow.
|
||||
func (h *FedWikiPartialsHandler) RestoreSite(w http.ResponseWriter, r *http.Request) {
|
||||
act, ok := h.beginRowAction(w, r, integration.LifecycleSetStatus, "active")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
h.changeStatus(w, r, act, "active", act.site.ForceReducedAt.Valid)
|
||||
if act.site.Status != "archived" {
|
||||
h.siteActionConflict(w)
|
||||
return
|
||||
}
|
||||
h.changeStatus(w, r, act, "active", false)
|
||||
}
|
||||
|
||||
// KeepSiteActive handles POST /partials/fedwiki/sites/{domain}/keep-active —
|
||||
@@ -469,10 +477,12 @@ func (h *FedWikiPartialsHandler) KeepSiteActive(w http.ResponseWriter, r *http.R
|
||||
|
||||
// changeStatus records a status change on the action's site and starts its
|
||||
// workflow. A rotation (bringing a force-reduced site back into the active
|
||||
// set) checks and stamps the swap cooldown in the transaction that records
|
||||
// the request, under the per-workspace lock, so a refused or repeated
|
||||
// request never burns the window (audit #51); the workflow clears the
|
||||
// site's downgrade-parked mark with its new status.
|
||||
// set) takes the workspace lock, so it is answered as a repeat, refused while
|
||||
// another rotation of the workspace is open or inside the cooldown window,
|
||||
// and recorded in one transaction; it stamps nothing, because the workflow
|
||||
// stamps when it succeeds. The workflow clears the site's downgrade-parked
|
||||
// mark with its new status. A free fill, an archive and a delete take no
|
||||
// workspace lock (design D10).
|
||||
func (h *FedWikiPartialsHandler) changeStatus(w http.ResponseWriter, r *http.Request, act rowAction, target string, rotation bool) {
|
||||
ctx := r.Context()
|
||||
ws := act.session.WorkspaceID
|
||||
@@ -482,32 +492,16 @@ func (h *FedWikiPartialsHandler) changeStatus(w http.ResponseWriter, r *http.Req
|
||||
|
||||
var answer integration.LifecycleAnswer
|
||||
var refusal string
|
||||
if rotation && h.SwapCooldown > 0 {
|
||||
err := h.withWorkspaceTx(ctx, ws, func(ctx context.Context, tx *sql.Tx, q fwmod.Querier) error {
|
||||
a, err := h.lockedRepeat(ctx, tx, act, integration.LifecycleSetStatus, target)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if a.Kind != 0 {
|
||||
answer = a
|
||||
return errRollback
|
||||
}
|
||||
if msg := h.cooldownMsgFor(ctx, q, ws); msg != "" {
|
||||
refusal = msg
|
||||
return errRollback
|
||||
}
|
||||
if answer, err = fwmod.RecordSiteRequestInTx(ctx, tx, spec, act.site.Domain); err != nil {
|
||||
return err
|
||||
}
|
||||
if answer.Kind != integration.LifecycleRecorded {
|
||||
return errRollback
|
||||
}
|
||||
return q.UpsertSiteSwapPolicy(ctx, ws)
|
||||
})
|
||||
if err != nil && !errors.Is(err, errRollback) {
|
||||
if rotation {
|
||||
var err error
|
||||
if answer, refusal, err = h.recordRotation(ctx, act, spec, target); err != nil {
|
||||
if h.answerMissingSite(w, err, act.site.SiteID) {
|
||||
return
|
||||
}
|
||||
if errors.Is(err, errSiteChanged) {
|
||||
h.siteActionConflict(w)
|
||||
return
|
||||
}
|
||||
h.Logger.Error("failed to record a rotation", slog.Any("error", err))
|
||||
h.siteActionResult(w, "Couldn't change which site is active. Try again later.")
|
||||
return
|
||||
@@ -537,7 +531,7 @@ func (h *FedWikiPartialsHandler) changeStatus(w http.ResponseWriter, r *http.Req
|
||||
CurrentStatus: act.site.Status,
|
||||
TargetStatus: target,
|
||||
ClearForceReduced: rotation,
|
||||
}, ws, act.addr)
|
||||
}, ws, atAddress(act.addr))
|
||||
if !started {
|
||||
h.siteActionResult(w, "Couldn't update the site. Try again.")
|
||||
return
|
||||
@@ -545,27 +539,126 @@ func (h *FedWikiPartialsHandler) changeStatus(w http.ResponseWriter, r *http.Req
|
||||
h.siteActionResult(w, "")
|
||||
}
|
||||
|
||||
// recordRotation records a return's request in the workspace transaction:
|
||||
// the repeat check, the open-rotation and cooldown refusals, then the
|
||||
// request. It returns the answer or the refusal sentence; an error is a
|
||||
// database error.
|
||||
func (h *FedWikiPartialsHandler) recordRotation(ctx context.Context, act rowAction, spec integration.LifecycleRequestSpec, target string) (answer integration.LifecycleAnswer, refusal string, err error) {
|
||||
ws := act.session.WorkspaceID
|
||||
err = h.withWorkspaceTx(ctx, ws, func(ctx context.Context, tx *sql.Tx, q fwmod.Querier) error {
|
||||
a, err := h.lockedRepeat(ctx, tx, act, integration.LifecycleSetStatus, target)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if a.Kind != 0 {
|
||||
answer = a
|
||||
return errRollback
|
||||
}
|
||||
if refusal, err = h.rotationRefusal(ctx, q, ws); err != nil || refusal != "" {
|
||||
if err == nil {
|
||||
err = errRollback
|
||||
}
|
||||
return err
|
||||
}
|
||||
if err := h.holdReturnSite(ctx, tx, q, act, spec.InstanceID); err != nil {
|
||||
return err
|
||||
}
|
||||
if answer, err = fwmod.RecordSiteRequestInTx(ctx, tx, spec, act.site.Domain); err != nil {
|
||||
return err
|
||||
}
|
||||
if answer.Kind != integration.LifecycleRecorded {
|
||||
return errRollback
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if errors.Is(err, errRollback) {
|
||||
err = nil
|
||||
}
|
||||
return answer, refusal, err
|
||||
}
|
||||
|
||||
// errSiteChanged ends a return's intake whose site is no longer what made the
|
||||
// action a return.
|
||||
var errSiteChanged = errors.New("the site changed since the list loaded")
|
||||
|
||||
// holdReturnSite takes the return's instance lock, then its site row's lock,
|
||||
// and re-checks under the row lock what made the action a return. A row that
|
||||
// is gone, or is no longer the member's with the posted domain, is answered as
|
||||
// any original site is (MissingSiteError); a row no longer read-only and
|
||||
// marked is answered with errSiteChanged. The
|
||||
// farm sync writes the row under the same lock, so the mark it would clear
|
||||
// is either already gone here or kept until this transaction commits. The
|
||||
// instance lock comes first (lock rule 5); RecordSiteRequestInTx takes it
|
||||
// again without waiting.
|
||||
func (h *FedWikiPartialsHandler) holdReturnSite(ctx context.Context, tx *sql.Tx, q fwmod.Querier, act rowAction, instanceID string) error {
|
||||
if err := db.Lock(ctx, tx, db.Lifecycle, instanceID); err != nil {
|
||||
return fmt.Errorf("lock lifecycle instance: %w", err)
|
||||
}
|
||||
row, err := q.LockSiteStatusByID(ctx, instanceID)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return &fwmod.MissingSiteError{InstanceID: instanceID}
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("lock return site: %w", err)
|
||||
}
|
||||
if row.WorkspaceID != act.session.WorkspaceID || row.Domain != act.site.Domain {
|
||||
return &fwmod.MissingSiteError{InstanceID: instanceID}
|
||||
}
|
||||
if row.Status != "readonly" || !row.ForceReducedAt.Valid {
|
||||
return errSiteChanged
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// rotationRefusal is the sentence that refuses a rotation's intake under the
|
||||
// workspace lock: the rotation-busy sentence while another rotation of the
|
||||
// workspace is open, then the cooldown sentence inside the window (design
|
||||
// D9). It is empty when the rotation may be recorded.
|
||||
func (h *FedWikiPartialsHandler) rotationRefusal(ctx context.Context, q fwmod.Querier, ws string) (string, error) {
|
||||
open, err := q.WorkspaceHasOpenRotation(ctx, fwmod.WorkspaceHasOpenRotationParams{
|
||||
WorkspaceID: ws,
|
||||
ConnectionID: h.connectionID(),
|
||||
SwapCause: string(acts.InstancesSwapped),
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if open {
|
||||
return msgActiveSiteBusy, nil
|
||||
}
|
||||
return h.cooldownMsgFor(ctx, q, ws), nil
|
||||
}
|
||||
|
||||
// lockedRepeat looks the action's address up again inside the workspace
|
||||
// lock: a second submission that passed the first lookup before the first
|
||||
// committed is then answered as a repeat, not refused by the cooldown the
|
||||
// first one stamped. It returns a zero answer when the address is empty.
|
||||
// committed is then answered as a repeat, not refused by the open-rotation
|
||||
// check or the cooldown. It returns a zero answer when the address is empty or another workspace's.
|
||||
func (h *FedWikiPartialsHandler) lockedRepeat(ctx context.Context, tx *sql.Tx, act rowAction, operation, status string) (integration.LifecycleAnswer, error) {
|
||||
_, held, found, err := integration.LookupLifecycleRequest(ctx, tx, act.session.WorkspaceID, act.addr.Instance, act.addr.Generation)
|
||||
if err != nil || !found {
|
||||
spec := h.repeatSpec(act.session, act.addr, operation, act.site.Domain, status)
|
||||
answer, _, err := integration.AnswerLifecycleRepeat(ctx, tx, spec)
|
||||
if err != nil {
|
||||
return integration.LifecycleAnswer{}, err
|
||||
}
|
||||
if sameRowRequest(held, operation, act.site.Domain, status, act.session.PersonID) {
|
||||
return integration.LifecycleAnswer{Kind: integration.LifecycleRepeatOpen}, nil
|
||||
if answer.Kind == integration.LifecycleNotFound {
|
||||
return integration.LifecycleAnswer{}, nil
|
||||
}
|
||||
return integration.LifecycleAnswer{Kind: integration.LifecycleConflict}, nil
|
||||
return answer, nil
|
||||
}
|
||||
|
||||
// repeatSpec is the spec a row action would record at its address, built from
|
||||
// the path's domain, for the repeat lookup (design D7).
|
||||
func (h *FedWikiPartialsHandler) repeatSpec(session *auth.UserSession, addr requestAddress, operation, domain, status string) integration.LifecycleRequestSpec {
|
||||
return newRequestSpec(h.connectionID(), session.WorkspaceID, session.PersonID, operation, addr, "",
|
||||
requestParams{Domain: domain, Status: status})
|
||||
}
|
||||
|
||||
// swapActiveSite parks the workspace's least-recently-modified active site
|
||||
// and activates the action's site. In the transaction that holds the
|
||||
// per-workspace lock and stamps the cooldown it records the activated site's
|
||||
// request and a set_status request for the parked site, both under the
|
||||
// swap's workflow id, so the one-open rule covers the parked site while the
|
||||
// swap runs (design D27).
|
||||
// per-workspace lock it records the activated site's request, with the member
|
||||
// as its person, and a set_status request for the parked site, with no person,
|
||||
// under the swap's workflow id, and links both to one act (design D9). The
|
||||
// one-open rule covers the parked site while the swap runs (design D27). The
|
||||
// cooldown stamp is written when the swap succeeds, not here.
|
||||
func (h *FedWikiPartialsHandler) swapActiveSite(w http.ResponseWriter, r *http.Request, act rowAction) {
|
||||
ctx := r.Context()
|
||||
ws := act.session.WorkspaceID
|
||||
@@ -577,6 +670,7 @@ func (h *FedWikiPartialsHandler) swapActiveSite(w http.ResponseWriter, r *http.R
|
||||
refusal string
|
||||
park requestAddress
|
||||
parkDom string
|
||||
actID string
|
||||
)
|
||||
err := h.withWorkspaceTx(ctx, ws, func(ctx context.Context, tx *sql.Tx, q fwmod.Querier) error {
|
||||
a, err := h.lockedRepeat(ctx, tx, act, integration.LifecycleSetStatus, "active")
|
||||
@@ -587,18 +681,12 @@ func (h *FedWikiPartialsHandler) swapActiveSite(w http.ResponseWriter, r *http.R
|
||||
answer = a
|
||||
return errRollback
|
||||
}
|
||||
if msg := h.cooldownMsgFor(ctx, q, ws); msg != "" {
|
||||
refusal = msg
|
||||
return errRollback
|
||||
}
|
||||
open, err := integration.OpenRequestsByWorkspace(ctx, tx, ws, conn)
|
||||
if err != nil {
|
||||
if refusal, err = h.rotationRefusal(ctx, q, ws); err != nil || refusal != "" {
|
||||
if err == nil {
|
||||
err = errRollback
|
||||
}
|
||||
return err
|
||||
}
|
||||
if hasOpenSwap(open) {
|
||||
refusal = msgActiveSiteBusy
|
||||
return errRollback
|
||||
}
|
||||
locked, err := q.ListActiveSitesByWorkspace(ctx, ws)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -618,7 +706,7 @@ func (h *FedWikiPartialsHandler) swapActiveSite(w http.ResponseWriter, r *http.R
|
||||
|
||||
answer, err = integration.RecordLifecycleRequestInTx(ctx, tx, newRequestSpec(conn, ws, act.session.PersonID,
|
||||
integration.LifecycleSetStatus, act.addr, workflowID,
|
||||
requestParams{Domain: act.site.Domain, Status: "active", SwapParkSiteID: parked.SiteID}))
|
||||
requestParams{Domain: act.site.Domain, Status: "active"}))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -635,7 +723,14 @@ func (h *FedWikiPartialsHandler) swapActiveSite(w http.ResponseWriter, r *http.R
|
||||
refusal = msgActiveSiteBusy
|
||||
return errRollback
|
||||
}
|
||||
return q.UpsertSiteSwapPolicy(ctx, ws)
|
||||
actID, err = integration.RecordLifecycleAct(ctx, tx, integration.LifecycleAct{
|
||||
Cause: acts.InstancesSwapped,
|
||||
ActorPersonID: act.session.PersonID,
|
||||
CorrelationID: middleware.GetRequestID(ctx),
|
||||
Asked: answer.RequestID,
|
||||
Consequent: []string{parkAnswer.RequestID},
|
||||
})
|
||||
return err
|
||||
})
|
||||
if err != nil && !errors.Is(err, errRollback) {
|
||||
if h.answerMissingSite(w, err, act.site.SiteID) {
|
||||
@@ -659,7 +754,7 @@ func (h *FedWikiPartialsHandler) swapActiveSite(w http.ResponseWriter, r *http.R
|
||||
WorkspaceID: ws,
|
||||
ActivateDomain: act.site.Domain,
|
||||
ParkDomain: parkDom,
|
||||
}, ws, act.addr, park)
|
||||
}, ws, ofAct(actID))
|
||||
if !started {
|
||||
h.siteActionResult(w, "Couldn't change the active site. Try again.")
|
||||
return
|
||||
@@ -696,7 +791,7 @@ func (h *FedWikiPartialsHandler) DeleteSite(w http.ResponseWriter, r *http.Reque
|
||||
Generation: act.addr.Generation,
|
||||
WorkspaceID: ws,
|
||||
Domain: act.site.Domain,
|
||||
}, ws, act.addr)
|
||||
}, ws, atAddress(act.addr))
|
||||
if !started {
|
||||
h.siteActionResult(w, "Failed to initiate site deletion")
|
||||
return
|
||||
@@ -730,38 +825,15 @@ func (h *FedWikiPartialsHandler) DismissRequest(w http.ResponseWriter, r *http.R
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
// acknowledgeRequest records the dismissal of the outcome at addr, in one
|
||||
// transaction. A swap is one request recorded as two rows under one
|
||||
// workflow id (design D27), and only the activated site's row has a
|
||||
// notice, so dismissing it acknowledges the parked site's row as well.
|
||||
// acknowledgeRequest records the dismissal of the outcome at addr. One call
|
||||
// acknowledges the address's row and every declined or failed row of its act
|
||||
// (design D12), so a swap's two rows go together.
|
||||
func (h *FedWikiPartialsHandler) acknowledgeRequest(ctx context.Context, workspaceID string, addr requestAddress) error {
|
||||
if h.Database == nil {
|
||||
return errors.New("no database to record a dismissal")
|
||||
}
|
||||
return db.InTx(ctx, h.Database, db.Plain, func(tx *sql.Tx) error {
|
||||
if _, err := integration.AcknowledgeLifecycleRequest(ctx, tx, workspaceID, addr.Instance, addr.Generation); err != nil {
|
||||
return err
|
||||
}
|
||||
_, held, found, err := integration.LookupLifecycleRequest(ctx, tx, workspaceID, addr.Instance, addr.Generation)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if found && decodeParams(held.Parameters).SwapParkSiteID != "" {
|
||||
rows, err := integration.OpenRequestsByWorkspace(ctx, tx, workspaceID, held.ConnectionID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, row := range rows {
|
||||
if row.WorkflowID != held.WorkflowID || row.InstanceID == held.InstanceID || row.Status == integration.LifecycleAccepted {
|
||||
continue
|
||||
}
|
||||
if _, err := integration.AcknowledgeLifecycleRequest(ctx, tx, workspaceID, row.InstanceID, row.Generation); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
_, err := integration.AcknowledgeLifecycleRequest(ctx, h.Database, workspaceID, addr.Instance, addr.Generation)
|
||||
return err
|
||||
}
|
||||
|
||||
// siteActionResult writes the outcome of a row action: on success an
|
||||
@@ -788,8 +860,8 @@ func (h *FedWikiPartialsHandler) siteActionConflict(w http.ResponseWriter) {
|
||||
// withWorkspaceTx runs fn inside a transaction that holds a per-workspace
|
||||
// Postgres advisory lock (the fedwiki-workspace family's, released on commit or
|
||||
// rollback), serializing a workspace's active-site rotations so two tabs
|
||||
// cannot interleave the cooldown check-and-stamp or the park-target
|
||||
// selection (audit #51). fn receives the transaction and a querier on it;
|
||||
// cannot interleave the open-rotation check, the cooldown read or the
|
||||
// park-target selection (audit #51). fn receives the transaction and a querier on it;
|
||||
// returning an error rolls the transaction back, otherwise it commits.
|
||||
// READ COMMITTED lets protected site reads see a purge that held the instance lock.
|
||||
func (h *FedWikiPartialsHandler) withWorkspaceTx(ctx context.Context, workspaceID string, fn func(context.Context, *sql.Tx, fwmod.Querier) error) error {
|
||||
@@ -800,7 +872,11 @@ func (h *FedWikiPartialsHandler) withWorkspaceTx(ctx context.Context, workspaceI
|
||||
if err := db.Lock(ctx, tx, db.FedWikiWorkspace, workspaceID); err != nil {
|
||||
return err
|
||||
}
|
||||
return fn(ctx, tx, fwmod.New(tx))
|
||||
var q fwmod.Querier = fwmod.New(tx)
|
||||
if h.wrapTxQuerier != nil {
|
||||
q = h.wrapTxQuerier(q)
|
||||
}
|
||||
return fn(ctx, tx, q)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -871,16 +947,16 @@ func (v requestsView) createRows(siteIDs []string) []SiteViewModel {
|
||||
}
|
||||
|
||||
// notices are the undismissed declined and failed requests, newest first,
|
||||
// one per request the member made. A swap's parked site is left out: the
|
||||
// swap is the member's Keep active on the other site, whose notice tells
|
||||
// it. siteStatus is each site's current status, by id.
|
||||
// one per request the member made. A consequent request of an act is left
|
||||
// out: the act is the member's request on the asked row, whose notice tells
|
||||
// it (design D12). siteStatus is each site's current status, by id.
|
||||
func (v requestsView) notices(siteStatus map[string]string, logger *slog.Logger) []notice.Notice {
|
||||
rows := make([]integration.LifecycleRequest, 0, len(v.outcomes))
|
||||
for _, row := range v.outcomes {
|
||||
if _, open := v.open[row.InstanceID]; open {
|
||||
continue
|
||||
}
|
||||
if decodeParams(row.Parameters).SwapActivateSiteID != "" {
|
||||
if row.ActRole.String == integration.LifecycleActConsequent {
|
||||
continue
|
||||
}
|
||||
rows = append(rows, row)
|
||||
@@ -889,12 +965,14 @@ func (v requestsView) notices(siteStatus map[string]string, logger *slog.Logger)
|
||||
out := make([]notice.Notice, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
p := decodeParams(row.Parameters)
|
||||
sentence := noticeSentence(p.Domain, requestAction(row.Operation, p, siteStatus[row.InstanceID]), row.ReasonCode.String)
|
||||
sentence := noticeSentence(p.Domain, requestAction(row, p, siteStatus[row.InstanceID]), row.ReasonCode.String)
|
||||
if row.ReasonCode.String == workflows.ReasonSiteMissing {
|
||||
sentence = p.Domain + " was deleted."
|
||||
if _, exists := siteStatus[row.InstanceID]; exists && p.SwapParkSiteID != "" {
|
||||
if _, exists := siteStatus[row.InstanceID]; !exists {
|
||||
sentence = p.Domain + " was deleted."
|
||||
} else if row.ActID.Valid {
|
||||
// The asked row of a swap whose parked site was deleted.
|
||||
for _, peer := range v.rows {
|
||||
if peer.InstanceID == p.SwapParkSiteID && peer.WorkflowID == row.WorkflowID {
|
||||
if peer.ActID == row.ActID && peer.ActRole.String == integration.LifecycleActConsequent {
|
||||
sentence = p.Domain + " wasn't kept active. " + decodeParams(peer.Parameters).Domain + " was deleted."
|
||||
break
|
||||
}
|
||||
@@ -1001,16 +1079,6 @@ func (h *FedWikiPartialsHandler) answerMissingSite(w http.ResponseWriter, err er
|
||||
return true
|
||||
}
|
||||
|
||||
// hasOpenSwap reports whether a workspace is already changing its active site.
|
||||
func hasOpenSwap(rows []integration.LifecycleRequest) bool {
|
||||
for _, row := range rows {
|
||||
if row.Status == integration.LifecycleAccepted && workflows.IsSwapRequestWorkflowID(row.WorkflowID) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// answerSiteIntake renders a policy refusal or the lifecycle address's answer.
|
||||
func (h *FedWikiPartialsHandler) answerSiteIntake(w http.ResponseWriter, answer integration.LifecycleAnswer, refusal string) bool {
|
||||
if refusal != "" {
|
||||
@@ -1020,15 +1088,16 @@ func (h *FedWikiPartialsHandler) answerSiteIntake(w http.ResponseWriter, answer
|
||||
return h.answerRecord(w, answer)
|
||||
}
|
||||
|
||||
// recordParkRequest records the outgoing half of a swap in the caller's transaction.
|
||||
// recordParkRequest records the outgoing half of a swap in the caller's
|
||||
// transaction, the swap's consequent request: it names no person.
|
||||
func (h *FedWikiPartialsHandler) recordParkRequest(ctx context.Context, tx *sql.Tx, act rowAction, instance, domain, workflowID string) (requestAddress, integration.LifecycleAnswer, error) {
|
||||
gens, err := integration.NextGenerations(ctx, tx, []string{instance})
|
||||
if err != nil {
|
||||
return requestAddress{}, integration.LifecycleAnswer{}, err
|
||||
}
|
||||
park := requestAddress{Instance: instance, Generation: gens[instance]}
|
||||
answer, err := integration.RecordLifecycleRequestInTx(ctx, tx, newRequestSpec(h.connectionID(), act.session.WorkspaceID, act.session.PersonID,
|
||||
answer, err := integration.RecordLifecycleRequestInTx(ctx, tx, newRequestSpec(h.connectionID(), act.session.WorkspaceID, "",
|
||||
integration.LifecycleSetStatus, park, workflowID,
|
||||
requestParams{Domain: domain, Status: "readonly", SwapActivateSiteID: act.site.SiteID}))
|
||||
requestParams{Domain: domain, Status: "readonly"}))
|
||||
return park, answer, err
|
||||
}
|
||||
|
||||
@@ -4,13 +4,19 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"html"
|
||||
"log/slog"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"go.temporal.io/api/serviceerror"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/forms"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/integration"
|
||||
)
|
||||
|
||||
// Scenario: core's index.html renders only generic card shells
|
||||
@@ -178,10 +184,10 @@ func TestSitesCardCreateControlAtAndOverLimit(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Scenario (design D6): the swap-cooldown Keep active and Restore buttons
|
||||
// were the other two hand-rolled disabled+title buttons the
|
||||
// disabled-outside-part lint rule would otherwise refuse; both now render
|
||||
// through the shared part with their cooldown reason in the DOM.
|
||||
// Scenario (design D6): the swap-cooldown Keep active button was one of the
|
||||
// hand-rolled disabled+title buttons the disabled-outside-part lint rule would
|
||||
// otherwise refuse; it renders through the shared part with its cooldown
|
||||
// reason in the DOM. An archived row's Restore is never gated by the cooldown.
|
||||
func TestSitesCardCooldownButtonsUseThePart(t *testing.T) {
|
||||
h, err := NewFedWikiPartialsHandler(FedWikiPartialsConfig{
|
||||
Logger: slog.Default(),
|
||||
@@ -199,7 +205,7 @@ func TestSitesCardCooldownButtonsUseThePart(t *testing.T) {
|
||||
ID: "site-1", Domain: "wiki.example.test", Status: "readonly", IsReadonly: true,
|
||||
}},
|
||||
ArchivedSites: []SiteViewModel{{
|
||||
ID: "site-2", Domain: "archived.example.test", IsForceReduced: true,
|
||||
ID: "site-2", Domain: "archived.example.test", Status: "archived", IsArchived: true,
|
||||
}},
|
||||
})
|
||||
if rec.Code != 200 {
|
||||
@@ -209,16 +215,22 @@ func TestSitesCardCooldownButtonsUseThePart(t *testing.T) {
|
||||
if strings.Contains(body, "disabled title=") {
|
||||
t.Errorf("cooldown buttons must not hand-roll disabled+title: %s", body)
|
||||
}
|
||||
for _, want := range []string{
|
||||
`aria-describedby="fedwiki-site-keep-active-reason-site-1"`,
|
||||
`aria-describedby="fedwiki-site-restore-reason-site-2"`,
|
||||
} {
|
||||
if !strings.Contains(body, want) {
|
||||
t.Errorf("cooldown button missing %q: %s", want, body)
|
||||
}
|
||||
if want := `aria-describedby="fedwiki-site-keep-active-reason-site-1"`; !strings.Contains(body, want) {
|
||||
t.Errorf("cooldown button missing %q: %s", want, body)
|
||||
}
|
||||
if strings.Count(body, "Wait 2 hours before swapping another site.") < 2 {
|
||||
t.Errorf("both cooldown buttons should carry the cooldown reason: %s", body)
|
||||
if !strings.Contains(body, "Wait 2 hours before swapping another site.") {
|
||||
t.Errorf("Keep active should carry the cooldown reason: %s", body)
|
||||
}
|
||||
if strings.Contains(body, "fedwiki-site-restore-reason") {
|
||||
t.Errorf("an archived row's Restore must not be gated by the cooldown: %s", body)
|
||||
}
|
||||
restore := `hx-post="/partials/fedwiki/sites/archived.example.test/restore"`
|
||||
i := strings.Index(body, restore)
|
||||
if i < 0 {
|
||||
t.Fatalf("an archived row shows no Restore with the cooldown on: %s", body)
|
||||
}
|
||||
if end := strings.Index(body[i:], "</button>"); end < 0 || strings.Contains(body[i:i+end], "disabled") {
|
||||
t.Errorf("an archived row's Restore is not enabled with the cooldown on: %s", body[i:])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -299,3 +311,156 @@ func TestSitesEmptyStateNamesTheActiveBlocker(t *testing.T) {
|
||||
t.Error("no-published-plan and entitlement-blocked (member's plan excludes it) states render identical copy")
|
||||
}
|
||||
}
|
||||
|
||||
// Scenario (design D13): while a swap is pending the card keeps Keep active
|
||||
// enabled on the workspace's other read-only rows and shows Pending with no
|
||||
// actions on the two pending rows; a click on another read-only row answers
|
||||
// the rotation-busy sentence. While a return is pending with the pool below
|
||||
// its limit, a click on an unmarked read-only row is a free fill and is
|
||||
// recorded.
|
||||
func TestSitesCardWhileARotationIsPending(t *testing.T) {
|
||||
t.Run("a swap", func(t *testing.T) {
|
||||
e := newSiteEnv(t, 1)
|
||||
e.h.SwapCooldown = 24 * time.Hour
|
||||
r := newSwapRig(e)
|
||||
otherID, otherDomain := e.site("other"+e.uniq, "readonly")
|
||||
if rec := e.keepActive(r.chosenDomain, r.chosenID); !accepted(rec) {
|
||||
t.Fatalf("swap = %d %q", rec.Code, rec.Body.String())
|
||||
}
|
||||
list := e.sitesList()
|
||||
other := rowFor(t, list, otherDomain)
|
||||
if !strings.Contains(other, "Keep active") || !strings.Contains(other, "hx-post") || strings.Contains(other, "disabled") {
|
||||
t.Errorf("the other read-only row does not offer an enabled Keep active:\n%s", other)
|
||||
}
|
||||
for _, domain := range []string{r.parkDomain, r.chosenDomain} {
|
||||
row := rowFor(t, list, domain)
|
||||
if !strings.Contains(row, ">Pending<") {
|
||||
t.Errorf("pending row %s lacks the Pending badge:\n%s", domain, row)
|
||||
}
|
||||
for _, action := range []string{"Archive", "Keep active", "Restore", "Dismiss", "hx-post", "data-action-url"} {
|
||||
if strings.Contains(row, action) {
|
||||
t.Errorf("pending row %s renders %q:\n%s", domain, action, row)
|
||||
}
|
||||
}
|
||||
}
|
||||
before := e.counts()
|
||||
rec := e.keepActive(otherDomain, otherID)
|
||||
if !says(rec, msgActiveSiteBusy) || e.counts() != before {
|
||||
t.Errorf("click during a swap = %q, counts %+v, want %q and %+v", rec.Body.String(), e.counts(), msgActiveSiteBusy, before)
|
||||
}
|
||||
})
|
||||
t.Run("a return", func(t *testing.T) {
|
||||
e := newSiteEnv(t, 3)
|
||||
e.h.SwapCooldown = 24 * time.Hour
|
||||
markedID, markedDomain := e.markedSite("marked")
|
||||
fillID, fillDomain := e.site("fill"+e.uniq, "readonly")
|
||||
if rec := e.keepActive(markedDomain, markedID); !accepted(rec) {
|
||||
t.Fatalf("return = %d %q", rec.Code, rec.Body.String())
|
||||
}
|
||||
if fill := rowFor(t, e.sitesList(), fillDomain); !strings.Contains(fill, "Keep active") || strings.Contains(fill, "disabled") {
|
||||
t.Errorf("the unmarked read-only row does not offer an enabled Keep active:\n%s", fill)
|
||||
}
|
||||
rec := e.keepActive(fillDomain, fillID)
|
||||
if !accepted(rec) || e.requestCount(fillID) != 1 {
|
||||
t.Errorf("click during a return = %d %q with %d requests, want a recorded free fill", rec.Code, rec.Body.String(), e.requestCount(fillID))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Scenario (design D13, F11, F15, F17, F20): the first render after a
|
||||
// rotation's success has stamped shows Keep active disabled with the cooldown
|
||||
// sentence when the cooldown is on, and enabled when it is off. After a
|
||||
// rotation that failed to start, failed or was declined nothing is stamped, so
|
||||
// Keep active is enabled at once.
|
||||
func TestSitesCardAfterARotationEnds(t *testing.T) {
|
||||
const cooldownSentence = "The active site changes once every 1 day(s)"
|
||||
type rotation struct {
|
||||
name string
|
||||
limit int
|
||||
// start begins a rotation and returns the instances whose requests it
|
||||
// recorded and the other read-only row the card is checked on.
|
||||
start func(e *siteEnv) (ids []string, otherDomain string)
|
||||
}
|
||||
swap := func(e *siteEnv) ([]string, string) {
|
||||
r := newSwapRig(e)
|
||||
_, other := e.site("other"+e.uniq, "readonly")
|
||||
e.keepActive(r.chosenDomain, r.chosenID)
|
||||
return []string{r.chosenID, r.parkID}, other
|
||||
}
|
||||
ret := func(e *siteEnv) ([]string, string) {
|
||||
markedID, markedDomain := e.markedSite("marked")
|
||||
_, other := e.site("other"+e.uniq, "readonly")
|
||||
e.keepActive(markedDomain, markedID)
|
||||
return []string{markedID}, other
|
||||
}
|
||||
rotations := []rotation{{"a swap", 1, swap}, {"a return", 3, ret}}
|
||||
|
||||
// enabled and disabled read the other row's Keep active in a render.
|
||||
check := func(t *testing.T, e *siteEnv, otherDomain string, disabled bool, when string) {
|
||||
t.Helper()
|
||||
row := rowFor(t, e.sitesList(), otherDomain)
|
||||
if !strings.Contains(row, "Keep active") {
|
||||
t.Fatalf("%s: the row has no Keep active:\n%s", when, row)
|
||||
}
|
||||
if got := strings.Contains(row, "disabled"); got != disabled {
|
||||
t.Errorf("%s: Keep active disabled = %v, want %v:\n%s", when, got, disabled, row)
|
||||
}
|
||||
if got := strings.Contains(html.UnescapeString(row), cooldownSentence); got != disabled {
|
||||
t.Errorf("%s: the cooldown sentence shown = %v, want %v:\n%s", when, got, disabled, row)
|
||||
}
|
||||
if !disabled && !strings.Contains(row, "hx-post") {
|
||||
t.Errorf("%s: Keep active is not a live control:\n%s", when, row)
|
||||
}
|
||||
}
|
||||
|
||||
// end finishes the open request of each instance with one outcome.
|
||||
end := func(e *siteEnv, ids []string, status, reason string) {
|
||||
t := e.t
|
||||
t.Helper()
|
||||
for _, id := range ids {
|
||||
var gen int64
|
||||
if err := e.db.QueryRowContext(e.ctx, `SELECT generation FROM core.lifecycle_requests WHERE instance_id = $1 AND status = 'accepted'`, id).Scan(&gen); err != nil {
|
||||
t.Fatalf("the open request of %s: %v", id, err)
|
||||
}
|
||||
e.finish(id, gen, status, reason)
|
||||
}
|
||||
}
|
||||
|
||||
for _, rot := range rotations {
|
||||
for _, cooldown := range cooldowns {
|
||||
name := rot.name + ", cooldown off"
|
||||
if cooldown > 0 {
|
||||
name = rot.name + ", cooldown on"
|
||||
}
|
||||
t.Run(name+", success stamped", func(t *testing.T) {
|
||||
e := newSiteEnv(t, rot.limit)
|
||||
e.h.SwapCooldown = cooldown
|
||||
ids, other := rot.start(e)
|
||||
check(t, e, other, false, "while the rotation is pending")
|
||||
end(e, ids, integration.LifecycleSucceeded, "")
|
||||
e.stamp()
|
||||
check(t, e, other, cooldown > 0, "on the first render after the success")
|
||||
})
|
||||
for _, outcome := range []struct{ name, status, reason string }{
|
||||
{"failed", integration.LifecycleFailed, "retries_exhausted"},
|
||||
{"declined", integration.LifecycleDeclined, "quota_exceeded"},
|
||||
} {
|
||||
t.Run(name+", "+outcome.name, func(t *testing.T) {
|
||||
e := newSiteEnv(t, rot.limit)
|
||||
e.h.SwapCooldown = cooldown
|
||||
ids, other := rot.start(e)
|
||||
end(e, ids, outcome.status, outcome.reason)
|
||||
check(t, e, other, false, "after the rotation "+outcome.name)
|
||||
})
|
||||
}
|
||||
t.Run(name+", failed to start", func(t *testing.T) {
|
||||
e := newSiteEnv(t, rot.limit)
|
||||
e.h.SwapCooldown = cooldown
|
||||
e.temporal.startErr = context.DeadlineExceeded
|
||||
e.temporal.describeErr = serviceerror.NewNotFound("no such workflow")
|
||||
_, other := rot.start(e)
|
||||
check(t, e, other, false, "after a rotation that failed to start")
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,486 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
||||
// SPDX-FileCopyrightText: 2025-2026 Christian Galo
|
||||
|
||||
package web
|
||||
|
||||
// A rotation's intake through the handlers (lifecycle-request-acts design D8
|
||||
// to D10): a return takes the workspace lock whatever the cooldown, is
|
||||
// refused while another rotation of the workspace is open or inside the
|
||||
// window, and a free fill, an archive and a delete take no part in either.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"html"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/db"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/integration"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/fedwiki/fedwikitest"
|
||||
fwmod "git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/fedwiki/store"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/fedwiki/workflows"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/testkit/dbtest"
|
||||
)
|
||||
|
||||
const returnFailed = "Couldn't change which site is active. Try again later."
|
||||
|
||||
// markedSite is a read-only site a plan downgrade parked: Keep active on it
|
||||
// below the limit is a return.
|
||||
func (e *siteEnv) markedSite(label string) (id, domain string) {
|
||||
e.t.Helper()
|
||||
id, domain = e.site(label+e.uniq, "readonly")
|
||||
fedwikitest.ForceReduce(e.t, e.db, domain)
|
||||
return id, domain
|
||||
}
|
||||
|
||||
// says reports whether the answer carries want, as the member reads it.
|
||||
func says(rec *httptest.ResponseRecorder, want string) bool {
|
||||
return strings.Contains(html.UnescapeString(rec.Body.String()), want)
|
||||
}
|
||||
|
||||
// earlyAnswer is a lock wait's Abort: it reports an answer that arrived while
|
||||
// the lock was still held.
|
||||
func earlyAnswer(answers <-chan *httptest.ResponseRecorder) func() error {
|
||||
return func() error {
|
||||
select {
|
||||
case rec := <-answers:
|
||||
return fmt.Errorf("answered before the lock was released: %q", rec.Body.String())
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var cooldowns = []time.Duration{0, 24 * time.Hour}
|
||||
|
||||
// TestReturnsSerializeOnTheWorkspaceLock: two returns of one workspace with
|
||||
// the cooldown off wait on the lock a side transaction holds, and when it
|
||||
// releases, one records and the other ends with the rotation-busy sentence
|
||||
// (F3's serialization).
|
||||
func TestReturnsSerializeOnTheWorkspaceLock(t *testing.T) {
|
||||
e := newSiteEnv(t, 3)
|
||||
firstID, firstDomain := e.markedSite("first")
|
||||
secondID, secondDomain := e.markedSite("second")
|
||||
firstGen, secondGen := e.nextGen(firstID), e.nextGen(secondID)
|
||||
|
||||
side := dbtest.Tx(t, e.db)
|
||||
sidePID := int(side.Int(`SELECT pg_backend_pid()`))
|
||||
if err := db.Lock(context.Background(), side.Tx(), db.FedWikiWorkspace, e.ws); err != nil {
|
||||
t.Fatalf("take the workspace lock on the side: %v", err)
|
||||
}
|
||||
answers := make(chan *httptest.ResponseRecorder, 2)
|
||||
go func() { answers <- e.rowAction(e.h.KeepSiteActive, "keep-active", firstDomain, firstID, firstGen) }()
|
||||
go func() { answers <- e.rowAction(e.h.KeepSiteActive, "keep-active", secondDomain, secondID, secondGen) }()
|
||||
dbtest.AwaitLockWait(t, e.db, dbtest.Backend{BlockedBy: sidePID, Waiters: 2, Abort: earlyAnswer(answers)})
|
||||
if got := e.counts().requests; got != 0 {
|
||||
t.Fatalf("%d requests recorded while the workspace lock is held", got)
|
||||
}
|
||||
if err := side.Tx().Rollback(); err != nil {
|
||||
t.Fatalf("release the workspace lock: %v", err)
|
||||
}
|
||||
var recorded, busy int
|
||||
for range 2 {
|
||||
switch rec := <-answers; {
|
||||
case accepted(rec):
|
||||
recorded++
|
||||
case says(rec, msgActiveSiteBusy):
|
||||
busy++
|
||||
default:
|
||||
t.Errorf("answer = %d %q, want accepted or the rotation-busy sentence", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
if recorded != 1 || busy != 1 || e.counts().requests != 1 || e.counts().starts != 1 {
|
||||
t.Errorf("accepted %d, busy %d, requests %d, starts %d; want one of each answer and one request and start",
|
||||
recorded, busy, e.counts().requests, e.counts().starts)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReturnAndSwapExcludeEachOther: a return during an open swap and a swap
|
||||
// during an open return answer the rotation-busy sentence, the cooldown on or
|
||||
// off, and record nothing (F3).
|
||||
func TestReturnAndSwapExcludeEachOther(t *testing.T) {
|
||||
for _, cooldown := range cooldowns {
|
||||
t.Run("a return during an open swap, cooldown "+cooldown.String(), func(t *testing.T) {
|
||||
e := newSiteEnv(t, 2)
|
||||
e.h.SwapCooldown = cooldown
|
||||
e.site("incumbent"+e.uniq, "active")
|
||||
e.site("second"+e.uniq, "active")
|
||||
chosenID, chosenDomain := e.site("chosen"+e.uniq, "readonly")
|
||||
markedID, markedDomain := e.markedSite("marked")
|
||||
if rec := e.keepActive(chosenDomain, chosenID); !accepted(rec) {
|
||||
t.Fatalf("swap = %d %q", rec.Code, rec.Body.String())
|
||||
}
|
||||
e.setUsage(1) // the pool has room again, so Keep active on the marked site is a return
|
||||
before := e.counts()
|
||||
rec := e.keepActive(markedDomain, markedID)
|
||||
if !says(rec, msgActiveSiteBusy) || e.counts() != before {
|
||||
t.Errorf("return during a swap = %q, counts %+v, want %q and %+v", rec.Body.String(), e.counts(), msgActiveSiteBusy, before)
|
||||
}
|
||||
})
|
||||
t.Run("a swap during an open return, cooldown "+cooldown.String(), func(t *testing.T) {
|
||||
e := newSiteEnv(t, 2)
|
||||
e.h.SwapCooldown = cooldown
|
||||
e.site("incumbent"+e.uniq, "active")
|
||||
markedID, markedDomain := e.markedSite("marked")
|
||||
chosenID, chosenDomain := e.site("chosen"+e.uniq, "readonly")
|
||||
if rec := e.keepActive(markedDomain, markedID); !accepted(rec) {
|
||||
t.Fatalf("return = %d %q", rec.Code, rec.Body.String())
|
||||
}
|
||||
e.setUsage(2) // the pool is full again, so Keep active on the other site is a swap
|
||||
before := e.counts()
|
||||
rec := e.keepActive(chosenDomain, chosenID)
|
||||
if !says(rec, msgActiveSiteBusy) || e.counts() != before {
|
||||
t.Errorf("swap during a return = %q, counts %+v, want %q and %+v", rec.Body.String(), e.counts(), msgActiveSiteBusy, before)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestReturnInsideTheCooldownWindow: a return inside the window answers the
|
||||
// cooldown sentence and records nothing, and with the cooldown off the same
|
||||
// stamp refuses nothing (F4).
|
||||
func TestReturnInsideTheCooldownWindow(t *testing.T) {
|
||||
t.Run("on", func(t *testing.T) {
|
||||
e := newSiteEnv(t, 3)
|
||||
e.h.SwapCooldown = 24 * time.Hour
|
||||
markedID, markedDomain := e.markedSite("marked")
|
||||
e.stamp()
|
||||
before := e.counts()
|
||||
rec := e.keepActive(markedDomain, markedID)
|
||||
if !says(rec, "try again in about") || e.counts() != before {
|
||||
t.Errorf("return in the window = %q, counts %+v, want the cooldown sentence and %+v", rec.Body.String(), e.counts(), before)
|
||||
}
|
||||
})
|
||||
t.Run("off", func(t *testing.T) {
|
||||
e := newSiteEnv(t, 3)
|
||||
markedID, markedDomain := e.markedSite("marked")
|
||||
e.stamp()
|
||||
if rec := e.keepActive(markedDomain, markedID); !accepted(rec) {
|
||||
t.Errorf("return with the cooldown off = %d %q, want accepted", rec.Code, rec.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestReturnDatabaseError: a database error in a return's transaction answers
|
||||
// the rotation sentence with the cooldown off or on (F9); a free fill, a
|
||||
// Restore and an archive keep the single-site sentence.
|
||||
func TestReturnDatabaseError(t *testing.T) {
|
||||
const injected = `RAISE EXCEPTION 'injected failure'; RETURN NEW;`
|
||||
for _, cooldown := range cooldowns {
|
||||
t.Run("a return, cooldown "+cooldown.String(), func(t *testing.T) {
|
||||
e := newSiteEnv(t, 3)
|
||||
e.h.SwapCooldown = cooldown
|
||||
markedID, markedDomain := e.markedSite("marked")
|
||||
e.failRequestInsert(markedID, injected)
|
||||
before := e.counts()
|
||||
rec := e.keepActive(markedDomain, markedID)
|
||||
if !says(rec, returnFailed) || e.counts() != before {
|
||||
t.Errorf("return = %q, counts %+v, want %q and %+v", rec.Body.String(), e.counts(), returnFailed, before)
|
||||
}
|
||||
})
|
||||
}
|
||||
const single = "Couldn't update the site. Try again."
|
||||
t.Run("a free fill", func(t *testing.T) {
|
||||
e := newSiteEnv(t, 3)
|
||||
id, domain := e.site("fill"+e.uniq, "readonly")
|
||||
e.failRequestInsert(id, injected)
|
||||
if rec := e.keepActive(domain, id); !says(rec, single) {
|
||||
t.Errorf("free fill = %q, want %q", rec.Body.String(), single)
|
||||
}
|
||||
})
|
||||
t.Run("a Restore", func(t *testing.T) {
|
||||
e := newSiteEnv(t, 3)
|
||||
id, domain := e.site("restore"+e.uniq, "archived")
|
||||
e.failRequestInsert(id, injected)
|
||||
if rec := e.rowAction(e.h.RestoreSite, "restore", domain, id, e.nextGen(id)); !says(rec, single) {
|
||||
t.Errorf("restore = %q, want %q", rec.Body.String(), single)
|
||||
}
|
||||
})
|
||||
t.Run("an archive", func(t *testing.T) {
|
||||
e := newSiteEnv(t, 3)
|
||||
id, domain := e.site("archive"+e.uniq, "active")
|
||||
e.failRequestInsert(id, injected)
|
||||
if rec := e.rowAction(e.h.ArchiveSite, "archive", domain, id, e.nextGen(id)); !says(rec, single) {
|
||||
t.Errorf("archive = %q, want %q", rec.Body.String(), single)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestFreeFillAndArchiveDuringAnOpenRotation: with a return open, a free fill
|
||||
// of an unmarked read-only site and an archive are recorded alone, with no
|
||||
// header, whatever the cooldown (F10).
|
||||
func TestFreeFillAndArchiveDuringAnOpenRotation(t *testing.T) {
|
||||
for _, cooldown := range cooldowns {
|
||||
t.Run("cooldown "+cooldown.String(), func(t *testing.T) {
|
||||
e := newSiteEnv(t, 4)
|
||||
e.h.SwapCooldown = cooldown
|
||||
incumbentID, incumbentDomain := e.site("incumbent"+e.uniq, "active")
|
||||
markedID, markedDomain := e.markedSite("marked")
|
||||
fillID, fillDomain := e.site("fill"+e.uniq, "readonly")
|
||||
if rec := e.keepActive(markedDomain, markedID); !accepted(rec) {
|
||||
t.Fatalf("return = %d %q", rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec := e.keepActive(fillDomain, fillID); !accepted(rec) {
|
||||
t.Errorf("free fill during a return = %d %q, want accepted", rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec := e.rowAction(e.h.ArchiveSite, "archive", incumbentDomain, incumbentID, e.nextGen(incumbentID)); !accepted(rec) {
|
||||
t.Errorf("archive during a return = %d %q, want accepted", rec.Code, rec.Body.String())
|
||||
}
|
||||
if got, want := e.counts(), (intakeCounts{requests: 3, headers: 0, starts: 3, stamps: 0}); got != want {
|
||||
t.Errorf("counts = %+v, want %+v", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// statementLog records, in order, the two reads of a rotation's intake whose
|
||||
// order design D8 fixes.
|
||||
type statementLog struct {
|
||||
mu sync.Mutex
|
||||
names []string
|
||||
}
|
||||
|
||||
func (l *statementLog) add(name string) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
l.names = append(l.names, name)
|
||||
}
|
||||
|
||||
func (l *statementLog) all() []string {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
return append([]string(nil), l.names...)
|
||||
}
|
||||
|
||||
// recordingQuerier wraps the store's querier and logs the open-rotation read
|
||||
// and the stamp read.
|
||||
type recordingQuerier struct {
|
||||
fwmod.Querier
|
||||
log *statementLog
|
||||
}
|
||||
|
||||
func (r recordingQuerier) WorkspaceHasOpenRotation(ctx context.Context, arg fwmod.WorkspaceHasOpenRotationParams) (bool, error) {
|
||||
r.log.add("WorkspaceHasOpenRotation")
|
||||
return r.Querier.WorkspaceHasOpenRotation(ctx, arg)
|
||||
}
|
||||
|
||||
func (r recordingQuerier) GetSiteSwapPolicy(ctx context.Context, workspaceID string) (time.Time, error) {
|
||||
r.log.add("GetSiteSwapPolicy")
|
||||
return r.Querier.GetSiteSwapPolicy(ctx, workspaceID)
|
||||
}
|
||||
|
||||
// rotationRig is a workspace with two active sites, a read-only site for a
|
||||
// swap, a second one for a later swap and a marked one for a return, and a
|
||||
// swap of the first read-only site that succeeded and stamped.
|
||||
type rotationRig struct {
|
||||
nextChosenID, nextChosenDomain string
|
||||
markedID, markedDomain string
|
||||
}
|
||||
|
||||
func newFinishedSwapRig(e *siteEnv) rotationRig {
|
||||
e.t.Helper()
|
||||
e.site("incumbent"+e.uniq, "active")
|
||||
e.site("second"+e.uniq, "active")
|
||||
chosenID, chosenDomain := e.site("chosen"+e.uniq, "readonly")
|
||||
var r rotationRig
|
||||
r.nextChosenID, r.nextChosenDomain = e.site("nextchosen"+e.uniq, "readonly")
|
||||
r.markedID, r.markedDomain = e.markedSite("marked")
|
||||
gen := e.nextGen(chosenID)
|
||||
if rec := e.rowAction(e.h.KeepSiteActive, "keep-active", chosenDomain, chosenID, gen); !accepted(rec) {
|
||||
e.t.Fatalf("first swap = %d %q", rec.Code, rec.Body.String())
|
||||
}
|
||||
in := e.temporal.inputs[0].(workflows.SwapSiteRequestInput)
|
||||
e.finish(chosenID, gen, integration.LifecycleSucceeded, "")
|
||||
e.finish(in.ParkInstanceID, in.ParkGeneration, integration.LifecycleSucceeded, "")
|
||||
e.stamp()
|
||||
return r
|
||||
}
|
||||
|
||||
// TestIntakeReadsOpenRotationsBeforeTheStamp pins design D8's order for a
|
||||
// swap and a return: the open-rotation read comes first. A commit between
|
||||
// the two reads (F6) cannot be reached without pausing the transaction
|
||||
// between two statements; this order is what holds it.
|
||||
func TestIntakeReadsOpenRotationsBeforeTheStamp(t *testing.T) {
|
||||
want := []string{"WorkspaceHasOpenRotation", "GetSiteSwapPolicy"}
|
||||
t.Run("a swap", func(t *testing.T) {
|
||||
e := newSiteEnv(t, 1)
|
||||
e.h.SwapCooldown = 24 * time.Hour
|
||||
log := &statementLog{}
|
||||
e.h.wrapTxQuerier = func(q fwmod.Querier) fwmod.Querier { return recordingQuerier{q, log} }
|
||||
r := newSwapRig(e)
|
||||
if rec := e.keepActive(r.chosenDomain, r.chosenID); !accepted(rec) {
|
||||
t.Fatalf("swap = %d %q", rec.Code, rec.Body.String())
|
||||
}
|
||||
if got := log.all(); !slices.Equal(got, want) {
|
||||
t.Errorf("a swap's intake read %v, want %v", got, want)
|
||||
}
|
||||
})
|
||||
t.Run("a return", func(t *testing.T) {
|
||||
e := newSiteEnv(t, 3)
|
||||
e.h.SwapCooldown = 24 * time.Hour
|
||||
log := &statementLog{}
|
||||
e.h.wrapTxQuerier = func(q fwmod.Querier) fwmod.Querier { return recordingQuerier{q, log} }
|
||||
markedID, markedDomain := e.markedSite("marked")
|
||||
if rec := e.keepActive(markedDomain, markedID); !accepted(rec) {
|
||||
t.Fatalf("return = %d %q", rec.Code, rec.Body.String())
|
||||
}
|
||||
if got := log.all(); !slices.Equal(got, want) {
|
||||
t.Errorf("a return's intake read %v, want %v", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestRotationWhoseSuccessCommittedBeforeTheOpenRotationRead (F5): the
|
||||
// earlier swap finished and stamped before the intake's first read, so the
|
||||
// open-rotation read finds nothing and the stamp read finds the window. With
|
||||
// the cooldown on a swap and a return answer the cooldown sentence and write
|
||||
// nothing; with it off both are recorded, a swap with a header.
|
||||
func TestRotationWhoseSuccessCommittedBeforeTheOpenRotationRead(t *testing.T) {
|
||||
const cooldownSentence = "try again in about"
|
||||
for _, cooldown := range cooldowns {
|
||||
t.Run("a swap, cooldown "+cooldown.String(), func(t *testing.T) {
|
||||
e := newSiteEnv(t, 2)
|
||||
e.h.SwapCooldown = cooldown
|
||||
r := newFinishedSwapRig(e)
|
||||
e.setUsage(2)
|
||||
before := e.counts()
|
||||
rec := e.keepActive(r.nextChosenDomain, r.nextChosenID)
|
||||
got := e.counts()
|
||||
if cooldown > 0 {
|
||||
if !says(rec, cooldownSentence) || got != before {
|
||||
t.Errorf("swap = %q, counts %+v, want the cooldown sentence and %+v", rec.Body.String(), got, before)
|
||||
}
|
||||
return
|
||||
}
|
||||
if !accepted(rec) || got.headers != before.headers+1 || got.requests != before.requests+2 {
|
||||
t.Errorf("swap = %d %q, counts %+v, want accepted with one more header and two more requests than %+v", rec.Code, rec.Body.String(), got, before)
|
||||
}
|
||||
})
|
||||
t.Run("a return, cooldown "+cooldown.String(), func(t *testing.T) {
|
||||
e := newSiteEnv(t, 2)
|
||||
e.h.SwapCooldown = cooldown
|
||||
r := newFinishedSwapRig(e)
|
||||
e.setUsage(1)
|
||||
before := e.counts()
|
||||
rec := e.keepActive(r.markedDomain, r.markedID)
|
||||
got := e.counts()
|
||||
if cooldown > 0 {
|
||||
if !says(rec, cooldownSentence) || got != before {
|
||||
t.Errorf("return = %q, counts %+v, want the cooldown sentence and %+v", rec.Body.String(), got, before)
|
||||
}
|
||||
return
|
||||
}
|
||||
if !accepted(rec) || got.requests != before.requests+1 || got.headers != before.headers {
|
||||
t.Errorf("return = %d %q, counts %+v, want accepted with one more request and no header than %+v", rec.Code, rec.Body.String(), got, before)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestRepeatInsideTheWorkspaceLock: two submissions of one address that both
|
||||
// passed the first lookup and wait on the workspace lock are both answered as
|
||||
// accepted, with one request and one start; the second is not refused by the
|
||||
// open-rotation check (D9 step 1, D10).
|
||||
func TestRepeatInsideTheWorkspaceLock(t *testing.T) {
|
||||
for _, kind := range []string{"a return", "a swap"} {
|
||||
t.Run(kind, func(t *testing.T) {
|
||||
var e *siteEnv
|
||||
var id, domain string
|
||||
if kind == "a return" {
|
||||
e = newSiteEnv(t, 3)
|
||||
id, domain = e.markedSite("marked")
|
||||
} else {
|
||||
e = newSiteEnv(t, 1)
|
||||
r := newSwapRig(e)
|
||||
id, domain = r.chosenID, r.chosenDomain
|
||||
}
|
||||
gen := e.nextGen(id)
|
||||
side := dbtest.Tx(t, e.db)
|
||||
sidePID := int(side.Int(`SELECT pg_backend_pid()`))
|
||||
if err := db.Lock(context.Background(), side.Tx(), db.FedWikiWorkspace, e.ws); err != nil {
|
||||
t.Fatalf("take the workspace lock on the side: %v", err)
|
||||
}
|
||||
answers := make(chan *httptest.ResponseRecorder, 2)
|
||||
for range 2 {
|
||||
go func() { answers <- e.rowAction(e.h.KeepSiteActive, "keep-active", domain, id, gen) }()
|
||||
}
|
||||
dbtest.AwaitLockWait(t, e.db, dbtest.Backend{BlockedBy: sidePID, Waiters: 2, Abort: earlyAnswer(answers)})
|
||||
if err := side.Tx().Rollback(); err != nil {
|
||||
t.Fatalf("release the workspace lock: %v", err)
|
||||
}
|
||||
for range 2 {
|
||||
if rec := <-answers; !accepted(rec) {
|
||||
t.Errorf("answer = %d %q, want accepted", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
if n := e.requestCount(id); n != 1 || len(e.temporal.starts()) != 1 {
|
||||
t.Errorf("%d requests and %d starts, want one of each", n, len(e.temporal.starts()))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// An outcome that holds the policy row open does not hold up intake: the
|
||||
// cooldown read takes no lock (design D15), so it reads the last committed
|
||||
// stamp and the return is recorded while the outcome is still open.
|
||||
func TestIntakeReadsTheStampWithoutALock_DB(t *testing.T) {
|
||||
e := newSiteEnv(t, 3)
|
||||
e.h.SwapCooldown = 24 * time.Hour
|
||||
e.exec(`INSERT INTO fedwiki.site_swap_policy (workspace_id, last_swap_at) VALUES ($1, NOW() - INTERVAL '2 days')`, e.ws)
|
||||
markedID, markedDomain := e.markedSite("stamped")
|
||||
|
||||
outcome := dbtest.Tx(t, e.db)
|
||||
if err := fwmod.New(outcome.Tx()).UpsertSiteSwapPolicy(e.ctx, e.ws); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
answer := make(chan *httptest.ResponseRecorder, 1)
|
||||
go func() { answer <- e.keepActive(markedDomain, markedID) }()
|
||||
select {
|
||||
case rec := <-answer:
|
||||
if !accepted(rec) {
|
||||
t.Errorf("a return beside an open outcome = %d %q, want accepted on the committed stamp", rec.Code, rec.Body.String())
|
||||
}
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("intake waited for the outcome that holds the policy row")
|
||||
}
|
||||
}
|
||||
|
||||
// TestReturnWaitsForTheSyncsSiteRow: the farm sync holds a marked site's row
|
||||
// as its status write does; a member's Keep active on that site waits on the
|
||||
// row, and once the sync has written the row archived (clearing the mark) and
|
||||
// committed, the intake records nothing and answers that the site changed.
|
||||
func TestReturnWaitsForTheSyncsSiteRow(t *testing.T) {
|
||||
e := newSiteEnv(t, 3)
|
||||
markedID, markedDomain := e.markedSite("marked")
|
||||
gen := e.nextGen(markedID)
|
||||
|
||||
side := dbtest.Tx(t, e.db)
|
||||
sidePID := int(side.Int(`SELECT pg_backend_pid()`))
|
||||
if _, err := fwmod.New(side.Tx()).LockSiteStatusByDomain(context.Background(), markedDomain); err != nil {
|
||||
t.Fatalf("lock the site row on the side: %v", err)
|
||||
}
|
||||
before := e.counts()
|
||||
answer := make(chan *httptest.ResponseRecorder, 1)
|
||||
go func() { answer <- e.rowAction(e.h.KeepSiteActive, "keep-active", markedDomain, markedID, gen) }()
|
||||
dbtest.AwaitLockWait(t, e.db, dbtest.Backend{BlockedBy: sidePID, Abort: earlyAnswer(answer)})
|
||||
|
||||
if _, err := fwmod.New(side.Tx()).UpsertSiteFromFarm(context.Background(), fwmod.UpsertSiteFromFarmParams{
|
||||
WorkspaceID: e.ws, Domain: markedDomain, Status: "archived"}); err != nil {
|
||||
t.Fatalf("write the row archived on the side: %v", err)
|
||||
}
|
||||
if err := side.Tx().Commit(); err != nil {
|
||||
t.Fatalf("commit the sync's write: %v", err)
|
||||
}
|
||||
rec := <-answer
|
||||
if !says(rec, msgSiteChanged) || !isRefresh(rec) || e.counts() != before {
|
||||
t.Errorf("return after the sync archived the row = %q, counts %+v, want %q, a refresh and %+v", rec.Body.String(), e.counts(), msgSiteChanged, before)
|
||||
}
|
||||
if got := e.id(`SELECT status FROM fedwiki.sites WHERE site_id = $1`, markedID); got != "archived" {
|
||||
t.Errorf("site status = %s, want archived", got)
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ package web
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -48,3 +49,37 @@ func TestWorkspaceTxTakesTheWorkspaceLock(t *testing.T) {
|
||||
t.Errorf("the rotation returned %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReturnTakesTheWorkspaceLock holds that a return takes the workspace lock
|
||||
// with the cooldown off, and that a free fill, which is no rotation, does not
|
||||
// wait for it.
|
||||
func TestReturnTakesTheWorkspaceLock(t *testing.T) {
|
||||
e := newSiteEnv(t, 3)
|
||||
markedID, markedDomain := e.markedSite("marked")
|
||||
fillID, fillDomain := e.site("fill"+e.uniq, "readonly")
|
||||
|
||||
side := dbtest.Tx(t, e.db)
|
||||
sidePID := int(side.Int(`SELECT pg_backend_pid()`))
|
||||
if err := db.Lock(context.Background(), side.Tx(), db.FedWikiWorkspace, e.ws); err != nil {
|
||||
t.Fatalf("take the workspace lock on the side: %v", err)
|
||||
}
|
||||
gen := e.nextGen(markedID)
|
||||
answer := make(chan *httptest.ResponseRecorder, 1)
|
||||
go func() { answer <- e.rowAction(e.h.KeepSiteActive, "keep-active", markedDomain, markedID, gen) }()
|
||||
dbtest.AwaitLockWait(t, e.db, dbtest.Backend{BlockedBy: sidePID, Abort: earlyAnswer(answer)})
|
||||
|
||||
if rec := e.keepActive(fillDomain, fillID); !accepted(rec) {
|
||||
t.Errorf("a free fill waited for or was refused by the workspace lock: %d %q", rec.Code, rec.Body.String())
|
||||
}
|
||||
select {
|
||||
case rec := <-answer:
|
||||
t.Fatalf("the return was answered while the lock was held: %q", rec.Body.String())
|
||||
default:
|
||||
}
|
||||
if err := side.Tx().Rollback(); err != nil {
|
||||
t.Fatalf("release the workspace lock: %v", err)
|
||||
}
|
||||
if rec := <-answer; !accepted(rec) {
|
||||
t.Errorf("return after the lock was released = %d %q, want accepted", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -193,7 +193,7 @@ func recordArchiveTime(t *testing.T, row recordArchiveCase) {
|
||||
parkedDomain := "incumbent." + env.root
|
||||
parked := env.insertSite(parkedDomain, "active", false)
|
||||
var parkedGeneration int64
|
||||
generation, parkedGeneration = env.swapRequests(id, parked, "archive-time-"+id)
|
||||
generation, parkedGeneration, _ = env.swapRequests(id, parked, "archive-time-"+id)
|
||||
err = env.acts.RecordSwapActivity(env.ctx, RecordSwapInput{WorkspaceID: env.ws, Activate: LifecycleRequestRef{InstanceID: id, Generation: generation}, Park: LifecycleRequestRef{InstanceID: parked, Generation: parkedGeneration}, ActivateDomain: domain, ParkDomain: parkedDomain, FinishedAt: time.Now()})
|
||||
if status, _ := env.request(parked, parkedGeneration); status != "succeeded" {
|
||||
t.Errorf("parked request = %s", status)
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
||||
// SPDX-FileCopyrightText: 2025-2026 Christian Galo
|
||||
|
||||
package workflows
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
fwmod "git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/fedwiki/store"
|
||||
)
|
||||
|
||||
func TestIsReturn(t *testing.T) {
|
||||
marked := sql.NullTime{Time: time.Now(), Valid: true}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
status string
|
||||
mark sql.NullTime
|
||||
target string
|
||||
want bool
|
||||
}{
|
||||
{"a marked read-only site returning to active", "readonly", marked, "active", true},
|
||||
{"the same site unmarked is a free fill", "readonly", sql.NullTime{}, "active", false},
|
||||
{"an archived site with no mark is a Restore", "archived", sql.NullTime{}, "active", false},
|
||||
{"a marked archived site returning to active", "archived", marked, "active", true},
|
||||
{"a marked site already active", "active", marked, "active", false},
|
||||
{"a marked site archived", "readonly", marked, "archived", false},
|
||||
{"a marked site kept read-only", "readonly", marked, "readonly", false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
row := fwmod.LockSiteStatusByIDRow{Status: tc.status, ForceReducedAt: tc.mark}
|
||||
if got := isReturn(row, tc.target); got != tc.want {
|
||||
t.Errorf("isReturn(%s, marked %v, %s) = %v, want %v", tc.status, tc.mark.Valid, tc.target, got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -216,7 +216,7 @@ func recordSwapWithoutAUsageRow(t *testing.T) {
|
||||
e := newBareEnv(t, 0)
|
||||
s := e.swapSites()
|
||||
e.exec(`UPDATE fedwiki.sites SET status = 'readonly' WHERE site_id = $1`, s.parkID)
|
||||
gen, parkGen := e.swapRequests(s.activateID, s.parkID, "swap-bare")
|
||||
gen, parkGen, _ := e.swapRequests(s.activateID, s.parkID, "swap-bare")
|
||||
if err := e.acts.RecordSwapActivity(e.ctx, RecordSwapInput{
|
||||
Activate: LifecycleRequestRef{InstanceID: s.activateID, Generation: gen}, Park: LifecycleRequestRef{InstanceID: s.parkID, Generation: parkGen},
|
||||
WorkspaceID: e.ws, ActivateDomain: s.activate, ParkDomain: s.park, FinishedAt: time.Now()}); err != nil {
|
||||
@@ -225,6 +225,7 @@ func recordSwapWithoutAUsageRow(t *testing.T) {
|
||||
e.wantRequests("succeeded", LifecycleRequestRef{InstanceID: s.activateID, Generation: gen}, LifecycleRequestRef{InstanceID: s.parkID, Generation: parkGen})
|
||||
e.wantSiteStatus(s.activate, "active")
|
||||
e.wantNoUsageRowCreated()
|
||||
e.wantStamp("after a swap on a pool with no usage row")
|
||||
}
|
||||
|
||||
// The sweep's park and reactivation commit the status they write.
|
||||
|
||||
@@ -185,7 +185,7 @@ func checkRecordPlacement(t *testing.T, row placementRecordCase) {
|
||||
parkedID = env.insertSite(parkedName, "active", false)
|
||||
env.placeServable(parkedName, parkedID)
|
||||
dbtest.On(t, env.db).Exec(`UPDATE domains.placements SET servable=false WHERE resource_ref=$1`, parkedID)
|
||||
generation, parkedGeneration = env.swapRequests(id, parkedID, "placement-"+id)
|
||||
generation, parkedGeneration, _ = env.swapRequests(id, parkedID, "placement-"+id)
|
||||
run = func() error {
|
||||
return env.acts.RecordSwapActivity(env.ctx, RecordSwapInput{WorkspaceID: env.ws, Activate: LifecycleRequestRef{InstanceID: id, Generation: generation}, Park: LifecycleRequestRef{InstanceID: parkedID, Generation: parkedGeneration}, ActivateDomain: name, ParkDomain: parkedName, FinishedAt: time.Now()})
|
||||
}
|
||||
|
||||
@@ -369,7 +369,9 @@ type RecordSiteStatusInput struct {
|
||||
|
||||
// RecordSiteStatusActivity writes the site's new status, the clearing of its
|
||||
// downgrade-parked mark, and the request's outcome in one transaction (design
|
||||
// D28); finishAllWith removes the request's hold and recounts the pool, so
|
||||
// D28). When isReturn holds for the locked row, the same transaction stamps
|
||||
// the workspace's swap policy, after the site rows and before the usage row
|
||||
// (design D15); finishAllWith removes the request's hold and recounts the pool, so
|
||||
// the figure follows the row. The site's trigger writes placement servability
|
||||
// in that same transaction.
|
||||
//
|
||||
@@ -385,12 +387,15 @@ func (a *Activities) RecordSiteStatusActivity(ctx context.Context, in RecordSite
|
||||
FinishedAt: in.FinishedAt,
|
||||
}, func(tx *sql.Tx) error {
|
||||
q := fwmod.New(tx)
|
||||
if _, err := lockRequestSite(ctx, q, in.InstanceID, in.WorkspaceID, in.Domain); err != nil {
|
||||
locked, err := lockRequestSite(ctx, q, in.InstanceID, in.WorkspaceID, in.Domain)
|
||||
if err != nil {
|
||||
if errorType(err) != "" {
|
||||
return err
|
||||
}
|
||||
return fmt.Errorf("record status of %s: %w", in.Domain, err)
|
||||
}
|
||||
// Read before SetSiteStatusByID clears the mark.
|
||||
returned := isReturn(locked, in.Status)
|
||||
if _, err := q.SetSiteStatusByID(ctx, fwmod.SetSiteStatusByIDParams{SiteID: in.InstanceID, Status: in.Status}); err != nil {
|
||||
return fmt.Errorf("record status of %s: %w", in.Domain, err)
|
||||
}
|
||||
@@ -399,11 +404,26 @@ func (a *Activities) RecordSiteStatusActivity(ctx context.Context, in RecordSite
|
||||
return fmt.Errorf("clear force_reduced on %s: %w", in.Domain, err)
|
||||
}
|
||||
}
|
||||
if returned {
|
||||
if err := q.UpsertSiteSwapPolicy(ctx, in.WorkspaceID); err != nil {
|
||||
return fmt.Errorf("stamp the return of %s: %w", in.Domain, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
// isReturn reports whether recording target on the locked row is a return:
|
||||
// the row carries the downgrade mark, is not active, and the target is
|
||||
// active. The mark separates a return from a free fill, which never stamps,
|
||||
// and from a Restore of an archived row, which carries none. A row the
|
||||
// re-upgrade sweep already made active is not a return: the member's request
|
||||
// changed nothing.
|
||||
func isReturn(locked fwmod.LockSiteStatusByIDRow, target string) bool {
|
||||
return locked.ForceReducedAt.Valid && locked.Status != "active" && target == "active"
|
||||
}
|
||||
|
||||
// RecordSiteDeletedInput is a permanent delete's local half.
|
||||
type RecordSiteDeletedInput struct {
|
||||
InstanceID string
|
||||
|
||||
@@ -6,7 +6,6 @@ package workflows
|
||||
import (
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go.temporal.io/sdk/temporal"
|
||||
@@ -94,13 +93,6 @@ func SwapRequestWorkflowID(activateSiteID string, generation int64) string {
|
||||
return swapRequestWorkflowPrefix + activateSiteID + "-" + itoa(generation)
|
||||
}
|
||||
|
||||
// IsSwapRequestWorkflowID reports whether a request's workflow id names a
|
||||
// request-driven swap, so a handler can tell a workspace's open swap from
|
||||
// its other open requests.
|
||||
func IsSwapRequestWorkflowID(workflowID string) bool {
|
||||
return strings.HasPrefix(workflowID, swapRequestWorkflowPrefix)
|
||||
}
|
||||
|
||||
const swapRequestWorkflowPrefix = "swap-fedwiki-site-"
|
||||
|
||||
func DeleteRequestWorkflowID(siteID string, generation int64) string {
|
||||
|
||||
@@ -55,6 +55,7 @@ type reqEnv struct {
|
||||
subject string
|
||||
root string
|
||||
requests []string // instances whose requests cleanup removes
|
||||
actIDs []string // acts cleanup removes after the requests
|
||||
}
|
||||
|
||||
func newReqEnv(t *testing.T, limit, usage int) *reqEnv {
|
||||
@@ -79,6 +80,9 @@ func newReqEnv(t *testing.T, limit, usage int) *reqEnv {
|
||||
for _, inst := range e.requests {
|
||||
_, _ = database.ExecContext(e.ctx, `DELETE FROM core.lifecycle_requests WHERE instance_id = $1`, inst)
|
||||
}
|
||||
for _, id := range e.actIDs {
|
||||
_, _ = database.ExecContext(e.ctx, `DELETE FROM core.acts WHERE act_id = $1`, id)
|
||||
}
|
||||
})
|
||||
return e
|
||||
}
|
||||
@@ -93,20 +97,35 @@ func (e *reqEnv) exec(q string, args ...any) {
|
||||
// record records a request as a handler would and returns its generation.
|
||||
func (e *reqEnv) record(instance, op, workflowID string, params map[string]any) int64 {
|
||||
e.t.Helper()
|
||||
next, err := integration.NextGenerations(e.ctx, e.db, []string{instance})
|
||||
gen, _ := e.recordAs(e.db, instance, op, workflowID, e.person, params)
|
||||
return gen
|
||||
}
|
||||
|
||||
// recordAs records one request in the given database handle or transaction,
|
||||
// naming person (empty for a consequent request), and returns its generation
|
||||
// and id.
|
||||
func (e *reqEnv) recordAs(q integration.DBTX, instance, op, workflowID, person string, params map[string]any) (int64, string) {
|
||||
e.t.Helper()
|
||||
next, err := integration.NextGenerations(e.ctx, q, []string{instance})
|
||||
if err != nil {
|
||||
e.t.Fatal(err)
|
||||
}
|
||||
raw, _ := json.Marshal(params)
|
||||
a, err := integration.RecordLifecycleRequest(e.ctx, e.db, integration.LifecycleRequestSpec{
|
||||
spec := integration.LifecycleRequestSpec{
|
||||
InstanceID: instance, Generation: next[instance], ConnectionID: e.conn, ResourceKey: "fedwiki_sites",
|
||||
WorkspaceID: e.ws, Operation: op, Parameters: raw, WorkflowID: workflowID, RequestedByPersonID: e.person,
|
||||
})
|
||||
WorkspaceID: e.ws, Operation: op, Parameters: raw, WorkflowID: workflowID, RequestedByPersonID: person,
|
||||
}
|
||||
var a integration.LifecycleAnswer
|
||||
if tx, ok := q.(*sql.Tx); ok {
|
||||
a, err = integration.RecordLifecycleRequestInTx(e.ctx, tx, spec)
|
||||
} else {
|
||||
a, err = integration.RecordLifecycleRequest(e.ctx, e.db, spec)
|
||||
}
|
||||
if err != nil || a.Kind != integration.LifecycleRecorded {
|
||||
e.t.Fatalf("record %s on %s: %+v, %v", op, instance, a, err)
|
||||
}
|
||||
e.requests = append(e.requests, instance)
|
||||
return next[instance]
|
||||
return next[instance], a.RequestID
|
||||
}
|
||||
|
||||
func (e *reqEnv) newInstance() string {
|
||||
@@ -565,6 +584,97 @@ func TestStatusRequests_DB(t *testing.T) {
|
||||
t.Run("a site that changed hands is declined", siteThatChangedHandsIsDeclined)
|
||||
}
|
||||
|
||||
// seedStamp writes a stamp from two days ago and returns it as stored.
|
||||
func (e *reqEnv) seedStamp() time.Time {
|
||||
e.t.Helper()
|
||||
e.exec(`INSERT INTO fedwiki.site_swap_policy (workspace_id, last_swap_at) VALUES ($1, NOW() - INTERVAL '2 days')
|
||||
ON CONFLICT (workspace_id) DO UPDATE SET last_swap_at = EXCLUDED.last_swap_at`, e.ws)
|
||||
return e.wantStamp("after seeding")
|
||||
}
|
||||
|
||||
func (e *reqEnv) wantStampKept(want time.Time, when string) {
|
||||
e.t.Helper()
|
||||
if at, ok := e.stamp(); !ok || !at.Equal(want) {
|
||||
e.t.Errorf("%s: stamp = %v (present %v), want the earlier %v kept", when, at, ok, want)
|
||||
}
|
||||
}
|
||||
|
||||
// The worker reads no cooldown, so every test here runs with it off: a return
|
||||
// stamps because it succeeded, and nothing else decides.
|
||||
func TestReturnStampsOnSuccess_DB(t *testing.T) {
|
||||
t.Run("a return on a marked read-only site stamps and clears the mark", func(t *testing.T) {
|
||||
e := newReqEnv(t, 3, 0)
|
||||
in := e.startActivation("return", "readonly")
|
||||
e.wantNoStamp("before the return, recorded with no stamp")
|
||||
e.wantOutput(e.runStatus(gateVersions[0], in), "succeeded", "")
|
||||
if status, marked := siteState(t, e.db, in.Domain); status != "active" || marked {
|
||||
t.Errorf("site = %s, marked %v", status, marked)
|
||||
}
|
||||
e.wantStamp("after a return")
|
||||
})
|
||||
t.Run("a failed farm call read back as applied records the success and stamps", func(t *testing.T) {
|
||||
e := newReqEnv(t, 3, 0)
|
||||
in := e.startActivation("readbackreturn", "readonly")
|
||||
e.farm.HoldIn(in.Domain, e.subject, "active")
|
||||
e.farm.Refuse(in.Domain, "active")
|
||||
e.wantOutput(e.runStatus(gateVersions[0], in), "succeeded", "")
|
||||
e.wantSiteStatus(in.Domain, "active")
|
||||
e.wantStamp("after a return the farm applied")
|
||||
})
|
||||
t.Run("a return whose site the sweep reactivated during the farm call stamps nothing", func(t *testing.T) {
|
||||
e := newReqEnv(t, 3, 0)
|
||||
in := e.startActivation("swept", "readonly")
|
||||
e.farm.OnFirst(in.Domain, "active", func() {
|
||||
e.exec(`UPDATE fedwiki.sites SET status = 'active', force_reduced_at = NULL WHERE site_id = $1`, in.InstanceID)
|
||||
})
|
||||
e.wantOutput(e.runStatus(gateVersions[0], in), "succeeded", "")
|
||||
e.wantSite(in.Domain, "active", false)
|
||||
e.wantNoStamp("after the sweep brought the site back")
|
||||
})
|
||||
t.Run("a free fill and a Restore stamp nothing", func(t *testing.T) {
|
||||
e := newReqEnv(t, 3, 0)
|
||||
fill := e.startActivation("freefill", "readonly")
|
||||
e.exec(`UPDATE fedwiki.sites SET force_reduced_at = NULL WHERE site_id = $1`, fill.InstanceID)
|
||||
fill.ClearForceReduced = false
|
||||
e.wantOutput(e.runStatus(gateVersions[0], fill), "succeeded", "")
|
||||
e.wantSiteStatus(fill.Domain, "active")
|
||||
restore := e.startActivation("restored", "archived")
|
||||
e.wantOutput(e.runStatus(gateVersions[0], restore), "succeeded", "")
|
||||
e.wantSiteStatus(restore.Domain, "active")
|
||||
e.wantNoStamp("after a free fill and a Restore")
|
||||
})
|
||||
t.Run("a decline, a failed farm call and a refused record leave the wait as it was", func(t *testing.T) {
|
||||
declined := newReqEnv(t, 1, 1)
|
||||
declined.fill()
|
||||
in := declined.startActivation("gated", "readonly")
|
||||
seeded := declined.seedStamp()
|
||||
declined.wantOutput(declined.runStatus(gateVersions[0], in), "declined", ReasonActiveLimitReached)
|
||||
declined.wantStampKept(seeded, "after a decline at the gate")
|
||||
|
||||
failed := newReqEnv(t, 3, 0)
|
||||
in = failed.startActivation("farmfailed", "readonly")
|
||||
seeded = failed.seedStamp()
|
||||
failed.farm.HoldIn(in.Domain, failed.subject, "readonly")
|
||||
failed.farm.Refuse(in.Domain, "active")
|
||||
failed.wantOutput(failed.runStatus(gateVersions[0], in), "failed", ReasonRetriesExhausted)
|
||||
failed.wantStampKept(seeded, "after a failed farm call")
|
||||
|
||||
refused := newReqEnv(t, 3, 0)
|
||||
in = refused.startActivation("recordrefused", "readonly")
|
||||
seeded = refused.seedStamp()
|
||||
refused.exec(`UPDATE fedwiki.sites SET domain = $2 WHERE site_id = $1`, in.InstanceID, "changed."+refused.root)
|
||||
err := refused.acts.RecordSiteStatusActivity(refused.ctx, RecordSiteStatusInput{InstanceID: in.InstanceID, Generation: in.Generation,
|
||||
WorkspaceID: refused.ws, Domain: in.Domain, Status: "active", ClearForceReduced: true, FinishedAt: time.Now()})
|
||||
if errorType(err) != SiteAuthorizationError {
|
||||
t.Errorf("record = %v, want a refusal for a changed site", err)
|
||||
}
|
||||
refused.wantStampKept(seeded, "after a refused record")
|
||||
if status, _ := refused.request(in.InstanceID, in.Generation); status != "accepted" {
|
||||
t.Errorf("request = %s, want it left accepted", status)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func restoreAtTheActiveLimitIsDeclined(t *testing.T) {
|
||||
e := newReqEnv(t, 1, 1)
|
||||
e.fill()
|
||||
@@ -629,6 +739,7 @@ func rotationClearsTheDowngradeMark(t *testing.T) {
|
||||
if status, forceReduced := siteState(t, e.db, domain); status != "active" || forceReduced {
|
||||
t.Errorf("site = %s, force-reduced %v", status, forceReduced)
|
||||
}
|
||||
e.wantStamp("after the rotation")
|
||||
if rows := e.wantFigure("after the rotation"); rows != 1 {
|
||||
t.Errorf("rows and holds = %d, want the one site the rotation activated", rows)
|
||||
}
|
||||
@@ -716,6 +827,7 @@ func refusedSwapLeavesBothSites(t *testing.T) {
|
||||
e.wantSiteStatus(s.park, "active")
|
||||
e.wantSite(s.activate, "readonly", true)
|
||||
e.wantPatchTail(s.park + "=active")
|
||||
e.wantNoStamp("after a swap the farm refused")
|
||||
}
|
||||
|
||||
// The activation is refused on every attempt, and so is each attempt's own
|
||||
@@ -791,7 +903,15 @@ func TestRecordSwapWritesStatusesWithItsOutcomes_DB(t *testing.T) {
|
||||
activate := "reserve." + e.root
|
||||
parkID := e.insertSite(park, "active", false)
|
||||
activateID := e.insertSite(activate, "readonly", true)
|
||||
gen, parkGen := e.swapRequests(activateID, parkID, "swap-tx")
|
||||
gen, parkGen, actID := e.swapRequests(activateID, parkID, "swap-tx")
|
||||
var linked int
|
||||
if err := e.db.QueryRowContext(e.ctx,
|
||||
`SELECT count(*) FROM core.lifecycle_requests WHERE act_id = $1 AND act_cause = 'instances_swapped'`, actID).Scan(&linked); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if linked != 2 {
|
||||
t.Fatalf("requests linked to the swap's act = %d, want 2", linked)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(e.ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
@@ -852,6 +972,9 @@ func TestRecordSwapWritesStatusesWithItsOutcomes_DB(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestSettleOpenRequests_DB(t *testing.T) {
|
||||
// The act cases run first, each in its own workspace, so their counts
|
||||
// are not those of this test's own rows.
|
||||
settleActCases(t)
|
||||
e := newReqEnv(t, 5, 0)
|
||||
age := func(instance string) {
|
||||
e.exec(`UPDATE core.lifecycle_requests SET created_at = NOW() - INTERVAL '10 minutes' WHERE instance_id = $1`, instance)
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
enumspb "go.temporal.io/api/enums/v1"
|
||||
"go.temporal.io/api/serviceerror"
|
||||
"go.temporal.io/api/workflowservice/v1"
|
||||
@@ -40,18 +41,24 @@ type SettleCounts struct {
|
||||
// SettleOpenRequests settles the connection's accepted requests that are
|
||||
// older than SettleRequestAge and whose workflow has not recorded an outcome
|
||||
// (design D27). It runs at the top of FedWiki's startup, before the sync
|
||||
// check, wherever Temporal is configured. Every outcome it records goes
|
||||
// through finishAllWith, so a finish removes the request's hold and recounts
|
||||
// the pool (design D9):
|
||||
// check, wherever Temporal is configured. The requests settle in groups
|
||||
// (actGroups): a request with no act is a group of one, and an act's requests
|
||||
// are one group, described once through its first member, because they share
|
||||
// one workflow. Every outcome it records goes through finishAllWith, one call
|
||||
// per group, so a finish removes the requests' holds and recounts the pool
|
||||
// (design D9). Settle passes no apply and never stamps.
|
||||
//
|
||||
// - NotFound: the process died between commit and start; the request ends
|
||||
// - NotFound: the process died between commit and start; the group ends
|
||||
// failed with not_started. It is never restarted.
|
||||
// - running: nothing; the workflow records its own outcome.
|
||||
// - closed, a group that carries an act: the group ends failed with
|
||||
// retries_exhausted in one call, even if the farm applied the action.
|
||||
// - closed, a create: the farm call may have succeeded, so the reconcile
|
||||
// workflow reads the farm's entry and records the outcome.
|
||||
// - closed, a status change to active that still holds a slot: the farm may
|
||||
// have applied it, so the status reconcile workflow reads the farm's entry
|
||||
// and records the outcome; the request stays accepted with its slot held.
|
||||
// and records the outcome, stamping a return; the request stays accepted
|
||||
// with its slot held.
|
||||
// - closed, any other operation: the request ends failed with
|
||||
// retries_exhausted, and the site keeps its observed status.
|
||||
// - any other error: nothing; the next boot tries again.
|
||||
@@ -65,74 +72,140 @@ func SettleOpenRequests(ctx context.Context, c LifecycleClient, database *sql.DB
|
||||
return counts, err
|
||||
}
|
||||
counts.Seen = len(rows)
|
||||
finish := func(r integration.LifecycleRequest, reason string) {
|
||||
if _, err := finishAllWith(ctx, database, []integration.LifecycleOutcome{{
|
||||
s := &settler{ctx: ctx, c: c, database: database, taskQueue: taskQueue, now: now, logger: logger, counts: &counts}
|
||||
for _, group := range actGroups(rows) {
|
||||
s.settle(group)
|
||||
}
|
||||
return counts, nil
|
||||
}
|
||||
|
||||
// actGroups groups listed requests the way settle ends them (design D16). A
|
||||
// request with no act, a stored swap's rows included, is a group of one. An
|
||||
// act's requests form one group: the asked request first, then the
|
||||
// consequent requests in listing order, which is the order intake records
|
||||
// them and the workflow passes them, so the instance locks follow lock
|
||||
// rule 6. Groups come in the order their first listed member appears.
|
||||
func actGroups(rows []integration.LifecycleRequest) [][]integration.LifecycleRequest {
|
||||
var groups [][]integration.LifecycleRequest
|
||||
byAct := map[uuid.UUID]int{}
|
||||
for _, r := range rows {
|
||||
if !r.ActID.Valid {
|
||||
groups = append(groups, []integration.LifecycleRequest{r})
|
||||
continue
|
||||
}
|
||||
at, seen := byAct[r.ActID.UUID]
|
||||
if !seen {
|
||||
byAct[r.ActID.UUID] = len(groups)
|
||||
groups = append(groups, []integration.LifecycleRequest{r})
|
||||
continue
|
||||
}
|
||||
if r.ActRole.String == integration.LifecycleActAsked {
|
||||
groups[at] = append([]integration.LifecycleRequest{r}, groups[at]...)
|
||||
} else {
|
||||
groups[at] = append(groups[at], r)
|
||||
}
|
||||
}
|
||||
return groups
|
||||
}
|
||||
|
||||
// settler carries one boot pass's collaborators.
|
||||
type settler struct {
|
||||
ctx context.Context
|
||||
c LifecycleClient
|
||||
database *sql.DB
|
||||
taskQueue string
|
||||
now time.Time
|
||||
logger *slog.Logger
|
||||
counts *SettleCounts
|
||||
}
|
||||
|
||||
func (s *settler) settle(group []integration.LifecycleRequest) {
|
||||
r := group[0]
|
||||
n := len(group)
|
||||
desc, err := s.c.DescribeWorkflowExecution(s.ctx, r.WorkflowID, "")
|
||||
var notFound *serviceerror.NotFound
|
||||
switch {
|
||||
case errors.As(err, ¬Found):
|
||||
s.counts.NotStarted += n
|
||||
s.finish(group, ReasonNotStarted)
|
||||
case err != nil:
|
||||
s.counts.Unanswered += n
|
||||
s.logger.Warn("lifecycle request left open: Temporal did not describe its workflow",
|
||||
slog.String("request_id", r.RequestID), slog.String("workflow_id", r.WorkflowID), slog.Any("error", err))
|
||||
case desc.GetWorkflowExecutionInfo().GetStatus() == enumspb.WORKFLOW_EXECUTION_STATUS_RUNNING:
|
||||
s.counts.Running += n
|
||||
case r.ActID.Valid:
|
||||
s.counts.Exhausted += n
|
||||
s.finish(group, ReasonRetriesExhausted)
|
||||
default:
|
||||
s.settleClosed(r)
|
||||
}
|
||||
}
|
||||
|
||||
// settleClosed settles a request with no act whose workflow is closed.
|
||||
func (s *settler) settleClosed(r integration.LifecycleRequest) {
|
||||
if r.Operation == integration.LifecycleCreate {
|
||||
s.start(r, "create", ReconcileCreateWorkflowID(r.InstanceID), ReconcileFedWikiSiteCreateWorkflow, ReconcileSiteCreateInput{
|
||||
ConnectionID: r.ConnectionID,
|
||||
InstanceID: r.InstanceID,
|
||||
Generation: r.Generation,
|
||||
})
|
||||
return
|
||||
}
|
||||
held, err := holdsActivationSlot(s.ctx, s.database, r)
|
||||
switch {
|
||||
case err != nil:
|
||||
s.counts.Unanswered++
|
||||
s.logger.Warn("lifecycle request left open: its hold could not be read",
|
||||
slog.String("request_id", r.RequestID), slog.Any("error", err))
|
||||
case held:
|
||||
s.start(r, "status", ReconcileStatusWorkflowID(r.InstanceID, r.Generation), ReconcileFedWikiSiteStatusWorkflow, ReconcileSiteStatusInput{
|
||||
ConnectionID: r.ConnectionID,
|
||||
InstanceID: r.InstanceID,
|
||||
Generation: r.Generation,
|
||||
})
|
||||
default:
|
||||
s.counts.Exhausted++
|
||||
s.finish([]integration.LifecycleRequest{r}, ReasonRetriesExhausted)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *settler) start(r integration.LifecycleRequest, kind, id string, wf, in any) {
|
||||
if _, err := s.c.ExecuteWorkflow(s.ctx, client.StartWorkflowOptions{ID: id, TaskQueue: s.taskQueue}, wf, in); err != nil && !AlreadyRunning(err) {
|
||||
s.counts.Unanswered++
|
||||
s.logger.Warn("could not start the "+kind+" reconcile",
|
||||
slog.String("request_id", r.RequestID), slog.Any("error", err))
|
||||
return
|
||||
}
|
||||
s.counts.Reconciling++
|
||||
}
|
||||
|
||||
// finish ends the group failed with reason in one finishAllWith call.
|
||||
func (s *settler) finish(group []integration.LifecycleRequest, reason string) {
|
||||
outs := make([]integration.LifecycleOutcome, len(group))
|
||||
for i, r := range group {
|
||||
outs[i] = integration.LifecycleOutcome{
|
||||
InstanceID: r.InstanceID,
|
||||
Generation: r.Generation,
|
||||
Status: integration.LifecycleFailed,
|
||||
ReasonCode: reason,
|
||||
FinishedAt: now,
|
||||
}}, nil, nil); err != nil {
|
||||
if settledSince(ctx, database, r, err) {
|
||||
// A reconcile recorded the outcome between the listing and
|
||||
// this finish: the request is settled, which is not an error.
|
||||
logger.Info("lifecycle request already settled",
|
||||
slog.String("request_id", r.RequestID), slog.String("reason", reason))
|
||||
return
|
||||
}
|
||||
counts.FinishErrored++
|
||||
logger.Error("could not settle lifecycle request",
|
||||
slog.String("request_id", r.RequestID), slog.String("reason", reason), slog.Any("error", err))
|
||||
FinishedAt: s.now,
|
||||
}
|
||||
}
|
||||
start := func(r integration.LifecycleRequest, kind, id string, wf, in any) {
|
||||
if _, err := c.ExecuteWorkflow(ctx, client.StartWorkflowOptions{ID: id, TaskQueue: taskQueue}, wf, in); err != nil && !AlreadyRunning(err) {
|
||||
counts.Unanswered++
|
||||
logger.Warn("could not start the "+kind+" reconcile",
|
||||
slog.String("request_id", r.RequestID), slog.Any("error", err))
|
||||
return
|
||||
}
|
||||
counts.Reconciling++
|
||||
_, err := finishAllWith(s.ctx, s.database, outs, nil, nil)
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
for _, r := range rows {
|
||||
desc, err := c.DescribeWorkflowExecution(ctx, r.WorkflowID, "")
|
||||
var notFound *serviceerror.NotFound
|
||||
switch {
|
||||
case errors.As(err, ¬Found):
|
||||
counts.NotStarted++
|
||||
finish(r, ReasonNotStarted)
|
||||
case err != nil:
|
||||
counts.Unanswered++
|
||||
logger.Warn("lifecycle request left open: Temporal did not describe its workflow",
|
||||
slog.String("request_id", r.RequestID), slog.String("workflow_id", r.WorkflowID), slog.Any("error", err))
|
||||
case desc.GetWorkflowExecutionInfo().GetStatus() == enumspb.WORKFLOW_EXECUTION_STATUS_RUNNING:
|
||||
counts.Running++
|
||||
case r.Operation == integration.LifecycleCreate:
|
||||
start(r, "create", ReconcileCreateWorkflowID(r.InstanceID), ReconcileFedWikiSiteCreateWorkflow, ReconcileSiteCreateInput{
|
||||
ConnectionID: r.ConnectionID,
|
||||
InstanceID: r.InstanceID,
|
||||
Generation: r.Generation,
|
||||
})
|
||||
default:
|
||||
held, err := holdsActivationSlot(ctx, database, r)
|
||||
switch {
|
||||
case err != nil:
|
||||
counts.Unanswered++
|
||||
logger.Warn("lifecycle request left open: its hold could not be read",
|
||||
slog.String("request_id", r.RequestID), slog.Any("error", err))
|
||||
case held:
|
||||
start(r, "status", ReconcileStatusWorkflowID(r.InstanceID, r.Generation), ReconcileFedWikiSiteStatusWorkflow, ReconcileSiteStatusInput{
|
||||
ConnectionID: r.ConnectionID,
|
||||
InstanceID: r.InstanceID,
|
||||
Generation: r.Generation,
|
||||
})
|
||||
default:
|
||||
counts.Exhausted++
|
||||
finish(r, ReasonRetriesExhausted)
|
||||
}
|
||||
}
|
||||
if settledSince(s.ctx, s.database, group, err) {
|
||||
// An outcome was recorded between the listing and this finish: the
|
||||
// group is settled, which is not an error.
|
||||
s.logger.Info("lifecycle request already settled",
|
||||
slog.String("request_id", group[0].RequestID), slog.String("reason", reason))
|
||||
return
|
||||
}
|
||||
return counts, nil
|
||||
s.counts.FinishErrored += len(group)
|
||||
s.logger.Error("could not settle lifecycle request",
|
||||
slog.String("request_id", group[0].RequestID), slog.String("reason", reason), slog.Any("error", err))
|
||||
}
|
||||
|
||||
// holdsActivationSlot reports whether a request is a status change to active
|
||||
@@ -148,17 +221,26 @@ func holdsActivationSlot(ctx context.Context, database *sql.DB, r integration.Li
|
||||
return fwmod.New(database).SlotHoldExists(ctx, r.RequestID)
|
||||
}
|
||||
|
||||
// settledSince reports whether a finish failed because the request holds
|
||||
// another outcome by now: finishAllWith refuses a finish of a request that is
|
||||
// no longer accepted with LifecycleRequestMissing, and the request is read
|
||||
// again to tell that from a request that does not exist.
|
||||
func settledSince(ctx context.Context, database *sql.DB, r integration.LifecycleRequest, finishErr error) bool {
|
||||
// settledSince reports whether a finish failed because the group holds other
|
||||
// outcomes by now: finishAllWith refuses a finish of a request that is no
|
||||
// longer accepted with LifecycleRequestMissing, and each member is read again
|
||||
// to tell that from a request that does not exist. The group is settled when
|
||||
// every member reads back as not accepted; a missing or accepted member is
|
||||
// not, because lockOutcomes refuses a partly finished set and the finish
|
||||
// counts as errored.
|
||||
func settledSince(ctx context.Context, database *sql.DB, group []integration.LifecycleRequest, finishErr error) bool {
|
||||
if errorType(finishErr) != LifecycleRequestMissing {
|
||||
return false
|
||||
}
|
||||
row, err := integration.New(database).GetLifecycleRequestByAddress(ctx, integration.GetLifecycleRequestByAddressParams{
|
||||
InstanceID: r.InstanceID,
|
||||
Generation: r.Generation,
|
||||
})
|
||||
return err == nil && row.Status != integration.LifecycleAccepted
|
||||
q := integration.New(database)
|
||||
for _, r := range group {
|
||||
row, err := q.GetLifecycleRequestByAddress(ctx, integration.GetLifecycleRequestByAddressParams{
|
||||
InstanceID: r.InstanceID,
|
||||
Generation: r.Generation,
|
||||
})
|
||||
if err != nil || row.Status == integration.LifecycleAccepted {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
||||
// SPDX-FileCopyrightText: 2025-2026 Christian Galo
|
||||
|
||||
package workflows
|
||||
|
||||
// Fixtures for the boot settle's tests of an act's requests (design D16).
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
enumspb "go.temporal.io/api/enums/v1"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/integration"
|
||||
)
|
||||
|
||||
// ageRequests makes the requests of the instances old enough for settle.
|
||||
func (e *reqEnv) ageRequests(instances ...string) {
|
||||
e.t.Helper()
|
||||
for _, inst := range instances {
|
||||
e.exec(`UPDATE core.lifecycle_requests SET created_at = NOW() - INTERVAL '10 minutes' WHERE instance_id = $1`, inst)
|
||||
}
|
||||
}
|
||||
|
||||
// agedSwap records a swap and its act as the handler does and ages both
|
||||
// requests. It returns the sites, the two requests' addresses (the
|
||||
// activation's first) and the act's id.
|
||||
func (e *reqEnv) agedSwap(wf string) (swapSites, []LifecycleRequestRef, string) {
|
||||
e.t.Helper()
|
||||
s := e.swapSites()
|
||||
gen, parkGen, actID := e.swapRequests(s.activateID, s.parkID, wf)
|
||||
e.ageRequests(s.activateID, s.parkID)
|
||||
return s, []LifecycleRequestRef{{InstanceID: s.activateID, Generation: gen}, {InstanceID: s.parkID, Generation: parkGen}}, actID
|
||||
}
|
||||
|
||||
// wantSettledTogether requires both requests of a swap to hold the outcome and
|
||||
// to have been finished by one transaction, and the act's header to be kept.
|
||||
func (e *reqEnv) wantSettledTogether(refs []LifecycleRequestRef, actID, status, reason string) {
|
||||
e.t.Helper()
|
||||
for _, ref := range refs {
|
||||
if got, why := e.request(ref.InstanceID, ref.Generation); got != status || why != reason {
|
||||
e.t.Errorf("request %s = %s/%s, want %s/%s", ref.InstanceID, got, why, status, reason)
|
||||
}
|
||||
}
|
||||
var writers, headers int
|
||||
if err := e.db.QueryRowContext(e.ctx,
|
||||
`SELECT count(DISTINCT xmin::text) FROM core.lifecycle_requests WHERE act_id = $1`, actID).Scan(&writers); err != nil {
|
||||
e.t.Fatal(err)
|
||||
}
|
||||
if writers != 1 {
|
||||
e.t.Errorf("the act's requests were finished by %d transactions, want 1", writers)
|
||||
}
|
||||
if err := e.db.QueryRowContext(e.ctx, `SELECT count(*) FROM core.acts WHERE act_id = $1`, actID).Scan(&headers); err != nil {
|
||||
e.t.Fatal(err)
|
||||
}
|
||||
if headers != 1 {
|
||||
e.t.Errorf("act headers = %d, want the header kept", headers)
|
||||
}
|
||||
}
|
||||
|
||||
// settleSwap runs the boot pass over a swap whose workflow is in the given
|
||||
// state ("" for a workflow Temporal does not know).
|
||||
func (e *reqEnv) settleSwap(wf string, state enumspb.WorkflowExecutionStatus) (SettleCounts, *fakeLifecycleClient) {
|
||||
e.t.Helper()
|
||||
fake := &fakeLifecycleClient{status: map[string]enumspb.WorkflowExecutionStatus{}}
|
||||
if state != enumspb.WORKFLOW_EXECUTION_STATUS_UNSPECIFIED {
|
||||
fake.status[wf] = state
|
||||
}
|
||||
counts, err := SettleOpenRequests(e.ctx, fake, e.db, e.conn, "queue", time.Now(), e.acts.Logger)
|
||||
if err != nil {
|
||||
e.t.Fatal(err)
|
||||
}
|
||||
return counts, fake
|
||||
}
|
||||
|
||||
// settleActCases are the cases of TestSettleOpenRequests_DB that end an act's
|
||||
// requests, and the requests that carry no act next to them.
|
||||
func settleActCases(t *testing.T) {
|
||||
t.Run("a swap that never started ends both requests together and stamps nothing (F23)", func(t *testing.T) {
|
||||
e := newReqEnv(t, 3, 0)
|
||||
s, refs, actID := e.agedSwap("swap-notstarted")
|
||||
counts, _ := e.settleSwap("swap-notstarted", enumspb.WORKFLOW_EXECUTION_STATUS_UNSPECIFIED)
|
||||
if counts.Seen != 2 || counts.NotStarted != 2 || counts.FinishErrored != 0 {
|
||||
t.Errorf("counts = %+v", counts)
|
||||
}
|
||||
e.wantSettledTogether(refs, actID, "failed", ReasonNotStarted)
|
||||
e.wantNoStamp("after settle")
|
||||
e.wantSiteStatus(s.activate, "readonly")
|
||||
})
|
||||
t.Run("a swap closed without an outcome ends both requests together, applied or not (F24)", func(t *testing.T) {
|
||||
e := newReqEnv(t, 3, 0)
|
||||
s, refs, actID := e.agedSwap("swap-closed")
|
||||
e.farm.HoldIn(s.activate, e.subject, "active")
|
||||
e.farm.HoldIn(s.park, e.subject, "readonly")
|
||||
counts, fake := e.settleSwap("swap-closed", enumspb.WORKFLOW_EXECUTION_STATUS_FAILED)
|
||||
if counts.Exhausted != 2 || counts.Reconciling != 0 || counts.FinishErrored != 0 || len(fake.started) != 0 {
|
||||
t.Errorf("counts = %+v, starts = %+v", counts, fake.started)
|
||||
}
|
||||
e.wantSettledTogether(refs, actID, "failed", ReasonRetriesExhausted)
|
||||
e.wantNoStamp("after settle")
|
||||
e.wantSiteStatus(s.activate, "readonly")
|
||||
e.wantSiteStatus(s.park, "active")
|
||||
if reads := e.farmReads(); reads != 0 {
|
||||
t.Errorf("settle read the farm %d times", reads)
|
||||
}
|
||||
})
|
||||
t.Run("a swap whose workflow runs is left alone", func(t *testing.T) {
|
||||
e := newReqEnv(t, 3, 0)
|
||||
_, refs, _ := e.agedSwap("swap-running")
|
||||
counts, _ := e.settleSwap("swap-running", enumspb.WORKFLOW_EXECUTION_STATUS_RUNNING)
|
||||
if counts.Running != 2 {
|
||||
t.Errorf("counts = %+v", counts)
|
||||
}
|
||||
e.wantRequests(integration.LifecycleAccepted, refs...)
|
||||
})
|
||||
t.Run("a stored swap's two rows with no act each settle alone", func(t *testing.T) {
|
||||
e := newReqEnv(t, 3, 0)
|
||||
activate := e.insertSite("stored-reserve."+e.root, "readonly", true)
|
||||
park := e.insertSite("stored-incumbent."+e.root, "active", false)
|
||||
wf := "swap-fedwiki-site-stored"
|
||||
gen := e.record(activate, integration.LifecycleSetStatus, wf, map[string]any{"status": "active", "swap_park_site_id": park})
|
||||
parkGen := e.record(park, integration.LifecycleSetStatus, wf, map[string]any{"status": "readonly", "swap_activate_site_id": activate})
|
||||
e.ageRequests(activate, park)
|
||||
// The activation holds its slot, so it goes to the status reconcile;
|
||||
// the park holds none and ends failed.
|
||||
if gate, err := e.acts.HoldSiteSlotActivity(e.ctx, HoldSiteSlotInput{InstanceID: activate, Generation: gen, WorkspaceID: e.ws}); err != nil || !gate.Held {
|
||||
t.Fatalf("the activation's gate: %+v, %v", gate, err)
|
||||
}
|
||||
counts, fake := e.settleSwap(wf, enumspb.WORKFLOW_EXECUTION_STATUS_FAILED)
|
||||
if counts.Seen != 2 || counts.Reconciling != 1 || counts.Exhausted != 1 || len(fake.started) != 1 {
|
||||
t.Errorf("counts = %+v, starts = %+v", counts, fake.started)
|
||||
}
|
||||
e.wantRequests(integration.LifecycleAccepted, LifecycleRequestRef{InstanceID: activate, Generation: gen})
|
||||
if status, reason := e.request(park, parkGen); status != "failed" || reason != ReasonRetriesExhausted {
|
||||
t.Errorf("park = %s/%s", status, reason)
|
||||
}
|
||||
e.wantNoStamp("after settle")
|
||||
})
|
||||
t.Run("a return closed holding no slot ends failed and stamps nothing (F22)", func(t *testing.T) {
|
||||
e := newReqEnv(t, 3, 0)
|
||||
in := e.startActivation("returnunheld", "readonly")
|
||||
e.ageRequests(in.InstanceID)
|
||||
fake := &fakeLifecycleClient{status: map[string]enumspb.WorkflowExecutionStatus{"wf-" + in.InstanceID: enumspb.WORKFLOW_EXECUTION_STATUS_FAILED}}
|
||||
if _, err := SettleOpenRequests(e.ctx, fake, e.db, e.conn, "queue", time.Now(), e.acts.Logger); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if status, reason := e.request(in.InstanceID, in.Generation); status != "failed" || reason != ReasonRetriesExhausted {
|
||||
t.Errorf("request = %s/%s", status, reason)
|
||||
}
|
||||
if len(fake.started) != 0 {
|
||||
t.Errorf("starts = %+v, want none", fake.started)
|
||||
}
|
||||
e.wantNoStamp("after settle")
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
||||
// SPDX-FileCopyrightText: 2025-2026 Christian Galo
|
||||
|
||||
package workflows
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/integration"
|
||||
)
|
||||
|
||||
// TestActGroups checks the groups settle ends together (design D16): a
|
||||
// request with no act is a group of one, an act's requests are one group with
|
||||
// the asked request first and the consequent requests in listing order.
|
||||
func TestActGroups(t *testing.T) {
|
||||
actA, actB := uuid.New(), uuid.New()
|
||||
plain := func(id string) integration.LifecycleRequest { return integration.LifecycleRequest{RequestID: id} }
|
||||
member := func(id string, act uuid.UUID, role string) integration.LifecycleRequest {
|
||||
return integration.LifecycleRequest{
|
||||
RequestID: id,
|
||||
ActID: uuid.NullUUID{UUID: act, Valid: true},
|
||||
ActCause: sql.NullString{String: "instances_swapped", Valid: true},
|
||||
ActRole: sql.NullString{String: role, Valid: true},
|
||||
}
|
||||
}
|
||||
asked, consequent := integration.LifecycleActAsked, integration.LifecycleActConsequent
|
||||
cases := []struct {
|
||||
name string
|
||||
rows []integration.LifecycleRequest
|
||||
want [][]string
|
||||
}{
|
||||
{"an empty list", nil, nil},
|
||||
{
|
||||
"the asked request first in the listing",
|
||||
[]integration.LifecycleRequest{member("a1", actA, asked), member("a2", actA, consequent)},
|
||||
[][]string{{"a1", "a2"}},
|
||||
},
|
||||
{
|
||||
"the asked request second in the listing",
|
||||
[]integration.LifecycleRequest{member("a2", actA, consequent), member("a1", actA, asked)},
|
||||
[][]string{{"a1", "a2"}},
|
||||
},
|
||||
{
|
||||
"an act next to unrelated requests",
|
||||
[]integration.LifecycleRequest{plain("p1"), member("a2", actA, consequent), plain("p2"), member("a1", actA, asked), member("b1", actB, asked)},
|
||||
[][]string{{"p1"}, {"a1", "a2"}, {"p2"}, {"b1"}},
|
||||
},
|
||||
{
|
||||
"a stored swap's two rows are two groups",
|
||||
[]integration.LifecycleRequest{plain("s1"), plain("s2")},
|
||||
[][]string{{"s1"}, {"s2"}},
|
||||
},
|
||||
{
|
||||
"several consequent requests keep their listing order",
|
||||
[]integration.LifecycleRequest{member("c1", actA, consequent), member("c2", actA, consequent), member("a1", actA, asked)},
|
||||
[][]string{{"a1", "c1", "c2"}},
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var got [][]string
|
||||
for _, g := range actGroups(tc.rows) {
|
||||
ids := make([]string, len(g))
|
||||
for i, r := range g {
|
||||
ids[i] = r.RequestID
|
||||
}
|
||||
got = append(got, ids)
|
||||
}
|
||||
if !reflect.DeepEqual(got, tc.want) {
|
||||
t.Errorf("groups = %v, want %v", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,17 @@ func (e *reqEnv) heldActivation(label string) SetSiteStatusRequestInput {
|
||||
return in
|
||||
}
|
||||
|
||||
// wantAMarkedReturnWithNoStamp requires the fixture's return to carry the
|
||||
// downgrade mark and the workspace no stamp, so what a reconcile does to them
|
||||
// is its own: the reconcile's input carries no ClearForceReduced.
|
||||
func (e *reqEnv) wantAMarkedReturnWithNoStamp(in SetSiteStatusRequestInput) {
|
||||
e.t.Helper()
|
||||
if _, marked := siteState(e.t, e.db, in.Domain); !marked {
|
||||
e.t.Fatal("the fixture's return is not marked")
|
||||
}
|
||||
e.wantNoStamp("before the reconcile")
|
||||
}
|
||||
|
||||
func reconcileInput(e *reqEnv, in SetSiteStatusRequestInput) ReconcileSiteStatusInput {
|
||||
return ReconcileSiteStatusInput{ConnectionID: e.conn, InstanceID: in.InstanceID, Generation: in.Generation}
|
||||
}
|
||||
@@ -82,7 +93,10 @@ func TestSettleHandsAClosedActivationToTheStatusReconcile_DB(t *testing.T) {
|
||||
if rows := e.wantFigure("after settle"); rows != 1 {
|
||||
t.Errorf("rows and holds = %d, want the slot the hold keeps", rows)
|
||||
}
|
||||
e.wantNoStamp("after settle, which never stamps")
|
||||
})
|
||||
t.Run("a return holding its slot: the reconcile settle starts records it and stamps (F21)", settleHeldReturnStamps)
|
||||
t.Run("a return holding its slot that the farm does not hold active fails, loses its hold and stamps nothing (F21)", settleHeldReturnFails)
|
||||
t.Run("no slot held: the request ends failed", func(t *testing.T) {
|
||||
e := newReqEnv(t, 3, 0)
|
||||
in := e.startActivation("settleunheld", "readonly")
|
||||
@@ -119,6 +133,63 @@ func TestSettleHandsAClosedActivationToTheStatusReconcile_DB(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
// settledReturn records a return that holds its slot, ages it, runs the boot
|
||||
// pass over its closed workflow and returns the reconcile input the pass
|
||||
// handed on.
|
||||
func settledReturn(t *testing.T, label string) (*reqEnv, SetSiteStatusRequestInput, ReconcileSiteStatusInput) {
|
||||
t.Helper()
|
||||
e := newReqEnv(t, 3, 0)
|
||||
in := e.heldActivation(label)
|
||||
e.ageRequests(in.InstanceID)
|
||||
fake := &runningByDefaultClient{fakeLifecycleClient{status: map[string]enumspb.WorkflowExecutionStatus{
|
||||
"wf-" + in.InstanceID: enumspb.WORKFLOW_EXECUTION_STATUS_FAILED,
|
||||
}}}
|
||||
if _, err := SettleOpenRequests(e.ctx, fake, e.db, e.conn, "queue", time.Now(), e.acts.Logger); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
started, ok := fake.inputs[0].(ReconcileSiteStatusInput)
|
||||
if len(fake.inputs) != 1 || !ok {
|
||||
t.Fatalf("inputs = %#v", fake.inputs)
|
||||
}
|
||||
return e, in, started
|
||||
}
|
||||
|
||||
// The reconcile that settle starts for a return whose farm holds the site
|
||||
// active records the success, clears the mark from the locked row although
|
||||
// its input carries no ClearForceReduced, and stamps.
|
||||
func settleHeldReturnStamps(t *testing.T) {
|
||||
e, in, started := settledReturn(t, "settlereturn")
|
||||
e.wantNoStamp("before the reconcile runs")
|
||||
e.farm.HoldIn(in.Domain, e.subject, "active")
|
||||
env := e.testEnv()
|
||||
env.ExecuteWorkflow(ReconcileFedWikiSiteStatusWorkflow, started)
|
||||
e.wantOutput(runOutput(t, env), "succeeded", "")
|
||||
if status, marked := siteState(t, e.db, in.Domain); status != "active" || marked {
|
||||
t.Errorf("site = %s, marked %v, want active with the mark cleared", status, marked)
|
||||
}
|
||||
if e.holds(in.InstanceID, in.Generation) {
|
||||
t.Error("the request still holds its slot")
|
||||
}
|
||||
e.wantStamp("after the reconcile")
|
||||
}
|
||||
|
||||
// The reconcile for a return the farm does not hold active fails the request,
|
||||
// removes the hold and stamps nothing.
|
||||
func settleHeldReturnFails(t *testing.T) {
|
||||
e, in, started := settledReturn(t, "settlereturnfailed")
|
||||
e.farm.HoldIn(in.Domain, e.subject, "readonly")
|
||||
env := e.testEnv()
|
||||
env.ExecuteWorkflow(ReconcileFedWikiSiteStatusWorkflow, started)
|
||||
e.wantOutput(runOutput(t, env), "failed", ReasonRetriesExhausted)
|
||||
if e.holds(in.InstanceID, in.Generation) {
|
||||
t.Error("the hold of a failed return stayed")
|
||||
}
|
||||
if status, marked := siteState(t, e.db, in.Domain); status != "readonly" || !marked {
|
||||
t.Errorf("site = %s, marked %v, want it parked as before", status, marked)
|
||||
}
|
||||
e.wantNoStamp("after a failed return")
|
||||
}
|
||||
|
||||
// Each row of design D9's status reconcile table that ends the request.
|
||||
func TestStatusReconcile_DB(t *testing.T) {
|
||||
cases := []struct {
|
||||
@@ -157,6 +228,7 @@ func TestStatusReconcile_DB(t *testing.T) {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
e := newReqEnv(t, 3, 0)
|
||||
in := e.heldActivation("reconcile" + string(rune('a'+i)))
|
||||
e.wantAMarkedReturnWithNoStamp(in)
|
||||
tc.setup(e, in)
|
||||
env := e.testEnv()
|
||||
env.ExecuteWorkflow(ReconcileFedWikiSiteStatusWorkflow, reconcileInput(e, in))
|
||||
@@ -180,6 +252,9 @@ func TestStatusReconcile_DB(t *testing.T) {
|
||||
if rows := e.wantFigure("after the reconcile"); rows != wantRows {
|
||||
t.Errorf("rows and holds = %d, want %d", rows, wantRows)
|
||||
}
|
||||
if _, stamped := e.stamp(); stamped != (tc.status == "succeeded") {
|
||||
t.Errorf("stamped = %v after a reconcile that ended %s", stamped, tc.status)
|
||||
}
|
||||
if reads := e.farmReads(); reads != tc.reads {
|
||||
t.Errorf("farm reads = %d, want %d", reads, tc.reads)
|
||||
}
|
||||
@@ -340,6 +415,147 @@ func TestSettleOfARequestSettledSinceTheListingIsNotAnError_DB(t *testing.T) {
|
||||
e.wantRequests(integration.LifecycleSucceeded, LifecycleRequestRef{InstanceID: in.InstanceID, Generation: in.Generation})
|
||||
e.wantSiteStatus(in.Domain, "active")
|
||||
e.wantFigure("after settle")
|
||||
t.Run("a swap group a concurrent outcome finished (F25)", settleSwapGroupSettledSince)
|
||||
t.Run("a hand edit that finished one request of an act before the listing (F26)", settleActWithOneFinishedBeforeTheListing)
|
||||
t.Run("a hand edit that finished one request of an act after the listing (F26)", settleActWithOneFinishedAfterTheListing)
|
||||
}
|
||||
|
||||
// handEdit finishes one request of an act as an operator's statement would,
|
||||
// with an outcome settle does not write.
|
||||
func (e *reqEnv) handEdit(ref LifecycleRequestRef) {
|
||||
e.exec(`UPDATE core.lifecycle_requests SET status = 'declined', reason_code = $3, finished_at = NOW()
|
||||
WHERE instance_id = $1 AND generation = $2`, ref.InstanceID, ref.Generation, ReasonSiteMissing)
|
||||
}
|
||||
|
||||
// A swap whose requests a concurrent outcome finished between the listing and
|
||||
// settle's finish is settled: an Info line, no Error line, no counted failure.
|
||||
func settleSwapGroupSettledSince(t *testing.T) {
|
||||
e := newReqEnv(t, 3, 0)
|
||||
s, refs, _ := e.agedSwap("swap-settledsince")
|
||||
fake := &settlingClient{
|
||||
runningByDefaultClient: runningByDefaultClient{fakeLifecycleClient{
|
||||
status: map[string]enumspb.WorkflowExecutionStatus{"swap-settledsince": enumspb.WORKFLOW_EXECUTION_STATUS_FAILED},
|
||||
}},
|
||||
settle: func() {
|
||||
if err := e.acts.RecordSwapActivity(e.ctx, RecordSwapInput{
|
||||
Activate: refs[0], Park: refs[1], WorkspaceID: e.ws,
|
||||
ActivateDomain: s.activate, ParkDomain: s.park, FinishedAt: time.Now(),
|
||||
}); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
},
|
||||
}
|
||||
var logs bytes.Buffer
|
||||
logger := slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug}))
|
||||
counts, err := SettleOpenRequests(e.ctx, fake, e.db, e.conn, "queue", time.Now(), logger)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if counts.FinishErrored != 0 || counts.Unanswered != 0 || counts.Seen != 2 {
|
||||
t.Errorf("counts = %+v", counts)
|
||||
}
|
||||
if strings.Contains(logs.String(), "level=ERROR") || !strings.Contains(logs.String(), "already settled") {
|
||||
t.Errorf("log = %s, want an Info line and no Error line", logs.String())
|
||||
}
|
||||
e.wantRequests(integration.LifecycleSucceeded, refs...)
|
||||
e.wantSiteStatus(s.activate, "active")
|
||||
}
|
||||
|
||||
// A request finished by hand before the listing leaves its act's other
|
||||
// request alone in the listing: settle ends that one by its workflow's state,
|
||||
// so the two end differently.
|
||||
func settleActWithOneFinishedBeforeTheListing(t *testing.T) {
|
||||
e := newReqEnv(t, 3, 0)
|
||||
_, refs, _ := e.agedSwap("swap-handbefore")
|
||||
e.handEdit(refs[1])
|
||||
counts, _ := e.settleSwap("swap-handbefore", enumspb.WORKFLOW_EXECUTION_STATUS_FAILED)
|
||||
if counts.Seen != 1 || counts.Exhausted != 1 || counts.FinishErrored != 0 {
|
||||
t.Errorf("counts = %+v", counts)
|
||||
}
|
||||
if status, reason := e.request(refs[0].InstanceID, refs[0].Generation); status != "failed" || reason != ReasonRetriesExhausted {
|
||||
t.Errorf("activation = %s/%s", status, reason)
|
||||
}
|
||||
if status, reason := e.request(refs[1].InstanceID, refs[1].Generation); status != "declined" || reason != ReasonSiteMissing {
|
||||
t.Errorf("park = %s/%s, want the hand edit kept", status, reason)
|
||||
}
|
||||
}
|
||||
|
||||
// A request finished by hand, or removed, after the listing makes lockOutcomes
|
||||
// refuse the partly finished set: settle counts the failures and changes
|
||||
// nothing, whichever member of the act the change touched.
|
||||
func settleActWithOneFinishedAfterTheListing(t *testing.T) {
|
||||
handEditRequest := func(e *reqEnv, ref LifecycleRequestRef) { e.handEdit(ref) }
|
||||
deleteRequest := func(e *reqEnv, ref LifecycleRequestRef) {
|
||||
e.exec(`DELETE FROM core.lifecycle_requests WHERE instance_id = $1 AND generation = $2`, ref.InstanceID, ref.Generation)
|
||||
}
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
member int
|
||||
kept bool
|
||||
change func(*reqEnv, LifecycleRequestRef)
|
||||
}{
|
||||
{"consequent hand edit", 1, true, handEditRequest},
|
||||
{"asked hand edit", 0, true, handEditRequest},
|
||||
{"consequent missing", 1, false, deleteRequest},
|
||||
{"asked missing", 0, false, deleteRequest},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) { settleActAfterMemberChanged(t, c.member, c.kept, c.change) })
|
||||
}
|
||||
t.Run("one missing and the other finished", settleActWithOneMissingAndOneFinished)
|
||||
}
|
||||
|
||||
// A member that is gone is not settled: with the other member finished by
|
||||
// hand, nothing in the group is accepted, and only the missing row tells the
|
||||
// finish's failure from a group that other outcomes settled.
|
||||
func settleActWithOneMissingAndOneFinished(t *testing.T) {
|
||||
e := newReqEnv(t, 3, 0)
|
||||
_, refs, _ := e.agedSwap("swap-gone")
|
||||
fake := &settlingClient{
|
||||
runningByDefaultClient: runningByDefaultClient{fakeLifecycleClient{
|
||||
status: map[string]enumspb.WorkflowExecutionStatus{"swap-gone": enumspb.WORKFLOW_EXECUTION_STATUS_FAILED},
|
||||
}},
|
||||
settle: func() {
|
||||
e.exec(`DELETE FROM core.lifecycle_requests WHERE instance_id = $1 AND generation = $2`, refs[0].InstanceID, refs[0].Generation)
|
||||
e.handEdit(refs[1])
|
||||
},
|
||||
}
|
||||
counts, err := SettleOpenRequests(e.ctx, fake, e.db, e.conn, "queue", time.Now(), e.acts.Logger)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if counts.Seen != 2 || counts.FinishErrored != 2 {
|
||||
t.Errorf("counts = %+v", counts)
|
||||
}
|
||||
if status, reason := e.request(refs[1].InstanceID, refs[1].Generation); status != "declined" || reason != ReasonSiteMissing {
|
||||
t.Errorf("park = %s/%s, want the hand edit kept", status, reason)
|
||||
}
|
||||
}
|
||||
|
||||
func settleActAfterMemberChanged(t *testing.T, member int, kept bool, change func(*reqEnv, LifecycleRequestRef)) {
|
||||
e := newReqEnv(t, 3, 0)
|
||||
s, refs, _ := e.agedSwap("swap-handafter")
|
||||
changed, other := refs[member], refs[1-member]
|
||||
fake := &settlingClient{
|
||||
runningByDefaultClient: runningByDefaultClient{fakeLifecycleClient{
|
||||
status: map[string]enumspb.WorkflowExecutionStatus{"swap-handafter": enumspb.WORKFLOW_EXECUTION_STATUS_FAILED},
|
||||
}},
|
||||
settle: func() { change(e, changed) },
|
||||
}
|
||||
counts, err := SettleOpenRequests(e.ctx, fake, e.db, e.conn, "queue", time.Now(), e.acts.Logger)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if counts.Seen != 2 || counts.FinishErrored != 2 || counts.Exhausted != 2 {
|
||||
t.Errorf("counts = %+v", counts)
|
||||
}
|
||||
e.wantRequests(integration.LifecycleAccepted, other)
|
||||
if kept {
|
||||
if status, reason := e.request(changed.InstanceID, changed.Generation); status != "declined" || reason != ReasonSiteMissing {
|
||||
t.Errorf("changed request = %s/%s, want the hand edit kept", status, reason)
|
||||
}
|
||||
}
|
||||
e.wantSiteStatus(s.activate, "readonly")
|
||||
e.wantNoStamp("after settle")
|
||||
}
|
||||
|
||||
// A database that fails the reconcile's read of its request a few times
|
||||
|
||||
@@ -145,8 +145,9 @@ type RecordSwapInput struct {
|
||||
|
||||
// RecordSwapActivity writes both sites' statuses, the parked site's
|
||||
// downgrade-parked mark and the cleared mark of the activated one, and
|
||||
// finishes both requests as succeeded, in one transaction: a retry after a
|
||||
// lost answer finds both requests finished and writes nothing again
|
||||
// finishes both requests as succeeded, in one transaction. When the activated
|
||||
// row it locked was not active, the transaction also stamps the workspace's
|
||||
// swap policy, after the site rows and before the usage row (design D15). A retry after a lost answer finds both requests finished and writes nothing again
|
||||
// (fedwiki-sites: a status change writes its status, usage and outcome
|
||||
// together). finishAllWith recounts the pool after the two rows are written.
|
||||
//
|
||||
@@ -198,6 +199,14 @@ func (a *Activities) RecordSwapActivity(ctx context.Context, in RecordSwapInput)
|
||||
if err := q.ClearForceReducedByID(ctx, in.Activate.InstanceID); err != nil {
|
||||
return fmt.Errorf("swap: clear the parked mark of %s: %w", in.ActivateDomain, err)
|
||||
}
|
||||
// The member's action brought the chosen site into the active set
|
||||
// unless the re-upgrade sweep did it during the farm calls; only the
|
||||
// first starts the cooldown.
|
||||
if activated.Status != "active" {
|
||||
if err := q.UpsertSiteSwapPolicy(ctx, in.WorkspaceID); err != nil {
|
||||
return fmt.Errorf("swap: stamp the rotation of workspace %s: %w", in.WorkspaceID, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
guard := func(tx *sql.Tx, counted recounted) error {
|
||||
|
||||
@@ -7,16 +7,34 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/acts"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/integration"
|
||||
)
|
||||
|
||||
// swapRequests records a Keep active swap's two requests as the handler
|
||||
// does, the activation first.
|
||||
func (e *reqEnv) swapRequests(activateID, parkID, wf string) (gen, parkGen int64) {
|
||||
// swapRequests records a Keep active swap as the handler does: the
|
||||
// activation, which names the person, then the park, which names none, then
|
||||
// their act, all in one transaction. It returns the two generations and the
|
||||
// act's id.
|
||||
func (e *reqEnv) swapRequests(activateID, parkID, wf string) (gen, parkGen int64, actID string) {
|
||||
e.t.Helper()
|
||||
gen = e.record(activateID, integration.LifecycleSetStatus, wf, map[string]any{"status": "active", "swap_park_site_id": parkID})
|
||||
parkGen = e.record(parkID, integration.LifecycleSetStatus, wf, map[string]any{"status": "readonly", "swap_activate_site_id": activateID})
|
||||
return gen, parkGen
|
||||
tx, err := e.db.BeginTx(e.ctx, nil)
|
||||
if err != nil {
|
||||
e.t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
gen, asked := e.recordAs(tx, activateID, integration.LifecycleSetStatus, wf, e.person, map[string]any{"status": "active"})
|
||||
parkGen, consequent := e.recordAs(tx, parkID, integration.LifecycleSetStatus, wf, "", map[string]any{"status": "readonly"})
|
||||
actID, err = integration.RecordLifecycleAct(e.ctx, tx, integration.LifecycleAct{
|
||||
Cause: acts.InstancesSwapped, ActorPersonID: e.person, Asked: asked, Consequent: []string{consequent},
|
||||
})
|
||||
if err != nil {
|
||||
e.t.Fatal(err)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
e.t.Fatal(err)
|
||||
}
|
||||
e.actIDs = append(e.actIDs, actID)
|
||||
return gen, parkGen, actID
|
||||
}
|
||||
|
||||
func (e *reqEnv) runSwap(activateID, parkID string, gen, parkGen int64, activate, park string) LifecycleWorkflowOutput {
|
||||
@@ -45,7 +63,7 @@ func (e *reqEnv) swapSites() swapSites {
|
||||
// activation's first.
|
||||
func (e *reqEnv) swap(s swapSites, wf string) (LifecycleWorkflowOutput, []LifecycleRequestRef) {
|
||||
e.t.Helper()
|
||||
gen, parkGen := e.swapRequests(s.activateID, s.parkID, wf)
|
||||
gen, parkGen, _ := e.swapRequests(s.activateID, s.parkID, wf)
|
||||
out := e.runSwap(s.activateID, s.parkID, gen, parkGen, s.activate, s.park)
|
||||
return out, []LifecycleRequestRef{{InstanceID: s.activateID, Generation: gen}, {InstanceID: s.parkID, Generation: parkGen}}
|
||||
}
|
||||
@@ -102,7 +120,7 @@ func sweepParksTheSwapsSiteInASharedPool(t *testing.T) {
|
||||
// Keep active at the limit records the swap while the sweep's park of
|
||||
// the same site is at the farm.
|
||||
e.farm.OnFirst(park, "readonly", func() {
|
||||
gen, parkGen = e.swapRequests(activateID, parkID, "swap-sweep-park")
|
||||
gen, parkGen, _ = e.swapRequests(activateID, parkID, "swap-sweep-park")
|
||||
})
|
||||
if out, err := e.acts.ReconcileFedWikiQuotaActivity(e.ctx, ReconcileFedWikiQuotaInput{WorkspaceID: e.ws}); err != nil || out.Parked != 1 {
|
||||
t.Fatalf("sweep = %+v, %v; want one park", out, err)
|
||||
@@ -118,6 +136,7 @@ func sweepParksTheSwapsSiteInASharedPool(t *testing.T) {
|
||||
t.Errorf("the farm's last status for the site the swap activated = %q, want readonly", last)
|
||||
}
|
||||
e.assertCounterMatchesRows("after the sweep's park and the swap")
|
||||
e.wantNoStamp("after a swap refused with QuotaExceeded")
|
||||
|
||||
if _, err := e.acts.ReconcileFedWikiQuotaActivity(e.ctx, ReconcileFedWikiQuotaInput{WorkspaceID: e.ws}); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -137,7 +156,7 @@ func sweepParksTheSwapsSiteAtALimitOfOne(t *testing.T) {
|
||||
governFedwikiLimit(t, e.db, e.ws, "force_reduce")
|
||||
var gen, parkGen int64
|
||||
e.farm.OnFirst(domains[0], "readonly", func() {
|
||||
gen, parkGen = e.swapRequests(activateID, ids[0], "swap-sweep-park-1")
|
||||
gen, parkGen, _ = e.swapRequests(activateID, ids[0], "swap-sweep-park-1")
|
||||
})
|
||||
if _, err := e.acts.ReconcileFedWikiQuotaActivity(e.ctx, ReconcileFedWikiQuotaInput{WorkspaceID: e.ws}); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -159,7 +178,7 @@ func sweepReactivatesTheSwapsSite(t *testing.T) {
|
||||
s := e.swapSites()
|
||||
var gen, parkGen int64
|
||||
e.farm.OnFirst(s.activate, "active", func() {
|
||||
gen, parkGen = e.swapRequests(s.activateID, s.parkID, "swap-sweep-reactivate")
|
||||
gen, parkGen, _ = e.swapRequests(s.activateID, s.parkID, "swap-sweep-reactivate")
|
||||
})
|
||||
if out, err := e.acts.ReconcileFedWikiQuotaActivity(e.ctx, ReconcileFedWikiQuotaInput{WorkspaceID: e.ws}); err != nil || out.Reactivated != 1 {
|
||||
t.Fatalf("sweep = %+v, %v; want one reactivation", out, err)
|
||||
@@ -171,12 +190,13 @@ func sweepReactivatesTheSwapsSite(t *testing.T) {
|
||||
t.Errorf("console park=%s activate=%s", p, a)
|
||||
}
|
||||
e.assertCounterMatchesRows("after the sweep's reactivation and the swap")
|
||||
e.wantNoStamp("when the sweep brought the chosen site back during the farm calls")
|
||||
}
|
||||
|
||||
func leftActiveSiteFreesASlot(t *testing.T) {
|
||||
e := newReqEnv(t, 2, 1)
|
||||
s := e.swapSites()
|
||||
gen, parkGen := e.swapRequests(s.activateID, s.parkID, "swap-free-slot")
|
||||
gen, parkGen, _ := e.swapRequests(s.activateID, s.parkID, "swap-free-slot")
|
||||
// Something outside the request took the parked site out of active, and
|
||||
// the figure still reads the slot it held until the swap recounts.
|
||||
e.exec(`UPDATE fedwiki.sites SET status = 'readonly' WHERE site_id = $1`, s.parkID)
|
||||
@@ -198,6 +218,23 @@ func TestSyncLeavesSitesWithOpenRequests_DB(t *testing.T) {
|
||||
t.Run("a sync during a failed swap leaves the restore the statuses before it", syncDuringAFailedSwap)
|
||||
t.Run("a sync during a successful swap", syncDuringASuccessfulSwap)
|
||||
t.Run("a sync during a plain activation", syncDuringAPlainActivation)
|
||||
for _, reported := range []string{"archived", "active"} {
|
||||
t.Run("a sync reporting a pending return's site "+reported, func(t *testing.T) { syncDuringAReturn(t, reported) })
|
||||
}
|
||||
}
|
||||
|
||||
// The mark of a pending return's site survives a sync that finds the farm
|
||||
// reporting the site archived or active: the sync skips a domain with an
|
||||
// accepted request and checks again under the row's lock. The return's
|
||||
// success clears the mark.
|
||||
func syncDuringAReturn(t *testing.T, reported string) {
|
||||
e := newReqEnv(t, 3, 0)
|
||||
in := e.startActivation("return-"+reported, "readonly")
|
||||
stub := siblingWorkspace(t, e.db, e.ws, 0, "stub")
|
||||
e.syncDuring(stub, SiteInfo{Name: in.Domain, Status: reported})
|
||||
e.wantSite(in.Domain, "readonly", true)
|
||||
e.wantOutput(e.runStatus(gateVersions[0], in), "succeeded", "")
|
||||
e.wantSite(in.Domain, "active", false)
|
||||
}
|
||||
|
||||
// syncDuring runs the sync, as the schedule would, against a farm listing
|
||||
@@ -218,7 +255,7 @@ func syncBetweenTheSwapsFarmCallsAndRecord(t *testing.T) {
|
||||
activateID := e.insertSite(activate, "readonly", true)
|
||||
siblingWorkspace(t, e.db, e.ws, 1, "sib")
|
||||
stub := siblingWorkspace(t, e.db, e.ws, 0, "stub")
|
||||
gen, parkGen := e.swapRequests(activateID, parkID, "swap-sync")
|
||||
gen, parkGen, _ := e.swapRequests(activateID, parkID, "swap-sync")
|
||||
in := SwapActiveSiteInput{WorkspaceID: e.ws, ParkSiteID: parkID, ActivateSiteID: activateID, ParkDomain: park, ActivateDomain: activate}
|
||||
if err := e.acts.SwapFarmSitesActivity(e.ctx, in); err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -19,7 +19,7 @@ import (
|
||||
// identitySwap records both requests and returns their unchanged workflow input.
|
||||
func identitySwap(env *reqEnv, sites swapSites) SwapSiteRequestInput {
|
||||
env.t.Helper()
|
||||
generation, parkGeneration := env.swapRequests(sites.activateID, sites.parkID, "identity-swap")
|
||||
generation, parkGeneration, _ := env.swapRequests(sites.activateID, sites.parkID, "identity-swap")
|
||||
return SwapSiteRequestInput{ConnectionID: env.conn, InstanceID: sites.activateID, Generation: generation,
|
||||
ParkInstanceID: sites.parkID, ParkGeneration: parkGeneration, WorkspaceID: env.ws,
|
||||
ActivateDomain: sites.activate, ParkDomain: sites.park}
|
||||
@@ -151,6 +151,7 @@ func checkSwapIdentity(t *testing.T, row swapIdentityCase) {
|
||||
if figure != count || env.holds(in.InstanceID, in.Generation) || env.holds(in.ParkInstanceID, in.ParkGeneration) {
|
||||
t.Errorf("%s: swap left wrong usage or holds", row.name)
|
||||
}
|
||||
env.wantNoStamp(row.name + ": a record refused with " + row.wantReason)
|
||||
}
|
||||
|
||||
// checkMissingRestoration checks retry duration and every PATCH addressed to either original.
|
||||
|
||||
@@ -5,6 +5,8 @@ package workflows
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -13,6 +15,37 @@ import (
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/testkit/dbtest"
|
||||
)
|
||||
|
||||
// stamp reads the workspace's cooldown stamp: the time the last rotation
|
||||
// that succeeded committed, and whether there is one.
|
||||
func (e *reqEnv) stamp() (time.Time, bool) {
|
||||
e.t.Helper()
|
||||
var at time.Time
|
||||
err := e.db.QueryRowContext(e.ctx, `SELECT last_swap_at FROM fedwiki.site_swap_policy WHERE workspace_id = $1`, e.ws).Scan(&at)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return time.Time{}, false
|
||||
}
|
||||
if err != nil {
|
||||
e.t.Fatal(err)
|
||||
}
|
||||
return at, true
|
||||
}
|
||||
|
||||
func (e *reqEnv) wantNoStamp(when string) {
|
||||
e.t.Helper()
|
||||
if at, ok := e.stamp(); ok {
|
||||
e.t.Errorf("%s: the workspace carries a stamp at %v, want none", when, at)
|
||||
}
|
||||
}
|
||||
|
||||
func (e *reqEnv) wantStamp(when string) time.Time {
|
||||
e.t.Helper()
|
||||
at, ok := e.stamp()
|
||||
if !ok {
|
||||
e.t.Errorf("%s: the workspace carries no stamp, want one", when)
|
||||
}
|
||||
return at
|
||||
}
|
||||
|
||||
// RecordSwapActivity's outcomes commit with its statuses, not before them:
|
||||
// with the activated site's row held, the activity waits on that site's
|
||||
// status write while both requests still read accepted from another
|
||||
@@ -27,7 +60,7 @@ func TestRecordSwapCommitsItsOutcomesWithItsStatuses_DB(t *testing.T) {
|
||||
activate := "reserve." + e.root
|
||||
parkID := e.insertSite(park, "active", false)
|
||||
activateID := e.insertSite(activate, "readonly", true)
|
||||
gen, parkGen := e.swapRequests(activateID, parkID, "swap-tx-out")
|
||||
gen, parkGen, _ := e.swapRequests(activateID, parkID, "swap-tx-out")
|
||||
|
||||
ctx, cancel := context.WithTimeout(e.ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
@@ -65,6 +98,7 @@ func TestRecordSwapCommitsItsOutcomesWithItsStatuses_DB(t *testing.T) {
|
||||
t.Errorf("request on %s = %s while the swap's status write waits, want accepted until the statuses commit with it", ref.InstanceID, status)
|
||||
}
|
||||
}
|
||||
e.wantNoStamp("while the swap's status write waits")
|
||||
|
||||
if err := holder.Rollback(); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -80,4 +114,82 @@ func TestRecordSwapCommitsItsOutcomesWithItsStatuses_DB(t *testing.T) {
|
||||
if status, fr := siteState(t, e.db, activate); status != "active" || fr {
|
||||
t.Errorf("activated site = %s, force-reduced %v", status, fr)
|
||||
}
|
||||
e.wantStamp("in the commit that finished the swap")
|
||||
}
|
||||
|
||||
// A lost answer retried after the commit finds both requests finished and
|
||||
// writes no second stamp: the stamp keeps the first commit's time.
|
||||
func TestRetriedSwapRecordKeepsTheFirstStamp_DB(t *testing.T) {
|
||||
e := newReqEnv(t, 1, 1)
|
||||
s := e.swapSites()
|
||||
gen, parkGen, _ := e.swapRequests(s.activateID, s.parkID, "swap-stamp-retry")
|
||||
in := RecordSwapInput{WorkspaceID: e.ws,
|
||||
Activate: LifecycleRequestRef{InstanceID: s.activateID, Generation: gen},
|
||||
Park: LifecycleRequestRef{InstanceID: s.parkID, Generation: parkGen},
|
||||
ActivateDomain: s.activate, ParkDomain: s.park, FinishedAt: time.Now()}
|
||||
if err := e.acts.RecordSwapActivity(e.ctx, in); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first := e.wantStamp("after the first record")
|
||||
e.exec(`UPDATE fedwiki.sites SET status = 'readonly' WHERE site_id = $1`, s.activateID)
|
||||
if err := e.acts.RecordSwapActivity(e.ctx, in); err != nil {
|
||||
t.Fatalf("retried record: %v", err)
|
||||
}
|
||||
if again, _ := e.stamp(); !again.Equal(first) {
|
||||
t.Errorf("stamp after the retry = %v, want the first commit's %v", again, first)
|
||||
}
|
||||
if e.siteStatus(s.activateID) != "readonly" {
|
||||
t.Error("the retry wrote the site rows again")
|
||||
}
|
||||
}
|
||||
|
||||
// A rotation the previous release recorded has no act: one shared
|
||||
// swap-fedwiki-site- workflow id, the two keys, and a park request that names
|
||||
// the member. It finishes from the workflow's recorded input on the new code
|
||||
// and stamps (design D17, F27).
|
||||
func TestARotationOfThePreviousReleaseStampsOnSuccess_DB(t *testing.T) {
|
||||
e := newReqEnv(t, 1, 1)
|
||||
s := e.swapSites()
|
||||
wf := swapRequestWorkflowPrefix + "previous-release-" + e.root
|
||||
gen := e.record(s.activateID, integration.LifecycleSetStatus, wf, map[string]any{"status": "active", "swap_park_site_id": s.parkID})
|
||||
parkGen := e.record(s.parkID, integration.LifecycleSetStatus, wf, map[string]any{"status": "readonly", "swap_activate_site_id": s.activateID})
|
||||
e.wantNoStamp("before the rotation finishes")
|
||||
|
||||
out := e.runSwap(s.activateID, s.parkID, gen, parkGen, s.activate, s.park)
|
||||
if out.Status != integration.LifecycleSucceeded {
|
||||
t.Fatalf("swap = %+v, want succeeded", out)
|
||||
}
|
||||
e.wantRequests(integration.LifecycleSucceeded,
|
||||
LifecycleRequestRef{InstanceID: s.activateID, Generation: gen},
|
||||
LifecycleRequestRef{InstanceID: s.parkID, Generation: parkGen})
|
||||
e.wantSite(s.activate, "active", false)
|
||||
e.wantSite(s.park, "readonly", true)
|
||||
e.wantStamp("after a rotation of the previous release succeeded")
|
||||
}
|
||||
|
||||
// The stamp follows the row the swap locked, not the mark: the farm sync can
|
||||
// write read-only onto a row that never carried one (design D8, D14).
|
||||
func TestASwapOfAnUnmarkedReadOnlySiteStamps_DB(t *testing.T) {
|
||||
e := newReqEnv(t, 1, 1)
|
||||
s := swapSites{park: "incumbent." + e.root, activate: "reserve." + e.root}
|
||||
s.parkID = e.insertSite(s.park, "active", false)
|
||||
s.activateID = e.insertSite(s.activate, "readonly", false)
|
||||
e.wantNoStamp("before the swap")
|
||||
|
||||
out, refs := e.swap(s, "swap-unmarked")
|
||||
if out.Status != integration.LifecycleSucceeded {
|
||||
t.Fatalf("swap = %+v, want succeeded", out)
|
||||
}
|
||||
e.wantRequests(integration.LifecycleSucceeded, refs...)
|
||||
e.wantStamp("after a swap of a site with no mark")
|
||||
}
|
||||
|
||||
// A return the previous release recorded is the same set_status request the
|
||||
// new code records, with no stamp before it runs; the cooldown is off.
|
||||
func TestAReturnOfThePreviousReleaseStampsOnSuccess_DB(t *testing.T) {
|
||||
e := newReqEnv(t, 3, 0)
|
||||
in := e.startActivation("previous-return", "readonly")
|
||||
e.wantNoStamp("before the return")
|
||||
e.wantOutput(e.runStatus(gateVersions[0], in), "succeeded", "")
|
||||
e.wantStamp("after a return of the previous release")
|
||||
}
|
||||
|
||||
@@ -121,3 +121,39 @@ func restoreOutlastsTheForwardAttempts(t *testing.T) {
|
||||
last, e.farm.Attempts(s.park, "active"))
|
||||
}
|
||||
}
|
||||
|
||||
// A swap whose farm call raises SiteMissing for the parked site, an
|
||||
// authorization error or another farm error ends without a success, so its
|
||||
// record step never runs and no stamp is written.
|
||||
func TestFailedFarmCallsOfASwapStampNothing_DB(t *testing.T) {
|
||||
for _, row := range []struct {
|
||||
name string
|
||||
parked bool
|
||||
answer int
|
||||
}{
|
||||
{"the farm holds no parked site", true, http.StatusNotFound},
|
||||
{"the farm refuses the parked site", true, http.StatusForbidden},
|
||||
{"the farm refuses the activated site", false, http.StatusForbidden},
|
||||
{"the farm cannot take the activated site", false, http.StatusServiceUnavailable},
|
||||
} {
|
||||
t.Run(row.name, func(t *testing.T) {
|
||||
e := newReqEnv(t, 1, 1)
|
||||
s := e.swapSites()
|
||||
if row.parked {
|
||||
e.farm.Refuse(s.park, "readonly").With(row.answer)
|
||||
} else {
|
||||
e.farm.Refuse(s.activate, "active").With(row.answer)
|
||||
}
|
||||
out, refs := e.swap(s, "swap-farm-error")
|
||||
if out.Status == "succeeded" {
|
||||
t.Fatalf("output = %+v, want a swap that did not succeed", out)
|
||||
}
|
||||
for _, ref := range refs {
|
||||
if status, _ := e.request(ref.InstanceID, ref.Generation); status == "succeeded" || status == "accepted" {
|
||||
t.Errorf("request on %s = %s, want a finished failure or decline", ref.InstanceID, status)
|
||||
}
|
||||
}
|
||||
e.wantNoStamp("after a farm call that failed")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -119,7 +119,7 @@ func (r *usageRun) recordRequests() {
|
||||
r.create = e.startCreate("made")
|
||||
r.archiveGen = e.record(r.archived.id, integration.LifecycleSetStatus, "wf-"+r.archived.id, map[string]any{"status": "archived"})
|
||||
r.restoreGen = e.record(r.restore.id, integration.LifecycleSetStatus, "wf-"+r.restore.id, map[string]any{"status": "active"})
|
||||
r.swapGen, r.swapParkGen = e.swapRequests(r.activated.id, r.parked.id, "swap-concurrent")
|
||||
r.swapGen, r.swapParkGen, _ = e.swapRequests(r.activated.id, r.parked.id, "swap-concurrent")
|
||||
inSibling := *e
|
||||
inSibling.ws = r.sibling
|
||||
r.deleteGen = inSibling.record(r.deleted.id, integration.LifecycleDelete, DeleteRequestWorkflowID(r.deleted.id, 1), map[string]any{})
|
||||
@@ -374,3 +374,60 @@ func (r *usageRun) wantEnd(t *testing.T) {
|
||||
t.Errorf("the figure at the end is %d, want the %d sites the run left active", figure, active)
|
||||
}
|
||||
}
|
||||
|
||||
// Two outcomes of one workspace that both stamp take disjoint instance locks
|
||||
// and site rows, then the policy row at the same position (design D15), so the
|
||||
// second waits for the first on the policy row alone and both finish. The
|
||||
// first is a side transaction that has written what a stamping outcome writes
|
||||
// before its stamp, and holds the policy row open.
|
||||
func TestStampingOutcomesOfOneWorkspaceSerializeOnThePolicyRow_DB(t *testing.T) {
|
||||
e := newReqEnv(t, 5, 0)
|
||||
e.seedStamp()
|
||||
first := e.startActivation("firststamp", "readonly")
|
||||
second := e.startActivation("secondstamp", "readonly")
|
||||
|
||||
ctx, cancel := context.WithTimeout(e.ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
side, err := e.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer side.Rollback()
|
||||
var sidePID int
|
||||
if err := side.QueryRowContext(ctx, `SELECT pg_backend_pid()`).Scan(&sidePID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := side.ExecContext(ctx, `UPDATE fedwiki.sites SET status = 'active', force_reduced_at = NULL WHERE site_id = $1`, first.InstanceID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := fwmod.New(side).UpsertSiteSwapPolicy(ctx, e.ws); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
done <- e.acts.RecordSiteStatusActivity(ctx, RecordSiteStatusInput{InstanceID: second.InstanceID, Generation: second.Generation,
|
||||
WorkspaceID: e.ws, Domain: second.Domain, Status: "active", ClearForceReduced: true, FinishedAt: time.Now()})
|
||||
}()
|
||||
dbtest.AwaitLockWait(t, e.db, dbtest.Backend{BlockedBy: sidePID, Abort: func() error {
|
||||
select {
|
||||
case err := <-done:
|
||||
return fmt.Errorf("the second outcome finished without waiting on the policy row: %v", err)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}})
|
||||
if status, _ := e.request(second.InstanceID, second.Generation); status != integration.LifecycleAccepted {
|
||||
t.Errorf("second request = %s while it waits on the policy row, want accepted", status)
|
||||
}
|
||||
if err := side.Commit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := <-done; err != nil {
|
||||
t.Fatalf("second outcome: %v", err)
|
||||
}
|
||||
if status, _ := e.request(second.InstanceID, second.Generation); status != integration.LifecycleSucceeded {
|
||||
t.Errorf("second request = %s, want succeeded", status)
|
||||
}
|
||||
e.wantSite(second.Domain, "active", false)
|
||||
}
|
||||
|
||||
@@ -184,6 +184,9 @@ read core.invoices.subscription_id
|
||||
read core.invoices.updated_at
|
||||
read core.invoices.voided_at
|
||||
read core.lifecycle_requests.acknowledged_at
|
||||
read core.lifecycle_requests.act_cause
|
||||
read core.lifecycle_requests.act_id
|
||||
read core.lifecycle_requests.act_role
|
||||
read core.lifecycle_requests.connection_id
|
||||
read core.lifecycle_requests.created_at
|
||||
read core.lifecycle_requests.finished_at
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
enumspb "go.temporal.io/api/enums/v1"
|
||||
"go.temporal.io/sdk/client"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/acts"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/db"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/entitlements"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/logging"
|
||||
@@ -262,7 +263,7 @@ func (h *OperatorPartialsHandler) RetryOrgTypePlanAct(w http.ResponseWriter, r *
|
||||
h.renderOrgTypeCard(w, r, ot, "", nil, failureReference(r, "Failed to retry"))
|
||||
return
|
||||
}
|
||||
if err != nil || entitlements.ActCause(place.Cause) != entitlements.ActOrgTypeDefaultChanged || place.OrgType.String != orgType {
|
||||
if err != nil || acts.Cause(place.Cause) != acts.OrgTypeDefaultChanged || place.OrgType.String != orgType {
|
||||
log.Warn("a retry named a plan act that was not made for this org type", slog.String("act_id", actID), slog.String("org_type", orgType))
|
||||
h.renderOrgTypeCard(w, r, ot, "", nil, "")
|
||||
return
|
||||
@@ -336,7 +337,7 @@ func (h *OperatorPartialsHandler) RetryLadderPlanAct(w http.ResponseWriter, r *h
|
||||
h.renderPlanLadderTiersPage(w, r, ladderID, "", failureReference(r, "Failed to retry"))
|
||||
return
|
||||
}
|
||||
if err != nil || entitlements.ActCause(place.Cause) != entitlements.ActTiersReordered || place.PlanLadderID.UUID.String() != ladderID {
|
||||
if err != nil || acts.Cause(place.Cause) != acts.TiersReordered || place.PlanLadderID.UUID.String() != ladderID {
|
||||
log.Warn("a retry named a plan act that was not made for this ladder", slog.String("act_id", actID), slog.String("plan_ladder_id", ladderID))
|
||||
h.renderPlanLadderTiersPage(w, r, ladderID, "", "")
|
||||
return
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-11-10
|
||||
@@ -0,0 +1,455 @@
|
||||
## Context
|
||||
|
||||
This change answers #184 (a FedWiki swap is held together by conventions, and the model must say whether one request can cover several instances before the published protocol, #171, fixes a request's shape), #328 (the swap cooldown starts at intake) and #329 (the farm sync keeps a parked site's mark on a row it writes archived or active). A path that does not begin with `internal/`, `docs/`, `openspec/` or `scripts/` is relative to `internal/integrations/fedwiki/`. "spec.md" or "<capability> spec" means `openspec/specs/<capability>/spec.md`, and "acts.md" means `docs/models/acts.md`. A bare `:N` cites the file named last.
|
||||
|
||||
### Terms
|
||||
|
||||
- A **rotation** is a change that brings a different site into a workspace's active set (plan-downgrade spec.md:107). It has two kinds:
|
||||
- a **swap**: Keep active while the pool is at its limit. The console parks the workspace's lowest-ranked active site, the one least recently modified on the farm (or created, when never modified; plan-downgrade spec.md:105), and activates the chosen one (`KeepSiteActive`, web/site_actions.go:444-467; `swapActiveSite`, :569).
|
||||
- a **return**: Keep active below the limit on a read-only site whose `force_reduced_at` mark is set (`changeStatus` with `rotation` true, web/site_actions.go:464). The plan-downgrade spec's scenario "Rotating a downgrade-parked reserve in is gated" (spec.md:148-153) says "restores"; it means Keep active on a parked read-only site (spec.md:105), not the Restore button. Restore acts on an archived row, and an archived row never carries a mark (D18), so Restore is never a return (D10).
|
||||
- A **free fill** is Keep active below the limit on a site with no mark, or Restore. The plan-downgrade spec always allows it and keeps it out of the cooldown (spec.md:107).
|
||||
- **The stamp** is `fedwiki.site_swap_policy.last_swap_at` (store/migrations/00001_init.sql:76-79). **The cooldown** is the `fedwiki-swap-cooldown` window; `cooldownMsgFor` compares it with the stamp and ignores the stamp when the window is 0 (web/partials.go:649-669). **The cooldown sentence** is "The active site changes once every N day(s); try again in about M day(s)." (web/partials.go:667).
|
||||
- **The site-busy sentence** is "A change to this site is already in progress" (`msgSiteBusy`, web/requests.go:111). **The rotation-busy sentence** is "A change to your active site is already in progress" (`msgActiveSiteBusy`, :112).
|
||||
- **The re-upgrade sweep** is the quota sweep's reactivation of marked read-only sites when a pool's limit rises (`reactivateSite`, workflows/reconcile.go:308; plan-downgrade spec.md:109). It checks for an open request only before its farm call (:309).
|
||||
- **The slot gate** is the activity of an activation's workflow that takes a slot hold before the farm call and declines when the pool is full. **The record step** is the local activity that records a success (`RecordSwapActivity`, `RecordSiteStatusActivity`). **The guard** is the check that `finishAllWith` runs on the recounted figure before it finishes any request (`recountGuard`, workflows/request_activities.go:183-185). **The stop window** is the time between stopping the old release and starting the new one in a deploy.
|
||||
- A **lifecycle act** is a `core.acts` row whose rows are lifecycle requests. A request's **link** is its three act columns (D1). The **asked** request is for the instance the actor chose; a **consequent** request is for an instance the console added to carry the action out.
|
||||
|
||||
### How rotations are recorded at HEAD
|
||||
|
||||
`swapActiveSite` runs one READ COMMITTED transaction under the FedWiki workspace advisory lock (`withWorkspaceTx`, web/site_actions.go:795-805). In order, it:
|
||||
1. answers a repeat through FedWiki's own content rule (`lockedRepeat`, :552-561, calling `sameRowRequest`, web/requests.go:175-188);
|
||||
2. reads the stamp (:590), then refuses when an accepted request's workflow id has the swap prefix (`hasOpenSwap`, :594-601, :1005-1012; `IsSwapRequestWorkflowID`, workflows/requests.go:97-104);
|
||||
3. takes the last row of `ListActiveSitesByWorkspace` as the site to park (:613) and takes both instance locks, activated site first (`CheckSwapRequestSites`, :615; store/request_intake.go:74);
|
||||
4. records two `set_status` requests under one workflow id, `swap-fedwiki-site-<site_id>-<generation>` (:573): the activated site's carries `swap_park_site_id` (:619-621); the parked site's carries `swap_activate_site_id` and names the member as its requesting person (`recordParkRequest`, :1024-1033);
|
||||
5. upserts the stamp (:638).
|
||||
|
||||
Nothing records the swap itself. Four readers rebuild it from the workflow id and the keys: the open-swap refusal (step 2); the dismissal, which acknowledges every row with the same workflow id (`acknowledgeRequest`, :737-764); the notice list, which leaves out a row carrying `swap_activate_site_id` (:883) and finds the parked site's row by key to name a deleted site (:893-901); and `requestAction`, which says "restored" only without `swap_park_site_id` (web/requests.go:97). FedWiki keeps `sameRowRequest` because core's rule, `sameLifecycleContent` (internal/integration/lifecycle.go:407-419), compares every parameter, and a repeated click could choose a different park site.
|
||||
|
||||
`changeStatus` (web/site_actions.go:476-547) takes the workspace lock only when `rotation && h.SwapCooldown > 0` (:485), and that branch answers a repeat, checks the cooldown, records and stamps (:505). With the cooldown off, a return records in its own transaction (:515-525), with no workspace lock and no refusal while a rotation is open.
|
||||
|
||||
A swap writes the stamp at intake, and so does a return when the cooldown is on, before the workflow starts. When a start fails and Temporal's describe answers NotFound, `startRequestWorkflow` deletes the requests one statement per address, outside a transaction, and only logs a failed delete (web/requests.go:221-246); nothing removes the stamp.
|
||||
|
||||
### Outcomes and settle at HEAD
|
||||
|
||||
Every outcome runs `finishAllWith` (workflows/request_activities.go:207-240), one READ COMMITTED transaction: `lockOutcomes` takes the instance locks in the order given and reads each request (:247-279), returning before `apply` when every request already holds the outcome (:213-215) and refusing a partly finished set (:273-275); `apply` then writes site rows (:216-220), and `DeleteSlotHolds`, the recount on the usage row, the guard and `FinishLifecycleRequest` per request follow (:221-237). `RecordSwapActivity` (workflows/swap.go:166-219) and `RecordSiteStatusActivity` (workflows/request_activities.go:380-403) write the site rows in their `apply`; `SetSiteStatusByID` clears `force_reduced_at` on any status but `readonly` (store/queries/sites.sql:402-414).
|
||||
|
||||
Boot settle (`SettleOpenRequests`, workflows/settle.go:58-136) describes each accepted request's workflow and finishes each row alone: NotFound ends `failed/not_started`; a closed activation holding a slot goes to the status reconcile (workflows/requests.go:826-876), which records success through `RecordSiteStatusActivity` with no `ClearForceReduced` (:859-866); any other closed request but a create ends `failed/retries_exhausted`.
|
||||
|
||||
## Goals / Non-Goals
|
||||
|
||||
**Goals:**
|
||||
- A request covers one instance. A swap records one `instances_swapped` act that both requests point at with a role, written by one enclosed function, `core.record_lifecycle_act`, which links only rows its own transaction inserted. Every reader finds a swap through its act, and nothing else groups requests.
|
||||
- Core's repeat rule answers every repeat (`sameRowRequest` goes); an act's requests are deleted together when their workflow cannot start, and settled together at boot.
|
||||
- A rotation stamps only when it succeeded and its action brought the chosen site into the active set (D14), and every rotation's intake takes the workspace lock and refuses while another rotation of the workspace is open.
|
||||
- No Temporal workflow command changes.
|
||||
- The farm sync keeps a site's mark only on a row it writes read-only (D18), so no archived row carries a mark and Restore never rotates (D10).
|
||||
|
||||
**Non-Goals:**
|
||||
- The swap policy's home under the protocol, and whether a connector may park on its own (#172).
|
||||
- `sameCreate`, the JSON delete's second read outside the instance lock, and `finishAllWith`'s Go copy of the finish rule (#174); instance locks on the unstarted delete (#229).
|
||||
- Converting stored swap requests.
|
||||
|
||||
## Decisions
|
||||
|
||||
### D1. The link is three columns on core.lifecycle_requests
|
||||
|
||||
Migration `internal/db/migrations/00041_lifecycle_request_acts.sql` adds nullable `act_id UUID`, `act_cause VARCHAR(50)` and `act_role VARCHAR(20)`, with:
|
||||
- `lifecycle_request_in_its_act`: FOREIGN KEY (act_id, act_cause) REFERENCES core.acts (act_id, cause), on `uq_acts_act_id_cause` (internal/db/migrations/00027_acts.sql:29), as `plan_act_detail_is_its_act` does (:63). A request can point only at an act of the cause it states.
|
||||
- `lifecycle_request_act_shape`: CHECK ((act_id IS NULL) = (act_cause IS NULL) AND (act_id IS NULL) = (act_role IS NULL)). PostgreSQL's default MATCH SIMPLE skips a row with any NULL referencing column, so without this check a row could carry an `act_id` that nothing verified.
|
||||
- `chk_lifecycle_requests_act_cause`: CHECK (act_cause IN ('instances_swapped')), because the foreign key alone accepts a plan cause.
|
||||
- `chk_lifecycle_requests_act_role`: CHECK (act_role IN ('asked', 'consequent')).
|
||||
- `lifecycle_request_consequent_names_no_person`: CHECK (act_role IS DISTINCT FROM 'consequent' OR requested_by_person_id IS NULL). The console, not a person, added a consequent request, so the database holds the rule that the parked site's request names no person.
|
||||
- `uq_lifecycle_requests_one_asked`: UNIQUE (act_id) WHERE act_role = 'asked'.
|
||||
- `idx_lifecycle_requests_act_id`: (act_id) WHERE act_id IS NOT NULL, for the statements that delete, acknowledge or read an act's requests; partial because most requests belong to no act.
|
||||
|
||||
One column means a request belongs to at most one act. Stored rows keep NULL. No workflow reads the parked request's person: `LifecycleRequesterSubject` (internal/integration/lifecycle.go:542) has one caller, `ReadFarmSiteActivity` (workflows/request_activities.go:105-112), which the swap workflow never runs (workflows/requests.go:660-723).
|
||||
|
||||
Alternatives considered: a join table, whose foreign key would block `DeleteUnstartedLifecycleRequest` unless it cascaded (a cascade deletes from a table of the act record, docs/models/acts.md invariant 17) and which every reader would join (`core.grants.act_id` is the precedent for a column); MATCH FULL in place of the shape check, which covers the pair and not `act_role`; naming the link `request_id`, which `core.acts.request_id` already uses for a log correlation id (internal/db/migrations/00027_acts.sql:44-45).
|
||||
|
||||
### D2. core.record_lifecycle_act links only rows its own transaction inserted
|
||||
|
||||
```
|
||||
core.record_lifecycle_act(p_cause VARCHAR, p_actor_type VARCHAR, p_actor_person_id UUID,
|
||||
p_actor_service_account_id UUID, p_request_id VARCHAR,
|
||||
p_asked_lifecycle_request UUID, p_consequent_lifecycle_requests UUID[]) RETURNS UUID
|
||||
LANGUAGE plpgsql SECURITY DEFINER SET search_path = core, pg_temp
|
||||
```
|
||||
|
||||
`core_owner` owns it. EXECUTE is revoked from PUBLIC and granted to `core_writer`, which the runtime user holds through `console_runtime` (internal/db/migrations/00029_runtime_group_role.sql:51); the revoke also keeps `scripts/db-reader-role.sql` runnable, since that script refuses while the read-only role could execute a SECURITY DEFINER function. It takes no note, because no lifecycle act offers one. It runs five steps:
|
||||
1. **Per-cause rules.** A CASE on the cause holds each lifecycle cause's rules, and its ELSE refuses, so a plan cause cannot get a header without its detail row or the rendezvous. For `instances_swapped`: one consequent request; `set_status` on every request; the asked request names the actor as its person; no consequent request names a person.
|
||||
2. **The rows.** It reads the named rows once, without a row lock. The ids are distinct, and every row exists, is `accepted`, carries no link, and belongs to one workspace and one connection.
|
||||
3. **Inserted by this transaction.** Each row's `xmin` equals `pg_current_xact_id()::xid`, as in `core.requeue_plan_act_obligations` (internal/db/migrations/00028_plan_act_obligations.sql:476). That test alone is not exact for a lifecycle request: an UPDATE gives a row a new xmin, so an old accepted row that this transaction only updated would pass. Each row's `created_at` must also equal `transaction_timestamp()`; the column always comes from its default, because `core_writer` holds no INSERT or UPDATE on it (D4). No path lets an older row pass both.
|
||||
4. **The header.** It inserts the `core.acts` row with a NULL note, `record_plan_act`'s 100-character rule on the request id (internal/db/migrations/00028_plan_act_obligations.sql:239), and `effective_at` from D3. The header comes first because the foreign key needs it; act-records spec:10 ("before any row that refers to it") holds, because no row refers to the act until step 5.
|
||||
5. **The link.** One UPDATE sets the three columns WHERE act_id IS NULL, and the function raises when fewer rows changed than it named.
|
||||
|
||||
Distinct instances need no check: `uq_lifecycle_requests_one_open` (internal/db/migrations/00024_integration_delivery_core.sql:229) allows one accepted request per instance. A linked row keeps every column the checks read, because `core_writer` cannot update the act columns, `workspace_id`, `connection_id`, `operation` or `requested_by_person_id` (D4), so no caller can add, move or clear a link.
|
||||
|
||||
The function asserts no rendezvous, because lock rule 1 (docs/database-locks.md:80) puts the rendezvous first in its transaction, a swap's transaction starts with the `fedwiki-workspace` lock, and no lifecycle act changes an entitlement. It takes no lock the intake does not already hold (Locks and transactions).
|
||||
|
||||
Alternatives considered: header first, with each recording writing `act_id`, which gives `core_writer` INSERT on the act columns so any insert could claim any act; one function that also inserts the requests, which restates the recording's rules (internal/integration/lifecycle.go:137-305) in SQL; `core.record_plan_act`, which asserts the rendezvous (internal/db/migrations/00028_plan_act_obligations.sql:211-215) and writes a detail row.
|
||||
|
||||
### D3. core.acts gains the cause; effective_at is the request's time
|
||||
|
||||
- One ALTER TABLE drops `chk_acts_cause` and adds it with six causes. `chk_plan_act_details_cause` keeps the five plan causes, because a lifecycle act has no detail row (acts.md invariant 2).
|
||||
- `effective_at` is the asked request's `created_at`, which equals `transaction_timestamp()` and the header's `created_at`. The act takes effect when it is requested, and whether the swap succeeded is read from its requests.
|
||||
- The comments on `core.acts` (internal/db/migrations/00027_acts.sql:40-41) and the RecordPlanAct query (internal/entitlements/queries/plan_acts.sql:2) name both writers; the comment on `core.lifecycle_requests` (internal/db/migrations/00024_integration_delivery_core.sql:236-237) says a request names the person whose action caused it, or no one for a consequent request.
|
||||
|
||||
Alternative considered: a `p_effective_at` from Go, as `record_plan_act` takes, a second clock that can disagree with the requests.
|
||||
|
||||
### D4. core_writer holds column INSERT and column UPDATE on core.lifecycle_requests
|
||||
|
||||
The Up revokes `core_writer`'s table INSERT and UPDATE (internal/db/migrations/00024_integration_delivery_core.sql:777-780). It grants INSERT on the nine columns `InsertLifecycleRequest` names (internal/integration/queries/lifecycle_requests.sql:22-24), and UPDATE on `status`, `reason_code`, `finished_at` and `acknowledged_at`, which `FinishLifecycleRequest` and `AcknowledgeLifecycleRequest` set (:52-55, :90-91). SELECT and DELETE stay. `git grep` finds no other production write. The `updated_at` trigger (internal/db/migrations/00024_integration_delivery_core.sql:232-235) needs no grant, because PostgreSQL checks the statement's SET list, not what a BEFORE trigger assigns. No query row-locks the table.
|
||||
|
||||
This forces per-schema-roles spec:405 to state the column lists, checked by `TestDeliveryTablePrivileges` (internal/db/integration_delivery_enclosure_test.go:219-229) with a refused write of `act_id`; spec:474 to let a locked entry name columns for INSERT as well as UPDATE, so `lockedTable` (internal/db/runtime_role_privileges_test.go:26-46) gains a column list per privilege and absorbs the outbox's special case; `internal/migrate/testdata/console-reader-columns.txt` to list the three columns as `read`; and `TestPlanActWritersAreEnclosedInTheCatalog` (internal/db/plan_act_obligations_test.go:277) and `TestRecordPlanActIgnoresACallersTemporaryTables` (internal/db/acts_test.go:204) to cover the new function.
|
||||
|
||||
Alternative considered: table grants plus a trigger guarding the act columns. Every enclosure in this schema is an absent grant (per-schema-roles spec:476).
|
||||
|
||||
### D5. The Go side of the record
|
||||
|
||||
- `LifecycleAnswer` (internal/integration/lifecycle.go:97-102) gains `RequestID`: `recordNew` keeps the id it discards at HEAD (:284), and `answerFromRow` (:393) copies it.
|
||||
- `internal/integration` gains `RecordLifecycleAct(ctx, tx *sql.Tx, act LifecycleAct) (string, error)`, with `LifecycleAct{Cause acts.Cause; ActorPersonID, CorrelationID, Asked string; Consequent []string}`. It takes a `*sql.Tx`, because a call outside the inserting transaction could only fail, and passes actor type `person`, as `writePlanAct` does (internal/entitlements/plan_act_runner.go:210). `CorrelationID` fills `core.acts.request_id`, since `RequestID` already names a lifecycle request's id in this package. It returns the database's refusal wrapped in an error; only a code defect reaches it, because the caller's own inserts satisfy every rule.
|
||||
- `LifecycleActAsked` and `LifecycleActConsequent` mirror `chk_lifecycle_requests_act_role`, as the status constants mirror theirs (internal/integration/lifecycle.go:25-31). sqlc regenerates `LifecycleRequest`.
|
||||
- The cause list moves from `internal/entitlements/act_cause.go` to a new leaf package, `internal/acts`: `acts.Cause`, the six constants (`TierAdded`, `TierRemoved`, `TiersReordered`, `OrgTypeDefaultChanged`, `PlanActRetried`, `InstancesSwapped`), and the lists `PlanCauses` and `LifecycleCauses`. About 45 references in 12 files change mechanically, and the stale comment that a new kind replaces "both constraints" (internal/entitlements/act_cause.go:7-9) goes.
|
||||
- `TestActCausesMirrorTheConstraints` (internal/entitlements/act_cause_test.go:31-56) moves to `internal/acts` with three cases: `chk_acts_cause` against every cause, `chk_plan_act_details_cause` against `PlanCauses`, `chk_lifecycle_requests_act_cause` against `LifecycleCauses`. A second test calls the writer with each plan cause and expects the refusal, so D2's CASE and the constraint cannot drift.
|
||||
|
||||
Alternatives considered for the cause list's home: `internal/integration`, which `internal/entitlements` already imports (internal/entitlements/outbox_requests.go:11), so plan vocabulary would live in the delivery package; or plan causes in `internal/entitlements` and `InstancesSwapped` in `internal/integration`, so two lists would mirror `chk_acts_cause`. The act record that every kind of act shares (docs/models/acts.md) gets a vocabulary package that imports nothing of the console.
|
||||
|
||||
### D6. The Down refuses while a lifecycle act exists
|
||||
|
||||
The Down first counts the `core.acts` rows with a lifecycle cause, in a DO block that raises and names the count when there is one. It then revokes the column grants by name, restores table INSERT and UPDATE, drops the function, the indexes, the constraints and the columns, restores both comments, and restores the five-cause `chk_acts_cause`. Once a lifecycle act exists the five-cause constraint cannot be re-added, and the statements run one by one would drop the columns that tie a swap's requests to their act, so the DO block refuses first. A rollback of this release does not need the Down: the previous image runs on the 00041 schema (Migration Plan), and a core Down runs by hand (docs/database-management.md:71-77). `requireMigrationUpDownUp` (internal/db/outgoing_default_rule_test.go:163-187) compares `pg_get_constraintdef` output (internal/db/integration_delivery_migration_test.go:168) on a database with no lifecycle act; a new test records a swap and expects the refusal.
|
||||
|
||||
Alternatives considered: restore `chk_acts_cause` NOT VALID when lifecycle headers exist, which leaves a constraint that describes a database it does not hold and still loses the links; delete the lifecycle headers, which purges the record (acts.md invariant 17).
|
||||
|
||||
### D7. A core lookup answers a repeat before anything is recorded
|
||||
|
||||
`internal/integration` exports `AnswerLifecycleRepeat(ctx, db DBTX, spec LifecycleRequestSpec) (LifecycleAnswer, LifecycleRequest, error)`. It runs `heldAt` (internal/integration/lifecycle.go:345) and `sameLifecycleContent` (:407) without the instance lock and answers: a zero `Kind` when nothing holds the address; `LifecycleNotFound` for another workspace's row; `LifecycleRepeatOpen` or `LifecycleRepeatFinished` with the held row; `LifecycleConflict` when the content differs. `answerAddress` (:311) calls the same helper, so the rule has one copy, and the recording under the lock stays the final answer; an older tab's generation that holds nothing is left to it, because only the read under the instance lock can call it a conflict reliably.
|
||||
|
||||
The lookup is enough because the asked request records the same content as a free fill and a return (`{domain, status: "active"}` and the member), so a repeated Keep active matches whichever branch its first click took. Each caller passes the spec it would record:
|
||||
- `beginRowAction` (web/site_actions.go:352-367) builds it from the path's domain before resolving the site, so a repeat after a permanent delete is answered from its record; a zero or NotFound answer goes on to the site checks, as `found == false` does at HEAD.
|
||||
- `lockedRepeat` (:552-561) calls it inside the workspace transaction.
|
||||
- The JSON delete's repeat check (web/api.go:553-566) calls it with `{domain}`: a repeat answers through `respondRepeat`, a conflict answers 409 with `msgAPIConflict`, and a zero or NotFound answer goes on. No JSON route (web/api.go:106-109) records a rotation.
|
||||
|
||||
`sameRowRequest` and the two swap fields of `requestParams` (web/requests.go:122-128) are deleted. `LookupLifecycleRequest` stays for the create repeat (web/site_actions.go:249), `recordSiteRequestInTx` (store/request_intake.go:45) and the JSON delete's second read (web/api.go:619), which #174 owns.
|
||||
|
||||
Alternatives considered: keep `sameRowRequest`, a weaker second copy; export `sameLifecycleContent` and let each handler pair it with a read, which lets a caller forget the workspace test `heldAt` makes.
|
||||
|
||||
### D8. How intake finds an open rotation
|
||||
|
||||
A new FedWiki store query, `WorkspaceHasOpenRotation(workspace_id, connection_id, swap_cause)`, is one EXISTS over `core.lifecycle_requests` left-joined to `fedwiki.sites` on `site_id = instance_id`. It is true when an accepted request of the workspace and connection either (a) has `act_cause = swap_cause`, passed from `acts.InstancesSwapped` so the cause has one spelling, or (b) is a `set_status` whose `parameters->>'status'` is `active` on a site whose `force_reduced_at` is set. It replaces `OpenRequestsByWorkspace` plus `hasOpenSwap` (web/site_actions.go:594-601). The store already reads core tables (`ListAllSitesForOperatorPage`), and `fedwiki_writer` holds `core_reader`, which reads the whole table (internal/db/migrations/00024_integration_delivery_core.sql:785-788).
|
||||
|
||||
Test (b) is the plan-downgrade definition of a return (spec.md:107); the mark stays until the success clears it in the commit that finishes the request (store/queries/sites.sql:402-414). An accepted Restore never matches test (b), because the row it acts on is archived and carries no mark (D18). Test (a) is needed because a swap's chosen site may carry no mark: the farm sync can write `readonly` onto an unmarked row (`UpsertSiteFromFarm`, store/queries/sites.sql:82-93). Test (b) is not a parameter-key convention: the retired conventions made one row point at another, while `status` is the row's own target, part of the content the repeat rule compares, and already read by the notices (web/requests.go:87-104). The re-upgrade sweep can therefore activate a pending return's site and clear its mark; test (b) then misses that return, and a second rotation may be recorded. That is harmless: the first return's site is already active and its success writes no stamp (F19).
|
||||
|
||||
Intake reads the open rotations before the stamp. Outcome transactions take no workspace lock (docs/database-locks.md:418-428), and a success commits its finish and its stamp together (D14). At READ COMMITTED each statement sees every earlier commit, so a rotation that commits before the open-rotation read is seen by the stamp read, and one that commits later was still open in the first read; in the order at HEAD (web/site_actions.go:590 before :594), a commit between the two reads passes both. One statement holds both tests, so a request and its site's mark are read in one snapshot.
|
||||
|
||||
Alternatives considered: test (b) in Go over `OpenRequestsByWorkspace` and the site list, which reads two snapshots; a FedWiki marker row per rotation, which adds state for facts the request and the site row already hold.
|
||||
|
||||
### D9. The swap's intake
|
||||
|
||||
The swap runs in one READ COMMITTED transaction under the workspace lock:
|
||||
|
||||
| Step | Finding | Answer |
|
||||
|---|---|---|
|
||||
| 1. Repeat (D7) | repeat / conflict | list refresh / "This site changed since the list loaded." and a refresh |
|
||||
| 2. Open rotation (D8) | open | the rotation-busy sentence |
|
||||
| 3. Cooldown | inside the window | the cooldown sentence |
|
||||
| 4. `ListActiveSitesByWorkspace` | no active site of its own | "You have reached your active site limit." |
|
||||
| 5. Park choice | the lowest-ranked row (:613) | |
|
||||
| 6. `CheckSwapRequestSites` | chosen / park site gone | "Site not found" / conflict and a refresh |
|
||||
| 7. Asked request | repeat / site busy (`LifecycleBusy`) / conflict / not found | refresh / the site-busy sentence / conflict / "Site not found" |
|
||||
| 8. Consequent request | not recorded | the rotation-busy sentence |
|
||||
| 9. `RecordLifecycleAct` | | |
|
||||
| Any error | | "Couldn't change the active site. Try again." |
|
||||
|
||||
Step 7 records `{domain, status: "active"}` with the member as person; its repeat case is a free fill of the same address that committed after step 1, since a free fill takes no workspace lock. Step 8 (`recordParkRequest`, :1024) records `{domain, status: "readonly"}` at the park site's next generation, with no person, under the swap's workflow id. Step 9 passes `acts.InstancesSwapped`, the member as actor, both `RequestID`s and the correlation id from `middleware.GetRequestID`, as internal/server/operator_plan_acts.go:292 does. The policy upsert (:638) goes; `SwapSiteRequestInput` is unchanged. The repeat check comes first so a second click of a swap is answered from its record: otherwise the open-rotation check would refuse a click of the swap still open, and the stamp its own success wrote would refuse a click after it succeeded.
|
||||
|
||||
**The member's person id.** The asked request and the act's actor need a non-empty person id (`act_actor_coherent`). A request reaches a handler only after `Config.Middleware` (internal/auth/auth.go:283, wired at internal/server/server.go:525) has run `sessionPersonExists`, which bounces an authenticated session that names no person to login (internal/auth/auth.go:326-330, :400-404). FedWiki declares no exemption (internal/integrations/fedwiki/fedwiki.go:328-335), and the handlers take the person from that session (`beginRowAction`, web/site_actions.go:331-337) into each request spec (:480, :619, :1030). A session without a person id therefore cannot reach Keep active or Restore, and F8 cannot arise from one.
|
||||
|
||||
Alternative considered: insert the header first and pass its id into each recording. Core's recording would gain an act argument, and `core_writer` would need INSERT on the act columns (D2).
|
||||
|
||||
### D10. The return's intake and free fills; Restore never rotates
|
||||
|
||||
`changeStatus` takes the workspace transaction whenever `rotation` is true, not only when `SwapCooldown > 0` (web/site_actions.go:485), in the swap's order: repeat, open rotation, cooldown, then `RecordSiteRequestInTx`. The stamp (:505) goes; `ClearForceReduced: rotation` stays in the workflow input. A free fill, an archive and a delete keep their own transaction with no workspace lock. A free fill is not refused while a rotation is open and does not count as one, because the plan-downgrade spec says it "SHALL always be allowed and SHALL NOT consult the cooldown" (spec.md:107); the slot gate still declines it when the pool is full.
|
||||
|
||||
**The return locks its site row.** After the instance lock and before the request is inserted, a return's intake locks its site row with `LockSiteStatusByID` and re-checks what made the action a return: the row is the member's workspace's, carries the posted domain, is `readonly` and has `force_reduced_at` set (web/site_actions.go, `holdReturnSite`). A missing row, or one of another workspace or domain, records nothing and gets the "Site not found" answer every original site gets (`MissingSiteError`); a row no longer read-only or no longer marked records nothing and gets `siteActionConflict` ("This site changed since the list loaded." and a refresh), the sentence a stale row already gets. The order is advisory locks, then the site row (docs/database-locks.md rule 5); `RecordSiteRequestInTx` takes the instance lock again without waiting, because the transaction already holds it, so `recordRotation` takes the instance lock itself before the row lock and the store function is unchanged. The sync takes no advisory lock, so no cycle forms. A free fill, an archive, a Restore and a delete take no site-row lock, and the swap is unchanged. Alternative considered: a variant of `RecordSiteRequestInTx` that locks the row, which adds a second recording function for one caller.
|
||||
|
||||
**The database-error sentence.** Every return's intake now records in the workspace transaction, so a database error in that transaction answers "Couldn't change which site is active. Try again later." (web/site_actions.go:512). At HEAD a return with the cooldown off answered "Couldn't update the site. Try again." (:522); a free fill, Restore and an archive still do. Alternative considered: choose the sentence by the cooldown setting. Rejected: the error comes from the same transaction either way.
|
||||
|
||||
**Restore never rotates.** `RestoreSite` calls `changeStatus` with `rotation` false, where it passes `act.site.ForceReducedAt.Valid` at HEAD (web/site_actions.go:432). `beginRowAction` does not read the row's status (web/site_actions.go:329-390), so a request to the restore route can name a read-only row. With `rotation` false, a marked one would record a return without the workspace lock, the open-rotation check or the cooldown, and its success would stamp (D14). `RestoreSite` therefore answers a row whose status is not `archived` with `siteActionConflict` ("This site changed since the list loaded." and a refresh), before anything is recorded. An archived row never carries a mark once the sync follows the mark rule (D18), so that argument would always be false. `SiteViewModel.IsForceReduced` (web/partials.go:147, :352) has one reader, the Restore gate (templates/fedwiki_sites.html:166-167); Keep active's gate reads `IsReadonly` and `CooldownMsg` (:116-127). The gate, `RestoreControl` (web/partials.go:295-306) and `IsForceReduced` therefore go, and Restore renders as on any archived row, as the button at :169-175. Restore takes no workspace lock, makes no open-rotation check, consults no cooldown and writes no stamp, and its database error keeps "Couldn't update the site. Try again.". The render test that checks both disabled controls (web/sites_render_test.go:181-223) keeps Keep active's half.
|
||||
|
||||
### D11. A swap whose workflow cannot start loses its requests in one statement
|
||||
|
||||
`startRequestWorkflow` (web/requests.go:221) takes one value naming what to delete: an address for a single request, or an act. For an act it calls a new core function, `DeleteUnstartedLifecycleAct(ctx, db, workspaceID, actID)`: `DELETE … WHERE act_id = $1 AND workspace_id = $2 AND status = 'accepted'`. The header stays, because a header is never deleted and `core.lifecycle_requests` is not a table of the act record, as `core.grants` is not. `DeleteUnstartedLifecycleRequest` (internal/integration/queries/lifecycle_requests.sql:62-70) gains `AND act_id IS NULL`, so no per-address delete can leave half an act. The rule lives in the query, not in a grant, because PostgreSQL cannot grant DELETE per column. The delete takes no instance lock, as at HEAD (#229).
|
||||
|
||||
The member sees "Couldn't change the active site. Try again." (web/site_actions.go:664), or "Couldn't update the site. Try again." for a return (:542), with no list refresh. The row posts the same address, which now holds nothing, so the retry records afresh with a new act and a new park generation, and no cooldown refuses it. If the delete fails, both requests stay accepted: the retry is answered as a repeat, the list shows Pending, and the next boot settle ends the act (D16).
|
||||
|
||||
Alternatives considered: delete the address's whole act through the address, which hides which rows go; finish the requests `failed/not_started`, after which the retry, posted to the same address without a refresh, would be answered as a repeat.
|
||||
|
||||
### D12. The readers find a swap through its act
|
||||
|
||||
- **Notice list** (`notices`, web/site_actions.go:877): a row whose `act_role` is `consequent` gets no notice, replacing the key test at :883.
|
||||
- **Deleted parked site** (:893-901): a row that ends `site_missing` while its own site exists names the consequent row of its act when `v.rows` holds one, using that row's `parameters.domain`, found by `act_id` and role. `v.rows` holds it: the consequent row also ends `site_missing`, is acknowledged only with the asked row, and stays its instance's latest request, because every later request resolves a site row first (web/site_actions.go:369; web/api.go:571). Otherwise the row takes the generic sentence (`noticeSentence`, web/requests.go:77-79), because "<domain> was deleted." would name a site that exists; only a stored swap row, which has no act, reaches that branch. `SiteMissing` is raised, or `site_missing` written, only when a console row that the request's workflow names is gone (workflows/request_identity.go:22, workflows/request_activities.go:341, :594, workflows/swap.go:45, workflows/requests.go:842-843). A single-site request names only its own row, so a row that ends `site_missing` while its own site exists can only be a swap's asked row whose parked site was deleted.
|
||||
- **`requestAction`** (web/requests.go:87) takes the row: "restored" requires an active target, an archived site, and a cause other than `instances_swapped`. It tests the cause, not membership, so a later kind of act does not change the verb.
|
||||
- **Dismissal** (`acknowledgeRequest`, web/site_actions.go:737-764) becomes one statement. `AcknowledgeLifecycleRequest` (internal/integration/queries/lifecycle_requests.sql:88-96) keeps its signature and acknowledges every declined or failed, unacknowledged row of the workspace at the address or in the address's act; a subquery finds the act, and a NULL act matches nothing.
|
||||
- **Deleted:** `hasOpenSwap` (web/site_actions.go:1005-1012) and `IsSwapRequestWorkflowID` (workflows/requests.go:97-104). `SwapRequestWorkflowID` keeps its form and only names the Temporal run.
|
||||
|
||||
Alternative considered for the parked-site sentence: one core query per such notice. `v.rows` already holds the row.
|
||||
|
||||
### D13. The sites card while a rotation is pending
|
||||
|
||||
Keep active's render does not change. `CooldownMsg` comes from the stamp (web/partials.go:393), which a success writes (D14), so while a rotation is pending the control that would start one renders enabled: Keep active on the other read-only rows (templates/fedwiki_sites.html:116-127). A click that would be a swap or a return answers the rotation-busy sentence; Keep active on an unmarked read-only row below the limit is a free fill and is recorded (D10). Pending rows show Pending with no actions (web/site_actions.go:841-845). The card polls while a request is open (web/partials.go:416), so the first render after a success that stamps (D14) shows Keep active disabled with the cooldown sentence, when the cooldown is on (web/partials.go:651-653).
|
||||
|
||||
Alternative considered: render the controls disabled with the rotation-busy sentence while a rotation is pending. Rejected, because the proposal's screens list fixes the enabled state of Keep active.
|
||||
|
||||
### D14. The transaction that records a rotation's success writes the stamp
|
||||
|
||||
One rule covers both kinds: the success transaction stamps only when the member's action brought the site into the active set, which the transaction sees as "the row it locked for the chosen site was not active". The wait starts only for a change the member's action made take effect (#328's rule). When the re-upgrade sweep reactivated the site during the farm call, the sweep brought it back, so the member's request changed nothing and nothing is stamped.
|
||||
|
||||
The stamp is `q.UpsertSiteSwapPolicy(ctx, in.WorkspaceID)`, which exists (store/queries/sites.sql:354-358); `console_runtime` holds `fedwiki_writer`, which has every privilege on the table (store/migrations/00001_init.sql:86). Only its comment changes, from "a swap just happened" to "a rotation succeeded".
|
||||
- **Swap.** `RecordSwapActivity` calls it at the end of its `apply` (workflows/swap.go:172-202), after clearing the activated site's mark (:198-200), when the activated row it locked (:181) was not active; it already reads that status (:188). There is no mark test, because a swap's chosen site may carry no mark (D8).
|
||||
- **Return.** `RecordSiteStatusActivity` calls it at the end of its closure (workflows/request_activities.go:386-403), after `SetSiteStatusByID`. It keeps the row `lockRequestSite` returns (discarded at :388), and `isReturn(locked fwmod.LockSiteStatusByIDRow, target string) bool` requires three facts: the row carries `force_reduced_at`, its locked status is not `active`, and the target is `active`. The mark separates a return from a free fill, which this activity also records and which never stamps. It reads the facts before `SetSiteStatusByID` clears the mark (store/queries/sites.sql:411).
|
||||
|
||||
An input flag would not do for a return: the status reconcile passes no `ClearForceReduced` (workflows/requests.go:859-866, :194-198); and the sweep can reactivate the site during the farm call and clear the mark (`SetSiteStatusByDomain`, store/queries/sites.sql:106-113).
|
||||
|
||||
**What follows:**
|
||||
- A refusal writes no stamp: `lockRequestSite` refuses before `apply` writes anything, and a QuotaExceeded from the swap's guard, or a failed finish, rolls the stamp back with the site writes (`apply` runs before the guard, workflows/request_activities.go:216-231).
|
||||
- A lost answer writes no second stamp: when every request holds the outcome, `finishAllWith` returns before `apply` (:213-215).
|
||||
- The worker never reads the cooldown: `Activities` carries none (workflows/activities.go:23-35). Every qualifying success stamps, so a cooldown turned on later measures from the last rotation that succeeded. The stamp's time is `NOW()` of the transaction that commits the success.
|
||||
- No failure stamps (F15-F20). A swap's farm failure or record refusal (workflows/requests.go:678-718) never reaches `RecordSwapActivity`'s commit; a return's gate decline, failed farm call (`statusChangeFailed`, :537-563) or refused record step (:645-650) ends through `FinishLifecycleRequestsActivity`, which runs no `apply`. When `statusChangeFailed` finds the change applied on the farm (:560-561), the run records the success and stamps.
|
||||
|
||||
Alternatives considered:
|
||||
- In the guard: `finishAllWith` skips the guard for a pool with no usage row (:228), `RecordSiteStatusActivity` has no guard, and the write would hold the pool's usage row longer, which every slot gate and recount waits on.
|
||||
- A separate local activity: it adds a command, which needs a version gate (D17), and a second transaction, so a crash between them leaves a success with no stamp.
|
||||
- A hook inside `finishAllWith` after `FinishLifecycleRequest`: it gains nothing and changes a function every outcome shares.
|
||||
- `FinishedAt` as the stamp's time: it is fixed when the local activity is first scheduled, so after a database outage the wait would start before the member could see the success.
|
||||
|
||||
### D15. The outcome transaction takes the policy row after the site rows and before the usage row
|
||||
|
||||
The order is: the lifecycle instance locks, in recorded order; the site rows (`LockSiteStatusByID`, park then activate for a swap); the site writes and, through the trigger, their placement rows; the workspace's policy row; `DeleteSlotHolds`; the usage row (`LockNumericUsage`, the count, the write); the guard; the request rows. The position follows from `apply` running before `DeleteSlotHolds` and the recount (workflows/request_activities.go:216-226).
|
||||
|
||||
The transaction takes no workspace lock. `fedwiki-workspace` comes before `lifecycle` in the family order (docs/database-locks.md:69-70, :81), and intake holds the workspace lock while it waits on instance locks in `CheckSwapRequestSites`, so an outcome that held an instance lock and then waited on the workspace lock could deadlock with intake. Two stamping transactions for one workspace hold disjoint instance locks and site rows (`uq_lifecycle_requests_one_open`) and take the policy row at the same position, so the second waits for the first and no cycle forms. No other path takes the usage row and then waits on the policy row. Intake no longer writes the policy row and reads it without a lock.
|
||||
|
||||
Alternative considered: after the usage row, in the guard (D14).
|
||||
|
||||
### D16. Boot settle finishes an act's requests together
|
||||
|
||||
`SettleOpenRequests` groups the listed rows with `actGroups(rows []integration.LifecycleRequest) [][]integration.LifecycleRequest`; a request with no act, including a stored swap row, is a group of one. For each group, settle describes the workflow of the group's first member once (all members of an act share one workflow id, web/site_actions.go:573, :619, :629); on NotFound it ends the group `failed/not_started` in one `finishAllWith` call; while the workflow runs it does nothing; when the workflow is closed it ends a request that carries an act, with its group, `failed/retries_exhausted` in one call, and a request with no act keeps the create reconcile and the held activation's status reconcile (workflows/settle.go:110-132). A request that carries an act never goes to the status reconcile, which settles one request.
|
||||
|
||||
The group's order is the asked request, then the consequent requests in listing order (`created_at, request_id`, internal/integration/queries/lifecycle_requests.sql:98-105). It matches the order intake records them (web/site_actions.go:619 before :629) and the workflow passes them (`[activate, park]`, workflows/requests.go:664), so it keeps lock rule 6, instance locks in recorded order (docs/database-locks.md:628-629), without relying on `uuidv7` order within one transaction. Both requests share `created_at`, so a listing never holds part of an act, unless a hand edit finished one of them (F26).
|
||||
|
||||
`settledSince` (workflows/settle.go:155-164) takes the group, because `lockOutcomes` refuses a partly finished set (workflows/request_activities.go:273-275). The group is settled when every member reads back as not accepted; a missing or accepted member counts as `FinishErrored`. The counters stay per request, so `Seen` remains their sum.
|
||||
|
||||
Settle passes no `apply` and never stamps: a swap closed without an outcome ends `retries_exhausted` on both requests even if the farm applied it. A swap takes no hold (workflows/settle.go:138-140). A return that holds its slot goes to the status reconcile, which stamps through D14.
|
||||
|
||||
Alternatives considered: fetch an act's unlisted members, which only a hand edit could leave unlisted; keep finishing one row at a time, which could end a swap's two rows in different states.
|
||||
|
||||
### D17. No workflow command changes, so no version gate
|
||||
|
||||
The replay histories (workflows/replay_test.go:54-80) pin the workflow inputs, including `ClearForceReduced` and the eight fields of `SwapSiteRequestInput`, the scheduled activities' names (:91-146), and the local-activity markers of the record steps, each holding an activity id, a type and the result. All eight recorded histories replay at `DefaultVersion`. The stamp inside two local-activity bodies changes what they write, not which commands the workflow issues, and replay uses a marker's recorded result without running the body. A rotation in flight at deploy therefore runs the new record-step body, and its success stamps (F27). Renaming either activity, adding a stamp step or a finish-by-act step would each need a gate, in the style of `slotHoldsVersion` (workflows/requests.go:344-349). `SwapSiteRequestInput` (:163-172) keeps `ParkInstanceID` and `ParkGeneration`: a run in flight builds both references from its recorded input (:662-664), and without the fields it would finish an empty reference and fail with `LifecycleRequestMissing`. The workflow gains no act id. `TestWorkflowHistoriesReplay` (workflows/replay_test.go:37) must pass on the histories as recorded.
|
||||
|
||||
Alternative considered: a version gate around the stamp. Rejected, because no command changes, so the gate would add a replay branch with nothing to branch on.
|
||||
|
||||
### D18. The farm sync keeps the mark only on a row it writes read-only
|
||||
|
||||
`UpsertSiteFromFarm` (store/queries/sites.sql:82-93) writes the farm's status without the rule that `SetSiteStatusByDomain` (:106-113) and `SetSiteStatusByID` (:405-411) apply. Its SET gains:
|
||||
|
||||
```sql
|
||||
force_reduced_at = CASE WHEN excluded.status = 'readonly' THEN fedwiki.sites.force_reduced_at END
|
||||
```
|
||||
|
||||
The sync's only production caller is `upsertCounted` (workflows/sync.go:428-444), reached from `writeStatus` (:513-531) when the row's status differs from the farm's (:365-371). Because `normalizeFarmStatus` maps the farm's `inactive` to `archived` (:26-35), a parked site archived on the farm becomes an archived row that keeps its mark at HEAD.
|
||||
|
||||
The reason is the rule the fedwiki-sites requirement "The quota sweep leaves sites that members are changing" states for every site: a mark is kept only while the site is `readonly` (spec.md:1316). The mark is set only by `SetForceReducedByDomain` and `SetForceReducedByID`, each in the transaction that writes `readonly` (workflows/reconcile.go:277-281, workflows/swap.go:189-192), and every status writer but the sync applies the rule. With the sync following it, an archived row never carries a mark (D10).
|
||||
|
||||
The sync cannot clear a pending return's mark. It skips a domain that has an accepted lifecycle request (workflows/sync.go:352) and checks again under the row's lock (:513-531, `requestOnSite` :540), and a return stays accepted until its success clears the mark (D8). That alone leaves one interleaving: the sync's check finds no request, a return's intake commits, and the sync's write then clears the mark, which would leave an accepted return on an unmarked archived row (F19a). The return's intake therefore holds the site row from its re-check through its commit (D10), and the sync's `LockSiteStatusByDomain` waits for that commit, so the sync's check, made under the lock, sees the accepted request. A return that waited on the row behind a sync's write finds the row archived or unmarked and records nothing.
|
||||
|
||||
Test: a store database test in `store/archive_time_db_test.go`, which already calls `UpsertSiteFromFarm` (:174). A marked row that the sync writes `archived` or `active` loses its mark; one that it writes `readonly` keeps it.
|
||||
|
||||
Alternatives considered:
|
||||
- Keep the query and Restore's rotation branch. Rejected: a member-visible rule (a Restore that waits on the cooldown) would rest on a row state the spec forbids.
|
||||
- Clear the mark in Go after the upsert. Rejected: it writes the same row a second time for a rule that one CASE states.
|
||||
|
||||
## Documents and spec deltas
|
||||
|
||||
This section lists the documents and the spec requirements that the decisions above change.
|
||||
|
||||
**docs/models/provider-integration.md** gains four invariants after invariant 18:
|
||||
- **[db]** A request covers one instance; the act columns are all set or all empty and tied to the header by `(act_id, act_cause)`; an act has at most one `asked` request; a `consequent` request names no person.
|
||||
- **[db-code]** Only `core.record_lifecycle_act` writes the act columns, only on requests its own transaction inserted, so a request joins an act when recorded and never moves; for `instances_swapped` the asked request names the act's actor as its person. `core_writer` holds INSERT and UPDATE only on the columns the request writers name.
|
||||
- **[app]** An action that changes several instances records one request for each in one transaction and groups them under one lifecycle act. Nothing else groups requests: no reader parses a workflow id or reads another request's identity from a request's parameters.
|
||||
- **[app]** An act only ties its requests together. When one request of an action fails, the console undoes the others itself, so a connector applies each request on its own.
|
||||
|
||||
The card's "Lifecycle request" entry (:31), the `core.lifecycle_requests` table row (:53) and per-instance dimension (:119) say a request records the person whose action caused it, or no one when the console added it to a person's act, in place of wording that a person made every request. A "Lifecycle act" entry, the table rows, the writers row (:57) and a request-versus-act dimension follow D1 to D16.
|
||||
|
||||
**docs/models/acts.md:** the summary (:4), the opening (:13, "Only plan acts exist today"), the writers table (:27, :37) and invariants 4 and 5 add the lifecycle act, its lack of a detail table and its writer, and limit the rendezvous rule to plan acts; invariant 2 (:49) says a lifecycle act's requests carry `chk_lifecycle_requests_act_cause` and `lifecycle_request_in_its_act`, so a later lifecycle cause enters that constraint as well as `chk_acts_cause`; a new [db-code] invariant lists the lifecycle writer's refusals; invariant 17 says `core.lifecycle_requests` is outside the record, so an unstarted act's header outlives its requests; "Business time vs wall clock" (:75) gives a lifecycle act's `effective_at` as its asked request's `created_at`. **docs/models/README.md:19** adds the lifecycle acts.
|
||||
|
||||
**docs/database-locks.md:** the workspace lock's row (:32) and "FedWiki at the handler" (:390-404) describe every rotation's intake (D9, D10), with no policy row; the row-lock table (:44-59) gains a "FedWiki swap policy row" entry (taken by both record steps after the site and placement rows and before the usage row; intake reads it without a lock); "When recording an outcome" (:418-436), rule 5 (:621-627) and rule 3's FedWiki clause (:82) place it there and add settle's one `finishAllWith` per act; the unstarted-delete paragraph (:550) adds `DeleteUnstartedLifecycleAct`.
|
||||
|
||||
**docs/building-an-integration.md:591-596:** an action that changes several instances records one request per instance, groups them with `RecordLifecycleAct`, deletes them with `DeleteUnstartedLifecycleAct` when the start is refused as not found, and undoes a succeeded request when another fails. A new lifecycle cause is provider-neutral: one core migration adds it to `chk_acts_cause` and `chk_lifecycle_requests_act_cause`, with its own branch in `core.record_lifecycle_act`, and its constant joins `acts.LifecycleCauses`.
|
||||
|
||||
**Spec deltas.** Each line gives a requirement title, copied from its spec, and what changes. A MODIFIED delta restates the whole requirement, so a rule this change adds goes into the requirement body, not only a scenario.
|
||||
|
||||
*provider-lifecycle-contract*
|
||||
- ADDED "A lifecycle request covers exactly one instance and an act groups an action's requests": the act, its two roles, one asked request, no person on a consequent request; the console undoes the others when one request of an action fails.
|
||||
- MODIFIED "The console owns intent; the provider owns canonical per-instance state": "the lifecycle requests people make" becomes the requests the console records for people's actions.
|
||||
- MODIFIED "A lifecycle request is addressed by an instance identifier the console chooses and a generation": the opening "one request a person makes" and the recorded-fields bullet name the person whose action caused the request, or none for a consequent request.
|
||||
- MODIFIED "A repeated lifecycle request is answered from its record": the act link is not content; a lookup before recording may answer a repeat or conflict, and the recording under the instance lock stays final.
|
||||
- MODIFIED "Lifecycle handlers answer when the workflow starts": the handler deletes all of an act's requests together; settle ends an act's requests in one transaction.
|
||||
|
||||
*desired-state-records*
|
||||
- MODIFIED "A lifecycle request is the record for one instance": the opening sentence; the act columns with their all-or-none shape, the foreign key, one asked request per act, and a null person on a consequent request.
|
||||
- MODIFIED "Recording a lifecycle request answers a repeat from its record": the act link is not content; acknowledging a declined or failed request also acknowledges those of its act.
|
||||
|
||||
*act-records*
|
||||
- MODIFIED "An act is recorded once, in one row that is never changed": a lifecycle act's header is written in the transaction that inserted its requests, after them and before the link; its `effective_at` is its asked request's `created_at`.
|
||||
- MODIFIED "An act's cause comes from a closed list": six causes; `chk_lifecycle_requests_act_cause` mirrors the lifecycle causes; the test compares three lists.
|
||||
- MODIFIED "What an act did is recorded in a detail table for its kind": a lifecycle act has none; its requests, tied by `(act_id, act_cause)`, are what it did.
|
||||
- MODIFIED "The rows an act writes point at it": lifecycle requests join; `core.lifecycle_requests` is outside the act record, so a swap whose workflow cannot start loses its requests and keeps its act (new scenario).
|
||||
- MODIFIED "The act record withholds personal text from the read-only roles": the act columns are listed as `read`.
|
||||
|
||||
*per-schema-roles*
|
||||
- MODIFIED "Writer role grants read-write data access": a third shape, column INSERT and column UPDATE with table SELECT and DELETE.
|
||||
- MODIFIED "Delivery tables and their invoker-rights functions are granted explicitly": on `core.lifecycle_requests`, `core_writer` holds SELECT, DELETE, INSERT on nine columns and UPDATE on four; the scenario "The application role writes the ordinary delivery tables" gains a refused write of `act_id`.
|
||||
- MODIFIED "Act record enclosure": six writers, `core.record_lifecycle_act` asserting no rendezvous; the scenarios naming "the five functions" and temporary-table shadowing cover it.
|
||||
- MODIFIED "The runtime group role's privileges are checked against the catalog": a locked entry names columns for INSERT as well as UPDATE.
|
||||
|
||||
*fedwiki-sites*
|
||||
- MODIFIED "Site lifecycle status is an observed projection" (the requirement that holds the sync's projection): the sync writes a site's mark only while the row it writes is `readonly`; new scenarios: the sync writes a marked site `archived` or `active` and the mark is dropped; the sync writes it `readonly` and the mark is kept.
|
||||
- ADDED "Intake refuses a rotation while another rotation of the workspace is open": every rotation's intake takes the workspace lock and refuses with the rotation-busy sentence, cooldown on or off.
|
||||
- ADDED "Only a rotation that succeeded stamps the swap cooldown": the success transaction stamps when the member's action brought the chosen site into the active set; a failed, declined or unstarted rotation stamps nothing; a return confirmed at boot stamps.
|
||||
- MODIFIED "A FedWiki site has at most one open lifecycle request": a swap is one act of two single-site requests recorded in the workspace-locked transaction with no stamp; the open-rotation refusal replaces the open-swap refusal.
|
||||
- MODIFIED "FedWiki lifecycle requests are recorded under the console's instance identifier and a generation": content names the person, or none for a consequent request, and not the act link.
|
||||
- MODIFIED "A repeated FedWiki lifecycle request is answered from its record": a lookup without the instance lock may answer first; a repeated swap matches by core's rule, because the park site left the parameters.
|
||||
- MODIFIED "FedWiki lifecycle handlers answer when the workflow starts": a swap's two requests are deleted in one statement.
|
||||
- MODIFIED "Each FedWiki lifecycle workflow records its own outcome": the success transaction also writes the stamp, in the body and in the scenario "A swap's retry changes no count"; the in-flight sentence is narrowed to the workflow's commands, because a record step runs the new body and an in-flight rotation's success stamps (D17); new scenario: a swap started by the previous release that succeeds writes the stamp.
|
||||
- MODIFIED "A FedWiki lifecycle request with no outcome is settled at boot": an act's requests settle in one transaction; a status reconcile that records a return's success stamps.
|
||||
- MODIFIED "FedWiki request outcomes show the console's own sentence for a reason code": the parked domain comes from the consequent request of the same act, not the request with the same workflow id; a stored row without an act reads the generic sentence (scenario "Only the parked site disappeared").
|
||||
- MODIFIED "Status and swap intake reads the original sites under the instance locks": "and its cooldown stamp" leaves the body, and the return's intake joins the workspace-locked transaction.
|
||||
- MODIFIED "A pool's site usage is a count taken under its usage row's lock" and "A slot a request holds in flight is a hold its gate stamps": the scenarios that speak of a member's "restore" of a parked read-only site say "Keep active", because Restore acts only on an archived row (D10).
|
||||
|
||||
*plan-downgrade*
|
||||
- MODIFIED "FedWiki site downgrade parks excess sites read-only": the body says the window starts only when a rotation succeeds and its action brought the chosen site into the active set, and that a rotation is refused while another of the workspace is open. A rotation is a Keep active at the limit or on a `force_reduced` site, and a Restore of an archived site is never one (D10, D18). The scenario "Rotating a downgrade-parked reserve in is gated" says "keeps active a `force_reduced` (parked) read-only site" in place of "restores a `force_reduced` (parked) site", and "the Keep active SHALL succeed" in place of "the restore SHALL succeed"; it stamps when that Keep active succeeds. New scenarios: a rotation that failed, was declined or never started leaves the wait as it was; a second rotation while one is open; a closed run that ended `retries_exhausted`; a swap whose chosen site the sweep reactivated stamps nothing.
|
||||
|
||||
No requirement is REMOVED. Every other requirement of these specs and of every other spec was read in full and states none of these rules (`git grep` over `openspec/specs` for the swap keys, the swap prefix, the stamp, the cooldown, `force_reduced_at`, the act writers and the cause list), so it stays as it is. "The FedWiki site list shows open requests on their rows and outcomes as notices" still holds (one notice per swap, and dismissal of both rows), and "The quota sweep leaves sites that members are changing" states the mark rule that D18 makes the sync follow, so it stays as it is.
|
||||
|
||||
## Failure table
|
||||
|
||||
| # | Path | Requests | Header | Stamp | Member sees |
|
||||
|---|---|---|---|---|---|
|
||||
| F1 | Second click of an open or finished swap | unchanged | unchanged | unchanged | list refresh, from the record |
|
||||
| F2 | The address holds other content (a stale tab posting a stored swap's address included) | unchanged | none | unchanged | "This site changed since the list loaded." and a refresh |
|
||||
| F3 | Swap or return while another rotation of the workspace is open, cooldown on or off. When two rotations' intakes run at once, the workspace lock serializes them and the second ends here | rolled back | none | unchanged | the rotation-busy sentence |
|
||||
| F4 | Swap or return inside the window | rolled back | none | unchanged | the cooldown sentence |
|
||||
| F5 | A rotation commits its success before the open-rotation read | cooldown on: rolled back; off: recorded | cooldown on: none; off: a swap's act is written | unchanged | the cooldown sentence / accepted |
|
||||
| F6 | A rotation commits its success between the open-rotation read and the stamp read | rolled back at D9 step 2 | none | unchanged | the rotation-busy sentence |
|
||||
| F7 | No active site of its own; chosen or park site gone; either site busy | rolled back | none | unchanged | D9 steps 4, 6, 7 and 8 |
|
||||
| F8 | Swap: the writer refuses (a code defect) or a database error | rolled back | none | unchanged | "Couldn't change the active site. Try again." |
|
||||
| F9 | Return: a database error in the intake transaction | rolled back | none | unchanged | "Couldn't change which site is active. Try again later." (D10) |
|
||||
| F10 | Free fill during an open rotation | recorded alone | none | unchanged | accepted |
|
||||
| F10a | Restore posted for a row that is not archived | none recorded | none | unchanged | "This site changed since the list loaded." and a refresh |
|
||||
| F11 | Start fails and describe answers NotFound | swap: both deleted in one statement; return: its request deleted | swap: stays | none | "Try again." sentence; the retry is accepted |
|
||||
| F12 | Start NotFound and the delete fails, or the start fails and describe does not answer NotFound | accepted | swap: stays | none | describe does not answer NotFound: accepted. NotFound and the delete fails: the "Try again." sentence, and the retry is answered as a repeat (D11). Pending until the workflow records an outcome or boot settle ends it (F23). Until then every other rotation of the workspace answers the rotation-busy sentence |
|
||||
| F13 | Swap recorded (`RecordSwapActivity` commits), also on a pool with no usage row, or a record answer lost and retried | both succeeded, once | stays | with the success; only the committing attempt writes it | the new active site |
|
||||
| F14 | Swap whose chosen site the re-upgrade sweep reactivated during the farm calls | both succeeded | stays | none | the chosen site active, the parked site read-only |
|
||||
| F15 | Record refused: SiteMissing, SiteAuthorizationError, QuotaExceeded | rolled back; farm restored; both declined | stays | none | one notice on the asked row |
|
||||
| F16 | Farm call SiteMissing for the parked site | farm restored; both `declined/site_missing` | stays | none | "<chosen> wasn't kept active. <parked> was deleted." |
|
||||
| F17 | Farm call SiteAuthorizationError, or another farm error | both declined, or farm restored and both failed | stays | none | one notice; Keep active enabled at once |
|
||||
| F18 | Return succeeds on a marked row that was not active, or its failed farm call reads back as applied | succeeded; mark cleared | none | written | the site, active |
|
||||
| F19 | Return whose site the sweep reactivated during the farm call | succeeded | none | none | the site active; a second rotation of the workspace may be recorded meanwhile (D8) |
|
||||
| F19a | Return's intake meets the sync's write of its site: the sync holds the row first and clears the mark / the return commits first | the return records nothing and answers "This site changed since the list loaded." with a refresh / the sync leaves the row and its mark | none | none | the list refreshes / Pending (D10, D18; `TestReturnWaitsForTheSyncsSiteRow`, `TestSyncLeavesSitesWithOpenRequests_DB`) |
|
||||
| F20 | Return declined or failed at the gate, the farm call or the record step | declined or failed | none | none | one notice; Keep active enabled at once |
|
||||
| F21 | Return closed holding its slot; farm holds it active / otherwise | status reconcile: succeeded / failed, hold removed | none | written at boot / none | the site / one notice |
|
||||
| F22 | Return closed without an outcome, holding no slot | settle: `failed/retries_exhausted` | none | none | one notice |
|
||||
| F23 | Rotation never started (process died after commit) | settle: `failed/not_started`, a swap's two in one transaction | swap: stays | none | one notice |
|
||||
| F24 | Swap workflow closed without an outcome | settle: both `failed/retries_exhausted`, one transaction | stays | none, even if the farm applied it | one notice |
|
||||
| F25 | Settle loses to a concurrent outcome | `settledSince` over the group: an info line | stays | as that outcome wrote it | as that outcome |
|
||||
| F26 | A hand edit finishes one request of an act: before the listing / between the listing and the finish | settle ends the listed request alone by its workflow's state, so the two end in different states / `lockOutcomes` refuses the group and settle counts `FinishErrored` | stays | none | one notice / unchanged |
|
||||
| F27 | An old release's rotation open at deploy | finishes from its input | none | a qualifying success stamps again, except when the old code's record step committed and lost its answer; a failure keeps the intake stamp; a return recorded with the cooldown off stamps for the first time | as before |
|
||||
| F28 | Stored swap rows: the parked row declined or failed and not dismissed / the activated row ended `site_missing` with its site existing | acknowledged by hand (Migration Plan) / unchanged | none | unchanged | no second notice / the generic sentence (D12) |
|
||||
| F29 | Rollback to the previous image after new swaps | old readers miss the link | stays | old intake stamps | two notices for a failed swap and a false "deleted" (Migration Plan, Rollback) |
|
||||
|
||||
## Locks and transactions
|
||||
|
||||
- **Intake:** D9's order for a swap; a return takes D9's first three steps, then its instance lock, then its site row's lock, and records (D10). Both take the workspace lock first. The swap takes no rendezvous, no site-row lock and no policy row; its two recordings take the instance locks `CheckSwapRequestSites` took already, without waiting.
|
||||
- **The writer:** the link UPDATE, the composite foreign key's `FOR KEY SHARE` on the new header and the new unique-index entries touch only this transaction's own rows. The header insert takes `FOR KEY SHARE` on the actor's `core.persons` row (`fk_acts_actor_person_id`, internal/db/migrations/00027_acts.sql:30). PostgreSQL re-runs every foreign-key check on an UPDATE of a row its own transaction inserted, so the link UPDATE takes `FOR KEY SHARE` again on the connection, resource-key, workspace and person rows the request inserts already hold (internal/db/migrations/00024_integration_delivery_core.sql:214-217). The writer waits on nothing the intake did not hold, and needs no place in rule 5 (docs/database-locks.md:621-627), as hold rows need none.
|
||||
- **Outcome:** D15's order. The upsert locks the existing policy row at `FOR NO KEY UPDATE` strength, because it sets no key column, or inserts under the primary key; a second upsert of the same key waits for the first commit. Its foreign key takes `FOR KEY SHARE` on the `core.workspaces` row, which conflicts with neither a request insert's key share nor a non-key update of the workspace.
|
||||
- **Migration:** 00041 holds ACCESS EXCLUSIVE on `core.lifecycle_requests` while it adds the columns and on `core.acts` while it replaces `chk_acts_cause`. It scans every request row to validate the new constraints over all-NULL columns, and every act row to validate the replaced `chk_acts_cause`.
|
||||
|
||||
## What is unverified
|
||||
|
||||
- That `INSERT … ON CONFLICT DO NOTHING RETURNING request_id` needs only the column INSERT grants and table SELECT, and that the `updated_at` trigger works under column UPDATE grants. PostgreSQL documents both; nothing here ran them.
|
||||
- Which tests build a swap by hand. The shared fixture `swapRequests` (workflows/swap_counter_db_test.go:15-20) has fourteen calls in nine files under `internal/integrations/fedwiki/workflows/`; it records each request in its own transaction (workflows/requests_db_test.go:94-110), which the writer refuses, and gives the parked request a person, which `lifecycle_request_consequent_names_no_person` refuses. The rewritten fixture records both requests and the act in one transaction. Tests outside the fixture that build swap rows or assert the swap keys were listed and not read: web/requests_db_test.go:684-689, :1119, :1718, web/quota_rows_db_test.go:150, :206, web/shared_pool_db_test.go:72.
|
||||
- Whether a deployment holds a marked row whose status is not `readonly`: the count in Migration Plan step 1 answers it, and D18's test was not run.
|
||||
- Go SDK replay internals were not read; no input or command changes. No recorded history exists for `ReconcileFedWikiSiteStatusWorkflow`, whose commands do not change.
|
||||
- What the farm sync writes on the two rows after F24, and whether any path deletes a workspace during a rotation (the delete would cascade to the policy row, store/migrations/00001_init.sql:77). Neither behaviour changes.
|
||||
- Whether goose's `Up`, run by the previous image with the ledger one version ahead, reports nothing to run. The previous image's pending check lists only embedded versions the ledger lacks (internal/db/migrations.go:297); goose's source was not read.
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
- [Column grants bind only the runtime role, and most tests log in as the superuser (docs/testing.md:179-185), so a missing grant, now or after a later column, passes the suite and fails in production] → One test runs every lifecycle statement, the writer included, under `SET LOCAL ROLE console_runtime`, and the catalog test pins the lists.
|
||||
- [The xmin test refuses rows written under a savepoint] → No lifecycle recording runs inside one. The production savepoints are the runtime-user checks (internal/db/runtime_user.go:115-117), the grant mark probe (internal/entitlements/grant_acts.go:775) and grant resumption (internal/entitlements/grant_resumption.go:147), and the function's comment says so, as internal/db/migrations/00028_plan_act_obligations.sql:449-452 does. The test kit's `Attempt` and `Refuse` use a savepoint (internal/testkit/dbtest/query.go:201-216), so the writer's tests insert at the top level of the test transaction and call the function under `Refuse`, which is safe because `pg_current_xact_id()` returns the top-level id.
|
||||
- [An intake holds the workspace lock while it waits on an instance lock, and every return now takes the lock] → A return's instance lock is its read-only site's, which the retention purge does not take (it locks archived sites through a farm delete of up to 30 seconds, docs/database-locks.md:488-500), so a return waits only behind another request or outcome on that site, as a return with the cooldown on did at HEAD. Restore, which can meet the purge's lock, takes no workspace lock (D10).
|
||||
- [A rotation whose workflow never started stays open until settle (F12)] → Settle ends it at boot or on its second pass (internal/integrations/fedwiki/fedwiki.go:515-532, :562). At HEAD with the cooldown on, the intake stamp refused the same rotations for the whole window.
|
||||
- [A swap the farm applied, whose workflow closed without an outcome, rotates without starting the wait] → It needs a run terminated by hand, a record step stopped by `LifecycleRequestMissing`, or one that ran out its retry window (workflows/requests.go:54); the boot log counts `Exhausted`, and the proposal accepts it.
|
||||
- [A return confirmed at boot after an outage stamps at boot] → The member saw Pending until then.
|
||||
- [An open swap stored before the deploy has no act, so test (a) never sees it, and test (b) misses it when its chosen site carries no mark] → Step 1 gates the deploy on a zero count. Step 3 explains why a swap recorded between the count and the stop is safe.
|
||||
- [Old and new releases together: a new intake whose success an old worker records writes no stamp] → The old release stops before the new one starts (docs/production-deployment.md, section 5).
|
||||
|
||||
## Migration Plan
|
||||
|
||||
Stored swap requests are not converted. A deployment whose step-1 counts are all zero (open swaps, open returns, marked rows that are not read-only) and whose step-4 listing is empty needs only step 7 and step 3's count of the marked rows that are not read-only, beyond stopping the old release, migrating and starting (steps 2 and 5), which every upgrade runs.
|
||||
|
||||
1. **Count, read-only, before stopping the old release** (`console_reader` can run it):
|
||||
```sql
|
||||
SELECT 'swap' AS kind, count(*) FROM core.lifecycle_requests lr
|
||||
WHERE lr.status = 'accepted'
|
||||
AND (lr.workflow_id LIKE 'swap-fedwiki-site-%'
|
||||
OR lr.parameters ?| ARRAY['swap_park_site_id','swap_activate_site_id'])
|
||||
UNION ALL
|
||||
SELECT 'return', count(*) FROM core.lifecycle_requests lr
|
||||
JOIN fedwiki.sites s ON s.site_id = lr.instance_id
|
||||
WHERE lr.status = 'accepted' AND lr.operation = 'set_status'
|
||||
AND lr.parameters->>'status' = 'active'
|
||||
AND s.force_reduced_at IS NOT NULL
|
||||
AND lr.workflow_id NOT LIKE 'swap-fedwiki-site-%';
|
||||
```
|
||||
Deploy only when both counts are 0: a stored open swap has no act, so the new intake may not see it, and a stored swap, or a stored return recorded with the cooldown on, was stamped at intake, so a later failure keeps that wait. The existing rollback check (no accepted request at all) is stricter and also satisfies this gate.
|
||||
|
||||
Then run a second read-only count, of the marked rows that are not read-only:
|
||||
```sql
|
||||
SELECT count(*) FROM fedwiki.sites
|
||||
WHERE force_reduced_at IS NOT NULL AND status <> 'readonly';
|
||||
```
|
||||
When it is not zero, step 3 clears those marks.
|
||||
Once the new release runs, an accepted Restore on such a row would match test (b) of D8 and refuse the workspace's other rotations until it finishes, and its success would stamp the cooldown (D14). The hand fix is the whole remedy; the code carries no compatibility path (D18).
|
||||
2. **Stop every process of the old release.**
|
||||
3. **Count again,** the marked rows that are not read-only included, because the old release's sync may have written one more before it stopped; as the runtime user, in the stop window, clear what that count finds:
|
||||
```sql
|
||||
UPDATE fedwiki.sites SET force_reduced_at = NULL
|
||||
WHERE force_reduced_at IS NOT NULL AND status <> 'readonly';
|
||||
```
|
||||
A rotation recorded between the count and the stop finishes from its input on the new code (D17). Such a swap has no act, so test (a) misses it, and test (b) misses it when its chosen site carries no mark; until it finishes, its workspace can record a second rotation. That is safe: `uq_lifecycle_requests_one_open` keeps the two rotations on disjoint instances, the swap's guard bounds the pool, and each qualifying success stamps. If the swap fails, its workspace keeps the old intake stamp; deleting that workspace's `fedwiki.site_swap_policy` row by hand lets the member rotate at once, and erases any earlier wait.
|
||||
4. **List the stored parked-site requests**, read-only, and acknowledge them as the runtime user in the stop window; `core_writer` keeps UPDATE on `acknowledged_at` under either schema:
|
||||
```sql
|
||||
SELECT request_id, workspace_id, instance_id, status, reason_code, finished_at
|
||||
FROM core.lifecycle_requests
|
||||
WHERE parameters ? 'swap_activate_site_id'
|
||||
AND status IN ('declined','failed') AND acknowledged_at IS NULL
|
||||
ORDER BY finished_at;
|
||||
|
||||
UPDATE core.lifecycle_requests SET acknowledged_at = NOW()
|
||||
WHERE parameters ? 'swap_activate_site_id'
|
||||
AND status IN ('declined','failed') AND acknowledged_at IS NULL;
|
||||
```
|
||||
5. **Migrate** to 00041, then **start** the new release.
|
||||
6. **Once every rotation counted in step 3 has finished,** run the listing of step 4 again and acknowledge what it finds; a stored swap whose farm cannot answer keeps retrying, so its parked row can end declined or failed long after the start.
|
||||
7. **Run `scripts/db-reader-role.sql` again**; until then `console_reader` cannot read the three columns.
|
||||
|
||||
**Rollback** is the previous image on the 00041 schema, once no lifecycle request is open:
|
||||
- The previous image's statements fit the column grants: its INSERT names exactly the nine granted columns, its UPDATEs set only the four granted ones, it never reads the new columns (sqlc expanded `SELECT *` and `lr.*` into the sixteen old ones, internal/integration/lifecycle_requests.sql.go:142, :417), and its boot check probes only `pool_provisions` INSERT and four other privileges (internal/db/runtime_user.go:630-655).
|
||||
- What degrades: its notice list filters on `swap_activate_site_id`, which a new swap lacks, so a failed or declined new swap shows two notices that its dismissal does not pair, and a new swap declined `site_missing` because its parked site was deleted reads "<chosen> was deleted." (web/site_actions.go:893-894), naming a site that exists. Its open-swap test still sees a new swap by the workflow-id prefix, and it stamps at intake again; stamps written at success stay valid.
|
||||
- Acknowledge the unpaired rows by hand: rows with `act_role = 'consequent' AND status IN ('declined','failed') AND acknowledged_at IS NULL`, and rows with `act_role = 'asked' AND reason_code = 'site_missing' AND acknowledged_at IS NULL` whose own `fedwiki.sites` row still exists (only a deleted parked site leaves it in place).
|
||||
- Rolling forward again repeats steps 1 to 7. The Down runs only before the first lifecycle act (D6).
|
||||
|
||||
## Open Questions
|
||||
|
||||
None.
|
||||
@@ -0,0 +1,216 @@
|
||||
## Why
|
||||
|
||||
A FedWiki workspace has as many active sites as its plan's limit allows; its other sites are read-only. A member can bring a read-only site back with Keep active.
|
||||
|
||||
When the pool is at its limit, Keep active is a **swap**. It parks the workspace's least recently modified active site (sets it read-only) and activates the chosen one. The console records a swap as two `set_status` lifecycle requests, one for each site, and records nothing for the swap itself.
|
||||
|
||||
Conventions hold the two requests together:
|
||||
- they share a workflow id, and its prefix marks a swap;
|
||||
- each request names the other site in its parameters (`swap_park_site_id`, `swap_activate_site_id`).
|
||||
|
||||
Four readers rebuild the swap from those conventions:
|
||||
- the refusal of a second swap;
|
||||
- the dismissal of a swap's notice;
|
||||
- the notice list, which leaves the parked site's request out;
|
||||
- the action a notice names ("restored" or "kept active").
|
||||
|
||||
FedWiki also keeps its own copy of the rule that answers a repeated request (`sameRowRequest`). That copy compares only the operation, the person, the domain and the target status. FedWiki needs it because core's rule (`sameLifecycleContent`) compares every parameter, and the activated site's parameters name the park site. The console chooses the park site when it records the first click, so a repeated click would never match (#184).
|
||||
|
||||
The published protocol (#171) will fix the shape of a lifecycle request for applications outside the console. Before it does, the provider integration model (`docs/models/provider-integration.md`) has to say whether one request can cover several instances. If it cannot, the model has to say what holds one action's requests together.
|
||||
|
||||
A workspace also waits a set period between two **rotations**, which the plan-downgrade spec defines as changes that bring a different site into the active set. There are two kinds:
|
||||
- a swap;
|
||||
- a **return**: Keep active below the limit on a read-only site that a plan downgrade or an earlier swap parked, which still carries its `force_reduced_at` mark.
|
||||
|
||||
The waiting period is the swap cooldown (`fedwiki-swap-cooldown`, 30 days by default). The console starts it by writing the time to `fedwiki.site_swap_policy` (the stamp).
|
||||
|
||||
A swap writes the stamp in the transaction that records its requests, before their workflow starts. A return does the same when the cooldown is on. Nothing ever removes the stamp. So a rotation still starts the wait when:
|
||||
- its workflow cannot start, after the member is told "Couldn't change the active site. Try again." or "Couldn't update the site. Try again.";
|
||||
- or it runs and fails or is declined.
|
||||
|
||||
The member's retry is then refused with the cooldown sentence, "The active site changes once every N day(s); try again in about M day(s).", until the period ends (#328).
|
||||
|
||||
## What Changes
|
||||
|
||||
- **A lifecycle request covers exactly one instance.** `docs/models/provider-integration.md` states this as an invariant. #171 is handed the rule for the protocol (see Related issues).
|
||||
- **An act groups the requests one action records.** An act is the existing header row for an action that writes several rows: `core.acts` records who acted, when, and why, with the reason drawn from a closed list of causes.
|
||||
- A swap records one act under a new provider-neutral cause, `instances_swapped`, and both of its requests point at it.
|
||||
- Each request in an act has a role:
|
||||
- the `asked` request is for the instance the actor chose;
|
||||
- a `consequent` request is for an instance the console added to carry the action out.
|
||||
|
||||
In a swap, the asked request activates the site the member chose, and the consequent request parks the site the console chose.
|
||||
- A swap's act is recorded when the swap is requested, and its `effective_at` is that time. Whether the swap succeeded is read from its requests.
|
||||
- Nothing else groups requests. No reader parses a workflow id or reads another row's identity from a request's parameters.
|
||||
- **One enclosed database function writes a lifecycle act.**
|
||||
- `core.record_lifecycle_act` is owned by `core_owner` and runs with its rights. It inserts the act header, then links the requests to it.
|
||||
- It refuses a request that the same transaction did not insert, so a link can never be added later or moved.
|
||||
- It is the only writer of the act columns on `core.lifecycle_requests`. `core_writer` keeps INSERT and UPDATE on the columns it writes today, instead of on the whole table, and keeps DELETE.
|
||||
- Unlike `core.record_plan_act`, it does not assert the materialization rendezvous. Lock rule 1 in `docs/database-locks.md` puts the rendezvous first in any transaction that takes it. A swap's transaction starts with the FedWiki workspace lock, so it cannot hold the rendezvous.
|
||||
- **The park site leaves the request parameters.**
|
||||
- The activated site's request no longer carries `swap_park_site_id`, and the parked site's request no longer carries `swap_activate_site_id`.
|
||||
- Core's repeat rule then answers every repeated swap. A new core lookup answers a repeat before anything is recorded, and `sameRowRequest` is deleted.
|
||||
- **The parked site's request names no requesting person.** The console chose that site, so the request does not claim the member asked for it. The act's actor is the member.
|
||||
- **Readers find a swap through its act.**
|
||||
- The refusal of a second swap, the dismissal, the notice list, the notice that names a deleted parked site, and the action a notice names all read the act and each request's role.
|
||||
- Dismissing a swap's notice still acknowledges the parked site's request too.
|
||||
- `IsSwapRequestWorkflowID` is deleted, and so is the prefix test it performs. The swap's workflow id keeps its form, `swap-fedwiki-site-<site_id>-<generation>`, and only names the Temporal run. No reader parses it.
|
||||
- **An act's requests are settled together.**
|
||||
- When the console starts, it settles each request whose workflow is gone. It now finishes all of an act's requests in one transaction, instead of one request at a time.
|
||||
- When a swap's workflow cannot start, its requests are deleted together (see Ride-alongs). The act header stays as the record of what was asked, because an act header is never deleted.
|
||||
- **The protocol gets the grouping rule, not the swap policy.** #171 is handed four points:
|
||||
- a request covers one instance;
|
||||
- an act id ties together the requests of one action;
|
||||
- when the console records an action as several requests, it undoes the others itself when one fails. For example, a swap that parked one site and could not activate the other sends the parked site back;
|
||||
- a connector therefore applies each request on its own.
|
||||
|
||||
Whether a connector may instead park a site on its own is part of #172 (see Out of scope).
|
||||
|
||||
## Ride-alongs
|
||||
|
||||
- **Only a rotation that succeeded starts the cooldown (#328).**
|
||||
- Both kinds of rotation now stamp in the transaction that records their success: `RecordSwapActivity` for a swap, `RecordSiteStatusActivity` for a return.
|
||||
- A rotation that never started, failed, or was declined leaves the wait as it was, so the member can follow "Try again.".
|
||||
- A swap whose workflow closed without recording an outcome ends `retries_exhausted` at boot and stamps nothing, even if the farm applied it.
|
||||
- A return in that state that still holds its activation slot is checked against the farm at boot instead; one that holds no slot ends `retries_exhausted` and stamps nothing. When that check records the return's success, it also stamps the cooldown and clears the site's `force_reduced_at` mark. It reads the mark from the site row it locked, because the check's input carries no rotation flag.
|
||||
- Both kinds stamp, whether or not the cooldown is on, only when the member's action brought the chosen site into the active set: the transaction that records the success sees that the row it locked for the chosen site was not active. A swap whose chosen site the re-upgrade sweep (which reactivates parked sites when the plan's limit rises) reactivated during the farm calls stamps nothing, because the sweep, not the member, brought the site back. Today a swap stamps even with the cooldown off, and a return only with it on. A cooldown turned on later therefore measures from the last rotation that succeeded.
|
||||
- **Intake refuses a rotation while another rotation of the workspace is open.**
|
||||
- Moving the stamp removes the guard that refused most concurrent rotations. Until now, a second swap was refused by the open-swap check. With the cooldown on, the stamp written at intake refused every other case through the cooldown sentence, with no check of its own: a second return, a return during an open swap, and a swap during an open return. With the cooldown off, nothing refused those three cases.
|
||||
- Intake now extends the open-swap refusal to every rotation, whether or not the cooldown is on, with the existing sentence "A change to your active site is already in progress". Every rotation's intake therefore takes the FedWiki workspace lock, which a return with the cooldown off does not take today. Intake reads the open rotations before the stamp, so a rotation that commits its success between the two reads is still seen.
|
||||
- **The farm sync keeps a site's mark only on a row it writes read-only (#329).** `UpsertSiteFromFarm` writes the farm's status without the rule that every other status write applies, so a parked site that the farm sync finds archived or active keeps its `force_reduced_at` mark. The query gains that rule. It rides here because this change decides which rows count as a return, and Restore on an archived row counted as one only because of this defect. With the fix an archived row never carries a mark, Restore never rotates, and the template's Restore gate goes. The sync skips a site with an open request, so the fix cannot clear the mark of a return that is still pending.
|
||||
- **An unstarted swap's two requests are deleted in one statement.** Today each request is deleted in its own statement, outside a transaction, and errors are only logged. If the second delete fails, one request is gone and the other stays accepted, so the parked site shows Pending until the console next starts.
|
||||
|
||||
## Strings
|
||||
|
||||
- **New:** none.
|
||||
- **Wider reach:**
|
||||
- "A change to your active site is already in progress" now also answers a Keep active that would be a swap or a return while another rotation of the workspace is open, whether or not the cooldown is on. With the cooldown on, the cooldown sentence answered most of these cases before; with it off, nothing refused them.
|
||||
- "Couldn't change which site is active. Try again later." now answers a database error in the transaction that records every return, where a return with the cooldown off answered "Couldn't update the site. Try again.". A free fill, Restore and an archive keep the second sentence.
|
||||
- **Kept, narrower reach:** the cooldown sentence no longer shows while a rotation is pending, and never follows a rotation that did not succeed.
|
||||
- **Kept:**
|
||||
- every swap and return notice;
|
||||
- "Couldn't change the active site. Try again." (a swap) and "Couldn't update the site. Try again." (a return), whose retry is now accepted.
|
||||
|
||||
### Visible changes for the screens review
|
||||
|
||||
- **While a rotation is pending, with the cooldown on:**
|
||||
- Keep active on the workspace's other read-only rows renders enabled, where it used to render disabled with the cooldown sentence (`templates/fedwiki_sites.html` disables it for every read-only row while the cooldown message is set). A click that would be a swap (the pool is at its limit) or a return (a marked site below the limit) answers "A change to your active site is already in progress". A click on an unmarked row below the limit is a free fill and is recorded.
|
||||
- Keep active renders disabled with the cooldown sentence from the first render after a rotation succeeds and starts the wait, and only while the cooldown is on.
|
||||
- The pending rows still show Pending and no actions.
|
||||
- **After a rotation that failed to start, failed or was declined:** Keep active is enabled again at once.
|
||||
- **Restore on an archived site** behaves the same whether or not a downgrade or a swap once parked it: the wait never disables it, and it never starts the wait.
|
||||
- **Everything else:** no change. The notices, the dismissal and the Pending badges look the same.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
None.
|
||||
|
||||
### Modified Capabilities
|
||||
|
||||
- `provider-lifecycle-contract`:
|
||||
- a request covers one instance and records the person whose action caused it, or no one when the console added it to a person's act;
|
||||
- an act groups the requests of one action;
|
||||
- an act's requests are deleted together when their workflow cannot start, and settled together;
|
||||
- a repeat can be answered before anything is recorded.
|
||||
- `desired-state-records`: a lifecycle request records its act and its role in it, and neither is part of the request's content.
|
||||
- `act-records`:
|
||||
- a second kind of act, `instances_swapped`, which has no detail table: its lifecycle requests, tied to it by `(act_id, act_cause)`, are what it did;
|
||||
- lifecycle requests join the rows that point at an act;
|
||||
- `core.lifecycle_requests` is not a table of the act record, as `core.grants` is not, so deleting an unstarted request leaves the record whole and the header can outlive it;
|
||||
- a lifecycle act takes effect when it is requested;
|
||||
- its columns join the columns the act record lists as readable by `console_reader`.
|
||||
- `per-schema-roles`:
|
||||
- a sixth enclosed act writer, which asserts no materialization rendezvous;
|
||||
- the delivery-table grants give `core_writer` column INSERT and column UPDATE and table DELETE on `core.lifecycle_requests`;
|
||||
- the runtime role's catalog check allows that table as a locked entry with column INSERT and UPDATE.
|
||||
- `fedwiki-sites`:
|
||||
- a swap is one act over two single-site requests;
|
||||
- the park site leaves the parameters, and the parked site's request names no person;
|
||||
- the open-swap refusal, the dismissal and the notices read the act;
|
||||
- the cooldown stamp moves to a rotation's success, including a return confirmed at boot;
|
||||
- the farm sync keeps a site's mark only on a row it writes read-only;
|
||||
- the open-rotation refusal covers every rotation, with the workspace lock taken whether or not the cooldown is on.
|
||||
- `plan-downgrade`:
|
||||
- only a rotation that succeeded starts the cooldown;
|
||||
- a rotation is refused while another rotation of the workspace is open.
|
||||
|
||||
## Impact
|
||||
|
||||
- **Migration `00041` (core):**
|
||||
- act columns on `core.lifecycle_requests` for the act id, the cause and the role, with:
|
||||
- an all-or-none check;
|
||||
- the composite foreign key to `core.acts`;
|
||||
- one asked request per act;
|
||||
- a check that a consequent request names no person;
|
||||
- an index for finding an act's requests;
|
||||
- `chk_acts_cause` replaced to add `instances_swapped`, while `chk_plan_act_details_cause` keeps the plan causes;
|
||||
- `core.record_lifecycle_act`;
|
||||
- the narrowed grants.
|
||||
- **Code:**
|
||||
- `internal/integration/lifecycle.go` and `queries/lifecycle_requests.sql`:
|
||||
- the recording's answer carries the request id;
|
||||
- the repeat lookup;
|
||||
- the act writer's wrapper;
|
||||
- the delete by act;
|
||||
- the acknowledgement by act;
|
||||
- settling by act;
|
||||
- `internal/entitlements/act_cause.go`: the cause list moves out of `internal/entitlements`, and its comment no longer says a new kind replaces both cause constraints;
|
||||
- `internal/integrations/fedwiki/web/site_actions.go`, `requests.go` and `api.go`:
|
||||
- intake;
|
||||
- the open-rotation refusal;
|
||||
- the notice list and its sentences;
|
||||
- the dismissal;
|
||||
- the JSON delete's repeat answer;
|
||||
- `RestoreSite` passes no rotation and answers a row that is not archived as changed;
|
||||
- `internal/integrations/fedwiki/workflows/requests.go`, `swap.go`, `request_activities.go` and `settle.go`: the stamp in `RecordSwapActivity` and `RecordSiteStatusActivity`, and settling by act;
|
||||
- `internal/integrations/fedwiki/store/queries/sites.sql`: `UpsertSiteFromFarm` keeps the mark only when it writes `readonly`;
|
||||
- `internal/integrations/fedwiki/templates/fedwiki_sites.html` and `web/partials.go`: the Restore gate, `RestoreControl` and `IsForceReduced` go;
|
||||
- `internal/migrate/testdata/console-reader-columns.txt`: the act columns, readable.
|
||||
- **Temporal:**
|
||||
- No workflow command changes. The stamp moves inside two existing local activities, and `SwapSiteRequestInput` keeps every field, so the recorded replay histories still replay.
|
||||
- A swap already running at deploy finishes the two requests named in its input.
|
||||
- **Tests:**
|
||||
- The shared swap fixture (`swapRequests`) records an act.
|
||||
- Rewritten:
|
||||
- the assertions that compare the park row's workflow id, tell a swap apart by `SwapRequestWorkflowID`, or set `SwapParkSiteID`;
|
||||
- `TestActCausesMirrorTheConstraints`, split so `chk_acts_cause` lists every cause and `chk_plan_act_details_cause` the plan causes;
|
||||
- `TestRuntimeRolePrivileges`' locked list and column check;
|
||||
- `TestDeliveryTablePrivileges`;
|
||||
- the render test that checks Keep active's and Restore's disabled controls, which keeps Keep active's half.
|
||||
- New:
|
||||
- the refusal of a second swap, which no test reaches today;
|
||||
- two concurrent returns;
|
||||
- a return during an open swap, and a swap during an open return;
|
||||
- a rotation that failed to start, failed or was declined, leaving the wait as it was;
|
||||
- a return confirmed at boot stamping the cooldown;
|
||||
- the writer function's refusals;
|
||||
- a store database test: a marked site that the sync writes archived or active loses its mark, and one it writes read-only keeps it;
|
||||
- the narrowed grants.
|
||||
- **Docs:**
|
||||
- `docs/models/provider-integration.md` and `docs/models/acts.md`, plus the Acts entry in `docs/models/README.md`;
|
||||
- `docs/database-locks.md`:
|
||||
- the workspace lock serializes the open-rotation check for every rotation, not the cooldown check and stamp;
|
||||
- a return takes it whether or not the cooldown is on;
|
||||
- the stamp leaves intake;
|
||||
- the outcome transaction's order gains the policy row, and the row-lock table gains an entry for it;
|
||||
- `docs/building-an-integration.md`: an action that records several requests records an act.
|
||||
- **Deploy:**
|
||||
- Stored swap requests are not converted.
|
||||
- Before deploying, count the marked sites that are not read-only (`SELECT count(*) FROM fedwiki.sites WHERE force_reduced_at IS NOT NULL AND status <> 'readonly'`). When the count is not zero, clear those marks by hand before the new release starts. Otherwise an accepted Restore on such a site would be taken for a return: it would refuse the workspace's other rotations until it finishes and would start the wait. The code carries no compatibility path.
|
||||
- Before deploying, count the open swaps and returns read-only, and deploy when none is open. A rotation recorded between the count and the stop of the old release finishes from its input. If it then fails, its workspace keeps the cooldown that the old intake stamp started.
|
||||
- Afterwards, acknowledge by hand every stored parked-site request that ended declined or failed and is not yet dismissed. It has no act, so the notice list no longer leaves it out, and its notice would appear beside the swap's own.
|
||||
- Run `scripts/db-reader-role.sql` again after migrating.
|
||||
|
||||
## Out of scope
|
||||
|
||||
- **Where the swap policy lives once FedWiki connects through the protocol (#172).** The policy is three rules: which site a swap parks, the cooldown, and the refusal of a second rotation while one is open. The two options are a console-side rotation rule over a list of instances, or a connector that parks a site on its own. Until #172 decides, all three stay in FedWiki.
|
||||
- **Instance locks on the unstarted delete (#229).** Deleting an unstarted request still takes no instance lock, so the delete can race another write to the same instance. The delete by act keeps that race, and #229 adds the locks.
|
||||
- **FedWiki's other request rules (#174).** `sameCreate`, the JSON delete's second read of the request outside the instance lock, and `finishAllWith`'s Go copy of the rule for which requests may be finished stay for #174, which moves FedWiki onto the protocol.
|
||||
|
||||
## Related issues
|
||||
|
||||
- **Closed by this change:** #184, #328 and #329.
|
||||
- **#171:** a comment with the grouping rule above.
|
||||
- **#172:** a comment that the swap policy's home is its question.
|
||||
@@ -0,0 +1,145 @@
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: An act is recorded once, in one row that is never changed
|
||||
|
||||
An action that writes several rows SHALL record itself in one row of `core.acts`, written in the same transaction as the rows it causes. A plan act's row SHALL be written in the same transaction as the first row it causes and before any row that refers to it. A lifecycle act's row (an act whose rows are lifecycle requests) SHALL be written by `core.record_lifecycle_act` in the transaction that inserted the act's lifecycle requests, after those requests are inserted and before the link that makes them refer to the act; the function SHALL refuse a request that its own transaction did not insert. The row SHALL carry the act's identifier (a UUIDv7), its cause, its actor, an optional note, the identifier of the request that made it when there is one, the time the act takes effect (`effective_at`) and the time the row was written (`created_at`). A lifecycle act's `effective_at` SHALL be the `created_at` of its asked request, so the act takes effect when it is requested. No process SHALL update or delete an act row, and the application's database role SHALL hold no privilege that would let it: progress, counts and outcomes SHALL be derived from the rows that point at the act, never stored on it.
|
||||
|
||||
#### Scenario: A committed act writes one row
|
||||
|
||||
- **WHEN** an operator commits an org type's default change
|
||||
- **THEN** exactly one `core.acts` row is written for it, in the commit's transaction
|
||||
- **AND** its cause, actor, effective time and write time are set
|
||||
|
||||
#### Scenario: A swap's act is written after its requests
|
||||
|
||||
- **WHEN** a member's swap commits two lifecycle requests and its act in one transaction
|
||||
- **THEN** exactly one `core.acts` row with cause `instances_swapped` is written for it, after both requests are inserted
|
||||
- **AND** its actor is that member
|
||||
- **AND** its `effective_at` equals the `created_at` of the asked request
|
||||
- **AND** both requests carry its id
|
||||
|
||||
#### Scenario: A request an earlier transaction inserted is not linked
|
||||
|
||||
- **WHEN** `core.record_lifecycle_act` is called naming a lifecycle request that an earlier transaction inserted
|
||||
- **THEN** the function refuses
|
||||
- **AND** no `core.acts` row is written for the call
|
||||
|
||||
#### Scenario: An act row is never rewritten
|
||||
|
||||
- **WHEN** the organizations an act reached are settled minutes after it committed
|
||||
- **THEN** no column of its `core.acts` row changes
|
||||
- **AND** an attempt by the application's role to update or delete the row is refused by the database
|
||||
|
||||
#### Scenario: A lifecycle act's row is not rewritten when its requests finish
|
||||
|
||||
- **WHEN** both requests of a swap's act end, succeeded, declined or failed
|
||||
- **THEN** no column of the act's `core.acts` row changes
|
||||
|
||||
### Requirement: An act's cause comes from a closed list
|
||||
|
||||
`core.acts.cause` SHALL be a `VARCHAR` constrained by a `CHECK` listing every cause, not an enumerated type and not a lookup table. The causes SHALL be exactly `tier_added`, `tier_removed`, `tiers_reordered`, `org_type_default_changed`, `plan_act_retried` and `instances_swapped` until a later change adds its own by replacing the constraint in its own core migration. Causes SHALL name what happened in the past tense and SHALL name no provider. `chk_lifecycle_requests_act_cause` on `core.lifecycle_requests` SHALL list exactly the lifecycle causes, today `instances_swapped`, and `chk_plan_act_details_cause` SHALL list exactly the plan causes. A later lifecycle cause SHALL enter both `chk_acts_cause` and `chk_lifecycle_requests_act_cause` in its own core migration, with its own branch in `core.record_lifecycle_act`, which SHALL refuse every cause it has no branch for. The Go code SHALL mirror the lists as typed constants, and a test SHALL compare the constants with the constraints' definitions in a migrated database: every cause with `chk_acts_cause`, the plan causes with `chk_plan_act_details_cause` and the lifecycle causes with `chk_lifecycle_requests_act_cause`.
|
||||
|
||||
#### Scenario: An unknown cause is refused
|
||||
|
||||
- **WHEN** a row is inserted into `core.acts` with a cause the constraint does not list
|
||||
- **THEN** the database refuses the insert
|
||||
|
||||
#### Scenario: The Go lists and the database lists agree
|
||||
|
||||
- **WHEN** the test reads `chk_acts_cause`, `chk_plan_act_details_cause` and `chk_lifecycle_requests_act_cause` from a migrated database
|
||||
- **THEN** the values of `chk_acts_cause` are exactly the Go cause constants
|
||||
- **AND** the values of `chk_plan_act_details_cause` are exactly the Go plan causes
|
||||
- **AND** the values of `chk_lifecycle_requests_act_cause` are exactly the Go lifecycle causes
|
||||
|
||||
#### Scenario: A plan cause is not a lifecycle cause
|
||||
|
||||
- **WHEN** `core.record_lifecycle_act` is called with each plan cause in turn
|
||||
- **THEN** the function refuses every call
|
||||
- **AND** no `core.acts` row is written
|
||||
|
||||
### Requirement: What an act did is recorded in a detail table for its kind
|
||||
|
||||
What a plan act did, beyond its header, SHALL be recorded in one detail table per kind of plan act, keyed by the act's id and tied to its act row by a composite foreign key on `(act_id, cause)`, so a detail row can belong only to an act of its own kind. A lifecycle act SHALL have no detail table: its lifecycle requests, each tied to its act row by the composite foreign key `lifecycle_request_in_its_act` on `(act_id, act_cause)`, are what it did, so a request can belong only to an act of the cause it states. Detail SHALL NOT be stored as JSONB. A detail row SHALL refer to catalog rows (ladders, products, org types) by id with no foreign key, beside the name each had when the act committed, so the record outlives a deleted or renamed catalog row and reads as it read then. A provider-specific detail table SHALL live in its provider's schema with a foreign key to `core.acts`.
|
||||
|
||||
#### Scenario: A detail row cannot belong to another kind's act
|
||||
|
||||
- **WHEN** a plan act detail row is inserted with a cause other than its act row's cause
|
||||
- **THEN** the database refuses the insert
|
||||
|
||||
#### Scenario: A deleted ladder leaves its acts readable
|
||||
|
||||
- **WHEN** a tier was added to a ladder and the ladder is later deleted
|
||||
- **THEN** the tier add's detail row still names the ladder by the name it had when the tier was added
|
||||
- **AND** the ladder's deletion is not refused because of the record
|
||||
|
||||
#### Scenario: A lifecycle act's requests are what it did
|
||||
|
||||
- **WHEN** a member's swap commits
|
||||
- **THEN** exactly two lifecycle requests carry its act's id, one with role `asked` and one with role `consequent`
|
||||
- **AND** no plan act detail row names the act
|
||||
|
||||
#### Scenario: A lifecycle request cannot belong to an act of another cause
|
||||
|
||||
- **WHEN** a lifecycle request is written with an `act_cause` that differs from the cause of the act row its `act_id` names
|
||||
- **THEN** the database refuses the write
|
||||
|
||||
### Requirement: The rows an act writes point at it
|
||||
|
||||
Every row an act inserts to record what happened or what was decided SHALL carry the act's id: its detail row, the org types it reaches, its records of organizations without a default pool, its obligations, every grant it creates (`core.grants.act_id`, a nullable foreign key to `core.acts`, nullable because other writers of grants do not record an act yet) and every lifecycle request of a lifecycle act. A lifecycle request SHALL carry its act's id, the act's cause and its role in the act (`asked` or `consequent`) in the columns `core.lifecycle_requests.act_id`, `act_cause` and `act_role`, which are all set or all NULL, and are NULL for a request that belongs to no act. Only `core.record_lifecycle_act` SHALL set them, and only on requests that its own transaction inserted, so a request joins an act only in the transaction that records it, and never moves to another act, leaves its act or joins one later. A grant that the default floor creates inside an act SHALL stay system-authored, with no granting person, while its `act_id` names the act. Catalog rows, rows of current state (provisions, positions, materialized entitlements) and the desired-state outbox SHALL NOT point at an act; the act's detail row records the catalog change. Transition rows SHALL point at their act once the functions that write them are replaced to do so; until then a transition SHALL name its act through its reason text.
|
||||
|
||||
`core.lifecycle_requests` SHALL NOT be a table of the act record, as `core.grants` is not. The application's role MAY delete lifecycle requests that never started, including all the requests of one lifecycle act in one statement, and that deletion SHALL leave the record whole: the act's row stays, unchanged, with no row pointing at it. No lifecycle request that belongs to an act SHALL be deleted apart from the others of its act.
|
||||
|
||||
#### Scenario: A default grant points at the act that conferred it
|
||||
|
||||
- **WHEN** an org type's default change initiates a plan-less organization onto the new default
|
||||
- **THEN** the default grant it creates carries that act's id
|
||||
- **AND** its `granted_by_person_id` is NULL
|
||||
|
||||
#### Scenario: A tier row does not point at its act
|
||||
|
||||
- **WHEN** a tier is added to a ladder
|
||||
- **THEN** the `plan_ladder_tiers` row carries no act id, and the act's detail row names the ladder and the product
|
||||
|
||||
#### Scenario: A swap's requests point at its act
|
||||
|
||||
- **WHEN** a member's swap commits
|
||||
- **THEN** both of its lifecycle requests carry the act's id, the cause `instances_swapped` and a role, `asked` for the site the member chose and `consequent` for the site the console parked
|
||||
- **AND** a request that belongs to no act has NULL in all three columns
|
||||
|
||||
#### Scenario: A swap whose workflow cannot start loses its requests and keeps its act
|
||||
|
||||
- **WHEN** a swap's two requests are committed and its workflow cannot start, so the console deletes the requests that never started
|
||||
- **THEN** both requests are deleted in one statement
|
||||
- **AND** the swap's `core.acts` row remains unchanged, with no row pointing at it
|
||||
|
||||
#### Scenario: A request of an act is not deleted alone
|
||||
|
||||
- **WHEN** the deletion of one unstarted request by its address names a request that belongs to an act
|
||||
- **THEN** that request is not deleted
|
||||
- **AND** the other request of its act is unchanged
|
||||
|
||||
### Requirement: The act record withholds personal text from the read-only roles
|
||||
|
||||
No column of `core.acts`, `core.plan_act_details`, `core.plan_act_reached_org_types`, `core.plan_act_orgs_without_pool` or `core.plan_act_obligations` other than `core.acts.note` SHALL hold a personal name, an email address or a person's free text. Neither read-only role SHALL read `core.acts.note`: `core_reader`, which every integration's writer role holds, SHALL hold SELECT on every other column of `core.acts` through column grants and none on the note; and `core.acts.note` SHALL be on `scripts/db-reader-role.sql`'s list of personal columns, with `internal/migrate/testdata/console-reader-columns.txt` listing it as `withhold` and every other column of the five tables, `core.grants.act_id`, `core.lifecycle_requests.act_id`, `core.lifecycle_requests.act_cause`, `core.lifecycle_requests.act_role`, `core.pool_provision_ladders.org_type` and `core.pool_provision_ladders.default_sourced` as `read`. An organization's name SHALL NOT be copied onto any of the five tables; a reader reaches it through the organization's id or the pool.
|
||||
|
||||
#### Scenario: The column list covers the act record
|
||||
|
||||
- **WHEN** the console-reader column test runs against a migrated database
|
||||
- **THEN** it passes with `core.acts.note` withheld and every other column of the five tables readable
|
||||
- **AND** the three act columns of `core.lifecycle_requests` are listed as `read`
|
||||
|
||||
#### Scenario: The read-only role cannot read a note
|
||||
|
||||
- **WHEN** `scripts/db-reader-role.sql` has run and a `console_reader` session selects `core.acts.note`
|
||||
- **THEN** the query is refused
|
||||
|
||||
#### Scenario: The read-only role reads a lifecycle request's act columns
|
||||
|
||||
- **WHEN** `scripts/db-reader-role.sql` has run and a `console_reader` session selects `act_id`, `act_cause` and `act_role` from `core.lifecycle_requests`
|
||||
- **THEN** the query succeeds
|
||||
|
||||
#### Scenario: An integration's writer role cannot read a note
|
||||
|
||||
- **WHEN** a session holding only `core_reader` selects `core.acts.note`
|
||||
- **THEN** PostgreSQL refuses the query on privilege grounds
|
||||
- **AND** the same session can select every other column of `core.acts`
|
||||
@@ -0,0 +1,183 @@
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: A lifecycle request is the record for one instance
|
||||
|
||||
`core.lifecycle_requests` SHALL record each request the console records for one instance (create, change status, delete), and a request SHALL cover exactly one instance. A request SHALL be addressed by (`instance_id`, `generation`), unique together: `instance_id` is the console's identifier for the instance, chosen by the console before the row exists, and has no column default; `generation` is positive. A request SHALL carry `request_id` (a database-generated UUID, its identity), `connection_id`, `resource_key`, `workspace_id` (the workspace the instance belongs to), `operation` limited to `create`, `set_status` and `delete`, `parameters` (a JSON object holding identifiers and public DNS names only), `status` limited to `accepted`, `succeeded`, `declined` and `failed` and defaulting to `accepted`, `reason_code`, `workflow_id`, `requested_by_person_id` (the person whose action caused the request, or NULL when the console added the request to a person's action), `finished_at`, `acknowledged_at`, and the act columns `act_id`, `act_cause` and `act_role`. CHECK constraints SHALL hold `finished_at` NULL exactly while `status = 'accepted'`, and SHALL allow `reason_code` only on a `declined` or `failed` request. A partial unique index SHALL allow at most one `accepted` request per instance.
|
||||
|
||||
The act columns SHALL tie a request to the `core.acts` row of the action that recorded it, and a request that belongs to no act SHALL hold NULL in all three:
|
||||
|
||||
- A CHECK constraint SHALL require `act_id`, `act_cause` and `act_role` to be all NULL or all set.
|
||||
- A foreign key over (`act_id`, `act_cause`) to (`act_id`, `cause`) of `core.acts` SHALL allow a request to point only at an act of the cause it states.
|
||||
- A CHECK constraint SHALL limit `act_cause` to `instances_swapped`, the lifecycle cause, so a request cannot point at a plan act.
|
||||
- A CHECK constraint SHALL limit `act_role` to `asked`, the request for the instance the actor chose, and `consequent`, a request for an instance the console added to carry the action out.
|
||||
- A partial unique index SHALL allow at most one `asked` request per act.
|
||||
- A CHECK constraint SHALL require `requested_by_person_id` to be NULL on a `consequent` request, because the console, not a person, added it.
|
||||
|
||||
Only `core.record_lifecycle_act` SHALL write the act columns, and only on requests that its own transaction inserted, so a request joins an act only in the transaction that records it, and never moves to another act, leaves its act or joins one later; the application's runtime role SHALL hold no INSERT or UPDATE privilege on them.
|
||||
|
||||
The console SHALL mint a new instance's identifier from the database's UUID generator, and every request's generation through `core.next_generation` over the instance's latest generation, so a request for an instance that has no requests is floored by the clock.
|
||||
|
||||
`declined` SHALL mean the instance's rules refused the request before anything changed in the application, and a declined request is refused again until something changes; `failed` SHALL mean the console tried, could not finish and compensated, or the work never started or closed without an outcome, and a retry can succeed. `reason_code` SHALL be a key the console maps to its own wording, never text from an application.
|
||||
|
||||
#### Scenario: One address holds one request
|
||||
|
||||
- **WHEN** a request exists at (instance I, generation G) and a write inserts another row at (I, G)
|
||||
- **THEN** the database rejects it with a unique violation
|
||||
|
||||
#### Scenario: One open request per instance
|
||||
|
||||
- **WHEN** instance I has an `accepted` request and a write inserts a second `accepted` request for I at a higher generation
|
||||
- **THEN** the database rejects it with a unique violation
|
||||
|
||||
#### Scenario: An unknown operation or status is refused
|
||||
|
||||
- **WHEN** a write inserts a request with `operation = 'list'`, or sets `status = 'pending'`
|
||||
- **THEN** the database rejects it with a check violation
|
||||
|
||||
#### Scenario: A finished request carries its finish time
|
||||
|
||||
- **WHEN** a write sets a request's `status` to `succeeded` without `finished_at`, or leaves `finished_at` set on an `accepted` request
|
||||
- **THEN** the database rejects it with a check violation
|
||||
|
||||
#### Scenario: A reason belongs to a declined or failed request
|
||||
|
||||
- **WHEN** a write sets `reason_code` on a request whose `status` is `accepted` or `succeeded`
|
||||
- **THEN** the database rejects it with a check violation
|
||||
|
||||
#### Scenario: The first request for an existing instance is floored by the clock
|
||||
|
||||
- **WHEN** the console mints a generation for an instance that has no requests
|
||||
- **THEN** the generation is at least the current time in microseconds since the Unix epoch
|
||||
|
||||
#### Scenario: A request with no act holds NULL in all three act columns
|
||||
|
||||
- **WHEN** a request is recorded for a single-instance action such as a create
|
||||
- **THEN** its `act_id`, `act_cause` and `act_role` are NULL
|
||||
|
||||
#### Scenario: The act columns are all set or all empty
|
||||
|
||||
- **WHEN** a write sets `act_id` on a request and leaves `act_cause` or `act_role` NULL, or sets `act_role` and leaves `act_id` NULL
|
||||
- **THEN** the database rejects it with a check violation
|
||||
|
||||
#### Scenario: A request points only at an act of the cause it states
|
||||
|
||||
- **WHEN** a write sets `act_cause` to `instances_swapped` and `act_id` to an act whose cause is `tier_added`
|
||||
- **THEN** the database rejects it with a foreign-key violation
|
||||
|
||||
#### Scenario: A request cannot state a plan cause
|
||||
|
||||
- **WHEN** a write sets `act_cause` to `tier_added` and `act_id` to an act whose cause is `tier_added`
|
||||
- **THEN** the database rejects it with a check violation
|
||||
|
||||
#### Scenario: An unknown act role is refused
|
||||
|
||||
- **WHEN** a write sets `act_role` to `parked`
|
||||
- **THEN** the database rejects it with a check violation
|
||||
|
||||
#### Scenario: An act has one asked request
|
||||
|
||||
- **WHEN** an act already has an `asked` request and a second request of the same act is written with `act_role = 'asked'`
|
||||
- **THEN** the database rejects it with a unique violation
|
||||
|
||||
#### Scenario: A consequent request names no person
|
||||
|
||||
- **WHEN** a write sets `act_role` to `consequent` on a request whose `requested_by_person_id` is set
|
||||
- **THEN** the database rejects it with a check violation
|
||||
|
||||
#### Scenario: The runtime role cannot write the act columns
|
||||
|
||||
- **WHEN** the application's runtime role inserts a request that names `act_id`, or updates `act_id`, `act_cause` or `act_role` on an existing request
|
||||
- **THEN** the database refuses the statement for lack of privilege
|
||||
|
||||
### Requirement: Recording a lifecycle request answers a repeat from its record
|
||||
|
||||
Recording a request SHALL, in one transaction that serializes with every other recording for the same instance, read the instance's latest generation and then insert the request or read what holds its address. A request's content SHALL be its `operation`, `workspace_id`, `requested_by_person_id` and `parameters`; its `act_id`, `act_cause` and `act_role` SHALL NOT be content, because the act's writer sets them after the request is recorded, so a repeat of a request that already belongs to an act is a repeat of the same content. Recording SHALL refuse an `operation` the connection's provider does not declare in `core.provider_operations`, and a `resource_key` that provider does not own. The answer SHALL be:
|
||||
|
||||
| What the address holds | Answer |
|
||||
|---|---|
|
||||
| nothing, and the generation is above the instance's latest | accepted, and the request is recorded |
|
||||
| a request with the same content, still `accepted` | accepted, and nothing new is recorded |
|
||||
| a request with the same content, finished | the stored outcome (`succeeded`, `declined` or `failed`) with its reason |
|
||||
| a request with different content, or nothing at a generation at or below the instance's latest | conflict, and nothing is recorded |
|
||||
|
||||
Finishing a request SHALL set its `status`, `reason_code` and `finished_at`, and SHALL fail when no request matches, rather than update nothing. Acknowledging a `declined` or `failed` request SHALL set `acknowledged_at` on that request and on every other `declined` or `failed`, unacknowledged request of its act in the same workspace; a request that belongs to no act SHALL be acknowledged alone. Recording or finishing a lifecycle request SHALL write no desired-state outbox row and SHALL NOT change any desired-state record.
|
||||
|
||||
#### Scenario: A new request is accepted and recorded
|
||||
|
||||
- **WHEN** a request is recorded for an instance at a generation above its latest
|
||||
- **THEN** the answer is accepted and the request is stored with `status = 'accepted'`
|
||||
|
||||
#### Scenario: An identical repeat while work runs is accepted again
|
||||
|
||||
- **WHEN** the same request is recorded twice while the first is still `accepted`
|
||||
- **THEN** both answers are accepted and exactly one row exists at the address
|
||||
|
||||
#### Scenario: An identical repeat after the work finished gets the stored outcome
|
||||
|
||||
- **WHEN** a request finished `declined` with `reason_code` `site_limit_reached` and the same request is recorded again
|
||||
- **THEN** the answer is declined with `site_limit_reached`, and no row is added
|
||||
|
||||
#### Scenario: The same address with different content is a conflict
|
||||
|
||||
- **WHEN** a request at (I, G) exists and a request at (I, G) with different `parameters` is recorded
|
||||
- **THEN** the answer is conflict, and the stored request is unchanged
|
||||
|
||||
#### Scenario: An older tab's generation is a conflict
|
||||
|
||||
- **WHEN** a request at generation G2 for instance I is recorded and finishes, and then a request at a lower generation G1 for I, never recorded before, is recorded
|
||||
- **THEN** the answer is conflict and nothing is recorded
|
||||
|
||||
#### Scenario: Concurrent recordings do not admit an older generation
|
||||
|
||||
- **WHEN** a recording at generation G1 for instance I starts while a recording at a higher G2 for I is in progress, and the G2 request is recorded and finished before the G1 recording completes
|
||||
- **THEN** the recording at G1 answers conflict and nothing is recorded at G1
|
||||
|
||||
#### Scenario: An undeclared operation is refused
|
||||
|
||||
- **WHEN** a request with `operation = 'set_status'` is recorded on a connection whose provider does not declare `set_status`
|
||||
- **THEN** recording fails and nothing is stored
|
||||
|
||||
#### Scenario: Finishing a missing request fails
|
||||
|
||||
- **WHEN** a finish is attempted for an (instance, generation) with no request
|
||||
- **THEN** the finish returns an error instead of succeeding with no row changed
|
||||
|
||||
#### Scenario: A repeated finish with the same outcome succeeds
|
||||
|
||||
- **WHEN** a request was finished `declined` with a reason, and the same finish is attempted again, as a retried activity whose first attempt committed does
|
||||
- **THEN** the finish succeeds and the request keeps its first finish time
|
||||
|
||||
#### Scenario: A finish with another outcome fails
|
||||
|
||||
- **WHEN** a request was finished `declined` and a finish as `succeeded` is attempted
|
||||
- **THEN** the finish returns an error and the request keeps its first outcome
|
||||
|
||||
#### Scenario: A repeat of a request that belongs to an act is a repeat
|
||||
|
||||
- **WHEN** a request is recorded, linked to an act as its `asked` request, and the same request is recorded again
|
||||
- **THEN** the answer is the stored answer for the address, accepted while the request is `accepted` and the stored outcome once it finished, and no row is added
|
||||
|
||||
#### Scenario: Acknowledging a request acknowledges its act's other failed requests
|
||||
|
||||
- **WHEN** an act's `asked` and `consequent` requests are both `declined` and unacknowledged, and the `asked` request is acknowledged
|
||||
- **THEN** both requests have `acknowledged_at` set
|
||||
|
||||
#### Scenario: Acknowledging leaves a succeeded request of the act as it was
|
||||
|
||||
- **WHEN** an act's `asked` request is `failed` and its `consequent` request is `succeeded`, and the `asked` request is acknowledged
|
||||
- **THEN** the `asked` request has `acknowledged_at` set and the `consequent` request does not
|
||||
|
||||
#### Scenario: Acknowledging a request with no act acknowledges only that request
|
||||
|
||||
- **WHEN** a `declined` request that belongs to no act is acknowledged while another request of the same workspace is `declined` and unacknowledged
|
||||
- **THEN** only the named request has `acknowledged_at` set
|
||||
|
||||
#### Scenario: A request of another workspace is not acknowledged
|
||||
|
||||
- **WHEN** a request is acknowledged under a workspace that does not own it
|
||||
- **THEN** no row changes and the request keeps `acknowledged_at` NULL
|
||||
|
||||
#### Scenario: A lifecycle request writes no desired-state outbox row
|
||||
|
||||
- **WHEN** a request is recorded and then finished `succeeded`
|
||||
- **THEN** `core.desired_state_outbox` gains no row from either write
|
||||
@@ -0,0 +1,648 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Intake refuses a rotation while another rotation of the workspace is open
|
||||
|
||||
A **rotation** SHALL be a Keep active that brings a different site into the workspace's active set: a **swap**, which parks the workspace's lowest-ranked active site and activates the chosen one because the pool is at its limit, or a **return**, which is a Keep active below the limit on a read-only site whose `force_reduced_at` is set. A Keep active below the limit on a read-only site with no mark, a Restore, an archive and a permanent delete SHALL NOT be rotations.
|
||||
|
||||
Every rotation's intake SHALL run in one READ COMMITTED transaction that holds the workspace's FedWiki lock, whether or not the swap cooldown is on, and SHALL take these steps in this order: answer a repeat from its record; refuse with "A change to your active site is already in progress" when the workspace has an open rotation; refuse with the cooldown sentence, "The active site changes once every N day(s); try again in about M day(s).", when the cooldown is on and the workspace's stamp lies inside its window; and then record the request. A workspace has an open rotation when an `accepted` request of its workspace and connection either belongs to an act whose cause is `instances_swapped`, or is a `set_status` request to `active` on a site whose `force_reduced_at` is set. One statement SHALL read both tests, and it SHALL run before the stamp is read, so that a rotation that commits its success between the two reads is seen by one of them. A refusal SHALL record no request and start no workflow.
|
||||
|
||||
A return's intake SHALL, after the instance lock and before it records, lock its site's row, and SHALL record only when the row, under that lock, is in the member's workspace with the posted domain, is `readonly` and has `force_reduced_at` set; a row that is missing, or is another workspace's or has another domain, SHALL record nothing and answer "Site not found" without a list refresh, and a row that is not `readonly` or has no mark SHALL record nothing and answer "This site changed since the list loaded." with a list refresh. The farm sync takes the same row, so a return either committed before the sync's lock and the sync leaves the site alone, or waits for the sync and finds the row as the sync left it.
|
||||
|
||||
A Keep active that is neither a swap nor a return (a free fill) SHALL be recorded in its own transaction without the workspace lock, SHALL NOT be refused while a rotation is open and SHALL NOT count as an open rotation, because a free fill is always allowed and never consults the cooldown; the slot gate SHALL still decline it when the pool is full. A Restore SHALL never be a rotation: it SHALL take no workspace lock, make no open-rotation check, consult no cooldown and write no stamp, and when the row it names is not `archived` it SHALL answer "This site changed since the list loaded." with a list refresh and record nothing.
|
||||
|
||||
A database error in the transaction that records a swap SHALL answer "Couldn't change the active site. Try again."; in the transaction that records a return, "Couldn't change which site is active. Try again later."; and in the transaction that records a free fill, a Restore or an archive, "Couldn't update the site. Try again."
|
||||
|
||||
While a rotation is open, the sites card SHALL render Keep active on the workspace's other read-only rows as it does when none is open: a click that would be a swap or a return SHALL answer "A change to your active site is already in progress", and a click that would be a free fill SHALL be recorded. Rows with an open request SHALL show Pending and no actions. Restore SHALL render on an archived row the same way whether or not a downgrade or a swap once parked the site, and the cooldown SHALL NOT disable it.
|
||||
|
||||
#### Scenario: A second swap is refused while one is open
|
||||
|
||||
- **WHEN** a swap of a workspace is open and the member asks Keep active on another read-only site that would also be a swap, with the cooldown off
|
||||
- **THEN** the answer SHALL be "A change to your active site is already in progress"
|
||||
- **AND** no request SHALL be recorded and no workflow SHALL start
|
||||
|
||||
#### Scenario: A return is refused while a swap is open
|
||||
|
||||
- **WHEN** a swap of a workspace is open and the member asks Keep active on a read-only site that carries `force_reduced_at` while the pool is below its limit
|
||||
- **THEN** the answer SHALL be "A change to your active site is already in progress" and nothing SHALL be recorded
|
||||
|
||||
#### Scenario: A swap is refused while a return is open
|
||||
|
||||
- **WHEN** a return is `accepted` on a site that still carries `force_reduced_at`, and the member then asks for a Keep active that would be a swap
|
||||
- **THEN** the answer SHALL be "A change to your active site is already in progress" and nothing SHALL be recorded
|
||||
|
||||
#### Scenario: Two returns at once
|
||||
|
||||
- **WHEN** two returns of one workspace reach intake at the same time, with the cooldown off
|
||||
- **THEN** the workspace lock SHALL serialize them, one SHALL be recorded and the other SHALL answer "A change to your active site is already in progress"
|
||||
|
||||
#### Scenario: A repeated swap is not refused as a second rotation
|
||||
|
||||
- **WHEN** a swap is open and the member's same Keep active request arrives again with the same instance identifier and generation
|
||||
- **THEN** the answer SHALL be the repeat's answer from the record (accepted, with a list refresh), not "A change to your active site is already in progress"
|
||||
|
||||
#### Scenario: A rotation that has finished no longer blocks
|
||||
|
||||
- **WHEN** a rotation of a workspace has succeeded, so that its requests are no longer `accepted`, and the cooldown is off
|
||||
- **THEN** a later rotation of that workspace SHALL be recorded
|
||||
|
||||
#### Scenario: The cooldown answers after the open-rotation check passes
|
||||
|
||||
- **WHEN** the cooldown is on, no rotation of the workspace is open and the workspace's stamp lies inside the window
|
||||
- **THEN** a swap or a return SHALL answer "The active site changes once every N day(s); try again in about M day(s)." and record nothing
|
||||
|
||||
#### Scenario: A free fill during an open rotation is recorded
|
||||
|
||||
- **WHEN** a rotation of a workspace is open and the member asks Keep active on a read-only site with no `force_reduced_at` while the pool is below its limit
|
||||
- **THEN** the request SHALL be recorded and accepted, and it SHALL NOT make a later rotation answer that a rotation is open
|
||||
|
||||
#### Scenario: A Restore is never refused as a rotation
|
||||
|
||||
- **WHEN** a rotation is open, or the cooldown is running, and the member restores an archived site while the pool is below its limit
|
||||
- **THEN** the Restore SHALL be recorded without the workspace lock and no stamp SHALL be written for it
|
||||
|
||||
#### Scenario: A Restore posted for a row that is not archived
|
||||
|
||||
- **WHEN** a request reaches the restore route for a site whose status is `readonly` or `active`
|
||||
- **THEN** the answer SHALL be "This site changed since the list loaded." with a list refresh, and no request SHALL be recorded
|
||||
|
||||
#### Scenario: A return meets the sync's write of its site
|
||||
|
||||
- **WHEN** the sync holds a marked read-only site's row, a member posts Keep active on it, and the sync writes the row archived and commits
|
||||
- **THEN** the intake SHALL wait for the commit, record nothing and answer "This site changed since the list loaded." with a list refresh
|
||||
|
||||
#### Scenario: A return's database error
|
||||
|
||||
- **WHEN** the transaction that records a return fails with a database error
|
||||
- **THEN** nothing SHALL be recorded and the answer SHALL be "Couldn't change which site is active. Try again later."
|
||||
|
||||
#### Scenario: The card while a rotation is open
|
||||
|
||||
- **WHEN** a rotation of a workspace is open, the cooldown is on and no rotation has succeeded in its window
|
||||
- **THEN** the card SHALL show Pending and no actions on the rotation's rows
|
||||
- **AND** Keep active on the workspace's other read-only rows SHALL render enabled
|
||||
|
||||
### Requirement: Only a rotation that succeeded stamps the swap cooldown
|
||||
|
||||
The swap cooldown SHALL start from the workspace's stamp, `fedwiki.site_swap_policy.last_swap_at`. Intake SHALL write no stamp. The transaction that records a rotation's success SHALL write the stamp, with the time of that transaction, whether or not the cooldown is on, when the member's action brought the chosen site into the active set, which that transaction sees as the row it locked for the chosen site not being `active`:
|
||||
|
||||
- a swap's record step SHALL write the stamp in the transaction that writes both sites' statuses, clears the activated site's mark and finishes both requests, when the activated site's locked row was not `active`;
|
||||
- a return's record step, which the status reconcile at boot also uses, SHALL write the stamp in the transaction that writes the site's status, clears its mark and finishes the request, when the row it locked carried `force_reduced_at`, was not `active` and the request's target is `active`, reading the mark before it is cleared.
|
||||
|
||||
A free fill, a Restore, an archive and a permanent delete SHALL NOT write the stamp. When the re-upgrade sweep reactivated the chosen site during the rotation's farm calls, the record SHALL write no stamp, because the sweep and not the member's action brought the site back. A refused record, a declined or failed outcome, a rotation whose workflow never started, a transaction that rolls back and a swap whose workflow closed without recording an outcome SHALL write no stamp; a swap that settle ends `retries_exhausted` SHALL start no wait even when the farm applied it. A return whose failed farm call reads back from the farm as applied, and a return that the status reconcile at boot confirms, SHALL record their success, and SHALL write the stamp when the row the record step locked still carried `force_reduced_at` and was not `active`. A success that is recorded again after its answer was lost SHALL write no second stamp. The workflow's record steps SHALL NOT read the cooldown, so a cooldown turned on later SHALL measure from the last rotation that succeeded.
|
||||
|
||||
#### Scenario: A swap that succeeds starts the wait
|
||||
|
||||
- **WHEN** a swap's record step commits and the chosen site's row it locked was not `active`, whether the cooldown is on or off
|
||||
- **THEN** the workspace's stamp SHALL be written in the same transaction that writes both statuses and finishes both requests
|
||||
|
||||
#### Scenario: A return that succeeds starts the wait
|
||||
|
||||
- **WHEN** a return succeeds and its record step finds the site's row still `readonly` with `force_reduced_at` set
|
||||
- **THEN** in one transaction the site SHALL be `active`, its mark SHALL be cleared, its request SHALL be `succeeded` and the workspace's stamp SHALL be written
|
||||
|
||||
#### Scenario: A swap that never started leaves the wait as it was
|
||||
|
||||
- **WHEN** a swap's workflow cannot start and its requests are deleted
|
||||
- **THEN** the workspace's stamp SHALL be as it was before the swap
|
||||
- **AND** the member's retry SHALL NOT be refused with the cooldown sentence because of that swap
|
||||
|
||||
#### Scenario: A declined or failed rotation leaves the wait as it was
|
||||
|
||||
- **WHEN** a swap or a return ends `declined` or `failed`, at the slot gate, the farm call or the record step
|
||||
- **THEN** no stamp SHALL be written, and when no earlier stamp lies inside the window, Keep active SHALL render enabled at once
|
||||
|
||||
#### Scenario: A rollback of the success writes no stamp
|
||||
|
||||
- **WHEN** the transaction that records a swap's success rolls back, for a refused guard or a failed finish
|
||||
- **THEN** the stamp SHALL roll back with the site writes and no stamp SHALL be left
|
||||
|
||||
#### Scenario: A swap whose chosen site the sweep reactivated stamps nothing
|
||||
|
||||
- **WHEN** the re-upgrade sweep reactivates the swap's chosen site during the swap's farm calls and the swap's record step then commits
|
||||
- **THEN** both requests SHALL end `succeeded` and no stamp SHALL be written
|
||||
|
||||
#### Scenario: A return whose site the sweep reactivated stamps nothing
|
||||
|
||||
- **WHEN** the re-upgrade sweep reactivates a return's site, clearing its mark, during the return's farm call and the record step then commits
|
||||
- **THEN** the request SHALL end `succeeded` and no stamp SHALL be written
|
||||
|
||||
#### Scenario: A return confirmed at boot stamps
|
||||
|
||||
- **WHEN** boot settle finds a closed return that holds its slot and the status reconcile finds the site `active` on the farm, and the record step finds the site's row still `readonly` with `force_reduced_at` set
|
||||
- **THEN** the site's mark SHALL be cleared and the workspace's stamp SHALL be written in the transaction that records the success
|
||||
|
||||
#### Scenario: A swap closed without an outcome stamps nothing
|
||||
|
||||
- **WHEN** a swap's workflow closed without recording an outcome and the farm holds the chosen site active
|
||||
- **THEN** boot settle SHALL end both requests `failed` with `retries_exhausted` and write no stamp
|
||||
|
||||
#### Scenario: A lost answer writes one stamp
|
||||
|
||||
- **WHEN** a swap's record transaction commits, its answer is lost and the step retries
|
||||
- **THEN** the retry SHALL return the recorded success and SHALL NOT write a second stamp
|
||||
|
||||
#### Scenario: A free fill and a Restore write no stamp
|
||||
|
||||
- **WHEN** a Keep active below the limit on a read-only site with no mark, or a Restore of an archived site, succeeds
|
||||
- **THEN** the workspace's stamp SHALL be unchanged
|
||||
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Site lifecycle status is an observed projection
|
||||
|
||||
`fedwiki.sites.status` SHALL reflect the site's observed lifecycle state on the farm (`active` / `readonly` / `archived`), reconciled by the sync workflow from the FarmManager `list`/`describe` read class, with the farm remaining the canonical source of truth. The sync SHALL also capture the observed `storage_bytes` and `last_modified_at` for each site. These captured fields are informational only — they SHALL NOT be enforced as limits in this change (storage metering is out of scope).
|
||||
|
||||
A site's `force_reduced_at` mark SHALL be kept only while the site is `readonly`. When the sync writes a status, it SHALL write the mark only while the row it writes is `readonly`: it SHALL clear the mark of a row it writes `archived` or `active`, and it SHALL leave the mark of a row it writes `readonly` as the row holds it. A row the sync writes `archived` SHALL therefore never carry a mark.
|
||||
|
||||
#### Scenario: Observed status reconciled from the farm
|
||||
|
||||
- **WHEN** a site's status changes on the farm and a sync runs
|
||||
- **THEN** the local `fedwiki.sites.status` SHALL be updated to the observed value
|
||||
|
||||
#### Scenario: Storage and last-modified captured but not enforced
|
||||
|
||||
- **WHEN** a sync runs and the farm reports `storageBytes` and `lastModified` for a site
|
||||
- **THEN** the system SHALL store them in `storage_bytes` and `last_modified_at`
|
||||
- **AND** the system SHALL NOT deny any action based on `storage_bytes`
|
||||
|
||||
#### Scenario: A parked site archived on the farm loses its mark
|
||||
|
||||
- **WHEN** a site that carries `force_reduced_at` is `readonly` locally, has no open request, and a sync finds it archived on the farm
|
||||
- **THEN** the sync SHALL write the row `archived` with `force_reduced_at` cleared
|
||||
|
||||
#### Scenario: A parked site made active on the farm loses its mark
|
||||
|
||||
- **WHEN** a site that carries `force_reduced_at` is `readonly` locally, has no open request, and a sync finds it active on the farm
|
||||
- **THEN** the sync SHALL write the row `active` with `force_reduced_at` cleared
|
||||
|
||||
#### Scenario: A site the sync writes read-only keeps its mark
|
||||
|
||||
- **WHEN** the sync's farm upsert writes status `readonly` onto a row whose `force_reduced_at` is set
|
||||
- **THEN** the sync SHALL write the row `readonly` and `force_reduced_at` SHALL be as the row held it before the write
|
||||
|
||||
#### Scenario: A pending return's mark is not cleared by the sync
|
||||
|
||||
- **WHEN** a return is `accepted` on a site that carries `force_reduced_at` and a sync finds the site archived or active on the farm
|
||||
- **THEN** the sync SHALL leave the row as it is, and the mark SHALL stay until the return's success clears it
|
||||
|
||||
### Requirement: FedWiki lifecycle requests are recorded under the console's instance identifier and a generation
|
||||
|
||||
Every create, archive, restore, keep-active and permanent delete a member starts from the sites list, and every create and delete through the JSON API, SHALL be recorded as a lifecycle request addressed by the instance identifier and a generation before its workflow starts. A lifecycle request SHALL cover exactly one instance: a swap SHALL record one request for each of its two sites, the activated site's addressed by its `site_id` and the generation of its row action, and the parked site's addressed by the parked site's `site_id` and a generation above the latest recorded for it. A site's instance identifier SHALL be its `site_id`. For a create from the form, the instance identifier and generation SHALL be minted when the form renders; for the one-click create on a verified domain, one instance identifier SHALL be minted per offered domain when the list renders. Each row action SHALL carry the site's `site_id` and a generation above the latest generation recorded for that site, computed when the list renders; a site with no recorded request SHALL receive a generation floored by the clock. Each render of the list or the form SHALL mint new values, so closing and reopening the create modal starts a new create. A request's content SHALL be its operation, its workspace, the person whose action caused it (no one for a request the console added to a person's act) and its parameters; the request's act, act cause and act role are its link to an act and SHALL NOT be part of its content. Parameters SHALL hold identifiers and public DNS names only. A form handler SHALL NOT mint the identifier itself, because an identifier minted per submission makes a double submit two requests; only the JSON API mints an instance identifier in the handler, for a create that carries none.
|
||||
|
||||
#### Scenario: A double submit is one request
|
||||
|
||||
- **WHEN** a member submits the create-site form twice with the same instance identifier and generation
|
||||
- **THEN** exactly one lifecycle request SHALL be recorded and exactly one create workflow SHALL start
|
||||
|
||||
#### Scenario: Row actions carry the next generation
|
||||
|
||||
- **WHEN** the sites list renders a site whose latest recorded request has generation G
|
||||
- **THEN** each of that site's actions SHALL carry its `site_id` and a generation above G
|
||||
|
||||
#### Scenario: A pre-existing site gets a first generation
|
||||
|
||||
- **WHEN** the sites list renders a site that has no recorded request
|
||||
- **THEN** its actions SHALL carry a generation no lower than the current time in microseconds since the Unix epoch
|
||||
|
||||
#### Scenario: The verified-domain banner hides while its create is open
|
||||
|
||||
- **WHEN** the sites list renders while a create request for a verified domain the banner would offer is still `accepted`
|
||||
- **THEN** the banner SHALL NOT offer a one-click create for that domain
|
||||
|
||||
#### Scenario: A swap records one request for each site
|
||||
|
||||
- **WHEN** a member's Keep active swaps site A in and site B out
|
||||
- **THEN** one request SHALL be recorded for A, naming the member, and one for B, naming no person
|
||||
- **AND** each request SHALL be addressed by its own site's `site_id` and generation, and the parameters of neither SHALL name the other site
|
||||
|
||||
### Requirement: FedWiki lifecycle handlers answer when the workflow starts
|
||||
|
||||
Each FedWiki lifecycle handler SHALL run its synchronous checks, record the request in one transaction, commit, and then start the workflow under the request's workflow id, and SHALL answer as soon as the start is confirmed. No handler SHALL wait for a workflow's result. A start that succeeds, or that answers that the workflow already started, SHALL be answered as accepted. Any other start error SHALL be resolved by describing the workflow: only when Temporal answers that the workflow does not exist SHALL the handler delete the request it recorded and answer with the existing synchronous error, so a retry is a fresh request; on any other answer the request SHALL stay `accepted` and the handler SHALL answer accepted. A request that belongs to an act SHALL NOT be deleted by its address alone: for a swap, the handler SHALL delete every `accepted` request of the swap's act in one statement and leave the act's header, and when that delete fails both requests SHALL stay `accepted`, so the member's retry is answered as a repeat and the next boot settle ends them. The existing synchronous error of a swap SHALL be "Couldn't change the active site. Try again." and of a return "Couldn't update the site. Try again.", each with no list refresh; a retry after the delete SHALL record a new act, with a new generation for the parked site. An accepted create from the form SHALL answer 200 with an empty body and an `HX-Trigger` naming `refreshSites` and `fedwikiCreateAccepted`, on which the create modal closes; an accepted row action SHALL answer with the list refresh and no message. The text "Still working; this is taking longer than expected. The site list will update when it finishes; refresh in a minute if it hasn't." and the "Done!" create confirmation SHALL NOT exist.
|
||||
|
||||
#### Scenario: A create answers at start
|
||||
|
||||
- **WHEN** a member submits a valid create and the workflow starts
|
||||
- **THEN** the response SHALL be 200 with an empty body and `HX-Trigger` containing `refreshSites` and `fedwikiCreateAccepted`
|
||||
- **AND** the response SHALL be sent without waiting for the workflow to finish
|
||||
|
||||
#### Scenario: A row action answers at start
|
||||
|
||||
- **WHEN** a member archives an active site and the workflow starts
|
||||
- **THEN** the response SHALL refresh the sites list without waiting for the workflow to finish
|
||||
|
||||
#### Scenario: A start that never happened is undone
|
||||
|
||||
- **WHEN** starting the workflow fails and describing it answers that it does not exist
|
||||
- **THEN** the recorded request SHALL be deleted
|
||||
- **AND** the member SHALL receive the existing synchronous error, such as "Failed to initiate site creation"
|
||||
|
||||
#### Scenario: An ambiguous start keeps the request
|
||||
|
||||
- **WHEN** starting the workflow returns a deadline error and describing it shows the workflow running
|
||||
- **THEN** the request SHALL stay `accepted` and the answer SHALL be accepted
|
||||
|
||||
#### Scenario: A swap that never started loses both requests together
|
||||
|
||||
- **WHEN** starting a swap's workflow fails and describing it answers that it does not exist
|
||||
- **THEN** both of the swap's requests SHALL be deleted in one statement and its act's header SHALL remain
|
||||
- **AND** the member SHALL receive "Couldn't change the active site. Try again." with no list refresh
|
||||
- **AND** the member's retry SHALL be recorded as a new act, and the swap that never started SHALL NOT make the cooldown refuse it
|
||||
|
||||
#### Scenario: A swap whose requests cannot be deleted stays pending
|
||||
|
||||
- **WHEN** starting a swap's workflow fails, describing it answers that it does not exist and the delete of its requests fails
|
||||
- **THEN** both requests SHALL stay `accepted` and the list SHALL show both sites as Pending
|
||||
- **AND** the member's retry SHALL be answered as a repeat
|
||||
|
||||
### Requirement: A repeated FedWiki lifecycle request is answered from its record
|
||||
|
||||
When a request arrives, the console SHALL, in one transaction that serializes requests for the instance, compare its address with what is recorded and answer as follows: an address that holds nothing, with a generation above the instance's latest, SHALL be recorded and accepted only after the operation's intake checks pass; an address holding a request with the same content that is still `accepted` SHALL be answered accepted, and nothing new SHALL start; an address holding a request with the same content that has finished SHALL be answered with its stored outcome (`succeeded`, `declined` or `failed`, with its reason code); an address holding a request with different content, or an empty address whose generation is at or below the instance's latest, SHALL be answered as a conflict, and nothing SHALL be recorded or started. Content SHALL be compared by one rule, the same for every request: the operation, the workspace, the requesting person and every parameter, never the request's link to an act. FedWiki SHALL keep no comparison of its own, and a swap's park site is not a parameter of either of its requests. A swap's asked request records the same content as a free fill or a return on the same site, so a repeated Keep active SHALL be answered from the first click's record whichever branch that click took. A lookup made without the instance lock MAY answer a repeat, a conflict or a request in another workspace before anything is recorded; the comparison under the instance lock SHALL remain the final answer, and an address that holds nothing at the lookup SHALL go on to the intake checks. A request is `declined` when the instance's rules refused it before anything changed on the farm: a full site limit, a name the domains registry refuses, a reactivation at the active limit, a site that changed hands, or a farm that holds the name for someone else; also when its original site disappeared before the local outcome could be recorded, even if the farm call had succeeded. A request is `failed` when the console tried, could not finish and compensated, or when the workflow never started or closed without recording an outcome. A row action SHALL look its request up by instance and generation before it resolves the site's domain, so a repeat that arrives after a permanent delete finished is still answered from its record; when the domain now names a site whose `site_id` differs from the posted instance, the answer SHALL be a conflict. A conflict on a row action SHALL answer "This site changed since the list loaded." and refresh the list. A recorded request in another workspace SHALL be answered on the row actions exactly as a site that does not exist ("Site not found") and on the create form and the JSON API as a conflict, never with its content. A create SHALL be looked up by its address on the form, and by its instance on the JSON API, before the requested name is checked against the domains registry, so a repeat of a create whose workflow already placed the name is answered from its record; a create whose instance is not recorded but already names a site SHALL be answered as a conflict, and nothing SHALL be recorded or started.
|
||||
|
||||
#### Scenario: A repeat after success returns the stored outcome
|
||||
|
||||
- **WHEN** a member's archive request has finished `succeeded` and the same instance identifier, generation and content arrive again
|
||||
- **THEN** the answer SHALL be the stored outcome and no workflow SHALL start
|
||||
|
||||
#### Scenario: An older tab is a conflict
|
||||
|
||||
- **WHEN** a request for a site finished under generation 20 and a stale tab then submits a request for the same site under generation 10
|
||||
- **THEN** the answer SHALL be a conflict, the row action SHALL show "This site changed since the list loaded.", and nothing SHALL be recorded or started
|
||||
|
||||
#### Scenario: Same address, different content
|
||||
|
||||
- **WHEN** a request arrives whose instance identifier and generation are already recorded with a different operation or different parameters
|
||||
- **THEN** the answer SHALL be a conflict and nothing SHALL be recorded or started
|
||||
|
||||
#### Scenario: Another workspace's request is not disclosed
|
||||
|
||||
- **WHEN** a member submits a row action whose instance identifier and generation address a request recorded in another workspace
|
||||
- **THEN** the answer SHALL be identical to the answer for a site that does not exist
|
||||
|
||||
#### Scenario: A custom-domain create repeated after its name was placed
|
||||
|
||||
- **WHEN** a create for a custom domain was accepted, its workflow has placed the name, and the same form submission or API create arrives again
|
||||
- **THEN** the answer SHALL be the one the first submission got, from the record
|
||||
- **AND** nothing SHALL be recorded or started
|
||||
|
||||
#### Scenario: A create under an existing site's identifier
|
||||
|
||||
- **WHEN** a create arrives whose instance identifier has no recorded request but names an existing site
|
||||
- **THEN** the answer SHALL be a conflict, and nothing SHALL be recorded or started
|
||||
|
||||
#### Scenario: A repeated swap is answered from its record
|
||||
|
||||
- **WHEN** a member's Keep active swapped two sites and the same request, with the same instance identifier and generation, arrives again while the swap is open
|
||||
- **THEN** the answer SHALL be accepted with a list refresh, and no second act, request or workflow SHALL start
|
||||
- **WHEN** it arrives again after the swap succeeded
|
||||
- **THEN** the answer SHALL be the stored outcome, not the cooldown sentence that the swap's own success started
|
||||
|
||||
#### Scenario: The parked site's address with other content is a conflict
|
||||
|
||||
- **WHEN** a stale tab posts a request to activate the site that a swap parked, under the generation of the swap's parked request
|
||||
- **THEN** the answer SHALL be a conflict, the row action SHALL show "This site changed since the list loaded.", and nothing SHALL be recorded or started
|
||||
|
||||
### Requirement: A FedWiki site has at most one open lifecycle request
|
||||
|
||||
A site SHALL have at most one `accepted` lifecycle request at a time. A second, different request on a site whose request is still open SHALL be refused synchronously with "A change to this site is already in progress" and SHALL NOT be recorded. A swap SHALL be one act, with the cause `instances_swapped` and the member as its actor, over two single-site requests, both recorded in the transaction that holds the workspace lock and neither writing a stamp: the asked request, a `set_status` request to `active` for the site being activated, which names the member as its requesting person, and the consequent request, a `set_status` request to `readonly` for the site it parks, which names no person, both under the swap's workflow id. The parameters of neither request SHALL name the other site, and the console SHALL find a swap through its act and each request's role, never through its workflow id or another request's parameters. A swap SHALL be refused with "A change to your active site is already in progress" when the workspace already has an open rotation or when the site it would park has an open request. While a swap runs, any request on the parked site SHALL be refused as already in progress. The swap's outcome SHALL finish both requests.
|
||||
|
||||
#### Scenario: Archiving the parked site during a swap is refused
|
||||
|
||||
- **WHEN** a swap that parks site B is still running and the member archives site B from another tab
|
||||
- **THEN** the archive SHALL be refused with "A change to this site is already in progress"
|
||||
- **AND** the workspace's active usage SHALL be changed only by the swap
|
||||
|
||||
#### Scenario: A swap waits for an open request on its park target
|
||||
|
||||
- **WHEN** site B has an open archive request and the member asks to keep site A active, which would park site B
|
||||
- **THEN** the swap SHALL be refused with "A change to your active site is already in progress" and nothing SHALL be recorded
|
||||
|
||||
#### Scenario: A swap is recorded as one act
|
||||
|
||||
- **WHEN** a member's Keep active swaps site A in and parks site B
|
||||
- **THEN** one act with the cause `instances_swapped` and the member as its actor SHALL be recorded, and the request for A SHALL be its asked request and the request for B its consequent request
|
||||
- **AND** the request for B SHALL name no requesting person, and no stamp SHALL be written
|
||||
|
||||
#### Scenario: A second swap is refused while one is open
|
||||
|
||||
- **WHEN** a swap of a workspace is open and the member asks for another swap in the same workspace
|
||||
- **THEN** the second swap SHALL be refused with "A change to your active site is already in progress", whether or not the cooldown is on, and nothing SHALL be recorded
|
||||
|
||||
### Requirement: Each FedWiki lifecycle workflow records its own outcome
|
||||
|
||||
Every FedWiki lifecycle workflow SHALL end by setting its request's status, reason code and finish time, and SHALL fail visibly in its own history when no recorded request matches. A create's site identifier SHALL be the request's instance identifier, used for the registry placement and the `fedwiki.sites` row; a create's success SHALL insert the `fedwiki.sites` row and mark the request `succeeded` in one transaction, so the list never shows the pending create and the new site together. A status change SHALL write the site's new status, remove its request's hold, recount the pool and write its request's outcome in one transaction, and the clearing of a site's force-reduced mark after a rotation SHALL commit in that same transaction. The transaction that records a rotation's success, a swap's or a return's, SHALL also write the workspace's swap-cooldown stamp when "Only a rotation that succeeded stamps the swap cooldown" requires it, so the success and its stamp commit or roll back together. Every outcome, declined and failed ones included, SHALL be recorded under the request's instance lock in a transaction that removes the request's hold and recounts the pool. Workflow inputs SHALL carry the request's connection identifier, instance identifier and generation. A run that was in flight when the console was upgraded SHALL replay its recorded history without failure: the create and status workflows SHALL choose between their recorded quota steps and the slot gate with a version check before their first command, and the swap and status workflows SHALL issue no new command for the stamp, so the record step of a rotation in flight SHALL run the current code, and a success it records SHALL write the stamp when "Only a rotation that succeeded stamps the swap cooldown" requires it.
|
||||
|
||||
#### Scenario: A successful create appears once
|
||||
|
||||
- **WHEN** a create workflow inserts its site row
|
||||
- **THEN** in the same transaction the request SHALL become `succeeded`
|
||||
- **AND** no rendering of the list SHALL show both the pending create row and the new site
|
||||
|
||||
#### Scenario: A swap's retry changes no count
|
||||
|
||||
- **WHEN** a swap's farm step fails and is retried, and the swap then succeeds
|
||||
- **THEN** the pool's figure SHALL equal its active rows and holds, both sites' statuses, both requests' outcomes and the workspace's stamp SHALL have been written in one transaction
|
||||
- **AND** when the swap fails instead, both sites SHALL keep the statuses they had, on the farm and in the console, and no stamp SHALL be written
|
||||
- **AND** while the farm cannot answer the PATCHes that send the sites back, both requests SHALL stay `accepted`
|
||||
- **AND** a 404 for a site SHALL leave that site out of the send-back, and any other refusal from the farm, a 4xx other than 408 or 429, SHALL finish both requests `failed` without another attempt once the other site's send-back has been tried
|
||||
|
||||
#### Scenario: A finish with no request fails
|
||||
|
||||
- **WHEN** a lifecycle workflow tries to record the outcome of a request that does not exist
|
||||
- **THEN** the recording step SHALL fail instead of updating nothing
|
||||
|
||||
#### Scenario: A run started before an upgrade finishes
|
||||
|
||||
- **WHEN** a create workflow started by the previous release is still running when the new release starts
|
||||
- **THEN** the run SHALL complete without a replay failure
|
||||
|
||||
#### Scenario: A status change started before an upgrade finishes
|
||||
|
||||
- **WHEN** a status change to `active` started by the previous release is still running when the new release starts
|
||||
- **THEN** the run SHALL complete without a replay failure, and its outcome SHALL leave the pool's figure equal to its active rows and holds
|
||||
|
||||
#### Scenario: A swap started by the previous release stamps when it succeeds
|
||||
|
||||
- **WHEN** a swap started by the previous release is still running when the new release starts and its record step then records the success while the chosen site's row is not `active`
|
||||
- **THEN** the run SHALL complete without a replay failure, and the workspace's stamp SHALL be written in the transaction that records the success
|
||||
|
||||
#### Scenario: A declined request frees its hold
|
||||
|
||||
- **WHEN** a create holding a slot ends `declined` with `name_taken`
|
||||
- **THEN** in the transaction that records the outcome its hold SHALL be removed and the pool's figure SHALL fall by one
|
||||
|
||||
#### Scenario: A missing swap site declines both requests
|
||||
|
||||
- **WHEN** either original swap site is missing at a farm or local record step
|
||||
- **THEN** no local swap status or mark SHALL be written and the missing-site step SHALL NOT retry
|
||||
- **AND** the workflow SHALL send surviving original sites back as a failed swap does, skipping absent or mismatched IDs and farm 404s
|
||||
- **AND** while the farm cannot answer, or the restoration's database read fails, both requests SHALL stay `accepted` and restoration SHALL retry
|
||||
- **AND** after restoration completes or receives a final refusal, unless cancelled, the workflow SHALL finish both requests `declined` with `site_missing` in one transaction that removes their holds and recounts
|
||||
- **AND** a final farm refusal SHALL be logged and SHALL NOT stop the other site's send-back from being tried
|
||||
- **AND** a same-name replacement SHALL receive no local write or restoration call
|
||||
|
||||
#### Scenario: A committed success stays successful after deletion
|
||||
|
||||
- **WHEN** the record transaction succeeded but its answer was lost, and the original site is deleted before the retry
|
||||
- **THEN** the retry SHALL return the recorded success without reapplying any site write or changing the outcome to declined
|
||||
|
||||
#### Scenario: A failed decline commit keeps its hold until retry
|
||||
|
||||
- **WHEN** a missing-site decline cannot commit
|
||||
- **THEN** the outcome, hold removal and recount SHALL all roll back
|
||||
- **AND** retrying the finish SHALL commit the decline and release the hold together
|
||||
|
||||
### Requirement: A FedWiki lifecycle request with no outcome is settled at boot
|
||||
|
||||
When Temporal is configured, FedWiki's startup SHALL, before it ensures or pauses the maintenance schedule, describe the workflow of every `accepted` request older than two minutes and act on the answer, at boot and once more after two minutes have passed since boot: when the workflow does not exist, the request SHALL end `failed` with `not_started`; when it is running, nothing SHALL change; when it closed and the request is a create, the console SHALL start a reconcile workflow, identified by the instance, that reads the farm's entry for the domain as a failed create does and then records the site and succeeds or compensates and fails; when it closed and the request is a status change to `active` that still holds a slot, the console SHALL start a status reconcile workflow, identified by the instance and generation, that reads the site's entry from the farm and records the status and succeeds when the farm holds the site in the requested status, ends the request `failed` with `retries_exhausted` when the farm holds it otherwise or not at all, ends it `declined` with `site_missing` when its original site row is gone at load or record time, and keeps the request `accepted` and its slot held while the farm cannot answer; when it closed and the request is any other operation, the request SHALL end `failed` with `retries_exhausted` and the site SHALL keep its observed status; on any other error, nothing SHALL change. The requests of one act SHALL be settled together: the pass SHALL describe the act's one workflow once and SHALL end every request of the act in one transaction, the asked request first and then the consequent requests in the order they were recorded, with `failed` and `not_started` when the workflow does not exist and with `failed` and `retries_exhausted` when it closed, and a request that belongs to an act SHALL NOT go to the status reconcile. When every listed request of an act already holds an outcome as the pass finishes them, the pass SHALL change none of them and SHALL report no failure; when only some of them do, or one of them is missing, the pass SHALL finish none of them and SHALL report the failure. A request of an act that was finished before the listing is not listed, and the pass settles the act's listed requests without it. A request that belongs to no act SHALL be settled alone. Every outcome settle records SHALL be written under the request's instance lock, with the request's hold removed and the pool recounted, and settle SHALL write no stamp. When the status reconcile records the success of a return, it SHALL clear the site's force-reduced mark and write the workspace's stamp as "Only a rotation that succeeded stamps the swap cooldown" requires. A request that never started SHALL NOT be restarted. The reconcile workflows' input SHALL carry identifiers only.
|
||||
|
||||
#### Scenario: A process that died before the start
|
||||
|
||||
- **WHEN** the console boots with an `accepted` request older than two minutes whose workflow Temporal does not know
|
||||
- **THEN** the request SHALL end `failed` with the reason `not_started`, and no workflow SHALL start for it
|
||||
|
||||
#### Scenario: The pass runs with the sync disabled
|
||||
|
||||
- **WHEN** the console boots with the FedWiki sync disabled and an `accepted` request whose workflow closed without recording an outcome
|
||||
- **THEN** the pass SHALL still settle the request
|
||||
|
||||
#### Scenario: A closed create the farm holds
|
||||
|
||||
- **WHEN** the pass finds a closed create workflow whose request is `accepted` and the farm's entry names the requester as owner
|
||||
- **THEN** the reconcile workflow SHALL insert the site row under the instance identifier and the request SHALL end `succeeded`
|
||||
|
||||
#### Scenario: A closed activation the farm made active
|
||||
|
||||
- **WHEN** the pass finds a closed status change to `active` whose request is `accepted` and holds a slot, and the farm's entry shows the site active
|
||||
- **THEN** the status reconcile SHALL write the site `active`, remove the hold, and end the request `succeeded`, and the site SHALL count once
|
||||
|
||||
#### Scenario: A closed activation the farm did not make
|
||||
|
||||
- **WHEN** the status reconcile reads the farm's entry and the site is `readonly`
|
||||
- **THEN** the request SHALL end `failed` with `retries_exhausted`, its hold SHALL be removed, and the site SHALL keep its `readonly` status
|
||||
|
||||
#### Scenario: A request committed just before a quick restart
|
||||
|
||||
- **WHEN** the console restarts within two minutes of committing an `accepted` request whose workflow never started
|
||||
- **THEN** the boot pass SHALL leave it, and a second pass, run once two minutes have passed since boot, SHALL end it `failed` with `not_started`
|
||||
|
||||
#### Scenario: Temporal unreachable at boot
|
||||
|
||||
- **WHEN** describing a workflow fails with an error other than not-found
|
||||
- **THEN** the request SHALL stay `accepted`
|
||||
|
||||
#### Scenario: A closed activation has lost its original site
|
||||
|
||||
- **WHEN** the status reconcile finds its original site ID missing, including when another row has the same name
|
||||
- **THEN** it SHALL end the request `declined` with `site_missing`, remove its hold and recount
|
||||
- **AND** it SHALL NOT call the farm after discovering the missing ID or write the replacement row
|
||||
|
||||
#### Scenario: A swap that never started is settled together
|
||||
|
||||
- **WHEN** the console boots with a swap's two `accepted` requests older than two minutes whose workflow Temporal does not know
|
||||
- **THEN** both requests SHALL end `failed` with `not_started` in one transaction, and no workflow SHALL start for either
|
||||
|
||||
#### Scenario: A swap whose workflow closed is settled together
|
||||
|
||||
- **WHEN** the pass finds a swap's workflow closed and both requests `accepted`
|
||||
- **THEN** both requests SHALL end `failed` with `retries_exhausted` in one transaction, neither SHALL go to the status reconcile, and no stamp SHALL be written
|
||||
|
||||
#### Scenario: A swap's outcome lands while settle runs
|
||||
|
||||
- **WHEN** a swap's record step finishes both requests after the pass listed them and before the pass finishes them
|
||||
- **THEN** the pass SHALL change neither request and the requests SHALL keep the outcome the workflow wrote
|
||||
|
||||
### Requirement: FedWiki request outcomes show the console's own sentence for a reason code
|
||||
|
||||
A declined or failed request SHALL carry a reason code, and the console SHALL describe it only with its own sentence for that code, never text from the farm or a workflow error string. The codes with standalone sentences SHALL be:
|
||||
|
||||
- `site_limit_reached` (declined): "You have reached your site limit."
|
||||
- `active_limit_reached` (declined): "You have reached your active site limit."
|
||||
- `name_refused` (declined): "That name can't be reserved. Choose another."
|
||||
- `name_taken` (declined): "A site with this name already exists."
|
||||
- `site_changed` (declined): "This site changed since the request."
|
||||
- `quota_unavailable` (failed): "Couldn't check your site limit. Try again later."
|
||||
- `retries_exhausted` (failed): "Couldn't finish. Try again later."
|
||||
- `not_started` (failed): "Couldn't start. Try again."
|
||||
|
||||
The declined reason `site_missing` SHALL render directly as a notice, with no standalone reason sentence. When the original status-change site or the activated swap site is gone, the notice SHALL read "<domain> was deleted.", including when both swap sites are gone. When only the parked site is gone, it SHALL read "<domain> wasn't kept active. <parked domain> was deleted.", taking the parked domain from the consequent request of the same act. A request that ends `site_missing` while its own site exists, and for which the list holds no consequent request of its act, SHALL read the generic notice for its action, "<domain> wasn't <action>. Try again later.", and never "<domain> was deleted.", because the notice cannot name a site that it does not find; only a swap request that belongs to no act can reach this case. Both swap requests SHALL carry `site_missing`, but only the asked request SHALL show a notice. These notices SHALL use the declined warning tone and existing dismissal behavior; neither SHALL infer the original identity from a same-name replacement.
|
||||
|
||||
Every other notice on the site list SHALL read "<domain> wasn't <action>." followed by its reason, with the domain as plain text, where the action is "created", "archived", "restored", "kept active" or "deleted" for a create, an archive, a restore, a keep active (a swap included) and a permanent delete. A request to make an archived site active SHALL read "restored" unless it belongs to an act whose cause is `instances_swapped`, which SHALL read "kept active". The reason SHALL be the code's sentence, except that `retries_exhausted`, and a code with no sentence, SHALL read "Try again later." and `not_started` SHALL read "Try again.", because the notice's first sentence already says that the request did not happen. The JSON API's message SHALL be the code's sentence. The Status column SHALL read Pending for an open request and never Declined or Failed. The texts "Join us and become a member for more sites." and every "Please try again later" clause of the workflow error strings these codes replace SHALL NOT be shown.
|
||||
|
||||
#### Scenario: A reactivation at the active limit
|
||||
|
||||
- **WHEN** a restore of an archived site ends `declined` because active usage is at the limit
|
||||
- **THEN** its notice SHALL read "<domain> wasn't restored. You have reached your active site limit."
|
||||
|
||||
#### Scenario: No farm text reaches the notice
|
||||
|
||||
- **WHEN** a create fails with a farm error whose body carries its own message
|
||||
- **THEN** the notice SHALL show only the console's sentence for the request's reason code
|
||||
|
||||
#### Scenario: A missing restore does not need the old row to name its outcome
|
||||
|
||||
- **WHEN** a restore ends declined/site_missing after its original row is deleted
|
||||
- **THEN** its notice SHALL read "<domain> was deleted."
|
||||
- **AND** it SHALL NOT describe the request as kept active because the old status is unavailable
|
||||
|
||||
#### Scenario: Only the parked site disappeared
|
||||
|
||||
- **WHEN** a swap ends declined/site_missing, its activated ID still exists and its parked ID is gone
|
||||
- **THEN** its one notice SHALL read "<domain> wasn't kept active. <parked domain> was deleted."
|
||||
- **AND** the parked domain SHALL come from the swap's consequent request's recorded parameters, not a name lookup
|
||||
- **AND** dismissing the notice SHALL acknowledge both requests
|
||||
|
||||
#### Scenario: Both swap sites disappeared
|
||||
|
||||
- **WHEN** a swap ends declined/site_missing and both original IDs are gone
|
||||
- **THEN** its one notice SHALL read "<domain> was deleted." using the activated request's domain
|
||||
- **AND** a replacement with that name SHALL NOT change which notice is selected
|
||||
|
||||
#### Scenario: A swap recorded without an act does not name a deleted site
|
||||
|
||||
- **WHEN** a request to activate a read-only site that exists ends declined/site_missing, belongs to no act and has no consequent request
|
||||
- **THEN** its notice SHALL read "<domain> wasn't kept active. Try again later." and SHALL NOT read "<domain> was deleted."
|
||||
|
||||
#### Scenario: A swap's activation of an archived site reads kept active
|
||||
|
||||
- **WHEN** a swap whose chosen site was archived when the member asked ends `failed` with `retries_exhausted`
|
||||
- **THEN** its notice SHALL read "<domain> wasn't kept active. Try again later."
|
||||
|
||||
### Requirement: Status and swap intake reads the original sites under the instance locks
|
||||
|
||||
Before recording a new FedWiki status or swap request, intake SHALL read the original site by ID under the request's existing instance lock in the recording transaction at READ COMMITTED and verify its workspace and domain. It SHALL add no site-row lock, except that a return locks its site's row as the rotation requirement above states. A rotation's intake, a swap's and a return's alike, SHALL take the workspace lock before its instance locks and SHALL read the original sites in that transaction. A swap SHALL take its existing instance locks in activation/park order, read both original sites before inserting either request, and roll back both records when either check fails. Repeats SHALL still be answered from their records, including after deletion. Create and permanent-delete intake SHALL remain unchanged.
|
||||
|
||||
A missing or foreign primary target SHALL refuse a new request synchronously with HTTP 200 and "Site not found", without a list refresh. A missing selected park target SHALL use the existing HTTP 200 conflict response, "This site changed since the list loaded.", with a list refresh. A same-name replacement SHALL never be substituted for the original ID. Other identity conflicts SHALL retain their conflict answer. Refusal SHALL record no request, start no workflow, take no hold and stamp no cooldown. A failure of the protected ID read SHALL remain an error, never an absent-site answer.
|
||||
|
||||
#### Scenario: Purge wins before intake
|
||||
|
||||
- **WHEN** retention holds the instance lock and deletes the site before a stale status action can record
|
||||
- **THEN** intake SHALL see the deletion after obtaining the lock and refuse without recording or starting work
|
||||
|
||||
#### Scenario: Intake wins before purge
|
||||
|
||||
- **WHEN** intake commits an accepted request before retention obtains the instance lock
|
||||
- **THEN** retention SHALL see the accepted request and leave the site alone
|
||||
|
||||
#### Scenario: The session's default isolation cannot hide the purge commit
|
||||
|
||||
- **WHEN** a status or swap intake waits for retention's instance lock on a session whose default isolation is REPEATABLE READ
|
||||
- **THEN** its transaction SHALL explicitly use READ COMMITTED and its protected ID read SHALL see retention's committed deletion
|
||||
|
||||
#### Scenario: The activated swap site disappears
|
||||
|
||||
- **WHEN** the swap's original activation site is missing at the protected read
|
||||
- **THEN** intake SHALL answer "Site not found" without a refresh, record neither request and leave the cooldown unchanged
|
||||
|
||||
#### Scenario: The selected park site disappears
|
||||
|
||||
- **WHEN** the swap's selected park site is missing at the protected read
|
||||
- **THEN** intake SHALL answer "This site changed since the list loaded." with a refresh, record neither request and leave the cooldown unchanged
|
||||
|
||||
#### Scenario: A status repeat survives deletion
|
||||
|
||||
- **WHEN** an identical status request is repeated after its original site row is gone
|
||||
- **THEN** intake SHALL return its recorded answer without requiring a site row
|
||||
|
||||
#### Scenario: A failed protected read does not claim a site is gone
|
||||
|
||||
- **WHEN** the protected intake ID read fails because the database cannot answer
|
||||
- **THEN** intake SHALL return its existing operation-error response and SHALL NOT answer "Site not found"
|
||||
|
||||
#### Scenario: A return's intake reads its site under the workspace lock
|
||||
|
||||
- **WHEN** a return reaches intake with the cooldown off
|
||||
- **THEN** intake SHALL take the workspace lock, then the site's instance lock, and read the original site in the transaction that records the request
|
||||
|
||||
### Requirement: A pool's site usage is a count taken under its usage row's lock
|
||||
|
||||
A pool's `fedwiki_sites` usage row SHALL hold the number of `active` `fedwiki.sites` rows in every workspace whose active primary pool is that pool, plus the holds that count toward it (see "A slot a request holds in flight is a hold its gate stamps"). Usage is pool-grain because an organization's workspaces draw down one pool. No FedWiki path SHALL add to or subtract from the figure. Every FedWiki transaction that inserts, deletes or changes the status of a site row, or inserts or deletes a hold, SHALL recount the pool it affects before it commits, by three statements in this order: lock the pool's usage row, count the rows and holds in a separate statement, and write the count. The transaction SHALL take the usage row's lock after the site rows and holds it writes and before any lifecycle request row it finishes, and SHALL run at READ COMMITTED, so the count reads every change committed before the lock was granted. A pool with no usage row SHALL be left without one: only the materializer creates the row.
|
||||
|
||||
FedWiki SHALL recount every pool holding a `fedwiki_sites` usage row at boot, before any request is settled, and at the end of every sync pass's projection, so a figure that went stale beside a write made outside a recounting transaction, or a row the materializer created at zero beside existing sites, is corrected without a member's action.
|
||||
|
||||
#### Scenario: Rows written outside the console are counted at the next recount
|
||||
|
||||
- **WHEN** a pool's figure reads 1, its active site rows number 64 because an import inserted them, and its limit is 64
|
||||
- **THEN** after the next boot or sync pass the pool's figure SHALL read 64
|
||||
- **AND** a member's create SHALL be declined with `site_limit_reached`, because the gate counts the rows under the lock whatever the stored figure reads
|
||||
|
||||
#### Scenario: Every workspace of the pool is counted
|
||||
|
||||
- **WHEN** an organization's two workspaces share one primary pool with a limit of 3, one holds one active site and the other two, and a member of the first submits a create
|
||||
- **THEN** the create SHALL be declined with `site_limit_reached`
|
||||
- **AND** the pool's figure SHALL read 3
|
||||
|
||||
#### Scenario: Boot counts the slots of requests running across the restart
|
||||
|
||||
- **WHEN** the console boots with a pool holding two active sites, one `accepted` create that holds a slot, one `accepted` activation that holds a slot, and a figure of 7
|
||||
- **THEN** after the boot recount the figure SHALL read 4
|
||||
- **AND** once both requests have finished with the create succeeded and the activation declined, the figure SHALL read 3
|
||||
|
||||
#### Scenario: A park that commits while a gate waits is counted
|
||||
|
||||
- **WHEN** the quota sweep's park of a site holds the pool's usage row and a create's gate waits on it
|
||||
- **THEN** after the park commits, the gate's count SHALL exclude the parked site
|
||||
|
||||
#### Scenario: A sweep reactivation and a member's Keep active count the site once
|
||||
|
||||
- **WHEN** a member's Keep active of a parked site has passed its gate and holds a slot, and the quota sweep reactivates the same site before the Keep active records its outcome
|
||||
- **THEN** from the sweep's commit the site SHALL count once, as an active row, and the Keep active's hold SHALL count for nothing
|
||||
- **AND** after the Keep active records its outcome the pool's figure SHALL equal its active row count
|
||||
|
||||
#### Scenario: A pool with no usage row is not given one
|
||||
|
||||
- **WHEN** a recount runs for the System tenant's workspace, whose pool has no `fedwiki_sites` usage row
|
||||
- **THEN** no usage row SHALL be created and the transaction SHALL commit its site change
|
||||
|
||||
#### Scenario: An outcome on a pool with no usage row is recorded
|
||||
|
||||
- **WHEN** a status change's record step runs for a workspace whose pool has no `fedwiki_sites` usage row
|
||||
- **THEN** the step SHALL commit the site's status and the request's outcome, and SHALL NOT retry for want of the row
|
||||
- **AND** only the slot gate, and the recorded quota activities that stand in for it, SHALL treat the missing row as a failure
|
||||
|
||||
### Requirement: A slot a request holds in flight is a hold its gate stamps
|
||||
|
||||
A create, and a status change to `active` that is not part of a swap, SHALL take its slot in a gate that runs in its workflow before the farm call, in one transaction: lock the request's instance, find the request still `accepted`, lock the site row of an activation (a create has none), lock the pool's usage row, count the pool's active rows and holds, and, only when that count is below the pool's `fedwiki_sites` limit, insert a row into `fedwiki.slot_holds` keyed by the request's identifier and write the new count; an activation whose site row is already `active` is stamped without that comparison. A hold SHALL count toward its pool while its request is `accepted` and its instance has no `active` site row. The transaction that records the request's outcome, whatever the outcome, SHALL delete the request's hold and recount.
|
||||
|
||||
The gate SHALL decline a create with `site_limit_reached`, and an activation with `active_limit_reached`, when the count has reached the limit or the pool has no `fedwiki_sites` entitlement. It SHALL fail the request with `quota_unavailable` when the pool, the entitlement or the usage row cannot be read, and it SHALL NOT treat a failed read of the entitlement as an absent one. An activation gate SHALL first require the original site row by ID, even when its hold already exists; a missing row SHALL end the request `declined` with `site_missing`, removing any existing hold and recounting in its finish transaction. A create SHALL require no site row. A gate whose hold already exists and whose required site still exists SHALL pass without comparing quota again, so a retry after a lost answer does not decline the request it already admitted. An activation whose site row is already `active` SHALL be stamped without comparing the count with the limit, and its hold SHALL count nothing while the row is active. A swap SHALL take no hold: its record step takes the slot for the site it activates in the transaction that writes both statuses.
|
||||
|
||||
#### Scenario: Two creates for the last slot
|
||||
|
||||
- **WHEN** a pool's limit is 3, it holds two active sites, and two creates reach their gates at once
|
||||
- **THEN** one gate SHALL stamp a hold and the other SHALL wait on the usage row, count the first's hold, and decline its create with `site_limit_reached`
|
||||
|
||||
#### Scenario: A create recorded but not yet gated holds nothing
|
||||
|
||||
- **WHEN** a pool's limit is 3, it holds two active sites, and two creates have been recorded but neither has reached its gate
|
||||
- **THEN** the pool's figure SHALL read 2, and the first create to reach its gate SHALL hold the last slot
|
||||
|
||||
#### Scenario: A retried gate keeps its slot
|
||||
|
||||
- **WHEN** the gate's transaction commits a hold that takes the pool's last slot and its answer is lost, and the activity runs again
|
||||
- **THEN** the second run SHALL find the hold and pass
|
||||
|
||||
#### Scenario: A failed entitlement read fails the create
|
||||
|
||||
- **WHEN** the gate cannot read the pool's `fedwiki_sites` entitlement because the database returns an error other than no rows
|
||||
- **THEN** after its attempts the request SHALL end `failed` with `quota_unavailable`, and the notice SHALL say that the site limit could not be checked
|
||||
|
||||
#### Scenario: An activation of a site that is already active is stamped
|
||||
|
||||
- **WHEN** the quota sweep has reactivated a parked site, and a member's Keep active of the same site then reaches its gate with the pool at its limit
|
||||
- **THEN** the gate SHALL stamp a hold without declining, and the pool's figure SHALL be unchanged
|
||||
- **AND** when the sweep parks the site again before the Keep active records its outcome, the hold SHALL count from the park's commit, and the Keep active's record SHALL leave the site counted once
|
||||
|
||||
#### Scenario: A finished request's hold never counts
|
||||
|
||||
- **WHEN** a hold row remains for a request that is no longer `accepted`
|
||||
- **THEN** no recount SHALL count it
|
||||
|
||||
#### Scenario: A run started before the upgrade holds no hold
|
||||
|
||||
- **WHEN** a create started by the previous release passed its quota step before the upgrade and is still running
|
||||
- **THEN** it SHALL finish on its recorded commands without a hold, and its site SHALL count from the moment its row is inserted
|
||||
|
||||
#### Scenario: A missing activation is not a create
|
||||
|
||||
- **WHEN** an activation's original site is deleted before its gate, whether or not the request already holds a slot and whether or not the pool is full
|
||||
- **THEN** the gate SHALL NOT stamp a new hold or answer active_limit_reached
|
||||
- **AND** the request SHALL end `declined` with `site_missing` and its finish SHALL remove any existing hold and recount
|
||||
@@ -0,0 +1,214 @@
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Writer role grants read-write data access
|
||||
|
||||
The `{schema}_writer` role SHALL have `SELECT`, `INSERT`, `UPDATE`, `DELETE`
|
||||
privileges on all tables in its schema, EXCEPT for `INSERT`, `UPDATE` and
|
||||
`DELETE` on any table that a capability spec explicitly designates as
|
||||
enclosed behind SECURITY DEFINER functions, EXCEPT for `INSERT` and
|
||||
`UPDATE` on any table that a capability spec explicitly designates as an
|
||||
insert enclosure, and EXCEPT for `INSERT` and `UPDATE` on any table that a
|
||||
capability spec explicitly designates as a column enclosure. It SHALL hold no
|
||||
other table privilege: `TRUNCATE`,
|
||||
`REFERENCES`, `TRIGGER` and `MAINTAIN` SHALL be revoked from it on every table
|
||||
of its schema, so that it cannot empty or lock a table, add a foreign key, or
|
||||
attach a trigger that fires with the privileges of a function owner.
|
||||
For each such enclosed table,
|
||||
`{schema}_writer`'s direct INSERT, UPDATE, DELETE and TRUNCATE privileges SHALL be
|
||||
revoked, and `{schema}_writer` SHALL instead be granted EXECUTE on the
|
||||
designated functions as its sole write path; SELECT on the enclosed table
|
||||
SHALL be unaffected. For each insert-enclosed table, `{schema}_writer` SHALL
|
||||
hold no INSERT, SHALL hold UPDATE only on the columns the designating spec
|
||||
names, and SHALL keep SELECT and DELETE; rows SHALL be inserted only by the
|
||||
SECURITY DEFINER triggers and functions that spec names. For each
|
||||
column-enclosed table, `{schema}_writer` SHALL hold no table-level INSERT and no
|
||||
table-level UPDATE, SHALL hold INSERT only on the columns the designating spec
|
||||
names for INSERT and UPDATE only on the columns it names for UPDATE, and SHALL
|
||||
keep SELECT and DELETE; a column that the spec names for neither privilege SHALL
|
||||
be set only by its default, by a trigger on the table, or by the SECURITY DEFINER function that spec names.
|
||||
The `core`
|
||||
schema's `pool_provisions`,
|
||||
`pool_provision_ladders`, and `pool_provision_transitions` tables are the
|
||||
first such enclosure — see the "Entitlements position-machinery enclosure"
|
||||
requirement in this same capability for the full grant/revoke posture and the
|
||||
five conferral functions; it is not repeated here. `core.person_cut_offs` is
|
||||
enclosed the same way, and so are the act record's five tables
|
||||
(`core.acts`, `core.plan_act_details`, `core.plan_act_reached_org_types`,
|
||||
`core.plan_act_orgs_without_pool` and `core.plan_act_obligations`). The
|
||||
obligations are a mutable work list, and they are enclosed rather than given
|
||||
column UPDATE grants so that every status change of an obligation goes
|
||||
through a function, and a transition the plan acts do not name is not a
|
||||
privilege the writer holds. `core.desired_state_outbox` is the first insert
|
||||
enclosure and `core.lifecycle_requests` is the first column enclosure — see the
|
||||
"Person cut-off enclosure", "Act record enclosure",
|
||||
"Desired-state outbox insert enclosure" and "Delivery tables and their
|
||||
invoker-rights functions are granted explicitly" requirements in this same
|
||||
capability.
|
||||
It SHALL reach the application's runtime user only through membership of
|
||||
`console_runtime` (see "Application login role wiring is explicit").
|
||||
|
||||
#### Scenario: Writer holds no privilege beyond the four
|
||||
|
||||
- **WHEN** every migration has run
|
||||
- **THEN** no `{schema}_writer` role and not `console_runtime` SHALL hold `TRUNCATE`, `REFERENCES`, `TRIGGER` or `MAINTAIN` on any table, partition or view of the streams' schemas
|
||||
- **AND** this SHALL hold for a fresh database and for one migrated by an earlier release
|
||||
|
||||
#### Scenario: Writer role can perform CRUD operations
|
||||
|
||||
- **WHEN** a session holding `core_writer` works on a `core` table that no capability spec encloses
|
||||
- **THEN** it SHALL be able to `SELECT`, `INSERT`, `UPDATE`, and `DELETE` rows in it
|
||||
- **AND** it SHALL NOT be able to `ALTER TABLE` or `DROP TABLE`
|
||||
|
||||
#### Scenario: Enclosed tables are excepted from the unqualified writer grant
|
||||
|
||||
- **WHEN** a capability spec designates one or more tables in a schema as
|
||||
enclosed behind SECURITY DEFINER functions (for example `core`'s
|
||||
three position tables)
|
||||
- **THEN** `{schema}_writer` SHALL NOT hold direct INSERT, UPDATE, DELETE or
|
||||
TRUNCATE privileges on those tables
|
||||
- **AND** `{schema}_writer` SHALL instead hold EXECUTE on the designated
|
||||
functions as its only path to writing them
|
||||
- **AND** `{schema}_writer`'s privileges on every other, non-enclosed table
|
||||
in the schema SHALL remain the unqualified SELECT/INSERT/UPDATE/DELETE
|
||||
grant
|
||||
|
||||
#### Scenario: Insert-enclosed tables refuse the writer's inserts
|
||||
|
||||
- **WHEN** a capability spec designates a table as an insert enclosure (for
|
||||
example `core.desired_state_outbox`)
|
||||
- **THEN** `{schema}_writer` SHALL NOT hold INSERT on that table
|
||||
- **AND** `{schema}_writer` SHALL hold UPDATE only on the columns that spec
|
||||
names, and SELECT and DELETE on the table
|
||||
|
||||
#### Scenario: Column-enclosed tables grant the writer named columns only
|
||||
|
||||
- **WHEN** a capability spec designates a table as a column enclosure (for
|
||||
example `core.lifecycle_requests`)
|
||||
- **THEN** `{schema}_writer` SHALL NOT hold INSERT or UPDATE on the table as a
|
||||
whole
|
||||
- **AND** `{schema}_writer` SHALL hold INSERT only on the columns that spec
|
||||
names for INSERT, UPDATE only on the columns it names for UPDATE, and SELECT
|
||||
and DELETE on the table
|
||||
|
||||
### Requirement: Delivery tables and their invoker-rights functions are granted explicitly
|
||||
|
||||
The migration that creates `core.provider_connections`, `core.target_mappings`, `core.desired_state_records`, `core.observed_projections` and `core.lifecycle_requests` SHALL grant each of them explicitly: all privileges to `core_owner`; SELECT, INSERT, UPDATE and DELETE to `core_writer`; SELECT to `core_reader`. `core.desired_state_content`, `core.generation_ceiling`, `core.next_generation` and `core.guard_desired_state_generation` SHALL run with invoker rights, and EXECUTE on them SHALL be granted to `core_owner`, `core_writer` and `core_reader`. An integration's writer role, which holds `core_reader`, SHALL be able to read every new delivery table and write none of them.
|
||||
|
||||
`core.lifecycle_requests` SHALL be a column enclosure once the migration that adds its act columns (`act_id`, `act_cause` and `act_role`) has run. That migration SHALL revoke `core_writer`'s table-level INSERT and UPDATE on it and SHALL grant `core_writer`: SELECT and DELETE on the table; INSERT on the nine columns that recording a request names, `instance_id`, `generation`, `connection_id`, `resource_key`, `workspace_id`, `operation`, `parameters`, `workflow_id` and `requested_by_person_id`; and UPDATE on the four columns that an outcome and an acknowledgement set, `status`, `reason_code`, `finished_at` and `acknowledged_at`. `core_writer` SHALL hold no INSERT and no UPDATE on any other column, so it cannot write `act_id`, `act_cause` or `act_role`, which only `core.record_lifecycle_act` writes ("Act record enclosure"), and cannot change a request's workspace, connection, operation or requested person after it is recorded.
|
||||
|
||||
#### Scenario: The application role writes the ordinary delivery tables
|
||||
|
||||
- **WHEN** a session holding `core_writer` inserts, updates and deletes rows in `core.provider_connections`, `core.target_mappings`, `core.desired_state_records` and `core.observed_projections`
|
||||
- **THEN** each statement SHALL succeed on privilege grounds
|
||||
|
||||
#### Scenario: The application role writes the columns a request writer names
|
||||
|
||||
- **WHEN** a session holding `core_writer` inserts a row into `core.lifecycle_requests` naming only the nine granted columns, sets `status`, `reason_code`, `finished_at` and `acknowledged_at` on a row, and deletes a row
|
||||
- **THEN** each statement SHALL succeed on privilege grounds
|
||||
|
||||
#### Scenario: The application role cannot write the act columns or the columns a request is addressed by
|
||||
|
||||
- **WHEN** a session holding `core_writer` inserts a row into `core.lifecycle_requests` that names `act_id`, `act_cause` or `act_role`, and updates `act_id`, `act_cause`, `act_role`, `workspace_id`, `connection_id`, `operation` or `requested_by_person_id` on an existing row
|
||||
- **THEN** PostgreSQL SHALL reject each statement on privilege grounds
|
||||
|
||||
#### Scenario: An integration writer reads and does not write
|
||||
|
||||
- **WHEN** a session holding only `fedwiki_writer` selects from `core.lifecycle_requests` and `core.desired_state_records`, and then inserts into `core.lifecycle_requests`
|
||||
- **THEN** the selects SHALL succeed
|
||||
- **AND** the insert SHALL be rejected on privilege grounds
|
||||
|
||||
#### Scenario: The reader computes a record's content
|
||||
|
||||
- **WHEN** a session holding only `core_reader` calls `core.desired_state_content` for a connection and a recipient
|
||||
- **THEN** the call SHALL succeed on privilege grounds
|
||||
|
||||
### Requirement: Act record enclosure
|
||||
|
||||
`core.acts`, `core.plan_act_details`, `core.plan_act_reached_org_types`, `core.plan_act_orgs_without_pool` and `core.plan_act_obligations` SHALL be enclosed: `core_writer` SHALL hold SELECT on each and no INSERT, UPDATE, DELETE or TRUNCATE on any. Six functions SHALL be the only writers of the five tables and of the act columns of `core.lifecycle_requests`: `core.record_plan_act` (an act row, its detail row and the org types it reaches), `core.write_plan_act_obligations` (one listing batch: the supersession of older open obligations, the insert of new ones and the records of organizations without a default pool), `core.settle_plan_act_obligation` (one obligation settled with its outcome), `core.record_plan_act_obligation_failure` (one failed attempt on a pending obligation), `core.requeue_plan_act_obligations` (a Retry's requeue) and `core.record_lifecycle_act` (an act row of a lifecycle cause, with no detail row, and the link of the lifecycle requests that its own transaction inserted to that act). Each SHALL be created `SECURITY DEFINER`, owned by `core_owner`, and SHALL declare `SET search_path = core, pg_temp`, with `pg_temp` pinned last; EXECUTE on each SHALL be revoked from `PUBLIC` and granted to `core_writer`. `core.record_plan_act`, for every cause but a Retry, SHALL first assert that the calling transaction holds the materialization rendezvous in exclusive mode; `core.record_plan_act` for a Retry, `core.write_plan_act_obligations`, `core.settle_plan_act_obligation` and `core.requeue_plan_act_obligations` SHALL first assert that it holds the rendezvous in either mode. `core.record_lifecycle_act` SHALL assert no rendezvous, because a lifecycle act changes no entitlement; it SHALL refuse a cause that is not a lifecycle cause, so that a plan cause cannot get a header without its detail row and its rendezvous assertion, and SHALL refuse, writing nothing, a request that its own transaction did not insert, one that is not `accepted`, one that already carries a link, and a set of requests that does not belong to one workspace and one connection. `core_reader` SHALL hold SELECT on `core.plan_act_details`, `core.plan_act_reached_org_types`, `core.plan_act_orgs_without_pool` and `core.plan_act_obligations`, and SELECT on every column of `core.acts` except `note`, through column grants. `core_owner` SHALL hold all privileges.
|
||||
|
||||
#### Scenario: The writer cannot write an act directly
|
||||
|
||||
- **WHEN** a session holding only `core_writer` inserts, updates or deletes a row of `core.acts`, `core.plan_act_details` or `core.plan_act_reached_org_types`
|
||||
- **THEN** PostgreSQL SHALL reject the statement on privilege grounds
|
||||
|
||||
#### Scenario: The writer cannot reopen or repoint an obligation
|
||||
|
||||
- **WHEN** a session holding only `core_writer` updates any column of `core.plan_act_obligations`, such as returning a failed row to `pending` or changing `superseded_by_act_id`
|
||||
- **THEN** PostgreSQL SHALL reject the statement on privilege grounds
|
||||
|
||||
#### Scenario: The writer settles and records failures through the functions
|
||||
|
||||
- **WHEN** a session holding only `core_writer` calls `core.settle_plan_act_obligation` inside a transaction that holds the rendezvous, and `core.record_plan_act_obligation_failure` in a plain one
|
||||
- **THEN** each call SHALL succeed and change only the named obligation
|
||||
|
||||
#### Scenario: The writer records a lifecycle act without the rendezvous
|
||||
|
||||
- **WHEN** a session holding only `core_writer` inserts two lifecycle requests and calls `core.record_lifecycle_act` for them in the same transaction, which holds no materialization rendezvous
|
||||
- **THEN** the call SHALL succeed
|
||||
- **AND** one `core.acts` row of the lifecycle cause SHALL exist, with no row in `core.plan_act_details`, and both requests SHALL carry its `act_id`
|
||||
|
||||
#### Scenario: The lifecycle function refuses a request its transaction did not insert
|
||||
|
||||
- **WHEN** a session holding only `core_writer` calls `core.record_lifecycle_act` in a transaction other than the one that inserted a named request
|
||||
- **THEN** the call SHALL be refused with an error
|
||||
- **AND** no `core.acts` row SHALL be written and no request SHALL change
|
||||
|
||||
#### Scenario: The lifecycle function refuses a plan cause
|
||||
|
||||
- **WHEN** a session holding only `core_writer` calls `core.record_lifecycle_act` with a cause that is a plan cause
|
||||
- **THEN** the call SHALL be refused with an error and write nothing
|
||||
|
||||
#### Scenario: The writer cannot join a request to an act directly
|
||||
|
||||
- **WHEN** a session holding only `core_writer` updates `act_id`, `act_cause` or `act_role` of a row of `core.lifecycle_requests`
|
||||
- **THEN** PostgreSQL SHALL reject the statement on privilege grounds
|
||||
|
||||
#### Scenario: PUBLIC cannot call the act functions
|
||||
|
||||
- **WHEN** a login role that is not a member of `core_writer`, and holds no other explicit grant, calls any of the six functions
|
||||
- **THEN** the call SHALL be rejected
|
||||
|
||||
#### Scenario: Pinned search_path resists temp-table shadowing
|
||||
|
||||
- **WHEN** a calling session has created a temporary table named `acts`, `plan_act_obligations` or `lifecycle_requests` and then calls `core.record_plan_act`, `core.write_plan_act_obligations` or `core.record_lifecycle_act`
|
||||
- **THEN** the function SHALL write the real `core` table
|
||||
- **AND** the caller's temporary table SHALL NOT be written
|
||||
|
||||
#### Scenario: The core reader cannot read a note
|
||||
|
||||
- **WHEN** a session holding only `core_reader` selects `core.acts.note`
|
||||
- **THEN** PostgreSQL SHALL reject the statement on privilege grounds
|
||||
|
||||
### Requirement: The runtime group role's privileges are checked against the catalog
|
||||
|
||||
A test SHALL read the catalog of a migrated database and fail unless, for `console_runtime`: every table, partitioned table and view in the schemas of the migration streams is readable; every such table outside an explicit list of locked tables holds `INSERT`, `UPDATE` and `DELETE`; each locked table holds exactly the privileges its entry lists among `INSERT`, `UPDATE` and `DELETE`, where an entry that names columns for `INSERT` or for `UPDATE` lists that privilege on exactly those columns and not on the table; no table, partitioned table, partition or view in those schemas grants it `TRUNCATE`, `REFERENCES`, `TRIGGER` or `MAINTAIN`; every entry of the list names an existing table; every stream's goose ledger is readable; `core.ensure_webhook_event_partitions` and `core.lock_plan_act_obligation` are executable; and no role other than `console_runtime` is a direct member of a writer role, apart from `fedwiki_writer`'s membership of `domains_writer`. Partitions SHALL be checked for reading and writing through their parent table. The migrations SHALL NOT use `ALTER DEFAULT PRIVILEGES`: each table's grants SHALL be written in the migration that creates it, or in a later migration of the same stream that names the table and narrows them, and an enclosure SHALL remain a grant that is absent.
|
||||
|
||||
#### Scenario: A forgotten grant fails the test
|
||||
|
||||
- **WHEN** a migration creates a table in one of the streams' schemas and grants nothing on it to its writer role
|
||||
- **THEN** the catalog test SHALL fail, naming the table and the privilege `console_runtime` lacks
|
||||
|
||||
#### Scenario: A lost revoke fails the test
|
||||
|
||||
- **WHEN** a migration grants `INSERT` on `core.pool_provisions` to `core_writer`, or to `console_runtime`
|
||||
- **THEN** the catalog test SHALL fail, naming the table and the privilege its locked entry does not list
|
||||
|
||||
#### Scenario: A column grant outside the entry fails the test
|
||||
|
||||
- **WHEN** a migration grants `INSERT` or `UPDATE` on `core.lifecycle_requests` as a whole, or on a column that its locked entry does not list for that privilege, such as `act_id`, to `core_writer` or to `console_runtime`
|
||||
- **THEN** the catalog test SHALL fail, naming the table, the privilege and the column
|
||||
|
||||
#### Scenario: A missing column grant fails the test
|
||||
|
||||
- **WHEN** a migration leaves `console_runtime` without `INSERT` on a column that the locked entry of `core.lifecycle_requests` lists for `INSERT`
|
||||
- **THEN** the catalog test SHALL fail, naming the table, the privilege and the column
|
||||
|
||||
#### Scenario: A privilege beyond the four fails the test
|
||||
|
||||
- **WHEN** a baseline or a migration grants `ALL` on a table to a writer role after the stream's revoke of `TRUNCATE`, `REFERENCES`, `TRIGGER` and `MAINTAIN`, or the revoke is missing
|
||||
- **THEN** the catalog test SHALL fail, naming the table and the privilege `TRIGGER`
|
||||
|
||||
#### Scenario: A stale entry fails the test
|
||||
|
||||
- **WHEN** the locked list names a table that no longer exists
|
||||
- **THEN** the catalog test SHALL fail, naming the entry
|
||||
@@ -0,0 +1,128 @@
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: FedWiki site downgrade parks excess sites read-only
|
||||
|
||||
When a downgrade lowers the `fedwiki_sites` limit below the count of active sites, the system SHALL park the excess sites read-only via `set_status(readonly)` so that active usage is restored to the new limit, but only where the reduction policy governing that pool's `fedwiki_sites` limit is `force_reduce`. Where that policy is `clamp`, the surplus is the member's: no site SHALL be parked, no `force_reduced_at` SHALL be stamped, and the over-limit state SHALL be resolved by refusing new creation alone. Where the policy is `block` or `defer`, it resolves to `clamp` and the system SHALL behave as under `clamp`. Under `force_reduce` the `limit`-many highest-ranked sites SHALL be kept active by default. The rank SHALL use each site's observed farm `last_modified_at`, or its `created_at` when no modification time has been recorded, descending; ties SHALL use `created_at` descending and then `site_id` descending. Only sync records farm modification times. Sites never observed by sync SHALL rank by creation time; disabling sync SHALL retain any times already recorded. Parked sites SHALL be stamped with `force_reduced_at`. Read-only parking SHALL be non-destructive; content is retained and remains readable.
|
||||
|
||||
The member MAY change which sites are active, subject to a per-workspace cooldown that gates **rotations**, which means bringing a *different* site into the active set in place of one already there. A transition **into** `active` SHALL be a rotation when the activated site is **force-reduced** (`force_reduced_at IS NOT NULL`, a site that a downgrade or an earlier swap parked), OR when it is a Keep active performed while active usage is at the limit (a swap that parks an incumbent to promote another). A Restore of an archived site SHALL never be a rotation. Restoring a site that is **not** force-reduced, the member's own incumbent, whether currently active or one they archived themselves, SHALL always be allowed and SHALL NOT consult the cooldown (it returns the status quo, not a rotation). The cooldown window SHALL start only when a rotation succeeds and the member's action brought the chosen site into the active set; the window SHALL start at the time that success is recorded, whether or not the cooldown is configured. A rotation that fails, is declined, or never starts SHALL leave the workspace's window as it was, and a rotation whose chosen site the re-upgrade sweep reactivated before the member's action took effect SHALL NOT start the window, because the sweep, not the member's action, brought that site back. The first rotation within a cooldown window SHALL be free and subsequent rotations SHALL be refused until the window elapses for that workspace; restoring an incumbent SHALL neither be refused nor start or extend the window. When a force-reduced site is rotated back into the active set, its `force_reduced_at` SHALL be cleared. The cooldown window SHALL be configurable, default 30 days, and any user-facing refusal message SHALL reflect the configured window.
|
||||
|
||||
A rotation is open from the moment the console accepts it until its outcome is recorded, except that a Keep active below the limit on a force-reduced site, which is not a swap, stops being open once the re-upgrade sweep has made that site active and cleared its `force_reduced_at`, because it no longer brings a different site into the active set. While a rotation of a workspace is open, the system SHALL refuse every other rotation of that workspace, whether or not the cooldown is configured, with the sentence "A change to your active site is already in progress", and SHALL record nothing for the refused rotation. A repeat of the open rotation's own request is not another rotation and SHALL be answered from its record. Restoring a site that is not force-reduced SHALL be allowed while a rotation is open, and it SHALL NOT count as a rotation.
|
||||
|
||||
When the limit later rises (re-upgrade), the system SHALL auto-reactivate `force_reduced_at` sites, in the same rank order, up to the new limit, clearing `force_reduced_at`; each reactivation SHALL be quota-gated.
|
||||
|
||||
The member's Keep-active swap SHALL use the same ranking to choose the lowest-ranked active site in that member's workspace to park.
|
||||
|
||||
Only an absent entitlement (`sql.ErrNoRows`) SHALL count as no limit. Any other entitlement-read error SHALL be logged at Warn with the pool and error; that pool SHALL be left unchanged for a later run.
|
||||
|
||||
#### Scenario: Downgrade parks excess sites and keeps the default active
|
||||
|
||||
- **WHEN** a member with 3 active sites is downgraded so the `fedwiki_sites` limit becomes 1, under a governing rule whose policy is `force_reduce`
|
||||
- **THEN** the highest-ranked site SHALL remain active
|
||||
- **AND** the other 2 sites SHALL be set read-only and stamped `force_reduced_at`
|
||||
- **AND** active `current_usage` SHALL equal 1 (the new limit)
|
||||
|
||||
#### Scenario: A clamp policy parks nothing
|
||||
|
||||
- **WHEN** a member with 3 active sites has the `fedwiki_sites` limit lowered to 1 under a governing rule whose policy is `clamp`
|
||||
- **THEN** no site SHALL be parked and none SHALL be stamped `force_reduced_at`
|
||||
- **AND** all 3 sites SHALL remain active and usable
|
||||
- **AND** new site creation SHALL be refused while active usage is above the limit
|
||||
|
||||
#### Scenario: Parked site content remains readable
|
||||
|
||||
- **WHEN** a site has been parked read-only by `force_reduce`
|
||||
- **THEN** its pages SHALL remain served and readable
|
||||
- **AND** edits, forks, and new pages SHALL be blocked
|
||||
|
||||
#### Scenario: Member swaps the active site, second swap refused by cooldown
|
||||
|
||||
- **WHEN** a member on a 1-site limit swaps which site is active for the first time
|
||||
- **THEN** the swap SHALL succeed (the chosen site becomes active, the prior one read-only)
|
||||
- **WHEN** the same member attempts a second swap before the cooldown elapses
|
||||
- **THEN** the swap SHALL be refused
|
||||
|
||||
#### Scenario: Restoring your incumbent active site is always free
|
||||
|
||||
- **WHEN** a member archives the site that was active (not force-reduced) and then restores that same site
|
||||
- **THEN** the restore SHALL be allowed without consulting the cooldown
|
||||
- **AND** it SHALL NOT stamp or extend the cooldown window
|
||||
|
||||
#### Scenario: Rotating a downgrade-parked reserve in is gated
|
||||
|
||||
- **WHEN** a member whose quota was reduced keeps active a `force_reduced` (parked) read-only site for the first time within the window
|
||||
- **THEN** the Keep active SHALL succeed, clear that site's `force_reduced_at`, and stamp the cooldown when it succeeds
|
||||
- **WHEN** the member tries to rotate in another `force_reduced` site before the window elapses
|
||||
- **THEN** that rotation SHALL be refused
|
||||
- **AND** restoring their own (non-force-reduced) incumbent SHALL still be allowed during the window
|
||||
|
||||
#### Scenario: A rotation that did not succeed leaves the wait as it was
|
||||
|
||||
- **WHEN** a member's swap is accepted, and its farm call fails, the console declines it, or its workflow cannot be started and its requests are deleted
|
||||
- **THEN** the workspace's cooldown stamp SHALL be as it was before the member's click: absent if it was absent, and unchanged if it was set
|
||||
- **AND** the member's next Keep active SHALL NOT be refused because of that rotation
|
||||
- **WHEN** a member's Keep active on a `force_reduced` site below the limit is accepted and then fails, is declined, or its workflow cannot be started and its request is deleted
|
||||
- **THEN** the workspace's cooldown stamp SHALL be as it was before the click, and the next Keep active SHALL NOT be refused because of that rotation
|
||||
|
||||
#### Scenario: A second rotation while one is open is refused
|
||||
|
||||
- **WHEN** a rotation of a workspace is open, and the member requests a swap, or Keep active on a `force_reduced` site, in the same workspace
|
||||
- **THEN** the system SHALL refuse it with "A change to your active site is already in progress", whether or not the cooldown is configured
|
||||
- **AND** the system SHALL record no request for the refused rotation and SHALL NOT change the cooldown stamp
|
||||
- **WHEN** the open rotation's outcome is recorded
|
||||
- **THEN** the member's next rotation SHALL NOT be refused for the open rotation, and while the cooldown is configured it SHALL be refused for the cooldown only until the window that the workspace's last stamped success started has elapsed
|
||||
|
||||
#### Scenario: Restoring an incumbent is allowed while a rotation is open
|
||||
|
||||
- **WHEN** a rotation of a workspace is open and the member restores a site of that workspace that is not force-reduced
|
||||
- **THEN** the restore SHALL be recorded and SHALL NOT be refused for the open rotation
|
||||
- **AND** it SHALL NOT start or extend the cooldown window
|
||||
|
||||
#### Scenario: A rotation that ended without an outcome starts no wait
|
||||
|
||||
- **WHEN** the workflow of a swap closes without recording an outcome, and the console, settling it at boot, ends both of its requests `failed` with reason `retries_exhausted`
|
||||
- **THEN** the cooldown stamp SHALL NOT be written, even when the farm applied the swap
|
||||
- **WHEN** the workflow of a Keep active on a `force_reduced` site closes without recording an outcome, holds no activation slot, and the console ends its request `failed` with reason `retries_exhausted`
|
||||
- **THEN** the cooldown stamp SHALL NOT be written
|
||||
|
||||
#### Scenario: A swap whose chosen site the sweep reactivated starts no wait
|
||||
|
||||
- **WHEN** the re-upgrade sweep finds no open request on a `force_reduced` site, a swap that activates that site is then accepted, and the sweep writes the site's reactivation during the swap's farm calls, before the swap's success is recorded
|
||||
- **THEN** the swap SHALL succeed with the chosen site active and the parked site read-only
|
||||
- **AND** the cooldown stamp SHALL NOT be written
|
||||
|
||||
#### Scenario: Cooldown window honors configuration
|
||||
|
||||
- **WHEN** the configured cooldown window is changed from its default
|
||||
- **THEN** rotations SHALL be gated by the configured window
|
||||
- **AND** the user-facing refusal message SHALL reflect the configured window
|
||||
|
||||
#### Scenario: Re-upgrade reactivates parked sites up to the new limit
|
||||
|
||||
- **WHEN** a member with 2 `force_reduced` read-only sites is upgraded so the limit becomes 3
|
||||
- **THEN** the system SHALL reactivate the `force_reduced` sites in the same rank order, up to the limit
|
||||
- **AND** the reactivated sites SHALL have `force_reduced_at` cleared
|
||||
|
||||
#### Scenario: No farm modification time has been recorded
|
||||
|
||||
- **WHEN** a force-reduce pool with three active sites and no recorded modification times has its limit lowered to one
|
||||
- **THEN** the most recently created site SHALL remain active and the other two SHALL be parked
|
||||
- **AND** a later re-upgrade SHALL choose among parked sites using the same fallback
|
||||
|
||||
#### Scenario: An unobserved site competes with an observed site
|
||||
|
||||
- **WHEN** an unobserved site's creation is newer than an observed site's recorded modification, but older than that observed site's creation
|
||||
- **THEN** the unobserved site SHALL rank ahead for both keeping active and reactivating
|
||||
- **AND** the observed site's recorded modification SHALL take precedence over its own creation time
|
||||
|
||||
#### Scenario: A failed entitlement read is not absence
|
||||
|
||||
- **WHEN** a pool's entitlement read fails with an error other than `sql.ErrNoRows`
|
||||
- **THEN** quota reconciliation SHALL log that error with the pool at Warn and leave the pool unchanged
|
||||
- **WHEN** the read returns `sql.ErrNoRows`
|
||||
- **THEN** reconciliation SHALL leave the pool unchanged without reporting an error
|
||||
|
||||
#### Scenario: Keep-active uses the same fallback to choose the parked site
|
||||
|
||||
- **WHEN** a workspace at its two-site limit has an unobserved active site whose creation is newer than an observed active site's recorded modification but older than that observed site's creation, and the member chooses Keep active on a third read-only site
|
||||
- **THEN** the swap SHALL choose the observed site to park, leaving the unobserved site active
|
||||
- **AND** a recorded modification time SHALL take precedence over that site's creation time, as in the sweep's ranking
|
||||
@@ -0,0 +1,247 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: A lifecycle request covers exactly one instance and an act groups an action's requests
|
||||
|
||||
A lifecycle request SHALL cover exactly one instance. An action that changes several instances SHALL record one lifecycle request for each, in one transaction, and SHALL group them under one lifecycle act: a `core.acts` row whose rows are lifecycle requests and which has no detail table.
|
||||
|
||||
- A request's link to its act SHALL be three columns on `core.lifecycle_requests`, `act_id`, `act_cause` and `act_role`. They SHALL be all set or all NULL, and `(act_id, act_cause)` SHALL refer to the act's header, so a request can point only at an act of the cause it states. A request SHALL belong to at most one act. A request that belongs to no act holds NULL in all three.
|
||||
- The role SHALL be `asked` or `consequent`. The `asked` request is for the instance the actor chose. A `consequent` request is for an instance the console added to carry the action out. An act SHALL have at most one `asked` request.
|
||||
- A `consequent` request SHALL record no requesting person, because the console, not a person, added it. The `asked` request of an act of cause `instances_swapped` SHALL record the act's actor as its requesting person.
|
||||
- An act of cause `instances_swapped` SHALL have one `asked` request and one `consequent` request, and both SHALL be `set_status` requests.
|
||||
- Only `core.record_lifecycle_act` SHALL write the three columns, and only on requests that its own transaction inserted, so a request joins an act only in the transaction that records it, and never moves to another act, leaves its act or joins one later.
|
||||
- An act SHALL only tie its requests together. When one request of an action fails, the console SHALL undo the others itself, so a provider applies each request on its own and is never asked to apply an act.
|
||||
- Nothing else SHALL group requests: no reader SHALL parse a workflow identifier or take another request's identity from a request's parameters to find the requests of one action.
|
||||
|
||||
#### Scenario: A swap records one act over two single-instance requests
|
||||
|
||||
- **WHEN** a member's action parks one active instance and activates another
|
||||
- **THEN** one `set_status` request SHALL be recorded for each instance, both in the transaction that records the act
|
||||
- **AND** one act of cause `instances_swapped` SHALL exist whose actor is the member
|
||||
- **AND** the request for the instance the member chose SHALL carry the role `asked` and name the member as its requesting person
|
||||
- **AND** the request for the parked instance SHALL carry the role `consequent` and name no requesting person
|
||||
|
||||
#### Scenario: The act columns are all set or all empty
|
||||
|
||||
- **WHEN** a statement writes `act_id` on a request without `act_cause` and `act_role`
|
||||
- **THEN** the database SHALL refuse it
|
||||
|
||||
#### Scenario: A request cannot point at an act of another cause
|
||||
|
||||
- **WHEN** a request states a cause that differs from the cause of the act it points at
|
||||
- **THEN** the database SHALL refuse it
|
||||
|
||||
#### Scenario: An act has one asked request
|
||||
|
||||
- **WHEN** a second request of role `asked` is linked to an act that already has one
|
||||
- **THEN** the database SHALL refuse it
|
||||
|
||||
#### Scenario: A consequent request names no person
|
||||
|
||||
- **WHEN** a request of role `consequent` records a requesting person
|
||||
- **THEN** the database SHALL refuse it
|
||||
|
||||
#### Scenario: A request cannot be linked by a later transaction or linked twice
|
||||
|
||||
- **WHEN** `core.record_lifecycle_act` is called for a request that an earlier transaction inserted, or for a request that already carries a link
|
||||
- **THEN** it SHALL refuse and write no header
|
||||
- **AND** the application's role SHALL be unable to write the act columns by any other statement
|
||||
|
||||
#### Scenario: A failed request of an act is undone by the console
|
||||
|
||||
- **WHEN** the console parked an instance for a swap and the provider then declines the activation of the chosen instance
|
||||
- **THEN** the console SHALL send the parked instance back to its previous state itself
|
||||
- **AND** the provider SHALL NOT be asked to apply the act as a whole
|
||||
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: The console owns intent; the provider owns canonical per-instance state
|
||||
|
||||
Canonical per-instance state SHALL live provider-side, in the application. The member-console SHALL own intent and aggregate facts: resource counts, limits, the desired-state record it keeps for each connection and recipient (`desired-state-records`), and the lifecycle requests the console records for people's actions. For every provider served through connections, the console SHALL keep an **observed projection** per connection and recipient: what the application reports holding for that recipient, with the generation and content hash it applied (`observed-state-read-back`). A projection row SHALL exist once the application has answered for the recipient, by a push answer or a read-back item. The projection SHALL be refreshed from the application's answers and its read class, and SHALL never be treated as authoritative over the application.
|
||||
|
||||
A per-recipient projection SHALL NOT be an instance list. An in-tree integration that keeps its own per-instance projection SHALL keep it as its only instance projection until the integration moves onto the generic core tables; for FedWiki that projection is `fedwiki.sites`.
|
||||
|
||||
#### Scenario: Console stores intent, application stays canonical
|
||||
|
||||
- **WHEN** a downgrade lowers an organization's `fedwiki_sites` limit
|
||||
- **THEN** the console SHALL record the new limit in the organization's desired-state record at FedWiki's connection, under a raised generation
|
||||
- **AND** `fedwiki.sites` SHALL keep each site's status as observed from the farm
|
||||
- **AND** the farm SHALL remain the canonical source of truth for each site's status
|
||||
|
||||
#### Scenario: The observed projection is refreshed via the read class
|
||||
|
||||
- **WHEN** the console reads a connection back
|
||||
- **THEN** it SHALL refresh each reported recipient's observed projection from the application's `list` answer (the read class)
|
||||
- **AND** it SHALL NOT treat the projection as an independent source of truth that can diverge from the application unreconciled
|
||||
|
||||
#### Scenario: The projection is kept per recipient, not per instance
|
||||
|
||||
- **WHEN** an organization holds three FedWiki sites and FedWiki's application has answered for that organization
|
||||
- **THEN** `core.observed_projections` SHALL hold exactly one row for FedWiki's connection and that organization
|
||||
- **AND** `fedwiki.sites` SHALL hold one row per site
|
||||
|
||||
### Requirement: A lifecycle request is addressed by an instance identifier the console chooses and a generation
|
||||
|
||||
A lifecycle request is one request, caused by a person's action, for one instance: to create it, change its status, or delete it. The console SHALL record each lifecycle request in `core.lifecycle_requests` before any work for it starts, addressed by the console's identifier for the instance and a generation, and the pair SHALL be unique.
|
||||
|
||||
- The instance identifier SHALL be a UUID the database generates. For a create submitted through a form, it SHALL be minted when the form renders, so a resubmission of that form carries the same identifier; an API client SHALL be able to send its own identifier for a create, and a create that carries none SHALL have one minted when it is received. For any other request, it SHALL be the identifier the console already holds for the instance.
|
||||
- The generation SHALL be minted when the form or list that submits the request renders and carried by the form, or minted when the request is received for an API request that carries none. It SHALL be above every generation earlier recorded for the instance and at least the database clock in microseconds since the Unix epoch, so neither identifier nor generation repeats after a reset or restore of the console's database. A posted generation comes from outside code: one above the clock floor plus one day (`core.generation_ceiling()`) SHALL be answered as a conflict and SHALL NOT be recorded.
|
||||
- A request SHALL record its connection, resource key, workspace, operation, requesting person and parameters. The requesting person SHALL be the person whose action caused the request, and SHALL be none for a consequent request of an act (see "A lifecycle request covers exactly one instance and an act groups an action's requests"). The operation SHALL be `create`, `set_status` or `delete` and one the connection's provider declares in `provider_operations`; the resource key SHALL be one the provider owns. Parameters SHALL carry identifiers and public DNS names only.
|
||||
- Recording a lifecycle request SHALL write no desired-state outbox row.
|
||||
|
||||
#### Scenario: Each create form carries its own identifiers
|
||||
|
||||
- **WHEN** a create form renders twice
|
||||
- **THEN** the two renders SHALL carry different instance identifiers and generations
|
||||
- **AND** submitting one render twice SHALL submit the same instance identifier and generation both times
|
||||
|
||||
#### Scenario: A first generation is floored by the clock
|
||||
|
||||
- **WHEN** a generation is minted for an instance that has no recorded request
|
||||
- **THEN** it SHALL be at least the database clock, in microseconds since the Unix epoch, at the moment it was minted
|
||||
|
||||
#### Scenario: A generation above the ceiling is refused
|
||||
|
||||
- **WHEN** a request for an instance carries a generation above `core.generation_ceiling()`, such as 9223372036854775807
|
||||
- **THEN** it SHALL be answered as a conflict and nothing SHALL be recorded
|
||||
- **AND** the instance's next generation SHALL still be computable
|
||||
|
||||
#### Scenario: An undeclared operation is not recorded
|
||||
|
||||
- **WHEN** a lifecycle request names an operation the connection's provider does not declare in `provider_operations`
|
||||
- **THEN** the request SHALL be refused
|
||||
- **AND** nothing SHALL be recorded and no workflow SHALL start
|
||||
|
||||
#### Scenario: A consequent request records no person
|
||||
|
||||
- **WHEN** the console adds a request for an instance to carry out a member's action
|
||||
- **THEN** the request SHALL record no requesting person
|
||||
- **AND** the request the member's action asked for SHALL record the member
|
||||
|
||||
### Requirement: A repeated lifecycle request is answered from its record
|
||||
|
||||
A request's content SHALL be its operation, workspace, requesting person and parameters. The link to an act (`act_id`, `act_cause` and `act_role`) SHALL NOT be content, so a repeat of a request that belongs to an act matches by the same rule as any other. A lookup of the address that takes no instance lock MAY answer a repeat, a conflict or not found before anything is recorded; a lookup that finds nothing held at the address SHALL leave the answer to the recording, and the recording under the instance lock SHALL stay the final answer. Recording a request SHALL serialize per instance the check of the instance's latest generation and the insert, and SHALL answer from what holds the address:
|
||||
|
||||
- nothing, and the generation is above the instance's latest: **accepted**, subject to the operation's synchronous checks; the request is recorded and its work starts;
|
||||
- a request with the same content that is still open: **accepted**, the answer the first submission got; nothing starts;
|
||||
- a request with the same content that has finished: its stored outcome, `succeeded`, `declined` or `failed`, with its reason;
|
||||
- a request with different content, or nothing at an address whose generation is at or below the instance's latest: **conflict**; nothing is recorded and nothing starts.
|
||||
|
||||
`declined` SHALL mean that the instance's rules refused the request before anything changed in the application, such as a limit reached or a name held by someone else. The same request will be refused again until something changes. `declined` SHALL also cover an original instance that disappeared before its outcome could be recorded, even if the application had already answered a call. `failed` SHALL mean the console tried, could not finish and compensated, or the work never started; the same request can succeed on retry. A reason SHALL be a key the console maps to its own wording, never text from the application.
|
||||
|
||||
At most one request per instance SHALL be open at a time: a second, different request while one is open SHALL be refused and not recorded. A request recorded in another workspace SHALL never be disclosed to the caller: it SHALL be answered as not found or as a conflict, without its content. Refusals that need no record, such as form validation or a missing session, SHALL stay synchronous and SHALL record nothing.
|
||||
|
||||
#### Scenario: An identical repeat while the work runs is accepted again
|
||||
|
||||
- **WHEN** a request is submitted twice with the same instance, generation and content while the first is still open
|
||||
- **THEN** both submissions SHALL be answered accepted
|
||||
- **AND** exactly one request SHALL be recorded and exactly one workflow started
|
||||
|
||||
#### Scenario: An identical repeat after the work finished returns the stored outcome
|
||||
|
||||
- **WHEN** a request that finished `declined` with a reason is submitted again with the same instance, generation and content
|
||||
- **THEN** the answer SHALL be `declined` with the same reason
|
||||
- **AND** nothing SHALL be recorded and no workflow SHALL start
|
||||
|
||||
#### Scenario: The same address with other content is a conflict
|
||||
|
||||
- **WHEN** a request is submitted with the instance and generation of a recorded request but different parameters
|
||||
- **THEN** the answer SHALL be a conflict
|
||||
- **AND** nothing SHALL be recorded and no workflow SHALL start
|
||||
|
||||
#### Scenario: An older tab's lower generation is a conflict
|
||||
|
||||
- **WHEN** an older tab submits a request at generation G1 for an instance after a newer tab's request at a generation G2 above G1 was recorded and finished
|
||||
- **THEN** the answer SHALL be a conflict
|
||||
- **AND** nothing SHALL be recorded
|
||||
|
||||
#### Scenario: One open request per instance
|
||||
|
||||
- **WHEN** a request for an instance is open and a different request for the same instance is submitted at a higher generation
|
||||
- **THEN** the second request SHALL be refused and not recorded
|
||||
|
||||
#### Scenario: Another workspace's request is not disclosed
|
||||
|
||||
- **WHEN** a caller submits an instance and generation recorded for another workspace
|
||||
- **THEN** the answer SHALL be not found or a conflict
|
||||
- **AND** it SHALL carry none of the recorded request's content or outcome
|
||||
|
||||
#### Scenario: A disappeared instance is declined after the application answered
|
||||
|
||||
- **WHEN** a provider discovers at its record step that the original instance no longer exists
|
||||
- **THEN** it SHALL decline the request without retrying that missing-instance step or applying the result to a replacement identified only by the old name
|
||||
|
||||
#### Scenario: A repeat of an act's request is answered from its record
|
||||
|
||||
- **WHEN** the request that an act's `asked` role covers is submitted again with the same instance, generation and content, while it is open or after it finished
|
||||
- **THEN** the answer SHALL be the one the first submission got or the stored outcome
|
||||
- **AND** no request, no act and no workflow SHALL be recorded or started
|
||||
|
||||
#### Scenario: A repeat is answered before anything is recorded
|
||||
|
||||
- **WHEN** a lookup finds a request with the same content at the submitted instance and generation, before the recording takes the instance lock
|
||||
- **THEN** the answer SHALL be that request's answer
|
||||
- **AND** nothing SHALL be recorded
|
||||
|
||||
#### Scenario: A lookup that finds nothing leaves the answer to the recording
|
||||
|
||||
- **WHEN** a lookup finds nothing held at the submitted instance and generation
|
||||
- **THEN** the recording under the instance lock SHALL give the answer, including a conflict when the generation is at or below the instance's latest
|
||||
|
||||
### Requirement: Lifecycle handlers answer when the workflow starts
|
||||
|
||||
A handler that accepts a lifecycle request SHALL record the request and commit, then start the request's workflow under the workflow identifier stored on the request, and SHALL answer accepted without waiting for the workflow's result. A start that succeeds, or that reports the workflow already started, SHALL be answered accepted. On any other start error the handler SHALL describe the workflow: only when the workflow engine reports that no such workflow exists SHALL the handler delete the request it inserted, or, for requests that belong to an act, all of the act's requests that are still open in one statement, and answer with a synchronous error; on any other answer it SHALL keep the request open and answer accepted.
|
||||
|
||||
A lifecycle workflow's inputs SHALL carry the request's connection identifier, instance identifier and generation. Every lifecycle workflow SHALL record its outcome, reason and finish time on its request as its last step, and that write SHALL fail when no request matches. A workflow that carries out an act SHALL carry these identifiers for each of the act's requests and SHALL record the outcome on all of them in one transaction. A request still open more than two minutes after it was recorded, whose workflow has not recorded an outcome, SHALL be settled at the next boot where the workflow engine is configured, and the requests of one act SHALL be settled together, in one transaction, by the state of their one workflow: when no workflow exists, the request SHALL end `failed` with the reason `not_started`; when the workflow closed and the request is a create, the console SHALL read the instance back from the application and record the outcome that reading supports; when the workflow closed and the request is any other operation, the request SHALL end `failed` with the reason `retries_exhausted`, except where the provider's specified recovery records the observed result or declines because the original instance is gone, and except that every request of an act ends `failed` with the reason `retries_exhausted` together and is never recovered one at a time; when the workflow is running or the engine does not answer, the request SHALL stay open. A request whose workflow never started SHALL never be restarted. An act's header SHALL stay when its requests are deleted, because a header is never deleted.
|
||||
|
||||
#### Scenario: The handler answers before the work finishes
|
||||
|
||||
- **WHEN** a lifecycle request is accepted and its workflow takes longer than the server's write timeout
|
||||
- **THEN** the handler SHALL answer accepted as soon as the workflow has started
|
||||
- **AND** the request SHALL stay open until the workflow records its outcome
|
||||
|
||||
#### Scenario: A start that never happened removes the request
|
||||
|
||||
- **WHEN** starting the workflow fails and describing it reports that no such workflow exists
|
||||
- **THEN** the handler SHALL delete the request it inserted and answer with a synchronous error
|
||||
- **AND** a retry by the person SHALL be recorded as a new request
|
||||
|
||||
#### Scenario: A requester who disconnects still gets the workflow
|
||||
|
||||
- **WHEN** the requester's connection closes after the request committed and while its workflow is being started
|
||||
- **THEN** the start and any describe that follows SHALL still run
|
||||
- **AND** the request SHALL NOT stay open with no workflow started
|
||||
|
||||
#### Scenario: An ambiguous start error keeps the request
|
||||
|
||||
- **WHEN** starting the workflow returns a deadline error and describing it reports the workflow running
|
||||
- **THEN** the handler SHALL keep the request open and answer accepted
|
||||
|
||||
#### Scenario: An outcome with no request fails the workflow step
|
||||
|
||||
- **WHEN** a lifecycle workflow records its outcome and no request matches its instance and generation
|
||||
- **THEN** the step SHALL fail rather than update no row
|
||||
|
||||
#### Scenario: A request that never started is settled at boot
|
||||
|
||||
- **WHEN** the console boots with Temporal configured and finds a request open for more than two minutes whose workflow does not exist
|
||||
- **THEN** the request SHALL end `failed` with the reason `not_started`
|
||||
- **AND** no workflow SHALL be started for it
|
||||
|
||||
#### Scenario: An act whose workflow never started loses all its open requests
|
||||
|
||||
- **WHEN** starting the workflow of an act's requests fails and describing it reports that no such workflow exists
|
||||
- **THEN** the handler SHALL delete every open request of the act in one statement and answer with a synchronous error
|
||||
- **AND** the act's header SHALL remain
|
||||
- **AND** a retry by the person SHALL be recorded as new requests under a new act
|
||||
|
||||
#### Scenario: An act's requests that never started are settled together
|
||||
|
||||
- **WHEN** the console boots with Temporal configured and finds the requests of one act open for more than two minutes whose workflow does not exist
|
||||
- **THEN** every request of the act SHALL end `failed` with the reason `not_started` in one transaction
|
||||
- **AND** no workflow SHALL be started for them
|
||||
|
||||
#### Scenario: An act's requests whose workflow closed end together
|
||||
|
||||
- **WHEN** the console boots and finds the requests of one act open for more than two minutes whose workflow closed without recording an outcome
|
||||
- **THEN** every request of the act SHALL end `failed` with the reason `retries_exhausted` in one transaction
|
||||
- **AND** no request of the act SHALL end in a different state from the others
|
||||
@@ -0,0 +1,98 @@
|
||||
Tests follow `docs/testing.md`: database tests open the database through `dbtest`, build their rows through the test kit or the package's fixtures, filter to the rows their own fixture made, and pass twice in a row without a reset. A test that holds one transaction open while a second blocks waits for the block with `dbtest.AwaitLockWait`, never a sleep, and releases its side transaction in cleanup. A test that takes an advisory lock takes it with `db.Lock` or `db.LockShared`, probes one with `dbtest.TryLock`, and waits on one by its family's `Statement()`. A test of a grant or an enclosure drops to `console_runtime` with `SET LOCAL ROLE` (`asRole`), because `TEST_DATABASE_URL` logs in as the superuser. The test kit's `Attempt` and `Refuse` use a savepoint, so a test of `core.record_lifecycle_act` inserts its requests at the top level of the test transaction and calls the function under `Refuse`.
|
||||
|
||||
Groups 1 to 8 are the parts of one commit, which the maintainer makes after review; group 9 is part of it and group 10 is not. The commit passes `make test` with the test stack up (`./bootstrap-stack.sh` from `test/` first, as `AGENTS.md` asks), which runs `make lint` first and then every package. Each group builds, and its own tests pass with `go test` on the packages it names, with these exceptions that the commit as a whole resolves:
|
||||
- `scripts/deadcode.sh` and `scripts/sqlc-unused` can report a core function or query of group 2 until the group of its first production caller lands (group 3 for the repeat lookup, the act writer and the delete by act; group 4 for the act-scoped acknowledge). A report after group 7 is a stop. `scripts/deadcode-testonly.txt` gains no entry for this change.
|
||||
- Groups 3 and 4 are one working state for the web package: the swap stops writing its two keys in task 3.3 and its readers move to the act in tasks 4.1 to 4.4, so the web package's tests pass only after task 4.4.
|
||||
- No new sentence reaches a member (proposal "Strings"); every sentence a task names already exists, so `filler-copy` finds nothing new.
|
||||
- A golden changes only by hand before the run, as `docs/testing.md` asks, and the run then passes without `-update`. A golden, route table or existing test result that changes outside the task that names it is a stop.
|
||||
- Learn a script's usage from its header or source, never by running it.
|
||||
|
||||
## 1. The migration and its database tests
|
||||
|
||||
- [x] 1.1 Before any grant is written, confirm the grant lists of `design.md` D4 from the code: `git grep -n -E '(INSERT INTO|UPDATE|DELETE FROM) core\.lifecycle_requests' -- internal ':!*_test.go' ':!*.sql.go'` lists only the statements of `internal/integration/queries/lifecycle_requests.sql` (`InsertLifecycleRequest`, `FinishLifecycleRequest`, `AcknowledgeLifecycleRequest`, the two deletes), `git grep -n 'FOR UPDATE\|FOR NO KEY UPDATE' internal/integration/queries/lifecycle_requests.sql` lists no row lock, and `InsertLifecycleRequest` names nine columns. A different result is a stop, because the column lists of task 1.5 would be wrong.
|
||||
- [x] 1.2 Add `internal/db/migrations/00041_lifecycle_request_acts.sql`, in the style of `00027_acts.sql`, with its Up section's first part (design D1): nullable `act_id UUID`, `act_cause VARCHAR(50)` and `act_role VARCHAR(20)` on `core.lifecycle_requests`; `lifecycle_request_in_its_act` (FOREIGN KEY `(act_id, act_cause)` REFERENCES `core.acts (act_id, cause)`, on `uq_acts_act_id_cause`); `lifecycle_request_act_shape`; `chk_lifecycle_requests_act_cause` (`'instances_swapped'` only); `chk_lifecycle_requests_act_role`; `lifecycle_request_consequent_names_no_person`; `uq_lifecycle_requests_one_asked`; `idx_lifecycle_requests_act_id`; a comment on each column. Add `TestLifecycleRequestActConstraints` in a new `internal/db/lifecycle_acts_test.go`: one table of rows that each break exactly one rule and are refused with that constraint's name (an `act_id` without a cause or without a role; a plan cause with a real plan act's id, which the foreign key alone accepts; a cause that does not match the act's; a role outside the two; a consequent request that names a person; two asked requests in one act), and the rows that are accepted (all three columns NULL; an asked and a consequent request of one `instances_swapped` header the test inserts directly as the superuser).
|
||||
- [x] 1.3 Up, second part (design D3): replace `chk_acts_cause` with the six-cause list in one ALTER TABLE, leave `chk_plan_act_details_cause` with the five plan causes, and reword the comments on `core.acts` (two writers) and on `core.lifecycle_requests` (a request names the person whose action caused it, or no one for a consequent request). Extend `TestActConstraints` (`internal/db/acts_test.go`) so a header with `instances_swapped` is accepted and `TestPlanActDetailConstraints` so a detail row with `instances_swapped` is refused with `chk_plan_act_details_cause`.
|
||||
- [x] 1.4 Up, third part: `core.record_lifecycle_act` with the signature, owner `core_owner`, `SECURITY DEFINER` and `SET search_path = core, pg_temp` of design D2, EXECUTE revoked from PUBLIC and granted to `core_writer`, and its five steps in order: the per-cause CASE whose ELSE refuses (for `instances_swapped`: one consequent request, `set_status` on every request, the asked request names the actor as its person, no consequent request names a person); one read of the named rows without a row lock (distinct ids; every row exists, is `accepted`, carries no link, and belongs to one workspace and one connection); the `xmin` test with `pg_current_xact_id()::xid` together with `created_at = transaction_timestamp()`; the header insert with a NULL note, the 100-character rule on the request id and `effective_at` equal to the asked request's `created_at`; one UPDATE that sets the three columns `WHERE act_id IS NULL` and raises when fewer rows changed than it named. Its comment says that no lifecycle recording runs inside a savepoint and why (`pg_current_xact_id()` and the `xmin` test), as `core.requeue_plan_act_obligations` does.
|
||||
- [x] 1.5 Up, fourth part (design D4): revoke `core_writer`'s table INSERT and UPDATE on `core.lifecycle_requests`, grant INSERT on the nine columns `InsertLifecycleRequest` names and UPDATE on `status`, `reason_code`, `finished_at` and `acknowledged_at`, keep SELECT and DELETE. No grant names `updated_at` or an act column.
|
||||
- [x] 1.6 Tests of the writer's happy path, in `internal/db/lifecycle_acts_test.go`: `TestRecordLifecycleActLinksItsOwnRows` records an asked and a consequent request at the top level of the test transaction, calls the function, and requires the three columns on both rows, the header's cause, actor, request id, NULL note and `effective_at` equal to the asked request's `created_at`; and `TestRecordLifecycleActStoresARequestIDOnlyWhenItFits`, the 100-character rule, modelled on `TestRecordPlanActStoresARequestIDOnlyWhenItFits`.
|
||||
- [x] 1.7 Tests of the writer's refusals, `TestRecordLifecycleActRefusals` in the same file, one case per rule and each refused with the function's own message: every plan cause (the ELSE); no consequent request, two consequent requests; a request whose operation is not `set_status`; an asked request that names no person or a person other than the actor; a consequent request that names a person; a repeated id; an id with no row; a request that is not `accepted`; a request that already carries a link; two requests of different workspaces; two of different connections; a request inserted by an earlier committed transaction (the `xmin` test); and a request an earlier transaction inserted and this one only updated, whose `xmin` passes and whose `created_at` does not (design D2 step 3). The failure-table row F8 (the writer refuses) is this test seen from the handler.
|
||||
- [x] 1.8 Tests of the enclosure and the grants. `TestDeliveryTablePrivileges` (`internal/db/integration_delivery_enclosure_test.go`) states the two column lists for `core_writer` on `core.lifecycle_requests` and adds a refused write of `act_id`, `act_cause` and `act_role` by an INSERT and by an UPDATE, a refused UPDATE of `workspace_id`, `connection_id`, `operation` and `requested_by_person_id`, and a refused INSERT that names an act column. `lockedTable` in `internal/db/runtime_role_privileges_test.go` gains a column list per privilege and absorbs the outbox's special case (`outboxTable`, `outboxUpdatableColumns`); `core.lifecycle_requests` joins `lockedTables` holding SELECT and DELETE with the two lists; `TestRuntimeRolePrivileges` checks the lists against the catalog. `TestPlanActWritersAreEnclosedInTheCatalog` (`internal/db/plan_act_obligations_test.go`) covers the sixth function (owner, `SECURITY DEFINER`, search path, EXECUTE only for `core_writer`, none for PUBLIC or `console_reader`) and `TestRecordPlanActIgnoresACallersTemporaryTables` (`internal/db/acts_test.go`) gains a case in which a temporary table named `lifecycle_requests` or `acts` shadows the real one and is not written. `TestCoreSecurityDefinerFunctionsPinTheirSearchPath` passes without an edit.
|
||||
- [x] 1.9 Add the Down section (design D6): a DO block that counts the `core.acts` rows with a lifecycle cause and raises, naming the count, when there is one; then the column revokes by name, table INSERT and UPDATE restored, the function, the indexes, the constraints and the columns dropped, both comments restored, and the five-cause `chk_acts_cause` restored. Add `TestLifecycleRequestActsMigrationUpDownUp` (`requireMigrationUpDownUp` with previous version 40 and version 41, in `internal/db/lifecycle_acts_test.go`, its two version constants named `lifecycleActsPrevious` and `lifecycleActsVersion`, as `acts_test.go` names `actsPrevious` and `actsVersion`) and `TestLifecycleRequestActsDownRefusesAnExistingAct`, which records a swap's act on a scratch database and requires the Down to refuse and name the count, and to leave the columns and constraints in place.
|
||||
- [x] 1.10 `internal/migrate/testdata/console-reader-columns.txt`: add `read core.lifecycle_requests.act_cause`, `act_id` and `act_role` by hand in the file's alphabetical order (after `acknowledged_at`), and run `TestConsoleReaderColumns` in `internal/migrate`; it passes without `-update`.
|
||||
|
||||
## 2. The core Go side
|
||||
|
||||
- [x] 2.1 Create the leaf package `internal/acts` (`cause.go`, with the repository's SPDX header, importing nothing of the console): `acts.Cause`, the six constants `TierAdded`, `TierRemoved`, `TiersReordered`, `OrgTypeDefaultChanged`, `PlanActRetried`, `InstancesSwapped`, and the lists `PlanCauses` and `LifecycleCauses`. Delete `internal/entitlements/act_cause.go` and change the references mechanically (`git grep -n 'ActCause\|ActTierAdded\|ActTierRemoved\|ActTiersReordered\|ActOrgTypeDefaultChanged\|ActPlanActRetried' -- internal` lists about 45 in 12 files, among them `internal/server/operator_plan_acts.go` and the entitlements files); the stale comment that a new kind replaces "both constraints" goes with the file. Reword the comment of the `RecordPlanAct` query in `internal/entitlements/queries/plan_acts.sql` to name both writers, and regenerate. `go build ./...` passes and the grep finds nothing outside `internal/acts`.
|
||||
- [x] 2.2 Move `TestActCausesMirrorTheConstraints` from `internal/entitlements/act_cause_test.go` to `internal/acts/cause_test.go` with three cases (`chk_acts_cause` against every cause, `chk_plan_act_details_cause` against `PlanCauses`, `chk_lifecycle_requests_act_cause` against `LifecycleCauses`, each compared through `pg_get_constraintdef`), and add `TestLifecycleActWriterRefusesEveryPlanCause`, which calls `core.record_lifecycle_act` with each plan cause and requires the refusal, so the function's CASE and the constraint cannot drift. Delete the old test file.
|
||||
- [x] 2.3 Regenerate sqlc (`make sqlc-generate`): `LifecycleRequest` gains `ActID`, `ActCause` and `ActRole`. In `internal/integration/lifecycle.go` add `LifecycleActAsked` and `LifecycleActConsequent`, with a comment naming `chk_lifecycle_requests_act_role`, and `TestLifecycleActRolesMirrorTheConstraint` in `internal/integration/lifecycle_db_test.go`, which compares them with `pg_get_constraintdef`.
|
||||
- [x] 2.4 `LifecycleAnswer` gains `RequestID` (design D5): `recordNew` keeps the id it discards, and `answerFromRow` copies it. `TestRecordLifecycleRequestAnswers_DB` (`internal/integration/lifecycle_db_test.go`) requires the id on a recorded request and on a repeat; the golden of `TestLifecycleAnswers_DB` (`internal/integration/lifecycle_answers_golden_db_test.go`) gains the field by hand only if its dump prints answer fields.
|
||||
- [x] 2.5 Export `AnswerLifecycleRepeat(ctx, db DBTX, spec LifecycleRequestSpec) (LifecycleAnswer, LifecycleRequest, error)` in `internal/integration/lifecycle.go` (design D7). It runs `heldAt` and `sameLifecycleContent` without the instance lock and answers a zero `Kind` when nothing holds the address, `LifecycleNotFound` for another workspace's row, `LifecycleRepeatOpen` or `LifecycleRepeatFinished` with the held row, and `LifecycleConflict` when the content differs; `answerAddress` calls the same helper, so the rule has one copy. `TestAnswerLifecycleRepeat_DB` covers each answer, an older tab's generation that holds nothing (zero, left to the recording), and a request that carries an act link, whose repeat still matches because the link is not content; `TestRecordLifecycleRequestAnswers_DB` and `TestRecordLifecycleRequestOlderTabAndFloors_DB` pass unchanged.
|
||||
- [x] 2.6 Add `RecordLifecycleAct(ctx, tx *sql.Tx, act LifecycleAct) (string, error)` with `LifecycleAct{Cause acts.Cause; ActorPersonID, CorrelationID, Asked string; Consequent []string}` (design D5), a `RecordLifecycleAct` query in `internal/integration/queries/lifecycle_requests.sql` that calls `core.record_lifecycle_act`, and the actor type `person`; `CorrelationID` fills `core.acts.request_id`. A database refusal comes back wrapped. `TestRecordLifecycleAct_DB` records two requests through `RecordLifecycleRequest` in one transaction, calls the wrapper, and reads back both rows' act columns and the header; a second case records a consequent request in an earlier transaction and requires the wrapped refusal.
|
||||
- [x] 2.7 Add `DeleteUnstartedLifecycleAct(ctx, db, workspaceID, actID)` (`DELETE ... WHERE act_id = $1 AND workspace_id = $2 AND status = 'accepted'`) and give `DeleteUnstartedLifecycleRequest` (same file) `AND act_id IS NULL` (design D11). Extend `TestLifecycleRequestListAndCleanup_DB`: the act delete removes both accepted requests and leaves the header; it removes nothing for another workspace's id or for a finished member; the per-address delete returns false for a request that belongs to an act and still deletes one that belongs to none.
|
||||
- [x] 2.8 Change `AcknowledgeLifecycleRequest` (`internal/integration/queries/lifecycle_requests.sql`, signature unchanged) so it acknowledges every declined or failed, unacknowledged row of the workspace at the address or in the address's act, found by a subquery, with a NULL act matching nothing (design D12). Extend `TestLifecycleAcknowledgeOnlyDeclinedOrFailed_DB`: a call at the asked request's address acknowledges both failed or declined rows; a call at the consequent request's address does the same; a succeeded member and another workspace's rows stay; a request with no act acknowledges only itself.
|
||||
|
||||
## 3. FedWiki intake
|
||||
|
||||
- [x] 3.1 Add the store query `WorkspaceHasOpenRotation(workspace_id, connection_id, swap_cause)` (design D8) in `internal/integrations/fedwiki/store/queries/sites.sql`, one EXISTS over `core.lifecycle_requests` left-joined to `fedwiki.sites` on `site_id = instance_id`, true for an accepted request of the workspace and connection that has `act_cause = swap_cause` or is a `set_status` to `active` on a site whose `force_reduced_at` is set; regenerate sqlc and add the method to `store`'s querier. Add `TestWorkspaceHasOpenRotation_DB` in `store/request_intake_db_test.go`: an open swap matches (also when its chosen site carries no mark); an open return on a marked read-only site matches; an open free fill on an unmarked read-only site does not; an accepted Restore on an archived row does not; a finished request, another workspace's and another connection's do not; and after the re-upgrade sweep cleared the mark of a pending return's site, the return no longer matches (design D8, failure-table row F19). The test runs under `SET LOCAL ROLE console_runtime`, so the read of `core.lifecycle_requests` and `fedwiki.sites` is proved for the runtime user.
|
||||
- [x] 3.2 Move the repeat answers to core (design D7), in `internal/integrations/fedwiki/web`. `beginRowAction` (`site_actions.go`) builds the spec the action would record from the path's domain before it resolves the site and calls `integration.AnswerLifecycleRepeat`, so a repeat after a permanent delete is answered from its record; a zero or `LifecycleNotFound` answer goes on to the site checks. `lockedRepeat` calls it inside the workspace transaction. The JSON delete's repeat check (`api.go`) calls it with `{domain}`: a repeat answers through `respondRepeat`, a conflict answers 409 with `msgAPIConflict`, a zero or `LifecycleNotFound` answer goes on, and no JSON route records a rotation. Delete `sameRowRequest` (`requests.go`); keep `LookupLifecycleRequest` for the create repeat, `recordSiteRequestInTx` and the JSON delete's second read. Extend `TestRowActionRepeatTable` (`requests_db_test.go`) with a repeat after a permanent delete answered from the record, and `TestAPIDelete` with a repeat and a conflict. This task is the failure-table rows F1 and F2 for the single-site actions.
|
||||
- [x] 3.3 Rewrite the swap's intake in `swapActiveSite` and `recordParkRequest` (`site_actions.go`) to the steps of design D9, in one READ COMMITTED transaction under the workspace lock: the repeat (3.2); `WorkspaceHasOpenRotation` (3.1) with the rotation-busy sentence; the cooldown read; `ListActiveSitesByWorkspace` and its limit sentence; the park choice; `CheckSwapRequestSites`; the asked request `{domain, status: "active"}` with the member as person, with no `swap_park_site_id`; the consequent request `{domain, status: "readonly"}` at the park site's next generation, under the swap's workflow id, with no person and no `swap_activate_site_id`; then `integration.RecordLifecycleAct` with `acts.InstancesSwapped`, the member as actor, both `RequestID`s and the correlation id from `middleware.GetRequestID`. The upsert of the stamp goes from intake. Delete `hasOpenSwap` and its use of `OpenRequestsByWorkspace`. `SwapSiteRequestInput` keeps every field. Rewrite every web test that builds or asserts a swap's rows or keys so that it builds the act through `RecordLifecycleAct` and asserts the new rows: `TestSwapHoldsBothSites` (`requests_db_test.go`, its two requests, no keys, no person on the park request, one act whose asked and consequent rows are these two), `TestKeepActiveUsesRecordedTimeOrCreation_DB`, `TestSiteIntakeRequiresOriginalRows_DB` (`request_identity_db_test.go`), which records no swap and needs no rewrite: after task 3.5 its `rotation zero` case takes the workspace lock before the instance lock its deletion holds, and it still passes, `quota_rows_db_test.go` and `shared_pool_db_test.go` where they read the swap's keys.
|
||||
- [x] 3.4 Tests of the swap's intake outcomes, in `web/requests_db_test.go` through the handler (`newSiteEnv`): a second click of an open swap and of a finished swap is answered from the record with a list refresh and records nothing (F1); the same address with other content, and a stale tab that posts a stored swap's address, answer "This site changed since the list loaded." and a refresh and write no header (F2); a swap while another swap of the workspace is open answers the rotation-busy sentence with the cooldown on and off, and records nothing and no header (F3; no test reaches the refusal of a second swap today); inside the cooldown window the swap answers the cooldown sentence with nothing recorded (F4); no active site of its own, the chosen or the park site gone, either site busy (`LifecycleBusy`), and the consequent request not recorded each answer their sentence of design D9 with the transaction rolled back (F7); a database error and a writer refusal answer "Couldn't change the active site. Try again." with both requests and the header rolled back (F8; if `newSiteEnv` has no seam that fails a chosen statement, add one first, in the test file); a successful intake leaves two accepted requests, one `instances_swapped` header whose actor is the member, and no stamp.
|
||||
- [x] 3.5 Change `changeStatus` (`site_actions.go`) so a return takes the workspace transaction whenever `rotation` is true, not only when `SwapCooldown > 0`, in the swap's order: repeat, open rotation, cooldown when the window is above 0, then `RecordSiteRequestInTx`; the upsert of the stamp goes; `ClearForceReduced: rotation` stays in the workflow input. A free fill, an archive and a delete keep their own transaction with no workspace lock and are not refused while a rotation is open (design D10). A database error in a return's transaction answers "Couldn't change which site is active. Try again later."; a free fill, a Restore and an archive keep "Couldn't update the site. Try again." Add to `web/requests_db_test.go` (or `web/swap_rotation_db_test.go` if the file grows past what its neighbours hold): two concurrent returns with the cooldown off, made deterministic with a side transaction that holds the workspace lock and `dbtest.AwaitLockWait`, where the second ends with the rotation-busy sentence (F3's serialization); a return during an open swap and a swap during an open return, each with the cooldown on and off (F3); a return inside the window (F4); a return's database error (F9); a free fill recorded while a rotation is open (F10) and an archive recorded while one is open; and `TestWorkspaceTxTakesTheWorkspaceLock` (`workspace_lock_db_test.go`) extended so a return takes the lock with the cooldown off.
|
||||
- [x] 3.6 Pin the order of the two reads of design D8 (F5, F6) in `web/swap_rotation_db_test.go`: a test that wraps the store's querier, records the statements an intake runs, and requires `WorkspaceHasOpenRotation` before the stamp read; and the F5 case, a rotation whose success committed before the open-rotation read, which the swap and the return answer with the cooldown sentence when the cooldown is on and accept when it is off, writing a header for a swap. The interleaving of F6, a commit between the two reads, cannot be reached without pausing the transaction between two statements; the order test is what holds it.
|
||||
- [x] 3.7 `startRequestWorkflow` (`web/requests.go`) takes one value that names what to delete, an address or an act, and for an act calls `integration.DeleteUnstartedLifecycleAct` (design D11); the swap passes its act id, the single-site actions their address. Extend `TestStartFailure` (`web/requests_db_test.go`): a swap whose start fails with describe answering NotFound loses both requests in one statement, keeps its header, and the retry from the same form is accepted with a new act, the next park generation and no cooldown refusal (F11, and the "Try again." sentence of a swap and of a return); a swap whose delete fails keeps both requests accepted, the retry is answered as a repeat, the list shows Pending, and another rotation of the workspace answers the rotation-busy sentence (F12); a start that fails with describe not answering NotFound keeps both requests accepted (F12).
|
||||
- [x] 3.8 Render test for the card while a rotation is pending (design D13): with the cooldown on and a swap pending, `web/sites_render_test.go` (or `TestSitesListStates`) requires Keep active enabled on the workspace's other read-only rows, Pending and no actions on the two pending rows (`TestPendingRowHasNoActions` passes unchanged), a click on another read-only row while the swap is pending answers the rotation-busy sentence; and, with a return pending and the pool below its limit, a click on an unmarked read-only row is recorded as a free fill (F10). `templates/fedwiki_sites.html` does not change in this task.
|
||||
|
||||
## 4. The readers of a swap
|
||||
|
||||
- [x] 4.1 The notice list (`notices`, `web/site_actions.go`, design D12): a row whose `act_role` is `consequent` gets no notice; a row that ends `site_missing` while its own site exists names the consequent row of its act found in `v.rows`, using that row's `parameters.domain`; with no such row it takes the generic sentence (`noticeSentence`, `web/requests.go`). Tests, in `web/requests_db_test.go`, `web/request_identity_db_test.go` and `web/sites_notices_test.go`: `TestSwapNoticeOnce` shows one notice for a failed swap; `TestMissingSiteNotices_DB` shows "<chosen> wasn't kept active. <parked> was deleted." when both rows of an act end `declined/site_missing` (F16); a stored asked row with no act that ends `site_missing` while its own site exists reads the generic sentence, and a stored parked row that is declined or failed and not acknowledged shows its own notice (F28).
|
||||
- [x] 4.2 `requestAction` (`web/requests.go`) takes the row and says "restored" only for an active target, an archived site and a cause other than `instances_swapped`; it tests the cause, not membership. Delete `SwapParkSiteID` and `SwapActivateSiteID` from `requestParams` and from the JSON the requests record. Rewrite the table of `TestNoticeSentences` (`web/requests_db_test.go`) that sets `SwapParkSiteID` so its swap case carries an act cause, and add a case for a Keep active of a parked site that is not a swap, which reads "kept active".
|
||||
- [x] 4.3 `acknowledgeRequest` (`web/site_actions.go`) becomes one `AcknowledgeLifecycleRequest` call for the row's address (design D12), with no read of the workspace's open requests and no workflow-id comparison. Extend `TestSwapNoticeOnce` and `TestDismissFailureKeepsNotice` so dismissing the asked row of a failed swap acknowledges the consequent row too, a failed dismissal keeps both notices, and dismissing a stored parked-site row that has no act acknowledges that row only.
|
||||
- [x] 4.4 Delete `IsSwapRequestWorkflowID` (`workflows/requests.go`) and every test of its prefix; `SwapRequestWorkflowID` keeps its form and only names the Temporal run. `git grep -n 'IsSwapRequestWorkflowID\|hasOpenSwap\|sameRowRequest\|swap_park_site_id\|swap_activate_site_id\|SwapParkSiteID\|SwapActivateSiteID' -- internal` then lists, outside the code the next groups replace, only the `swapRequests` fixture in `workflows/swap_counter_db_test.go`, which task 5.1 rewrites; task 10.4 runs the final grep. `go test ./internal/integrations/fedwiki/web/` passes.
|
||||
|
||||
## 5. Outcomes and the stamp
|
||||
|
||||
- [x] 5.1 Rewrite the shared fixture `swapRequests` (`workflows/swap_counter_db_test.go`) and the recording helper it calls (`e.record`, `workflows/requests_db_test.go`) so that one transaction records both requests and then the act through `integration.RecordLifecycleAct`: the activated request names the person, the parked request names none, neither carries a swap key, and the helper returns the act id besides the two generations. Read and rewrite its 14 calls in the nine files that use it (`archive_time_db_test.go`, `no_usage_row_db_test.go`, `placement_servability_db_test.go`, `purge_requests_db_test.go`, `requests_db_test.go`, `swap_counter_db_test.go`, `swap_identity_db_test.go`, `swap_record_db_test.go`, `usage_concurrent_db_test.go`) and the tests that build swap rows outside it that task 3.3 did not reach (the same grep as task 4.4 over `workflows/`). The workflows package's tests pass before any stamp is written.
|
||||
- [x] 5.2 `RecordSwapActivity` (`workflows/swap.go`) calls `q.UpsertSiteSwapPolicy(ctx, in.WorkspaceID)` at the end of its `apply`, after the activated site's mark is cleared, when the activated row it locked was not active (design D14); there is no mark test. The comment on `UpsertSiteSwapPolicy` (`store/queries/sites.sql`) changes from "a swap just happened" to "a rotation succeeded". Tests in `workflows/swap_record_db_test.go` and `workflows/swap_counter_db_test.go`: a recorded swap commits its two successes, the site rows and the stamp together, and `TestRecordSwapCommitsItsOutcomesWithItsStatuses_DB` reads the stamp in that commit (F13); on a pool with no usage row the swap still stamps (`TestOutcomeStepsOnAPoolWithoutAUsageRow_DB`, F13); a lost answer that is retried writes no second stamp and keeps the first commit's time (F13, "A swap's retry changes no count"); a swap whose chosen site the re-upgrade sweep reactivated during the farm calls succeeds and stamps nothing (F14); a record refused with `SiteMissing`, `SiteAuthorizationError` or `QuotaExceeded` leaves no stamp and both requests declined (F15, `TestSwapWithMissingSite_DB`); a farm call that raises `SiteMissing` for the parked site, and one that raises an authorization or another farm error, leave no stamp (F16, F17).
|
||||
- [x] 5.3 `RecordSiteStatusActivity` (`workflows/request_activities.go`) keeps the row `lockRequestSite` returns and calls `UpsertSiteSwapPolicy` at the end of its closure, after `SetSiteStatusByID`, when `isReturn(locked fwmod.LockSiteStatusByIDRow, target string) bool` holds: the row carries `force_reduced_at`, its locked status is not `active`, and the target is `active`; the facts are read before `SetSiteStatusByID` clears the mark (design D14). Add a table test of `isReturn` (marked and read-only with target active: true; the same unmarked, which is a free fill: false; an archived row with no mark, which is a Restore: false; a marked row already active: false; a target other than active: false). DB tests in `workflows/requests_db_test.go` and `workflows/status_reconcile_db_test.go`: a return on a marked row that was not active stamps and clears the mark (F18); a failed farm call that `statusChangeFailed` reads back as applied records the success and stamps (F18); a return whose site the sweep reactivated during the farm call stamps nothing (F19); a return declined at the gate, failed at the farm call and refused at the record step stamps nothing and leaves the wait as it was (F20); a free fill and a Restore stamp nothing; the stamp is written with the cooldown off, because the worker reads no cooldown.
|
||||
- [x] 5.4 Fix the outcome transaction's order (design D15) and test it. The stamp is written after the site writes and their placement rows and before `DeleteSlotHolds` and the usage row's lock, which `apply` running before the recount already gives; the transaction takes no workspace lock. Add to `workflows/usage_concurrent_db_test.go` (or `workflows/swap_counter_db_test.go`) `TestStampingOutcomesOfOneWorkspaceSerializeOnThePolicyRow_DB`: two stamping outcomes of one workspace on disjoint instances, one held open in a side transaction, where the second waits on the policy row (`dbtest.AwaitLockWait`) and both finish with no deadlock; and `TestIntakeReadsTheStampWithoutALock_DB` in `web/`, where an outcome holds the policy row open and the intake's cooldown read does not wait.
|
||||
- [x] 5.5 Hold the replay contract (design D17). `workflows/replay_test.go` and the recorded histories under its testdata do not change, `SwapSiteRequestInput` keeps `ParkInstanceID`, `ParkGeneration` and its other fields, and no workflow function adds, renames or reorders a command; `TestWorkflowHistoriesReplay` passes on the histories as recorded. Add `TestARotationOfThePreviousReleaseStampsOnSuccess_DB` in `workflows/swap_record_db_test.go`: requests built by hand in the old form (a shared `swap-fedwiki-site-` workflow id, the two keys, the park request naming the member, no act) are finished by `SwapFedWikiActiveSiteRequestWorkflow` from its recorded input and stamp, and a stored return recorded with the cooldown off stamps for the first time (F27).
|
||||
- [x] 5.6 Render half of design D13, in `web/sites_render_test.go` with the cooldown on: after a rotation's success has stamped, the first render of the card shows Keep active disabled with the cooldown sentence; with the cooldown off it shows Keep active enabled; after a rotation that failed to start, failed or was declined, Keep active is enabled at once (F11, F15, F17, F20).
|
||||
|
||||
## 6. Boot settle
|
||||
|
||||
- [x] 6.1 Add `actGroups(rows []integration.LifecycleRequest) [][]integration.LifecycleRequest` to `workflows/settle.go` (design D16): a request with no act, a stored swap row included, is a group of one; an act's requests form one group with the asked request first and the consequent requests in listing order. `TestActGroups` is a table test: two requests of one act in either listing order, an act next to unrelated requests, a stored swap's two rows as two groups, an empty list.
|
||||
- [x] 6.2 `SettleOpenRequests` settles per group. It describes the workflow of the group's first member once; NotFound ends the group `failed/not_started` in one `finishAllWith` call; a running workflow leaves the group alone; a closed workflow ends a group that carries an act `failed/retries_exhausted` in one call, and a request with no act keeps the create reconcile and the held activation's status reconcile; a request that carries an act never goes to the status reconcile. Settle passes no `apply` and never stamps. Extend `TestSettleOpenRequests_DB` (`workflows/requests_db_test.go`): a swap never started ends both requests `failed/not_started` in one transaction with its header kept and no stamp (F23); a swap closed without an outcome ends both `failed/retries_exhausted` in one transaction, with no stamp even when the farm applied it (F24); a stored swap's two rows with no act each settle alone by their workflow's state; a return closed holding no slot ends `failed/retries_exhausted` with no stamp (F22); `TestSettleOnAPoolWithoutAUsageRow_DB` passes.
|
||||
- [x] 6.3 `settledSince` (`workflows/settle.go`) takes the group: it is settled when every member reads back as not accepted, and a missing or accepted member counts as `FinishErrored`; the counters stay per request, so `Seen` stays their sum. Extend `TestSettleOfARequestSettledSinceTheListingIsNotAnError_DB` (`workflows/status_reconcile_db_test.go`) with a swap group that a concurrent outcome finished, which settle reports as an info line and no error (F25); and add the two cases of F26: a hand edit that finished one request of an act before the listing, which settle ends by its workflow's state alone so the two end differently, and one between the listing and the finish, which `lockOutcomes` refuses so settle counts `FinishErrored` and changes nothing.
|
||||
- [x] 6.4 A return that holds its slot goes to the status reconcile at boot and stamps through the record step (design D14, D16). In `TestSettleHandsAClosedActivationToTheStatusReconcile_DB` and `TestStatusReconcile_DB` (`workflows/status_reconcile_db_test.go`) require that, when the farm holds the site active, the reconcile records the success, clears the mark from the locked row although its input carries no `ClearForceReduced`, and stamps (F21); when the farm does not hold it active the request fails, the hold is removed and nothing is stamped (F21).
|
||||
|
||||
## 7. The sync's mark rule and Restore
|
||||
|
||||
- [x] 7.1 `UpsertSiteFromFarm` (`store/queries/sites.sql`) gains `force_reduced_at = CASE WHEN excluded.status = 'readonly' THEN fedwiki.sites.force_reduced_at END` in its SET (design D18); regenerate sqlc. Add to `store/archive_time_db_test.go`, beside the existing `UpsertSiteFromFarm` calls in `TestSiteArchiveTimeQueries_DB`, `TestUpsertSiteFromFarmKeepsTheMarkOnlyOnReadonly_DB`: a marked row that the sync writes `archived` loses its mark, one it writes `active` loses its mark, one it writes `readonly` keeps it, and an unmarked row stays unmarked. Read the existing tests that expect an archived or active row to keep a mark after the sync (each file that `git grep -l 'SyncSitesToDBActivity' -- 'internal/integrations/fedwiki/*_test.go'` lists and in which `git grep -n -i 'force_reduced'` finds a hit, today `workflows/sync_requests_db_test.go` and `workflows/usage_interleavings_db_test.go`) and rewrite each that does.
|
||||
- [x] 7.2 Extend `TestSyncLeavesSitesWithOpenRequests_DB` (`workflows/swap_counter_db_test.go`): a pending return's site, which the farm now reports archived and, in a second case, active, keeps its mark because the sync skips a domain with an accepted request and checks again under the row's lock, and the mark clears only when the return's success clears it (design D18).
|
||||
- [x] 7.3 `RestoreSite` (`web/site_actions.go`) calls `changeStatus` with `rotation` false and, before anything is recorded, answers a row whose status is not `archived` with `siteActionConflict` ("This site changed since the list loaded." and a refresh), as design D10 states. Add `TestRestoreOfANonArchivedRow_DB` (`web/requests_db_test.go`): a marked read-only row and an active row, each posted to the restore route, record nothing and answer the conflict (F10a); and `TestRestoreIsNeverARotation_DB`: a Restore of an archived row is accepted while a rotation of the workspace is open, inside the cooldown window and with the cooldown on, takes no workspace lock (`TestWorkspaceTxTakesTheWorkspaceLock` still passes), writes no stamp at intake (the record step's success stamping nothing is covered by the workflows test "a free fill and a Restore stamp nothing"), and answers "Couldn't update the site. Try again." on a database error.
|
||||
- [x] 7.4 Remove the Restore gate: `SiteViewModel.IsForceReduced` and `RestoreControl` (`web/partials.go`) go, the `{{ if and .IsForceReduced $.CooldownMsg }}` branch of `templates/fedwiki_sites.html` goes, and Restore renders as on any archived row. `TestSitesCardCooldownButtonsUseThePart` (`web/sites_render_test.go`) keeps Keep active's half and drops the Restore half; a new render case requires an archived row to show an enabled Restore with the cooldown on. No new sentence is added to the template. `git grep -n 'IsForceReduced\|RestoreControl' -- internal` finds nothing.
|
||||
- [x] 7.5 A return's intake locks its site row after the instance lock and before the request is inserted (`holdReturnSite` in `web/site_actions.go`, called from `recordRotation`), and re-checks under the lock that the row is still the member's with the posted domain, read-only and marked; a missing or foreign row records nothing and answers "Site not found", and a row no longer read-only or marked records nothing and answers `siteActionConflict` (design D10, D18, F19a). `TestReturnWaitsForTheSyncsSiteRow` (`web/swap_rotation_db_test.go`) holds the row as the sync's status write does, requires the intake to wait on it, writes the row archived through `UpsertSiteFromFarm` and commits, and requires nothing recorded and the stale-row sentence; the reverse order is held by `TestSyncLeavesSitesWithOpenRequests_DB` ("a sync reporting a pending return's site archived" and "active"). `TestWorkspaceTxTakesTheWorkspaceLock`, `TestReturnTakesTheWorkspaceLock` and the Restore and free-fill tests still show no site-row lock where none is taken. `docs/database-locks.md` ("FedWiki at the handler", the site row's entry, "In the farm sync") and the fedwiki-sites delta say so.
|
||||
|
||||
## 8. The remaining tests
|
||||
|
||||
- [x] 8.1 `TestLifecycleStatementsRunAsTheRuntimeRole_DB` in `internal/integration/lifecycle_db_test.go`: under `SET LOCAL ROLE console_runtime`, run every statement of the lifecycle path against `core.lifecycle_requests` (`InsertLifecycleRequest` with its `ON CONFLICT DO NOTHING RETURNING request_id`, `RecordLifecycleAct`, `FinishLifecycleRequest`, `AcknowledgeLifecycleRequest` by address and by act, both deletes, the lookups) and require each to succeed under the column grants, and that the `updated_at` trigger fires under column UPDATE. This is the test that catches a missing column grant, which the suite's superuser connection cannot (design "Risks"). A second case under the same role writes `act_id` by INSERT and by UPDATE and requires the privilege refusal.
|
||||
- [x] 8.2 `TestMigrationPlanStatementsRunAsTheirRoles_DB` in `internal/integrations/fedwiki/store/` (design "Migration Plan"): build stored rows by hand, in the old form (an open swap with the two keys and the workflow prefix, an open return on a marked read-only site, a declined parked-site request that is not acknowledged, a marked archived row), then run step 1's two counts and step 4's listing as `console_runtime` and require the counts and the listing to find exactly those rows (step 1 runs only before the new release writes any request, so the counts have no new-form row to exclude) and the listing to find none of the new-form rows; run step 3's UPDATE and step 4's UPDATE as `console_runtime` and require them to succeed and to change only the marked non-read-only row and the unacknowledged parked-site row. The SQL in the test is the SQL of design.md, copied unchanged.
|
||||
- [x] 8.3 A last pass over the tests named in `design.md` "What is unverified" that no task above already placed: read `TestQuotaSurfacesReadTheStoredFigure` and `TestQuotaSurfacesFollowTheStoredFigureNotTheRows` (`web/quota_rows_db_test.go`) and `TestKeepActiveSwapsWhenSiblingsFillThePool` (`web/shared_pool_db_test.go`), the three that tasks 3.3 and 4.2 name only by file or not at all, and confirm that none asserts a swap key, a parked request's person or the stamp at intake; rewrite any that does. `go test` of `internal/integrations/fedwiki/...`, `internal/integration`, `internal/acts`, `internal/db` and `internal/migrate` passes against a migrated database.
|
||||
|
||||
## 9. The documents
|
||||
|
||||
- [x] 9.1 `docs/models/provider-integration.md`: four invariants after invariant 18, worded as design "Documents and spec deltas" gives them (a request covers one instance, and its act columns are all set or all empty, tied to the header by `(act_id, act_cause)`, with at most one `asked` request per act and no person on a `consequent` request; only `core.record_lifecycle_act` writes the act columns, on requests its own transaction inserted, so a request joins an act when recorded and never moves to another act, and for `instances_swapped` the asked request names the act's actor as its person; `core_writer` holds INSERT and UPDATE only on the columns the request writers name; an action that changes several instances records one request per instance in one transaction and groups them under one lifecycle act, and nothing else groups requests; an act only ties its requests together, so a connector applies each request on its own). The card's "Lifecycle request" entry, the `core.lifecycle_requests` table row and the per-instance dimension say a request records the person whose action caused it, or no one when the console added it to a person's act; add a "Lifecycle act" entry, the table rows, `RecordLifecycleAct` and the act delete in the writers row, and a request-versus-act dimension. Each invariant carries its tag (`[db]`, `[db-code]`, `[app]`) as its neighbours do.
|
||||
- [x] 9.2 `docs/models/acts.md` and `docs/models/README.md`: the summary, the opening ("Only plan acts exist today"), the writers table and invariants 4 and 5 add the lifecycle act, its lack of a detail table and its writer, and limit the rendezvous rule to plan acts; invariant 2 says a lifecycle act's requests carry `chk_lifecycle_requests_act_cause` and `lifecycle_request_in_its_act`, so a later lifecycle cause enters that constraint as well as `chk_acts_cause`; a new `[db-code]` invariant lists the lifecycle writer's refusals; invariant 17 says `core.lifecycle_requests` is outside the record, so an unstarted act's header outlives its requests; "Business time vs wall clock" gives a lifecycle act's `effective_at` as its asked request's `created_at`; the README's acts line names the lifecycle acts.
|
||||
- [x] 9.3 `docs/database-locks.md`: the workspace lock's row and "FedWiki at the handler" describe every rotation's intake (the open-rotation check and the cooldown read under the lock, no policy row written, a return taking the lock with the cooldown off); the row-lock table gains a "FedWiki swap policy row" entry (taken by both record steps after the site and placement rows and before the usage row; intake reads it without a lock); "When recording an outcome", rule 5 and rule 3's FedWiki clause place the policy row there and add settle's one `finishAllWith` per act; the paragraph on the unstarted delete adds `DeleteUnstartedLifecycleAct`. The project lint's check of the document's family table passes.
|
||||
- [x] 9.4 `docs/building-an-integration.md`, the passage on actions that change several instances: such an action records one request per instance, groups them with `RecordLifecycleAct`, deletes them with `DeleteUnstartedLifecycleAct` when the start is refused as not found, and undoes a succeeded request when another fails; a new lifecycle cause is provider-neutral, added by one core migration to `chk_acts_cause` and `chk_lifecycle_requests_act_cause` with its own branch in `core.record_lifecycle_act`, and its constant joins `acts.LifecycleCauses`.
|
||||
- [x] 9.5 Re-read the six spec deltas under `openspec/changes/lifecycle-request-acts/specs/` against the code as it now stands, and correct a delta or a task where they disagree: the requirement titles are copied exactly from `openspec/specs/`, every rule this change adds is in a requirement body and not only in a scenario, and every scenario has the test that a task above names. A delta is corrected in the same commit; no file outside `tasks.md`, the six deltas, `design.md` and `proposal.md` of this change is touched here. act-records "A lifecycle act's row is not rewritten when its requests finish" is held by the enclosure that `TestActRecordIsEnclosed` (`internal/db/acts_test.go`) checks: `console_runtime` cannot UPDATE `core.acts`. provider-lifecycle-contract "A failed request of an act is undone by the console" is held by `TestSwapAndDeleteRequests_DB` ("a swap the farm keeps refusing leaves both sites as they were", "a failed swap whose farm could not take the parked site back restores it") and `TestSwapRestoreTakesTheFarmsDefiniteAnswer_DB` in `workflows/`.
|
||||
|
||||
## 10. Deploy notes and the closing checks
|
||||
|
||||
- [x] 10.1 Write the deploy notes into the commit message body, in operator terms and naming no deployment, from `design.md` "Migration Plan": count open swaps and open returns (both must be 0) and the marked rows that are not read-only; stop every process of the old release; count again and clear the marked non-read-only rows as the runtime user in the stop window; list and acknowledge the stored parked-site requests that ended declined or failed and are not dismissed; migrate to 00041 and start the new release; once the rotations counted in the stop window have finished, list the stored parked-site requests again and acknowledge what the listing finds; when a swap counted in the stop window fails, delete its workspace's `fedwiki.site_swap_policy` row by hand to let the member rotate at once, which also erases any earlier wait; run `scripts/db-reader-role.sql` again. State the rollback condition (the previous image on the 00041 schema, once no lifecycle request is open), what degrades on a rollback (two notices for a failed new swap and a false "deleted" sentence), the rows to acknowledge by hand after a rollback (consequent rows that ended declined or failed, and asked rows that ended `site_missing` while their own site row still exists, in both cases when not yet acknowledged), that rolling forward again repeats every step and that the Down refuses once a lifecycle act exists. The SQL is the SQL of `design.md`, unchanged and checked by task 8.2.
|
||||
- [x] 10.2 `make test` from the repository root with the test stack up (`./bootstrap-stack.sh` from `test/` first, then `docker compose up`): `make lint`, then every package. It passes without `-update`, with no golden, route table or existing test result changed outside the task that names it, and with `scripts/deadcode-testonly.txt` untouched.
|
||||
- [x] 10.3 `openspec validate lifecycle-request-acts --strict` passes.
|
||||
- [x] 10.4 The `git grep` checks the design names. Each runs over tracked files only; before the commit, pass `--untracked` so the new files are searched too. (a) `git grep -n 'IsSwapRequestWorkflowID\|hasOpenSwap\|sameRowRequest\|SwapParkSiteID\|SwapActivateSiteID\|IsForceReduced\|RestoreControl\|OpenRequestsByWorkspace' -- internal` lists, for `OpenRequestsByWorkspace`, only its definition in `internal/integration/lifecycle.go`, its test in `internal/integration/lifecycle_db_test.go` and the sites list's own read in `web/site_actions.go`, and none of the other names. (b) `git grep -n 'swap_park_site_id\|swap_activate_site_id' -- internal docs openspec/specs` lists only the hand-built stored rows of tasks 4.3, 5.5, 6.2 and 8.2 (rows in the previous release's form). (c) `git grep -n 'entitlements.ActCause\|ActTierAdded\|ActPlanActRetried' -- internal` finds nothing. (d) `git grep -n 'UpsertSiteSwapPolicy' -- 'internal/*.go'` finds callers only in `workflows/swap.go` and `workflows/request_activities.go`. (e) `git grep -n -E '(INSERT INTO|UPDATE|DELETE FROM) core\.lifecycle_requests' -- internal ':!*_test.go' ':!*.sql.go'` still lists only the statements of task 1.1. (f) `git grep -n 'status/[e]xplorations' -- internal docs openspec/changes/lifecycle-request-acts` finds nothing (the bracket keeps the pattern from matching this line), and no changed file names a deployment, a count from one or a maintainer. (g) Over `openspec/specs`, `git grep` for the swap keys, the swap prefix, the stamp, the cooldown, `force_reduced_at`, the act writers and the cause list finds the rules this change moved only in the six specs of the deltas (design "Documents and spec deltas", last paragraph).
|
||||
- [x] 10.5 Confirm the contract of design D17 and the non-goals: `git diff --stat` shows no change to `workflows/replay_test.go`, to the replay histories, or to a workflow command, and none to `sameCreate`, the JSON delete's second read or `finishAllWith`'s finish rule.
|
||||
- [ ] 10.6 On the maintainer's go, archive the change with `openspec archive lifecycle-request-acts` in its own commit, right after the implementation's, so the six deltas merge into `openspec/specs/`; run tasks 10.3 and 10.4 (g) before the archive.
|
||||
- [ ] 10.7 After the push, post on each of #184, #328 and #329 under `CONTRIBUTING.md`'s rules for forge text (item 1: it reads for someone who has never opened the repository, explains the console's terms once, and names no decision number, change name, date as narrative, deployment or count), and close it. Post the grouping rule (one instance a request, an act id for one action's requests, the console undoes the others when one fails, a connector applies each request on its own) on the issue for the published protocol, and a note that the swap policy's home is its question on the issue for where the swap policy lives, the two issues that `proposal.md` names under Related issues.
|
||||
Reference in New Issue
Block a user