mirror of
https://github.com/Stirling-Tools/Stirling-PDF.git
synced 2026-09-02 21:03:34 +03:00
Surface recorded failures in a notification bell (Review Flow PR 4) (#7478)
Review Flow PR 4. Stacked on #7477. Recorded failures appear in a notification bell, showing each reader the failures they are allowed to see and the actions they can actually take. Scope is deliberately viewing and routing only. Resolving a failure — retry, decrypt-and-retry — is #7479, which also brings the write path for it; nothing resolution-shaped ships here, not even dark. ## What's added **A notification bell** in the editor and the processor shell. Polls `GET /api/v1/notifications` every 30 seconds, shows an unread badge, and lists open failures newest first. Each row shows the failure's title, its message with **Copy error** and **Show full message** chips, an occurrence count, and its available actions. **A notification API** (`stirling.software.proprietary.notification`), derived from failures on read rather than stored in its own table: | Route | Purpose | |---|---| | `GET /api/v1/notifications` | the caller's open failures, newest first | Read-only by design: every action the bell offers is one the client runs on its own device, so there is nothing to post back. Every id is prefixed (`failure:<uuid>`), so the bell never holds a raw failure id it could hand to a failure endpoint. **Per-reader actions.** A `FailureKind` declares each action with an audience (`OWNER`, `TEAM_REVIEWER`, `ANYONE_WHO_SEES`). The server resolves that against the reader and derives `Ownership` (`MINE` / `THEIRS` / `UNOWNED`) from the row's actor, so an admin reviewing someone else's failure is not offered a document their browser does not hold. Adding a failure kind requires no frontend change. **Server-run and client-run actions are distinguished.** `FailureActionId` carries an `Execution` facet; the registry requires a bean only for server actions, and dispatching a client action on the failure surface returns 400. The notification projection goes further: it carries only client-run offers, so the bell cannot be sent a button it would refuse to draw. **Actions in the bell:** at most two. The owner of the document gets **View file** (opens it in the editor); a team reviewer gets **View in processor** (dev builds only). Dismiss stays on the failure queue in `/processor/documents` — deciding a failure's fate belongs to the review surface, not the panel that announces it. An action id the build has not wired is skipped rather than rendered dead, so the server can ship new kinds ahead of the clients that understand them. **Attended policy runs record their document.** `POST /api/v1/policies/{id}/run` accepts an optional opaque `fileId`, recorded when the run carries exactly one primary document. This is what lets a repeat fold onto one incident instead of opening a new one per upload, lets deleting the file clear its failure, and lets the owner open the document from the row. ## Behaviour changes - **The bell re-reads as soon as a failure you caused is recorded**, rather than leaving you to wait out a poll interval for news of your own upload. Applies to a failed tool run and to a policy run reaching `FAILED`. Other people's failures still arrive on the poll, which is what it is for. - **An action the reader cannot use is not rendered.** Where the server gave a reason for withholding it, that reason appears as the row's one-line note. An action that was never offered to that reader produces no note. - **Deleting a document closes every incident about it that the deleter caused**, including a failed policy run on their own upload, so a user's own errors leave the bell with the file rather than lingering with a dead button. - **The failures list in `/processor/documents` stays behind `import.meta.env.DEV`**, and View in processor is gated to match so it cannot navigate to a section that is not mounted. Both lift when failures get their own review screen. - **One poll for all bells.** The bell is mounted in three places; the list, document lookups and read marker are shared, so mounting more than one does not multiply requests. - `ACKNOWLEDGE` is no longer offered by any kind. The id, bean and status remain so existing rows stay readable. ## Known limits - The poll does not pause when the tab is hidden. - No retention or per-team cap on `file_run_events`. ## How to test Needs a proprietary or SaaS build with login enabled. `task dev:all`, then sign in. 1. **Create a failure.** Add a password-protected PDF to the editor and choose **Skip for now** when it asks to unlock. The upload starts a policy run that fails on it. 2. **Watch the bell.** The badge should appear within a second or two, not after 30 — this is the refresh-on-failure path. Open it: a row titled "Password-protected document" with the error message and the two chips. 3. **The buttons should be View file and View in processor, nothing else.** No Dismiss and no retries: dispositions live on the review surface, resolutions in #7479. 4. **View file** closes the panel and selects that document in the editor. 5. **Dismiss from the queue instead.** Open `/processor/documents` (dev build), find the row in the failures list and dismiss it there; the bell drops it on its next read. 6. **Confirm the local-document probe.** Create a second failure, then delete that file from the editor and reload. Its incident closes with it; a row whose document is still present keeps **View file**. 7. **Confirm attribution end to end.** Sign in as a plain member, run a shared policy on your own upload so it fails. The member sees their own row in the bell. Sign in as the team leader: they see it too, but with **View in processor** instead of **View file**, because the document is not in their browser. 8. **Confirm folding.** Add the same locked PDF again and skip again. The existing row's occurrence count increases rather than a second row appearing. 9. **Confirm one poll for many bells.** Open the editor and the processor in two tabs. Each tab issues its own poll, but within a tab the several mounted bells share one — the Network tab should show one `GET /api/v1/notifications` per 30s per tab, not three. ## Migration None. No new column and no new value in any CHECK-constrained enum; `CheckConstrainedEnumsTest` fails if that changes.
This commit is contained in:
+22
-15
@@ -1,20 +1,17 @@
|
||||
package stirling.software.proprietary.failure;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
/**
|
||||
* Why an action could not be dispatched. Carries a {@link Reason} rather than an HTTP status, so
|
||||
* the service stays web-agnostic and the controller owns the mapping.
|
||||
*/
|
||||
/** Carries a {@link Reason} rather than an HTTP status, so the service stays web-agnostic. */
|
||||
@Getter
|
||||
public class FailureActionException extends RuntimeException {
|
||||
|
||||
public enum Reason {
|
||||
/**
|
||||
* No such event, it belongs to another team, or the caller's team did not resolve. One
|
||||
* reason for all three, so the response does not vary with which it was. Unrelated to
|
||||
* {@link FailureKind#UNKNOWN}, which is an unclassified failure rather than a refused
|
||||
* action.
|
||||
* No such event, another team's, or an unresolved team: one reason, so the answer cannot
|
||||
* vary.
|
||||
*/
|
||||
EVENT_NOT_FOUND,
|
||||
|
||||
@@ -22,15 +19,13 @@ public class FailureActionException extends RuntimeException {
|
||||
ACTION_NOT_RECOGNISED,
|
||||
|
||||
/**
|
||||
* The action exists but this kind does not declare it, so an incoherent pairing (releasing
|
||||
* a document whose destination is what failed) cannot be dispatched even by hand.
|
||||
*
|
||||
* <p>Unreachable today: both kinds declare both actions, so no request can trip this guard
|
||||
* until a kind ships with a restricted action set. Declared now because the guard must
|
||||
* exist before that kind does, not after.
|
||||
* The action exists but this kind does not offer it, so it cannot be dispatched by hand.
|
||||
*/
|
||||
ACTION_NOT_DECLARED,
|
||||
|
||||
/** Offered, but the client is what runs it, so refused rather than half-performed. */
|
||||
ACTION_NOT_DISPATCHABLE,
|
||||
|
||||
/** The event is already closed, so no further transition is possible. */
|
||||
ALREADY_CLOSED
|
||||
}
|
||||
@@ -41,9 +36,21 @@ public class FailureActionException extends RuntimeException {
|
||||
this(reason, message, null);
|
||||
}
|
||||
|
||||
/** For a refusal that follows from a lower-level failure, so its stack is not dropped. */
|
||||
public FailureActionException(Reason reason, String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
this.reason = reason;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lives with the reasons it maps, so every surface that dispatches an action answers alike. A
|
||||
* closed row is a conflict, not a bad request: it was well-formed and valid a moment earlier.
|
||||
*/
|
||||
public static HttpStatus statusOf(Reason reason) {
|
||||
return switch (reason) {
|
||||
case EVENT_NOT_FOUND -> HttpStatus.NOT_FOUND;
|
||||
case ACTION_NOT_RECOGNISED, ACTION_NOT_DECLARED, ACTION_NOT_DISPATCHABLE ->
|
||||
HttpStatus.BAD_REQUEST;
|
||||
case ALREADY_CLOSED -> HttpStatus.CONFLICT;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+46
-5
@@ -1,11 +1,52 @@
|
||||
package stirling.software.proprietary.failure;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
/**
|
||||
* The actions a {@link FailureKind} may declare. Both are incident dispositions: they change how
|
||||
* the event is shown and touch nothing else, which is what makes them valid for every kind
|
||||
* including {@link FailureKind#UNKNOWN}, and why there is no {@code APPROVE} yet.
|
||||
* The actions a {@link FailureKind} may declare. Client actions are declared here rather than
|
||||
* invented per client, so the server keeps deciding what a kind offers, in what order and labelled
|
||||
* how.
|
||||
*/
|
||||
@Getter
|
||||
public enum FailureActionId {
|
||||
ACKNOWLEDGE,
|
||||
DISMISS
|
||||
|
||||
/**
|
||||
* Kept in the vocabulary for as long as any persisted row is {@code ACKNOWLEDGED}: such rows
|
||||
* must stay readable and closable whether or not any kind currently offers this.
|
||||
*/
|
||||
ACKNOWLEDGE(Execution.SERVER, "Acknowledge"),
|
||||
|
||||
DISMISS(Execution.SERVER, "Dismiss"),
|
||||
|
||||
/** Open the document behind the incident, in whichever client can resolve its id. */
|
||||
VIEW_FILE(Execution.CLIENT, "View file"),
|
||||
|
||||
VIEW_IN_PROCESSOR(Execution.CLIENT, "View in processor");
|
||||
|
||||
/** Dispatch refuses a {@code CLIENT} id, so this is enforced rather than merely documented. */
|
||||
public enum Execution {
|
||||
|
||||
/** {@link FailureActionRegistry} requires a {@link FailureAction} bean for these. */
|
||||
SERVER,
|
||||
|
||||
/**
|
||||
* Declared and rendered, never dispatched: the server has neither the file nor the tool.
|
||||
*/
|
||||
CLIENT
|
||||
}
|
||||
|
||||
private final Execution execution;
|
||||
|
||||
/** English fallback, for a client with no translation for the label key. */
|
||||
private final String defaultLabel;
|
||||
|
||||
FailureActionId(Execution execution, String defaultLabel) {
|
||||
this.execution = execution;
|
||||
this.defaultLabel = defaultLabel;
|
||||
}
|
||||
|
||||
/** Also whether it can be dispatched. */
|
||||
public boolean runsOnServer() {
|
||||
return execution == Execution.SERVER;
|
||||
}
|
||||
}
|
||||
|
||||
+13
-4
@@ -16,6 +16,9 @@ import lombok.extern.slf4j.Slf4j;
|
||||
* Resolves a {@link FailureActionId} to the bean that implements it. The startup check is the
|
||||
* point: because kinds declare action ids as data, one could name an action nobody implements,
|
||||
* which would otherwise show up as a button that 400s rather than as a failed boot.
|
||||
*
|
||||
* <p>Only {@link FailureActionId.Execution#SERVER} ids belong here: a bean for a client action is
|
||||
* refused, because dispatch could never reach it.
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@@ -25,6 +28,14 @@ public class FailureActionRegistry {
|
||||
|
||||
public FailureActionRegistry(List<FailureAction> actions) {
|
||||
for (FailureAction action : actions) {
|
||||
if (!action.id().runsOnServer()) {
|
||||
throw new IllegalStateException(
|
||||
"Action "
|
||||
+ action.id()
|
||||
+ " is run by the client, so "
|
||||
+ action.getClass().getName()
|
||||
+ " could never be dispatched");
|
||||
}
|
||||
FailureAction clash = byId.put(action.id(), action);
|
||||
if (clash != null) {
|
||||
throw new IllegalStateException(
|
||||
@@ -38,10 +49,7 @@ public class FailureActionRegistry {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fail fast if any kind declares an action with no handler, naming every gap rather than the
|
||||
* first, so one boot tells you everything that is missing.
|
||||
*/
|
||||
/** Names every gap rather than the first, so one boot tells you everything that is missing. */
|
||||
@PostConstruct
|
||||
void verifyEveryDeclaredActionHasAHandler() {
|
||||
List<String> gaps =
|
||||
@@ -49,6 +57,7 @@ public class FailureActionRegistry {
|
||||
.flatMap(
|
||||
kind ->
|
||||
kind.getActions().stream()
|
||||
.filter(FailureActionId::runsOnServer)
|
||||
.filter(action -> !byId.containsKey(action))
|
||||
.map(action -> kind.getId() + " -> " + action))
|
||||
.toList();
|
||||
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package stirling.software.proprietary.failure;
|
||||
|
||||
/**
|
||||
* Who an offered action is for, the read scope having already decided they may see the incident.
|
||||
* The distinction is possession, not seniority: a reviewer cannot reach a document only its owner
|
||||
* holds.
|
||||
*/
|
||||
public enum FailureAudience {
|
||||
OWNER,
|
||||
|
||||
/** Anyone who triages the team's incidents, whoever hit them. */
|
||||
TEAM_REVIEWER,
|
||||
|
||||
ANYONE_WHO_SEES
|
||||
}
|
||||
+44
-20
@@ -1,7 +1,11 @@
|
||||
package stirling.software.proprietary.failure;
|
||||
|
||||
import static stirling.software.proprietary.failure.FailureActionId.ACKNOWLEDGE;
|
||||
import static stirling.software.proprietary.failure.FailureActionId.DISMISS;
|
||||
import static stirling.software.proprietary.failure.FailureActionId.VIEW_FILE;
|
||||
import static stirling.software.proprietary.failure.FailureActionId.VIEW_IN_PROCESSOR;
|
||||
import static stirling.software.proprietary.failure.FailureAudience.ANYONE_WHO_SEES;
|
||||
import static stirling.software.proprietary.failure.FailureAudience.OWNER;
|
||||
import static stirling.software.proprietary.failure.FailureAudience.TEAM_REVIEWER;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
@@ -20,13 +24,8 @@ import lombok.Getter;
|
||||
* The registry of failure kinds, described as data: a stable id, i18n keys and an English fallback
|
||||
* like {@code ExceptionUtils.ErrorCode}, plus the facets a review surface needs.
|
||||
*
|
||||
* <p>Actions are declared here but implemented in {@link FailureAction} beans resolved by id, so a
|
||||
* new kind ships as a registry entry plus copy. Two members today: {@link #UNKNOWN} gives every
|
||||
* failed run a record, and kinds get promoted out of it as production shows what occurs.
|
||||
*
|
||||
* <p>A kind offers an acknowledgement only where there is something to acknowledge <em>doing</em>.
|
||||
* With nothing to fix, "seen it" and "clear it" are the same decision, so the row offers only the
|
||||
* one that clears it.
|
||||
* <p>A new kind ships as a registry entry plus copy. Each offer also says who it is for, since one
|
||||
* incident is read both by whoever hit it and by whoever reviews after them.
|
||||
*/
|
||||
@Getter
|
||||
public enum FailureKind {
|
||||
@@ -37,8 +36,9 @@ public enum FailureKind {
|
||||
FailureScope.FILE,
|
||||
errorCodes("E004"),
|
||||
fallback("This document is password-protected, so the pipeline could not read it."),
|
||||
offer(ACKNOWLEDGE),
|
||||
offer(DISMISS, "dismissSkipFile")),
|
||||
offer(VIEW_FILE, OWNER),
|
||||
offer(VIEW_IN_PROCESSOR, TEAM_REVIEWER),
|
||||
offer(DISMISS, ANYONE_WHO_SEES)),
|
||||
|
||||
UNKNOWN(
|
||||
FailureStage.INTERNAL,
|
||||
@@ -47,7 +47,11 @@ public enum FailureKind {
|
||||
FailureScope.RUN,
|
||||
noErrorCodes(),
|
||||
fallback("This run failed for a reason Stirling does not yet recognise."),
|
||||
offer(DISMISS));
|
||||
// Same order as every other kind: declaration order is display order, so the document
|
||||
// leads wherever it is offered rather than moving between failures.
|
||||
offer(VIEW_FILE, OWNER),
|
||||
offer(VIEW_IN_PROCESSOR, TEAM_REVIEWER),
|
||||
offer(DISMISS, ANYONE_WHO_SEES));
|
||||
|
||||
private static final String KEY_PREFIX = "portal.failures.kind.";
|
||||
private static final String ACTION_KEY_PREFIX = "portal.failures.action.";
|
||||
@@ -95,22 +99,26 @@ public enum FailureKind {
|
||||
}
|
||||
|
||||
/**
|
||||
* One action this kind offers, with the key to label it by. One ordered list rather than ids
|
||||
* plus a parallel map of overrides, which could disagree with each other.
|
||||
* One ordered list rather than ids plus parallel maps of audiences and labels, which could
|
||||
* disagree with each other.
|
||||
*
|
||||
* @param labelKeySuffix key under {@code portal.failures.action.}, or null for the generic
|
||||
* label
|
||||
*/
|
||||
private record Offer(FailureActionId id, String labelKeySuffix) {}
|
||||
private record Offer(FailureActionId id, FailureAudience audience, String labelKeySuffix) {}
|
||||
|
||||
/** An action labelled by this kind's own wording, where the generic label reads badly. */
|
||||
private static Offer offer(FailureActionId id, String labelKeySuffix) {
|
||||
return new Offer(id, labelKeySuffix);
|
||||
/** Declaration order is display order. */
|
||||
private static Offer offer(FailureActionId id, FailureAudience audience) {
|
||||
return new Offer(id, audience, null);
|
||||
}
|
||||
|
||||
/** An action labelled by the shared wording for that action. */
|
||||
private static Offer offer(FailureActionId id) {
|
||||
return new Offer(id, null);
|
||||
/**
|
||||
* As {@link #offer(FailureActionId, FailureAudience)}, but labelled by this kind's own wording
|
||||
* where the shared one reads badly.
|
||||
*/
|
||||
private static Offer offer(
|
||||
FailureActionId id, FailureAudience audience, String labelKeySuffix) {
|
||||
return new Offer(id, audience, labelKeySuffix);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -149,6 +157,22 @@ public enum FailureKind {
|
||||
return offers.stream().map(Offer::id).toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* What this kind offers, in declaration order, each with its label resolved. What a review
|
||||
* surface reads, so it never has to ask two separate questions about one offer.
|
||||
*/
|
||||
public List<OfferedAction> getOfferedActions() {
|
||||
return offers.stream()
|
||||
.map(
|
||||
offer ->
|
||||
new OfferedAction(
|
||||
offer.id(), labelKeyFor(offer.id()), offer.audience()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
/** One action as a kind declares it: what to call it and who it is for. */
|
||||
public record OfferedAction(FailureActionId id, String labelKey, FailureAudience audience) {}
|
||||
|
||||
/** Whether this kind offers {@code action}. The dispatch guard: see {@code FailureActionId}. */
|
||||
public boolean declares(FailureActionId action) {
|
||||
return offers.stream().anyMatch(offer -> offer.id() == action);
|
||||
|
||||
+11
-17
@@ -74,8 +74,10 @@ public class FileRunEventController {
|
||||
@Operation(
|
||||
summary = "Apply an action to a recorded failure",
|
||||
description =
|
||||
"Rejected with 400 if the failure's kind does not declare the action, so an"
|
||||
+ " action that makes no sense for a given failure cannot be applied.")
|
||||
"Rejected with 400 if the failure's kind does not declare the action, or if the"
|
||||
+ " action is one the client runs rather than the server, so neither an"
|
||||
+ " action that makes no sense for a given failure nor one the server"
|
||||
+ " cannot perform can be applied.")
|
||||
public FileRunEventView act(
|
||||
@PathVariable String eventId,
|
||||
@PathVariable String actionId,
|
||||
@@ -87,7 +89,8 @@ public class FileRunEventController {
|
||||
FileRunEvent updated = service.dispatch(eventId, actionId, inputs);
|
||||
return FileRunEventView.of(updated, service.availableActions(updated));
|
||||
} catch (FailureActionException e) {
|
||||
throw new ResponseStatusException(statusFor(e.getReason()), e.getMessage(), e);
|
||||
throw new ResponseStatusException(
|
||||
FailureActionException.statusOf(e.getReason()), e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -147,18 +150,6 @@ public class FileRunEventController {
|
||||
return Arrays.stream(FailureKind.values()).map(FailureKindView::of).toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* A closed row is a conflict rather than a bad request: the request was well-formed and would
|
||||
* have been valid a moment earlier.
|
||||
*/
|
||||
private static HttpStatus statusFor(FailureActionException.Reason reason) {
|
||||
return switch (reason) {
|
||||
case EVENT_NOT_FOUND -> HttpStatus.NOT_FOUND;
|
||||
case ACTION_NOT_RECOGNISED, ACTION_NOT_DECLARED -> HttpStatus.BAD_REQUEST;
|
||||
case ALREADY_CLOSED -> HttpStatus.CONFLICT;
|
||||
};
|
||||
}
|
||||
|
||||
/** Wrapped rather than a bare array so pagination can be added without breaking clients. */
|
||||
public record FileRunEventsResponse(List<FileRunEventView> events) {}
|
||||
|
||||
@@ -178,10 +169,13 @@ public class FileRunEventController {
|
||||
}
|
||||
}
|
||||
|
||||
/** Inputs an action declared it needs. Empty for both actions that exist today. */
|
||||
/**
|
||||
* Inputs an action declared it needs. Empty for every action the server runs today: the one
|
||||
* that needs a password is run by the client, which never sends it here.
|
||||
*/
|
||||
public record ActionRequest(Map<String, String> inputs) {
|
||||
|
||||
Map<String, String> safeInputs() {
|
||||
public Map<String, String> safeInputs() {
|
||||
return inputs == null ? Map.of() : inputs;
|
||||
}
|
||||
}
|
||||
|
||||
+6
-8
@@ -98,20 +98,18 @@ public interface FileRunEventRepository extends JpaRepository<FileRunEventEntity
|
||||
* Close the incidents about documents their owner deleted from the editor: the queue is what
|
||||
* needs attention, and a document that no longer exists needs none.
|
||||
*
|
||||
* <p>Restricted to that owner's own editor rows. File ids are minted by the client, so scoping
|
||||
* on team alone would let one caller close a colleague's incidents by naming ids. Processor
|
||||
* rows are excluded outright: nothing was deleted from an editor there.
|
||||
* <p>Scoped by the absence of a source rather than by origin: a source-fed run's {@code fileId}
|
||||
* is a hash no client can name. Narrowed to the owner's own rows, since clients mint the ids.
|
||||
*/
|
||||
@Modifying(clearAutomatically = true)
|
||||
@Transactional
|
||||
@Query(
|
||||
"update FileRunEventEntity e set e.status ="
|
||||
+ " stirling.software.proprietary.failure.FileRunEventStatus.FILE_REMOVED,"
|
||||
+ " e.statusActor = :actor, e.statusAt = :now where e.origin ="
|
||||
+ " stirling.software.proprietary.failure.FailureOrigin.TOOL and ((:teamId is"
|
||||
+ " null and e.teamId is null) or e.teamId = :teamId) and ((:actor is null and"
|
||||
+ " e.actor is null) or e.actor = :actor) and e.fileId in :fileIds and e.status in"
|
||||
+ " :allowedFrom")
|
||||
+ " e.statusActor = :actor, e.statusAt = :now where e.sourceId is null and"
|
||||
+ " ((:teamId is null and e.teamId is null) or e.teamId = :teamId) and"
|
||||
+ " ((:actor is null and e.actor is null) or e.actor = :actor) and e.fileId in"
|
||||
+ " :fileIds and e.status in :allowedFrom")
|
||||
int markFilesRemoved(
|
||||
@Param("teamId") Long teamId,
|
||||
@Param("actor") String actor,
|
||||
|
||||
+99
-35
@@ -21,12 +21,22 @@ import stirling.software.proprietary.policy.config.PolicyManagementAuthority;
|
||||
* team always comes from the authenticated principal, and scoping applies only when login is
|
||||
* enabled so single-user deployments keep working. When the team cannot be resolved the caller
|
||||
* reads nothing; see {@link #readScope()}.
|
||||
*
|
||||
* <p>The read scope decides who sees an incident; {@link #availableActions} decides who may act.
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class FileRunEventService {
|
||||
|
||||
/** Why an offered action came back disabled. Copy lives under {@code portal.failures}. */
|
||||
private static final String CLOSED_REASON_KEY = "portal.failures.disabled.closed";
|
||||
|
||||
private static final String UNATTENDED_REASON_KEY = "portal.failures.disabled.unattended";
|
||||
|
||||
/** The row never named a document, so unlike the unattended case no client can find one. */
|
||||
private static final String DOCUMENTLESS_REASON_KEY = "portal.failures.disabled.noDocument";
|
||||
|
||||
private final FileRunEventStore store;
|
||||
private final FailureActionRegistry actionRegistry;
|
||||
private final PolicyManagementAuthority policyManagementAuthority;
|
||||
@@ -116,36 +126,17 @@ public class FileRunEventService {
|
||||
* Dispatch an action against one event.
|
||||
*
|
||||
* @throws FailureActionException if the event is not the caller's, the action is unknown, the
|
||||
* event's kind does not declare the action, or the event is already closed
|
||||
* event's kind does not declare the action, the client is what runs the action, or the
|
||||
* event is already closed
|
||||
*/
|
||||
public FileRunEvent dispatch(String eventId, String actionId, Map<String, String> inputs) {
|
||||
// Whoever can see it can close it: a leader for the whole team, everyone else for the
|
||||
// failures they caused. Someone who fixes their own problem should not have to ask a leader
|
||||
// to clear the row.
|
||||
//
|
||||
// Closing the row is all this covers. Acting on the document behind it, such as supplying a
|
||||
// password for a retry, would need its own permission, and no such action exists yet.
|
||||
ReadScope scope = readScope();
|
||||
if (!scope.permitted()) {
|
||||
// Reported as "no such event", the same as an id from another team, so the response
|
||||
// does
|
||||
// not depend on whether the id happens to exist.
|
||||
throw new FailureActionException(
|
||||
FailureActionException.Reason.EVENT_NOT_FOUND, "No such event: " + eventId);
|
||||
}
|
||||
FileRunEvent event =
|
||||
store.find(eventId, scope.teamId())
|
||||
// Reported as "no such event" rather than a refusal, so a member cannot
|
||||
// learn that a colleague's incident exists by trying to close it.
|
||||
.filter(
|
||||
found ->
|
||||
scope.actor() == null
|
||||
|| scope.actor().equals(found.actor()))
|
||||
.orElseThrow(
|
||||
() ->
|
||||
new FailureActionException(
|
||||
FailureActionException.Reason.EVENT_NOT_FOUND,
|
||||
"No such event: " + eventId));
|
||||
// Audience decides what is offered, not what may be dispatched, so this scope is the whole
|
||||
// gate. A server action aimed at OWNER alone would need its own guard here.
|
||||
FileRunEvent event = requireVisible(eventId);
|
||||
|
||||
FailureActionId resolvedId = parseActionId(actionId);
|
||||
|
||||
@@ -156,6 +147,12 @@ public class FileRunEventService {
|
||||
FailureActionException.Reason.ACTION_NOT_DECLARED,
|
||||
"Kind " + event.kind().getId() + " does not offer action " + resolvedId);
|
||||
}
|
||||
// Without this a client could post VIEW_FILE and be answered as though something happened.
|
||||
if (!resolvedId.runsOnServer()) {
|
||||
throw new FailureActionException(
|
||||
FailureActionException.Reason.ACTION_NOT_DISPATCHABLE,
|
||||
"Action " + resolvedId + " is run by the client, not the server");
|
||||
}
|
||||
if (event.status().terminal()) {
|
||||
throw new FailureActionException(
|
||||
FailureActionException.Reason.ALREADY_CLOSED,
|
||||
@@ -174,23 +171,91 @@ public class FileRunEventService {
|
||||
return action.execute(event, inputs == null ? Map.of() : inputs, currentActor());
|
||||
}
|
||||
|
||||
/** "No such event" rather than a refusal, so trying does not confirm a colleague's exists. */
|
||||
private FileRunEvent requireVisible(String eventId) {
|
||||
ReadScope scope = readScope();
|
||||
if (!scope.permitted()) {
|
||||
return notFound(eventId);
|
||||
}
|
||||
return store.find(eventId, scope.teamId())
|
||||
.filter(found -> scope.actor() == null || scope.actor().equals(found.actor()))
|
||||
.orElseGet(() -> notFound(eventId));
|
||||
}
|
||||
|
||||
private FileRunEvent notFound(String eventId) {
|
||||
throw new FailureActionException(
|
||||
FailureActionException.Reason.EVENT_NOT_FOUND, "No such event: " + eventId);
|
||||
}
|
||||
|
||||
public Ownership ownershipOf(FileRunEvent event) {
|
||||
if (event.actor() == null) {
|
||||
return Ownership.UNOWNED;
|
||||
}
|
||||
String caller = currentActor();
|
||||
return event.actor().equals(caller) ? Ownership.MINE : Ownership.THEIRS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Which of an event's declared actions are usable right now. Decided per row, so the client
|
||||
* never renders a button that would be refused.
|
||||
* Offers resolved for one caller, so no client renders a button that would be refused. Outside
|
||||
* their audience is dropped, not disabled: greyed out would read as a permission problem.
|
||||
*/
|
||||
public List<AvailableAction> availableActions(FileRunEvent event) {
|
||||
Ownership ownership = ownershipOf(event);
|
||||
boolean reviewsTeam = reviewsTeam();
|
||||
boolean closed = event.status().terminal();
|
||||
return event.kind().getActions().stream()
|
||||
.map(
|
||||
action ->
|
||||
new AvailableAction(
|
||||
action,
|
||||
event.kind().labelKeyFor(action),
|
||||
!closed,
|
||||
closed ? "portal.failures.disabled.closed" : null))
|
||||
// Login disabled is excluded: its rows are unowned only for want of users, and its one
|
||||
// operator owns everything they can see.
|
||||
boolean unattended = enforced() && ownership == Ownership.UNOWNED;
|
||||
// Answered here, or the client reports "not on this device" about a document the row never
|
||||
// identified in the first place.
|
||||
boolean documentless = event.fileId() == null || event.fileId().isBlank();
|
||||
return event.kind().getOfferedActions().stream()
|
||||
.filter(offer -> offeredTo(offer.audience(), ownership, reviewsTeam))
|
||||
.map(offer -> availability(offer, closed, unattended, documentless))
|
||||
.toList();
|
||||
}
|
||||
|
||||
/** Enabled is derived from the reason, so a disabled button always has one to show. */
|
||||
private static AvailableAction availability(
|
||||
FailureKind.OfferedAction offer,
|
||||
boolean closed,
|
||||
boolean unattended,
|
||||
boolean documentless) {
|
||||
String reason = disabledReasonFor(offer.audience(), closed, unattended, documentless);
|
||||
return new AvailableAction(offer.id(), offer.labelKey(), reason == null, reason);
|
||||
}
|
||||
|
||||
/** Closed wins over everything, then the owner-only reasons, most specific first. */
|
||||
private static String disabledReasonFor(
|
||||
FailureAudience audience, boolean closed, boolean unattended, boolean documentless) {
|
||||
if (closed) {
|
||||
return CLOSED_REASON_KEY;
|
||||
}
|
||||
if (audience != FailureAudience.OWNER) {
|
||||
return null;
|
||||
}
|
||||
if (unattended) {
|
||||
return UNATTENDED_REASON_KEY;
|
||||
}
|
||||
return documentless ? DOCUMENTLESS_REASON_KEY : null;
|
||||
}
|
||||
|
||||
/** An unattended incident has no owner, so its reviewer inherits the owner's actions. */
|
||||
private static boolean offeredTo(
|
||||
FailureAudience audience, Ownership ownership, boolean reviewsTeam) {
|
||||
return switch (audience) {
|
||||
case OWNER ->
|
||||
ownership == Ownership.MINE || (ownership == Ownership.UNOWNED && reviewsTeam);
|
||||
case TEAM_REVIEWER -> reviewsTeam;
|
||||
case ANYONE_WHO_SEES -> true;
|
||||
};
|
||||
}
|
||||
|
||||
/** Login disabled has no roles, so its one operator triages everything. */
|
||||
private boolean reviewsTeam() {
|
||||
return !enforced() || policyManagementAuthority.canEditPolicies();
|
||||
}
|
||||
|
||||
private FailureActionId parseActionId(String actionId) {
|
||||
for (FailureActionId candidate : FailureActionId.values()) {
|
||||
if (candidate.name().equals(actionId)) {
|
||||
@@ -261,7 +326,6 @@ public class FileRunEventService {
|
||||
return applicationProperties.getSecurity().isEnableLogin();
|
||||
}
|
||||
|
||||
/** One action as offered for a specific event, with its resolved availability. */
|
||||
public record AvailableAction(
|
||||
FailureActionId id, String labelKey, boolean enabled, String disabledReasonKey) {}
|
||||
}
|
||||
|
||||
+13
-3
@@ -60,14 +60,24 @@ public record FileRunEventView(
|
||||
event.lastSeenAt() == null ? 0L : event.lastSeenAt().toEpochMilli());
|
||||
}
|
||||
|
||||
/** One button, as offered for this specific row. */
|
||||
/**
|
||||
* {@code defaultLabel} and {@code execution} let a client render and route an action it was
|
||||
* never built with. Declaration order is display order.
|
||||
*/
|
||||
public record ActionView(
|
||||
String id, String labelKey, boolean enabled, String disabledReasonKey) {
|
||||
String id,
|
||||
String labelKey,
|
||||
String defaultLabel,
|
||||
FailureActionId.Execution execution,
|
||||
boolean enabled,
|
||||
String disabledReasonKey) {
|
||||
|
||||
static ActionView of(FileRunEventService.AvailableAction action) {
|
||||
public static ActionView of(FileRunEventService.AvailableAction action) {
|
||||
return new ActionView(
|
||||
action.id().name(),
|
||||
action.labelKey(),
|
||||
action.id().getDefaultLabel(),
|
||||
action.id().getExecution(),
|
||||
action.enabled(),
|
||||
action.disabledReasonKey());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package stirling.software.proprietary.failure;
|
||||
|
||||
/**
|
||||
* Whose incident this is, from the reader's point of view. Derived on read, never persisted: one
|
||||
* row is {@code MINE} to whoever hit it and {@code THEIRS} to the leader reviewing after them.
|
||||
*/
|
||||
public enum Ownership {
|
||||
MINE,
|
||||
|
||||
/** A colleague's, visible because the caller reviews the team. */
|
||||
THEIRS,
|
||||
|
||||
/**
|
||||
* An unattended run: a folder, bucket or webhook is its only attribution, so there is no owner.
|
||||
*/
|
||||
UNOWNED
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package stirling.software.proprietary.notification;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Hidden;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
/**
|
||||
* Open to any authenticated user, unlike the failure endpoints it draws on: each source scopes its
|
||||
* own rows. Read-only, because every action a notification offers runs on the client's own device.
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/notifications")
|
||||
@Hidden
|
||||
@RequiredArgsConstructor
|
||||
@Tag(name = "Notifications", description = "Things worth telling the caller about")
|
||||
public class NotificationController {
|
||||
|
||||
/** How many notifications one read returns when the caller does not say: one panelful. */
|
||||
private static final int DEFAULT_LIMIT = 20;
|
||||
|
||||
/** The most one read may return however large a limit the caller asks for. */
|
||||
private static final int MAX_LIMIT = 100;
|
||||
|
||||
private final NotificationService notifications;
|
||||
|
||||
@GetMapping
|
||||
@Operation(
|
||||
summary = "List the caller's notifications",
|
||||
description =
|
||||
"Newest first. Derived from the sources that produce them, so there is nothing"
|
||||
+ " to mark read here yet: the client tracks what it has shown.")
|
||||
public NotificationsResponse list(@RequestParam(required = false) Integer limit) {
|
||||
int capped = Math.min(limit == null ? DEFAULT_LIMIT : Math.max(1, limit), MAX_LIMIT);
|
||||
return new NotificationsResponse(notifications.list(capped));
|
||||
}
|
||||
|
||||
/** Wrapped so paging or a total can be added without breaking clients. */
|
||||
public record NotificationsResponse(List<NotificationView> notifications) {}
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package stirling.software.proprietary.notification;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import stirling.software.proprietary.failure.FileRunEvent;
|
||||
import stirling.software.proprietary.failure.FileRunEventService;
|
||||
import stirling.software.proprietary.failure.FileRunEventView;
|
||||
|
||||
/**
|
||||
* Derived on read rather than stored: one source today, and a table would need a write path,
|
||||
* retention and a per-user read model first. Each source scopes its own rows, so this cannot widen.
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class NotificationService {
|
||||
|
||||
private final FileRunEventService fileRunEvents;
|
||||
|
||||
/** Newest first, and only open failures: one already dealt with is not news. */
|
||||
public List<NotificationView> list(int limit) {
|
||||
return fileRunEvents.list(null, null, limit).stream().map(this::fromFailure).toList();
|
||||
}
|
||||
|
||||
/** Prefixes the row id on the way out, so it is never sent bare. */
|
||||
private NotificationView fromFailure(FileRunEvent event) {
|
||||
return new NotificationView(
|
||||
NotificationSource.FAILURE.qualify(event.id()),
|
||||
NotificationSource.FAILURE,
|
||||
event.kind().getId(),
|
||||
event.origin(),
|
||||
fileRunEvents.ownershipOf(event),
|
||||
event.severity(),
|
||||
event.status(),
|
||||
event.kind().getTitleKey(),
|
||||
event.kind().getDefaultTitle(),
|
||||
event.detail(),
|
||||
event.fileId(),
|
||||
event.sourceId(),
|
||||
event.policyId(),
|
||||
event.occurrences(),
|
||||
event.createdAt(),
|
||||
event.lastSeenAt(),
|
||||
// A disposition such as Dismiss belongs to the review surface, not the bell.
|
||||
fileRunEvents.availableActions(event).stream()
|
||||
.filter(action -> !action.id().runsOnServer())
|
||||
.map(FileRunEventView.ActionView::of)
|
||||
.toList());
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package stirling.software.proprietary.notification;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* Which subsystem produced a notification. Every id is prefixed with it, so a client never holds
|
||||
* the producing row's own id and cannot reach that source's endpoints by accident.
|
||||
*/
|
||||
public enum NotificationSource {
|
||||
FAILURE;
|
||||
|
||||
private static final char SEPARATOR = ':';
|
||||
|
||||
public String prefix() {
|
||||
return name().toLowerCase(Locale.ROOT) + SEPARATOR;
|
||||
}
|
||||
|
||||
public String qualify(String sourceRowId) {
|
||||
return prefix() + sourceRowId;
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package stirling.software.proprietary.notification;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
import stirling.software.proprietary.failure.FailureOrigin;
|
||||
import stirling.software.proprietary.failure.FailureSeverity;
|
||||
import stirling.software.proprietary.failure.FileRunEventStatus;
|
||||
import stirling.software.proprietary.failure.FileRunEventView;
|
||||
import stirling.software.proprietary.failure.Ownership;
|
||||
|
||||
/**
|
||||
* A source's row flattened to what a bell renders. {@code fileId} is an opaque reference, never a
|
||||
* name, and two id spaces share it: {@code sourceId} tells them apart.
|
||||
*/
|
||||
public record NotificationView(
|
||||
String id,
|
||||
NotificationSource source,
|
||||
String kindId,
|
||||
FailureOrigin origin,
|
||||
Ownership ownership,
|
||||
FailureSeverity severity,
|
||||
FileRunEventStatus status,
|
||||
String titleKey,
|
||||
String defaultTitle,
|
||||
String detail,
|
||||
String fileId,
|
||||
String sourceId,
|
||||
String policyId,
|
||||
int occurrences,
|
||||
Instant createdAt,
|
||||
Instant lastSeenAt,
|
||||
List<FileRunEventView.ActionView> actions) {}
|
||||
+24
-2
@@ -576,7 +576,9 @@ public class PolicyController {
|
||||
+ " under 'fileInput', supporting files under 'assets[i].key' /"
|
||||
+ " 'assets[i].file' - only for bindings the policy does not already"
|
||||
+ " store). Runs regardless of the policy's enabled flag, which only"
|
||||
+ " gates automatic triggering. Returns a run id.")
|
||||
+ " gates automatic triggering. A single-document run may also send its"
|
||||
+ " own opaque 'fileId', which is recorded against any failure so the"
|
||||
+ " caller can resolve it back to that document. Returns a run id.")
|
||||
public ResponseEntity<JobResponse<Void>> runStoredPolicy(
|
||||
@PathVariable String policyId, @Valid @ModelAttribute PolicyRunFiles files)
|
||||
throws IOException {
|
||||
@@ -590,7 +592,14 @@ public class PolicyController {
|
||||
HttpStatus.NOT_FOUND, "No policy: " + policyId));
|
||||
stampPolicyAudit(policy.toDefinition());
|
||||
PolicyInputs inputs = toInputs(files);
|
||||
String runId = policyRunner.runWith(policy, inputs, PolicyProgressListener.NOOP).runId();
|
||||
String runId =
|
||||
policyRunner
|
||||
.runWith(
|
||||
policy,
|
||||
inputs,
|
||||
PolicyProgressListener.NOOP,
|
||||
documentReferenceFor(files, inputs))
|
||||
.runId();
|
||||
return ResponseEntity.accepted().body(new JobResponse<>(true, runId, null));
|
||||
}
|
||||
|
||||
@@ -722,6 +731,19 @@ public class PolicyController {
|
||||
return new PolicyInputs(primary, supportingFiles);
|
||||
}
|
||||
|
||||
/**
|
||||
* Only for a single-document run: an incident holds one file reference, so naming one of
|
||||
* several would attribute the failure to whichever bound first. Counted off resolved inputs,
|
||||
* not parts.
|
||||
*/
|
||||
private static String documentReferenceFor(PolicyRunFiles files, PolicyInputs inputs) {
|
||||
String fileId = files.getFileId();
|
||||
if (fileId == null || fileId.isBlank() || inputs.primary().size() != 1) {
|
||||
return null;
|
||||
}
|
||||
return fileId;
|
||||
}
|
||||
|
||||
private PolicyProgressListener streamListener(SseEmitter emitter) {
|
||||
return new PolicyProgressListener() {
|
||||
@Override
|
||||
|
||||
+14
-2
@@ -16,8 +16,8 @@ import lombok.Data;
|
||||
* from the multipart request via {@code @ModelAttribute}; the pipeline definition itself travels as
|
||||
* a separate typed {@code json} part.
|
||||
*
|
||||
* <p>Wire form: {@code fileInput} (repeated) for primaries, and {@code assets[i].key} / {@code
|
||||
* assets[i].file} for each supporting asset.
|
||||
* <p>Wire form: {@code fileInput} (repeated) for primaries, {@code assets[i].key} / {@code
|
||||
* assets[i].file} for each supporting asset, and the optional {@code fileId}.
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "Files for a policy run: primary documents plus keyed supporting assets")
|
||||
@@ -29,4 +29,16 @@ public class PolicyRunFiles {
|
||||
@Valid
|
||||
@Schema(description = "Supporting files, each bound to the asset key its step references")
|
||||
private List<NamedAsset> assets = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* Recorded against any failure of this run, so the client can resolve the row back to its
|
||||
* document. Opaque by contract, never a name, and only honoured for a single-document run.
|
||||
*/
|
||||
@Schema(
|
||||
description =
|
||||
"The caller's opaque id for the document being run, echoed onto any failure"
|
||||
+ " recorded for this run so the originating client can resolve it."
|
||||
+ " Ignored unless exactly one primary document is supplied. Never a"
|
||||
+ " filename.")
|
||||
private String fileId;
|
||||
}
|
||||
|
||||
+2
-1
@@ -151,7 +151,8 @@ public class PolicyEngine {
|
||||
* As {@link #runPolicy(Policy, PolicyInputs, PolicyProgressListener)}, recording which source
|
||||
* fed the run and its opaque reference to the document. The first says where an unattended
|
||||
* failure came from; the second says which document, and is what lets the same document failing
|
||||
* again fold into one incident. Both null for a user's upload.
|
||||
* again fold into one incident. With no source {@code fileIdentity} is the client's own
|
||||
* reference, with one it is that source's hash; this engine only carries it either way.
|
||||
*/
|
||||
public PolicyRunHandle runPolicy(
|
||||
Policy policy,
|
||||
|
||||
+9
-2
@@ -120,10 +120,17 @@ public class PolicyRunner {
|
||||
* Run a stored policy on caller-supplied files (e.g. an editor upload), bypassing its sources.
|
||||
* The supplied documents are still counted against the virtual {@link EditorSource}, scoped to
|
||||
* the policy's team, so the Sources overview reports the whole team's editor throughput.
|
||||
*
|
||||
* @param documentReference the caller's own opaque reference to the single document it runs on,
|
||||
* or null when it supplied none or several. Passed through untouched.
|
||||
*/
|
||||
public PolicyRunHandle runWith(
|
||||
Policy policy, PolicyInputs inputs, PolicyProgressListener listener) {
|
||||
PolicyRunHandle handle = policyEngine.runPolicy(policy, inputs, listener);
|
||||
Policy policy,
|
||||
PolicyInputs inputs,
|
||||
PolicyProgressListener listener,
|
||||
String documentReference) {
|
||||
PolicyRunHandle handle =
|
||||
policyEngine.runPolicy(policy, inputs, listener, null, documentReference);
|
||||
docCounter.record(EditorSource.counterKey(policy.teamId()), inputs.primary().size());
|
||||
return handle;
|
||||
}
|
||||
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package stirling.software.proprietary.failure;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Pins the five enums {@code file_run_events} stores behind CHECK constraints: adding a value is a
|
||||
* schema change dressed as a Java one, compiling here and failing against a real database.
|
||||
*/
|
||||
class CheckConstrainedEnumsTest {
|
||||
|
||||
@Test
|
||||
@DisplayName("no value has been added to a CHECK-constrained column's enum")
|
||||
void everyPersistedEnumStillMatchesTheShippedCheckConstraints() {
|
||||
assertThat(names(FileRunEventStatus.values()))
|
||||
.containsExactlyInAnyOrder(
|
||||
"NEW", "ACKNOWLEDGED", "DISMISSED", "RESOLVED", "FILE_REMOVED");
|
||||
assertThat(names(FailureOrigin.values()))
|
||||
.containsExactlyInAnyOrder("TOOL", "POLICY", "PIPELINE");
|
||||
assertThat(names(FailureStage.values()))
|
||||
.containsExactlyInAnyOrder("INPUT", "INTERNAL", "OUTPUT", "BLOCKED", "NEVER_RAN");
|
||||
assertThat(names(FailureSeverity.values()))
|
||||
.containsExactlyInAnyOrder("ERROR", "WARNING", "INFO");
|
||||
assertThat(names(FailureScope.values()))
|
||||
.containsExactlyInAnyOrder("FILE", "RUN", "POLICY", "SOURCE", "SERVER");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("the facets added since are derived, not stored")
|
||||
void nothingAddedToTheModelReachedTheTable() throws Exception {
|
||||
// Resolved per reader, so a column would hold the wrong answer for all but one person.
|
||||
List<Class<?>> persisted =
|
||||
Arrays.stream(FileRunEventEntity.class.getDeclaredFields())
|
||||
.filter(field -> !field.isSynthetic())
|
||||
.map(java.lang.reflect.Field::getType)
|
||||
.toList();
|
||||
|
||||
assertThat(persisted)
|
||||
.doesNotContain(
|
||||
FailureAudience.class,
|
||||
FailureActionId.class,
|
||||
FailureActionId.Execution.class,
|
||||
Ownership.class);
|
||||
// A plain varchar with no CHECK, which is what lets a new kind ship without a migration.
|
||||
assertThat(FileRunEventEntity.class.getDeclaredField("kindId").getType())
|
||||
.isEqualTo(String.class);
|
||||
}
|
||||
|
||||
private static List<String> names(Enum<?>[] values) {
|
||||
return Arrays.stream(values).map(Enum::name).toList();
|
||||
}
|
||||
}
|
||||
+94
-13
@@ -1,6 +1,9 @@
|
||||
package stirling.software.proprietary.failure;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static stirling.software.proprietary.failure.FailureAudience.ANYONE_WHO_SEES;
|
||||
import static stirling.software.proprietary.failure.FailureAudience.OWNER;
|
||||
import static stirling.software.proprietary.failure.FailureAudience.TEAM_REVIEWER;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
@@ -29,6 +32,13 @@ import stirling.software.common.util.ExceptionUtils;
|
||||
*/
|
||||
class FailureKindTest {
|
||||
|
||||
/** In full, so a declaration pairing the right action with the wrong audience cannot pass. */
|
||||
private static FailureKind.OfferedAction offered(
|
||||
FailureActionId id, FailureAudience audience, String labelKeySuffix) {
|
||||
return new FailureKind.OfferedAction(
|
||||
id, "portal.failures.action." + labelKeySuffix, audience);
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("every kind is well formed")
|
||||
class Invariants {
|
||||
@@ -60,6 +70,27 @@ class FailureKindTest {
|
||||
assertThat(kind.getId()).matches("^[A-Z][A-Z0-9_]*$");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(FailureKind.class)
|
||||
void declaresItsActionsInTheSameOrderAsEveryOtherKind(FailureKind kind) {
|
||||
// Declaration order is display order and the first usable offer is the row's primary,
|
||||
// so
|
||||
// two kinds disagreeing would flip the solid button between rows.
|
||||
List<FailureActionId> ranking =
|
||||
List.of(
|
||||
FailureActionId.VIEW_FILE,
|
||||
FailureActionId.VIEW_IN_PROCESSOR,
|
||||
FailureActionId.DISMISS);
|
||||
|
||||
List<FailureActionId> declared = kind.getActions();
|
||||
assertThat(ranking)
|
||||
.as("%s declares an action the shared ranking does not rank", kind.getId())
|
||||
.containsAll(declared);
|
||||
assertThat(declared)
|
||||
.as("%s declares its actions out of the shared order", kind.getId())
|
||||
.isEqualTo(ranking.stream().filter(declared::contains).toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void idsAreUnique() {
|
||||
Set<String> ids = new HashSet<>();
|
||||
@@ -88,6 +119,25 @@ class FailureKindTest {
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(FailureKind.class)
|
||||
void everyOfferSaysWhoItIsFor(FailureKind kind) {
|
||||
// Read per row to decide what a caller is shown, so a null would leak a button.
|
||||
for (FailureKind.OfferedAction offer : kind.getOfferedActions()) {
|
||||
assertThat(offer.audience())
|
||||
.as("%s offers %s", kind.getId(), offer.id())
|
||||
.isNotNull();
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(FailureKind.class)
|
||||
void offersEachActionAtMostOnce(FailureKind kind) {
|
||||
// The same action twice would be two buttons with one meaning, and labelKeyFor would
|
||||
// answer for the first.
|
||||
assertThat(kind.getActions()).doesNotHaveDuplicates();
|
||||
}
|
||||
|
||||
@Test
|
||||
void noTwoKindsClaimTheSameErrorCode() {
|
||||
// Computed independently of duplicateErrorCodes(), then checked against it: the boot
|
||||
@@ -182,10 +232,16 @@ class FailureKindTest {
|
||||
class Unknown {
|
||||
|
||||
@Test
|
||||
void offersOnlyTheActionThatClearsIt() {
|
||||
// Nothing here can be fixed, so "seen it" and "clear it" would be the same decision.
|
||||
// Offering both just asks the reviewer to press two buttons to reach one outcome.
|
||||
assertThat(FailureKind.UNKNOWN.getActions()).containsExactly(FailureActionId.DISMISS);
|
||||
void offersItsOwnerTheirDocumentAndTheRunToWhoeverReviews() {
|
||||
// Nothing here is known to be fixable, so the offers are just the places to look.
|
||||
assertThat(FailureKind.UNKNOWN.getOfferedActions())
|
||||
.containsExactly(
|
||||
offered(FailureActionId.VIEW_FILE, OWNER, "viewFile"),
|
||||
offered(
|
||||
FailureActionId.VIEW_IN_PROCESSOR,
|
||||
TEAM_REVIEWER,
|
||||
"viewInProcessor"),
|
||||
offered(FailureActionId.DISMISS, ANYONE_WHO_SEES, "dismiss"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -238,24 +294,49 @@ class FailureKindTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKindWithSomethingToFixOffersTheFixAndAWayToSkipIt() {
|
||||
assertThat(FailureKind.INPUT_PASSWORD_PROTECTED.getActions())
|
||||
.containsExactly(FailureActionId.ACKNOWLEDGE, FailureActionId.DISMISS);
|
||||
void offersTheDocumentToItsOwnerAndTheRunToItsReviewer() {
|
||||
// The point of the audiences: only the owner holds the document.
|
||||
assertThat(FailureKind.INPUT_PASSWORD_PROTECTED.getOfferedActions())
|
||||
.containsExactly(
|
||||
offered(FailureActionId.VIEW_FILE, OWNER, "viewFile"),
|
||||
offered(
|
||||
FailureActionId.VIEW_IN_PROCESSOR,
|
||||
TEAM_REVIEWER,
|
||||
"viewInProcessor"),
|
||||
offered(FailureActionId.DISMISS, ANYONE_WHO_SEES, "dismiss"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void overriddenLabelWinsOverTheGenericOne() {
|
||||
String label =
|
||||
FailureKind.INPUT_PASSWORD_PROTECTED.labelKeyFor(FailureActionId.DISMISS);
|
||||
assertThat(label).isEqualTo("portal.failures.action.dismissSkipFile");
|
||||
assertThat(label).isNotEqualTo(FailureKind.genericLabelKey(FailureActionId.DISMISS));
|
||||
void noKindOffersAcknowledgeAnyMore() {
|
||||
// Kept in the vocabulary for rows already ACKNOWLEDGED; offered by nothing, so
|
||||
// dispatchable by nothing.
|
||||
for (FailureKind kind : FailureKind.values()) {
|
||||
assertThat(kind.declares(FailureActionId.ACKNOWLEDGE))
|
||||
.as("%s offers ACKNOWLEDGE", kind.getId())
|
||||
.isFalse();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void genericLabelIsUsedWhenAKindDeclaresNoOverride() {
|
||||
void everyKindLabelsItsActionsWithTheSharedWordingToday() {
|
||||
// The per-kind override still exists for wording that reads badly in context.
|
||||
for (FailureKind kind : FailureKind.values()) {
|
||||
for (FailureActionId action : kind.getActions()) {
|
||||
assertThat(kind.labelKeyFor(action))
|
||||
.isEqualTo(FailureKind.genericLabelKey(action));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void genericLabelIsDerivedFromTheActionId() {
|
||||
assertThat(FailureKind.UNKNOWN.labelKeyFor(FailureActionId.DISMISS))
|
||||
.isEqualTo(FailureKind.genericLabelKey(FailureActionId.DISMISS))
|
||||
.isEqualTo("portal.failures.action.dismiss");
|
||||
assertThat(
|
||||
FailureKind.INPUT_PASSWORD_PROTECTED.labelKeyFor(
|
||||
FailureActionId.VIEW_IN_PROCESSOR))
|
||||
.isEqualTo("portal.failures.action.viewInProcessor");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+59
-12
@@ -128,7 +128,9 @@ class FileRunEventControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void carriesActionsAlreadyResolvedForTheRow() {
|
||||
void carriesActionsAlreadyResolvedForTheRowAndItsReader() {
|
||||
// A leader reading a colleague's password failure: the unlock is not theirs to do,
|
||||
// so it is not in the list at all.
|
||||
given(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f1");
|
||||
|
||||
List<FileRunEventView.ActionView> actions =
|
||||
@@ -136,10 +138,32 @@ class FileRunEventControllerTest {
|
||||
|
||||
assertThat(actions)
|
||||
.extracting(FileRunEventView.ActionView::id)
|
||||
.containsExactlyInAnyOrder("ACKNOWLEDGE", "DISMISS");
|
||||
.containsExactly("VIEW_IN_PROCESSOR", "DISMISS");
|
||||
assertThat(actions).allMatch(FileRunEventView.ActionView::enabled);
|
||||
}
|
||||
|
||||
@Test
|
||||
void carriesEnoughForAClientToRenderAndRouteAnActionItDoesNotKnow() {
|
||||
// The English fallback, which side runs it, and where the kind wants it: everything a
|
||||
// build with no copy for a newly shipped action still needs.
|
||||
given(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f1");
|
||||
|
||||
assertThat(controller.list(null, null, null).events().getFirst().actions())
|
||||
.allSatisfy(
|
||||
action -> {
|
||||
assertThat(action.defaultLabel()).isNotBlank();
|
||||
assertThat(action.execution()).isNotNull();
|
||||
})
|
||||
.filteredOn(action -> "VIEW_IN_PROCESSOR".equals(action.id()))
|
||||
.singleElement()
|
||||
.satisfies(
|
||||
action -> {
|
||||
assertThat(action.execution())
|
||||
.isEqualTo(FailureActionId.Execution.CLIENT);
|
||||
assertThat(action.defaultLabel()).isEqualTo("View in processor");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void showsAClosedRowsActionsDisabledWithAReasonRatherThanHidingThem() {
|
||||
// Only visible by asking for the closed status: the default queue drops it.
|
||||
@@ -162,14 +186,18 @@ class FileRunEventControllerTest {
|
||||
void filtersByStatusAndByKind() {
|
||||
FileRunEvent locked = given(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "locked");
|
||||
given(FailureKind.UNKNOWN, TEAM, "open");
|
||||
controller.act(locked.id(), "ACKNOWLEDGE", null);
|
||||
controller.act(locked.id(), "DISMISS", null);
|
||||
|
||||
assertThat(controller.list(FileRunEventStatus.ACKNOWLEDGED, null, null).events())
|
||||
.hasSize(1);
|
||||
assertThat(controller.list(null, "INPUT_PASSWORD_PROTECTED", null).events())
|
||||
assertThat(controller.list(FileRunEventStatus.DISMISSED, null, null).events())
|
||||
.extracting(FileRunEventView::fileId)
|
||||
.containsExactly("locked");
|
||||
// Acknowledged is still open work, so it stays in the default queue.
|
||||
// A dismissed row is decided, so the default queue holds only the other one.
|
||||
assertThat(controller.list(null, null, null).events())
|
||||
.extracting(FileRunEventView::fileId)
|
||||
.containsExactly("open");
|
||||
assertThat(controller.list(null, "INPUT_PASSWORD_PROTECTED", null).events())
|
||||
.extracting(FileRunEventView::fileId)
|
||||
.isEmpty();
|
||||
assertThat(controller.list(null, "NO_SUCH_KIND", null).events()).isEmpty();
|
||||
}
|
||||
|
||||
@@ -211,12 +239,31 @@ class FileRunEventControllerTest {
|
||||
void appliesADeclaredActionAndReturnsTheUpdatedRow() {
|
||||
FileRunEvent event = given(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f1");
|
||||
|
||||
FileRunEventView updated = controller.act(event.id(), "ACKNOWLEDGE", null);
|
||||
FileRunEventView updated = controller.act(event.id(), "DISMISS", null);
|
||||
|
||||
assertThat(updated.status()).isEqualTo(FileRunEventStatus.ACKNOWLEDGED);
|
||||
assertThat(updated.status()).isEqualTo(FileRunEventStatus.DISMISSED);
|
||||
assertThat(updated.statusActor()).isEqualTo("reviewer@example.com");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anActionTheClientRunsIsABadRequest() {
|
||||
// Offered, and still not the server's to perform: the document is in the browser.
|
||||
FileRunEvent event = given(FailureKind.UNKNOWN, TEAM, "f1");
|
||||
|
||||
assertThat(statusOf(() -> controller.act(event.id(), "VIEW_FILE", null)))
|
||||
.isEqualTo(HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anActionNoKindOffersAnyMoreIsABadRequest() {
|
||||
// ACKNOWLEDGE is still in the vocabulary for the rows that carry it, and still not
|
||||
// something any kind offers, so posting it is refused rather than applied.
|
||||
FileRunEvent event = given(FailureKind.UNKNOWN, TEAM, "f1");
|
||||
|
||||
assertThat(statusOf(() -> controller.act(event.id(), "ACKNOWLEDGE", null)))
|
||||
.isEqualTo(HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
@Test
|
||||
void acceptsAnAbsentBodyBecauseTheseActionsNeedNoInput() {
|
||||
FileRunEvent event = given(FailureKind.UNKNOWN, TEAM, "f1");
|
||||
@@ -238,7 +285,7 @@ class FileRunEventControllerTest {
|
||||
// 404 rather than 403, so the response does not confirm the row exists.
|
||||
FileRunEvent theirs = given(FailureKind.UNKNOWN, 99L, "f1");
|
||||
|
||||
assertThat(statusOf(() -> controller.act(theirs.id(), "ACKNOWLEDGE", null)))
|
||||
assertThat(statusOf(() -> controller.act(theirs.id(), "DISMISS", null)))
|
||||
.isEqualTo(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
@@ -248,7 +295,7 @@ class FileRunEventControllerTest {
|
||||
FileRunEvent event = given(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f1");
|
||||
controller.act(event.id(), "DISMISS", null);
|
||||
|
||||
assertThat(statusOf(() -> controller.act(event.id(), "ACKNOWLEDGE", null)))
|
||||
assertThat(statusOf(() -> controller.act(event.id(), "DISMISS", null)))
|
||||
.isEqualTo(HttpStatus.CONFLICT);
|
||||
}
|
||||
}
|
||||
@@ -276,7 +323,7 @@ class FileRunEventControllerTest {
|
||||
|
||||
assertThat(locked.actions())
|
||||
.extracting(FailureKindView.ActionDeclaration::labelKey)
|
||||
.contains("portal.failures.action.dismissSkipFile");
|
||||
.contains("portal.failures.action.viewFile", "portal.failures.action.dismiss");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+36
-20
@@ -120,13 +120,20 @@ class FileRunEventHttpIntegrationTest {
|
||||
// Epoch millis, not an ISO string: the client renders relative times from a number.
|
||||
assertThat(row.get("lastSeenAt").isNumber()).isTrue();
|
||||
|
||||
// Resolved for this reader: a leader looking at a colleague's password failure is
|
||||
// offered the run and a way to close the row, not a password they do not have.
|
||||
JsonNode actions = row.get("actions");
|
||||
assertThat(actions).hasSize(2);
|
||||
assertThat(actions.get(0).get("id").asString()).isEqualTo("ACKNOWLEDGE");
|
||||
assertThat(actions.get(0).get("id").asString()).isEqualTo("VIEW_IN_PROCESSOR");
|
||||
assertThat(actions.get(0).get("labelKey").asString())
|
||||
.isEqualTo("portal.failures.action.acknowledge");
|
||||
.isEqualTo("portal.failures.action.viewInProcessor");
|
||||
assertThat(actions.get(0).get("defaultLabel").asString())
|
||||
.isEqualTo("View in processor");
|
||||
assertThat(actions.get(0).get("execution").asString()).isEqualTo("CLIENT");
|
||||
assertThat(actions.get(0).get("enabled").asBoolean()).isTrue();
|
||||
assertThat(actions.get(0).get("disabledReasonKey").isNull()).isTrue();
|
||||
assertThat(actions.get(1).get("id").asString()).isEqualTo("DISMISS");
|
||||
assertThat(actions.get(1).get("execution").asString()).isEqualTo("SERVER");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -154,16 +161,17 @@ class FileRunEventHttpIntegrationTest {
|
||||
void coercesQueryParametersAndFiltersOnThem() throws Exception {
|
||||
String locked = seed(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "locked", "b");
|
||||
seed(FailureKind.UNKNOWN, TEAM, "open", "a");
|
||||
post("/api/v1/file-run-events/" + locked + "/actions/ACKNOWLEDGE", "{\"inputs\":{}}");
|
||||
post("/api/v1/file-run-events/" + locked + "/actions/DISMISS", "{\"inputs\":{}}");
|
||||
|
||||
JsonNode acknowledged =
|
||||
mapper.readTree(get("/api/v1/file-run-events?status=ACKNOWLEDGED").body())
|
||||
JsonNode dismissed =
|
||||
mapper.readTree(get("/api/v1/file-run-events?status=DISMISSED").body())
|
||||
.get("events");
|
||||
assertThat(acknowledged).hasSize(1);
|
||||
assertThat(dismissed).hasSize(1);
|
||||
|
||||
JsonNode byKind =
|
||||
mapper.readTree(
|
||||
get("/api/v1/file-run-events?kindId=INPUT_PASSWORD_PROTECTED")
|
||||
get("/api/v1/file-run-events?status=DISMISSED"
|
||||
+ "&kindId=INPUT_PASSWORD_PROTECTED")
|
||||
.body())
|
||||
.get("events");
|
||||
assertThat(byKind).hasSize(1);
|
||||
@@ -269,25 +277,23 @@ class FileRunEventHttpIntegrationTest {
|
||||
String id = seed(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f1", "boom");
|
||||
|
||||
HttpResponse<String> response =
|
||||
post(
|
||||
"/api/v1/file-run-events/" + id + "/actions/ACKNOWLEDGE",
|
||||
"{\"inputs\":{}}");
|
||||
post("/api/v1/file-run-events/" + id + "/actions/DISMISS", "{\"inputs\":{}}");
|
||||
|
||||
assertThat(response.statusCode()).isEqualTo(200);
|
||||
JsonNode row = mapper.readTree(response.body());
|
||||
assertThat(row.get("status").asString()).isEqualTo("ACKNOWLEDGED");
|
||||
assertThat(row.get("status").asString()).isEqualTo("DISMISSED");
|
||||
assertThat(row.get("statusActor").asString()).isEqualTo(ACTOR);
|
||||
}
|
||||
|
||||
@Test
|
||||
void acceptsAPopulatedInputsMap() throws Exception {
|
||||
// Nothing consumes inputs yet, but the shape must bind so the first action that needs
|
||||
// one (a password) does not discover a broken contract.
|
||||
// No server action consumes inputs, but the shape must still bind rather than 400, so a
|
||||
// client that posts an empty or stale map is not refused over its body.
|
||||
String id = seed(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f1", "locked");
|
||||
|
||||
HttpResponse<String> response =
|
||||
post(
|
||||
"/api/v1/file-run-events/" + id + "/actions/ACKNOWLEDGE",
|
||||
"/api/v1/file-run-events/" + id + "/actions/DISMISS",
|
||||
"{\"inputs\":{\"password\":\"hunter2\"}}");
|
||||
|
||||
assertThat(response.statusCode()).isEqualTo(200);
|
||||
@@ -315,15 +321,27 @@ class FileRunEventHttpIntegrationTest {
|
||||
.isEqualTo(400);
|
||||
}
|
||||
|
||||
@Test
|
||||
void mapsAnActionTheClientRunsToBadRequest() throws Exception {
|
||||
// Declared by the kind, refused here: over the wire, so a client that posts a retry
|
||||
// gets a refusal rather than a 200 implying the server did something.
|
||||
String id = seed(FailureKind.UNKNOWN, TEAM, "f1", "boom");
|
||||
|
||||
assertThat(
|
||||
post(
|
||||
"/api/v1/file-run-events/" + id + "/actions/VIEW_FILE",
|
||||
"{\"inputs\":{}}")
|
||||
.statusCode())
|
||||
.isEqualTo(400);
|
||||
}
|
||||
|
||||
@Test
|
||||
void mapsAnotherTeamsRowToNotFound() throws Exception {
|
||||
String id = seed(FailureKind.UNKNOWN, 999L, "theirs", "boom");
|
||||
|
||||
assertThat(
|
||||
post(
|
||||
"/api/v1/file-run-events/"
|
||||
+ id
|
||||
+ "/actions/ACKNOWLEDGE",
|
||||
"/api/v1/file-run-events/" + id + "/actions/DISMISS",
|
||||
"{\"inputs\":{}}")
|
||||
.statusCode())
|
||||
.isEqualTo(404);
|
||||
@@ -336,9 +354,7 @@ class FileRunEventHttpIntegrationTest {
|
||||
|
||||
assertThat(
|
||||
post(
|
||||
"/api/v1/file-run-events/"
|
||||
+ id
|
||||
+ "/actions/ACKNOWLEDGE",
|
||||
"/api/v1/file-run-events/" + id + "/actions/DISMISS",
|
||||
"{\"inputs\":{}}")
|
||||
.statusCode())
|
||||
.isEqualTo(409);
|
||||
|
||||
+289
-35
@@ -1,6 +1,7 @@
|
||||
package stirling.software.proprietary.failure;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -60,14 +61,20 @@ class FileRunEventServiceTest {
|
||||
}
|
||||
|
||||
private FileRunEvent given(FailureKind kind, Long teamId, String fileId) {
|
||||
return givenHitBy("author@example.com", kind, teamId, fileId);
|
||||
}
|
||||
|
||||
/** As {@link #given} but naming who the incident belongs to, which decides its ownership. */
|
||||
private FileRunEvent givenHitBy(String actor, FailureKind kind, Long teamId, String fileId) {
|
||||
return store.record(
|
||||
new RecordFailure(
|
||||
kind,
|
||||
FailureOrigin.POLICY,
|
||||
teamId,
|
||||
"author@example.com",
|
||||
actor,
|
||||
"policy-1",
|
||||
"run-1",
|
||||
// Distinct per file, so a RUN-scoped kind does not fold two rows into one.
|
||||
"run-" + fileId,
|
||||
null,
|
||||
fileId,
|
||||
"detail"));
|
||||
@@ -77,11 +84,28 @@ class FileRunEventServiceTest {
|
||||
@DisplayName("acknowledge")
|
||||
class Acknowledge {
|
||||
|
||||
/**
|
||||
* No kind offers it, so it cannot be dispatched; exercised directly for rows that have it.
|
||||
*/
|
||||
private FileRunEvent acknowledge(FileRunEvent event, String actor) {
|
||||
return new AcknowledgeAction(store).execute(event, Map.of(), actor);
|
||||
}
|
||||
|
||||
@Test
|
||||
void isNoLongerOfferedSoItCannotBeDispatched() {
|
||||
FileRunEvent event = given(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f1");
|
||||
|
||||
assertThatThrownBy(() -> service.dispatch(event.id(), "ACKNOWLEDGE", Map.of()))
|
||||
.isInstanceOf(FailureActionException.class)
|
||||
.extracting(e -> ((FailureActionException) e).getReason())
|
||||
.isEqualTo(FailureActionException.Reason.ACTION_NOT_DECLARED);
|
||||
}
|
||||
|
||||
@Test
|
||||
void movesANewEventToAcknowledgedAndStampsTheActor() {
|
||||
FileRunEvent event = given(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f1");
|
||||
|
||||
FileRunEvent updated = service.dispatch(event.id(), "ACKNOWLEDGE", Map.of());
|
||||
FileRunEvent updated = acknowledge(event, ACTOR);
|
||||
|
||||
assertThat(updated.status()).isEqualTo(FileRunEventStatus.ACKNOWLEDGED);
|
||||
assertThat(updated.statusActor()).isEqualTo(ACTOR);
|
||||
@@ -91,16 +115,24 @@ class FileRunEventServiceTest {
|
||||
@Test
|
||||
void isANoOpWhenAlreadyAcknowledgedSoOwnershipIsNotStolen() {
|
||||
FileRunEvent event = given(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f1");
|
||||
FileRunEvent first = service.dispatch(event.id(), "ACKNOWLEDGE", Map.of());
|
||||
Instant originalAt = first.statusAt();
|
||||
Instant originalAt = acknowledge(event, ACTOR).statusAt();
|
||||
|
||||
when(userService.getCurrentUsername()).thenReturn("someone-else@example.com");
|
||||
FileRunEvent second = service.dispatch(event.id(), "ACKNOWLEDGE", Map.of());
|
||||
FileRunEvent second = acknowledge(event, "someone-else@example.com");
|
||||
|
||||
assertThat(second.status()).isEqualTo(FileRunEventStatus.ACKNOWLEDGED);
|
||||
assertThat(second.statusActor()).isEqualTo(ACTOR);
|
||||
assertThat(second.statusAt()).isEqualTo(originalAt);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAlreadyAcknowledgedRowStaysReadableAndClosable() {
|
||||
FileRunEvent event = given(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f1");
|
||||
acknowledge(event, ACTOR);
|
||||
|
||||
assertThat(service.list(FileRunEventStatus.ACKNOWLEDGED, null, 10)).hasSize(1);
|
||||
assertThat(service.dispatch(event.id(), "DISMISS", Map.of()).status())
|
||||
.isEqualTo(FileRunEventStatus.DISMISSED);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@@ -118,7 +150,7 @@ class FileRunEventServiceTest {
|
||||
@Test
|
||||
void closesAnAcknowledgedEvent() {
|
||||
FileRunEvent event = given(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f1");
|
||||
service.dispatch(event.id(), "ACKNOWLEDGE", Map.of());
|
||||
new AcknowledgeAction(store).execute(event, Map.of(), ACTOR);
|
||||
|
||||
assertThat(service.dispatch(event.id(), "DISMISS", Map.of()).status())
|
||||
.isEqualTo(FileRunEventStatus.DISMISSED);
|
||||
@@ -180,7 +212,7 @@ class FileRunEventServiceTest {
|
||||
void anotherTeamsEventIsNotFound() {
|
||||
FileRunEvent theirs = given(FailureKind.UNKNOWN, 99L, "f1");
|
||||
|
||||
assertThatThrownBy(() -> service.dispatch(theirs.id(), "ACKNOWLEDGE", Map.of()))
|
||||
assertThatThrownBy(() -> service.dispatch(theirs.id(), "DISMISS", Map.of()))
|
||||
.isInstanceOf(FailureActionException.class)
|
||||
.extracting(e -> ((FailureActionException) e).getReason())
|
||||
.isEqualTo(FailureActionException.Reason.EVENT_NOT_FOUND);
|
||||
@@ -188,12 +220,44 @@ class FileRunEventServiceTest {
|
||||
|
||||
@Test
|
||||
void anUnknownEventIdIsNotFound() {
|
||||
assertThatThrownBy(() -> service.dispatch("nope", "ACKNOWLEDGE", Map.of()))
|
||||
assertThatThrownBy(() -> service.dispatch("nope", "DISMISS", Map.of()))
|
||||
.isInstanceOf(FailureActionException.class)
|
||||
.extracting(e -> ((FailureActionException) e).getReason())
|
||||
.isEqualTo(FailureActionException.Reason.EVENT_NOT_FOUND);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anActionTheClientRunsIsRefusedRatherThanPretendedTo() {
|
||||
// Answering 200 would tell the client something happened when nothing did.
|
||||
FileRunEvent event = given(FailureKind.UNKNOWN, TEAM, "f1");
|
||||
|
||||
assertThatThrownBy(() -> service.dispatch(event.id(), "VIEW_FILE", Map.of()))
|
||||
.isInstanceOf(FailureActionException.class)
|
||||
.extracting(e -> ((FailureActionException) e).getReason())
|
||||
.isEqualTo(FailureActionException.Reason.ACTION_NOT_DISPATCHABLE);
|
||||
|
||||
assertThat(store.find(event.id(), TEAM).orElseThrow().status())
|
||||
.isEqualTo(FileRunEventStatus.NEW);
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyClientActionIsRefusedWhicheverKindDeclaresIt() {
|
||||
// Over the whole vocabulary, so a client action added later cannot arrive dispatchable.
|
||||
for (FailureKind kind : FailureKind.values()) {
|
||||
FileRunEvent event = given(kind, TEAM, "f-" + kind.getId());
|
||||
for (FailureActionId action : kind.getActions()) {
|
||||
if (action.runsOnServer()) {
|
||||
continue;
|
||||
}
|
||||
assertThatThrownBy(() -> service.dispatch(event.id(), action.name(), Map.of()))
|
||||
.as("%s offers %s", kind.getId(), action)
|
||||
.isInstanceOf(FailureActionException.class)
|
||||
.extracting(e -> ((FailureActionException) e).getReason())
|
||||
.isEqualTo(FailureActionException.Reason.ACTION_NOT_DISPATCHABLE);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnknownActionIdIsRejected() {
|
||||
FileRunEvent event = given(FailureKind.UNKNOWN, TEAM, "f1");
|
||||
@@ -231,11 +295,6 @@ class FileRunEventServiceTest {
|
||||
FileRunEvent event = given(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f1");
|
||||
service.dispatch(event.id(), "DISMISS", Map.of());
|
||||
|
||||
assertThatThrownBy(() -> service.dispatch(event.id(), "ACKNOWLEDGE", Map.of()))
|
||||
.isInstanceOf(FailureActionException.class)
|
||||
.extracting(e -> ((FailureActionException) e).getReason())
|
||||
.isEqualTo(FailureActionException.Reason.ALREADY_CLOSED);
|
||||
|
||||
assertThatThrownBy(() -> service.dispatch(event.id(), "DISMISS", Map.of()))
|
||||
.isInstanceOf(FailureActionException.class)
|
||||
.extracting(e -> ((FailureActionException) e).getReason())
|
||||
@@ -244,18 +303,184 @@ class FileRunEventServiceTest {
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("available actions are resolved per row")
|
||||
class Availability {
|
||||
@DisplayName("ownership is derived against whoever is reading")
|
||||
class OwnershipDerivation {
|
||||
|
||||
@Test
|
||||
void openRowOffersEveryDeclaredActionEnabled() {
|
||||
FileRunEvent event = given(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f1");
|
||||
void theCallersOwnFailureIsMine() {
|
||||
FileRunEvent mine = givenHitBy(ACTOR, FailureKind.UNKNOWN, TEAM, "f1");
|
||||
|
||||
List<FileRunEventService.AvailableAction> actions = service.availableActions(event);
|
||||
assertThat(service.ownershipOf(mine)).isEqualTo(Ownership.MINE);
|
||||
}
|
||||
|
||||
assertThat(actions).hasSize(2);
|
||||
assertThat(actions).allMatch(FileRunEventService.AvailableAction::enabled);
|
||||
assertThat(actions).allMatch(action -> action.disabledReasonKey() == null);
|
||||
@Test
|
||||
void aColleaguesIsTheirs() {
|
||||
FileRunEvent theirs =
|
||||
givenHitBy("colleague@example.com", FailureKind.UNKNOWN, TEAM, "f1");
|
||||
|
||||
assertThat(service.ownershipOf(theirs)).isEqualTo(Ownership.THEIRS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnattendedRunsIsNobodys() {
|
||||
// A trigger-fired run has no user to name, so there is nobody to hand the fix to.
|
||||
FileRunEvent unattended = givenHitBy(null, FailureKind.UNKNOWN, TEAM, "f1");
|
||||
|
||||
assertThat(service.ownershipOf(unattended)).isEqualTo(Ownership.UNOWNED);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSameRowIsMineToOnePersonAndTheirsToAnother() {
|
||||
// Why it is derived: a stored answer would be wrong for everyone but one person.
|
||||
FileRunEvent event = givenHitBy(ACTOR, FailureKind.UNKNOWN, TEAM, "f1");
|
||||
assertThat(service.ownershipOf(event)).isEqualTo(Ownership.MINE);
|
||||
|
||||
when(userService.getCurrentUsername()).thenReturn("colleague@example.com");
|
||||
|
||||
assertThat(service.ownershipOf(event)).isEqualTo(Ownership.THEIRS);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("available actions are resolved per row and per reader")
|
||||
class Availability {
|
||||
|
||||
private List<FailureActionId> offeredFor(FileRunEvent event) {
|
||||
return service.availableActions(event).stream()
|
||||
.map(FileRunEventService.AvailableAction::id)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Test
|
||||
void theOwnerIsOfferedTheirDocumentAndNotTheReviewersView() {
|
||||
// The document is theirs to open; the processor view is for whoever reviews the team.
|
||||
when(authority.canEditPolicies()).thenReturn(false);
|
||||
FileRunEvent mine = givenHitBy(ACTOR, FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f1");
|
||||
|
||||
assertThat(offeredFor(mine))
|
||||
.containsExactly(FailureActionId.VIEW_FILE, FailureActionId.DISMISS);
|
||||
assertThat(service.availableActions(mine))
|
||||
.allMatch(FileRunEventService.AvailableAction::enabled);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aReviewerReadingAColleaguesIsNotOfferedTheDocumentTheyDoNotHave() {
|
||||
// Dropped, not disabled: greyed out would read as their permission problem.
|
||||
FileRunEvent theirs =
|
||||
givenHitBy(
|
||||
"colleague@example.com",
|
||||
FailureKind.INPUT_PASSWORD_PROTECTED,
|
||||
TEAM,
|
||||
"f1");
|
||||
|
||||
assertThat(offeredFor(theirs))
|
||||
.containsExactly(FailureActionId.VIEW_IN_PROCESSOR, FailureActionId.DISMISS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aReviewerInheritsTheOwnerActionsOnAnUnattendedRow() {
|
||||
// Nobody owns it, so without the inheritance the row could only ever be dismissed.
|
||||
FileRunEvent unattended =
|
||||
givenHitBy(null, FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f1");
|
||||
|
||||
assertThat(offeredFor(unattended))
|
||||
.containsExactly(
|
||||
FailureActionId.VIEW_FILE,
|
||||
FailureActionId.VIEW_IN_PROCESSOR,
|
||||
FailureActionId.DISMISS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void inheritedOwnerActionsComeBackDisabledWithTheReasonWhy() {
|
||||
// No browser holds a source-fed file, so it is stated rather than offered as a dead
|
||||
// button.
|
||||
FileRunEvent unattended =
|
||||
givenHitBy(null, FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f1");
|
||||
|
||||
assertThat(service.availableActions(unattended))
|
||||
.filteredOn(action -> action.id() != FailureActionId.DISMISS)
|
||||
.filteredOn(action -> action.id() != FailureActionId.VIEW_IN_PROCESSOR)
|
||||
.isNotEmpty()
|
||||
.allSatisfy(
|
||||
action -> {
|
||||
assertThat(action.enabled()).isFalse();
|
||||
assertThat(action.disabledReasonKey())
|
||||
.isEqualTo("portal.failures.disabled.unattended");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void theReviewersOwnActionsStayUsableOnAnUnattendedRow() {
|
||||
FileRunEvent unattended =
|
||||
givenHitBy(null, FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f1");
|
||||
|
||||
assertThat(service.availableActions(unattended))
|
||||
.filteredOn(
|
||||
action ->
|
||||
action.id() == FailureActionId.DISMISS
|
||||
|| action.id() == FailureActionId.VIEW_IN_PROCESSOR)
|
||||
.hasSize(2)
|
||||
.allMatch(FileRunEventService.AvailableAction::enabled);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theOwnersActionsAreDisabledWhenTheRowNamesNoDocument() {
|
||||
// Answered here, or the client calls it "not on this device" while it sits in their
|
||||
// own workbench.
|
||||
FileRunEvent documentless =
|
||||
givenHitBy(ACTOR, FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, null);
|
||||
|
||||
assertThat(service.ownershipOf(documentless)).isEqualTo(Ownership.MINE);
|
||||
assertThat(service.availableActions(documentless))
|
||||
.filteredOn(action -> action.id() != FailureActionId.DISMISS)
|
||||
.filteredOn(action -> action.id() != FailureActionId.VIEW_IN_PROCESSOR)
|
||||
.isNotEmpty()
|
||||
.allSatisfy(
|
||||
action -> {
|
||||
assertThat(action.enabled()).isFalse();
|
||||
assertThat(action.disabledReasonKey())
|
||||
.isEqualTo("portal.failures.disabled.noDocument");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRowThatNamesADocumentKeepsItsOwnerActionsUsable() {
|
||||
FileRunEvent withDocument =
|
||||
givenHitBy(ACTOR, FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f1");
|
||||
|
||||
assertThat(service.availableActions(withDocument))
|
||||
.isNotEmpty()
|
||||
.allMatch(FileRunEventService.AvailableAction::enabled);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMemberIsNotOfferedTheOwnerActionsOnAnUnattendedRow() {
|
||||
// The inheritance is the reviewer's: a member has no claim on a run nobody attended.
|
||||
when(authority.canEditPolicies()).thenReturn(false);
|
||||
FileRunEvent unattended =
|
||||
givenHitBy(null, FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f1");
|
||||
|
||||
assertThat(offeredFor(unattended)).containsExactly(FailureActionId.DISMISS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLoginDisabledOperatorKeepsTheirOwnActions() {
|
||||
// Unowned for want of users, not because nothing attended: the one operator holds the
|
||||
// file.
|
||||
ApplicationProperties props = new ApplicationProperties();
|
||||
props.getSecurity().setEnableLogin(false);
|
||||
FileRunEventService unsecured =
|
||||
new FileRunEventService(
|
||||
store,
|
||||
new FailureActionRegistry(List.of(new DismissAction(store))),
|
||||
authority,
|
||||
userService,
|
||||
props);
|
||||
FileRunEvent event = givenHitBy(null, FailureKind.INPUT_PASSWORD_PROTECTED, null, "f1");
|
||||
|
||||
assertThat(unsecured.availableActions(event))
|
||||
.extracting(FileRunEventService.AvailableAction::enabled)
|
||||
.containsOnly(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -275,21 +500,14 @@ class FileRunEventServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void carriesTheKindsOverriddenLabelWhereItHasOne() {
|
||||
FileRunEvent event = given(FailureKind.INPUT_PASSWORD_PROTECTED, TEAM, "f1");
|
||||
|
||||
assertThat(service.availableActions(event))
|
||||
.extracting(FileRunEventService.AvailableAction::labelKey)
|
||||
.contains("portal.failures.action.dismissSkipFile");
|
||||
}
|
||||
|
||||
@Test
|
||||
void fallsBackToTheGenericLabelWhereTheKindDeclaresNoOverride() {
|
||||
void carriesTheLabelKeyForEachOffer() {
|
||||
FileRunEvent event = given(FailureKind.UNKNOWN, TEAM, "f1");
|
||||
|
||||
assertThat(service.availableActions(event))
|
||||
.extracting(FileRunEventService.AvailableAction::labelKey)
|
||||
.containsExactly("portal.failures.action.dismiss");
|
||||
.containsExactly(
|
||||
"portal.failures.action.viewInProcessor",
|
||||
"portal.failures.action.dismiss");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -450,7 +668,43 @@ class FileRunEventServiceTest {
|
||||
complete.verifyEveryDeclaredActionHasAHandler();
|
||||
|
||||
for (FailureActionId id : FailureActionId.values()) {
|
||||
assertThat(complete.find(id)).isPresent();
|
||||
// Only server actions need a handler, which is why the boot check ignores the rest.
|
||||
assertThat(complete.find(id).isPresent()).isEqualTo(id.runsOnServer());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void doesNotAskForAHandlerForAnActionTheClientRuns() {
|
||||
// Otherwise every client action would need an empty handler beside it.
|
||||
FailureActionRegistry serverOnly =
|
||||
new FailureActionRegistry(
|
||||
List.of(new AcknowledgeAction(store), new DismissAction(store)));
|
||||
|
||||
assertThatCode(serverOnly::verifyEveryDeclaredActionHasAHandler)
|
||||
.doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesAHandlerForAnActionTheClientRuns() {
|
||||
// Dispatch refuses the id before resolving a handler, so the bean reads as live and is
|
||||
// not.
|
||||
assertThatThrownBy(() -> new FailureActionRegistry(List.of(new ClientSideAction())))
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("VIEW_FILE");
|
||||
}
|
||||
|
||||
/** A handler for a client action, which is exactly what must not be registered. */
|
||||
private static final class ClientSideAction implements FailureAction {
|
||||
|
||||
@Override
|
||||
public FailureActionId id() {
|
||||
return FailureActionId.VIEW_FILE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileRunEvent execute(
|
||||
FileRunEvent event, Map<String, String> inputs, String actor) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+33
-5
@@ -233,7 +233,7 @@ class FileRunEventStoreDbTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("closing deleted files touches only that owner's own open editor rows")
|
||||
@DisplayName("deleting a document closes every incident about it that the deleter caused")
|
||||
void markFilesRemovedIsScopedBySqlNotByTheCaller() {
|
||||
// The scoping is entirely in the JPQL, so the in-memory fake proves nothing about it:
|
||||
// it implements the same rules by hand and would agree with a wrong query.
|
||||
@@ -241,6 +241,10 @@ class FileRunEventStoreDbTest {
|
||||
store.record(
|
||||
RecordFailure.forEditor(
|
||||
FailureKind.UNKNOWN, TEAM, "owner@example.com", "f-1", "boom"));
|
||||
// Recorded by the processor, about the document they just deleted. Keying on origin left
|
||||
// these in the queue.
|
||||
FileRunEvent myPolicyRun =
|
||||
store.record(failure(FailureKind.UNKNOWN, TEAM, "owner@example.com", "f-1"));
|
||||
FileRunEvent theirs =
|
||||
store.record(
|
||||
RecordFailure.forEditor(
|
||||
@@ -253,21 +257,45 @@ class FileRunEventStoreDbTest {
|
||||
"owner@example.com",
|
||||
"f-1",
|
||||
"boom"));
|
||||
FileRunEvent fromProcessor = store.record(failure(FailureKind.UNKNOWN, TEAM, "f-1"));
|
||||
|
||||
int closed = store.markFilesRemoved(TEAM, "owner@example.com", List.of("f-1"));
|
||||
|
||||
assertThat(closed).isEqualTo(1);
|
||||
assertThat(closed).isEqualTo(2);
|
||||
assertThat(store.find(mine.id(), TEAM).orElseThrow().status())
|
||||
.isEqualTo(FileRunEventStatus.FILE_REMOVED);
|
||||
assertThat(store.find(myPolicyRun.id(), TEAM).orElseThrow().status())
|
||||
.as("their upload, their document, now deleted")
|
||||
.isEqualTo(FileRunEventStatus.FILE_REMOVED);
|
||||
assertThat(store.find(theirs.id(), TEAM).orElseThrow().status())
|
||||
.as("another person's incident about their own file")
|
||||
.isEqualTo(FileRunEventStatus.NEW);
|
||||
assertThat(store.find(otherTeam.id(), OTHER_TEAM).orElseThrow().status())
|
||||
.as("another team entirely")
|
||||
.isEqualTo(FileRunEventStatus.NEW);
|
||||
assertThat(store.find(fromProcessor.id(), TEAM).orElseThrow().status())
|
||||
.as("nothing was deleted from an editor here")
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("a source-fed incident survives a client naming its file id")
|
||||
void markFilesRemovedLeavesSourceFedRowsAlone() {
|
||||
// With login disabled the actor is null on both sides, so the absence of a source is all
|
||||
// that stands between a local delete and a sweep's incidents.
|
||||
FileRunEvent sweep =
|
||||
store.record(
|
||||
new RecordFailure(
|
||||
FailureKind.UNKNOWN,
|
||||
FailureOrigin.POLICY,
|
||||
null,
|
||||
null,
|
||||
"policy-1",
|
||||
"run-1",
|
||||
"src-watched-folder",
|
||||
"collides-with-a-client-id",
|
||||
"detail"));
|
||||
|
||||
int closed = store.markFilesRemoved(null, null, List.of("collides-with-a-client-id"));
|
||||
|
||||
assertThat(closed).isZero();
|
||||
assertThat(store.find(sweep.id(), null).orElseThrow().status())
|
||||
.isEqualTo(FileRunEventStatus.NEW);
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -134,7 +134,8 @@ class InMemoryFileRunEventRepository implements FileRunEventRepository {
|
||||
Collection<FileRunEventStatus> allowedFrom) {
|
||||
int closed = 0;
|
||||
for (FileRunEventEntity entity : rows.values()) {
|
||||
if (entity.getOrigin() != FailureOrigin.TOOL
|
||||
// Mirrors the real query: scoped by the absence of a source, not by origin.
|
||||
if (entity.getSourceId() != null
|
||||
|| !sameTeam(entity, teamId)
|
||||
|| !Objects.equals(entity.getActor(), actor)
|
||||
|| entity.getFileId() == null
|
||||
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
package stirling.software.proprietary.failure;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.common.service.UserServiceInterface;
|
||||
import stirling.software.proprietary.notification.NotificationController;
|
||||
import stirling.software.proprietary.notification.NotificationService;
|
||||
import stirling.software.proprietary.notification.NotificationSource;
|
||||
import stirling.software.proprietary.notification.NotificationView;
|
||||
import stirling.software.proprietary.policy.config.PolicyManagementAuthority;
|
||||
|
||||
/**
|
||||
* What the bell is given to render: never a raw event id, and only the actions the client itself
|
||||
* runs, resolved for this reader by the same service that scopes the queue.
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class NotificationProjectionTest {
|
||||
|
||||
private static final Long TEAM = 7L;
|
||||
private static final String ACTOR = "reviewer@example.com";
|
||||
|
||||
@Mock private PolicyManagementAuthority authority;
|
||||
@Mock private UserServiceInterface userService;
|
||||
|
||||
private FileRunEventStore store;
|
||||
private FileRunEventService failures;
|
||||
private NotificationController controller;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
ApplicationProperties props = new ApplicationProperties();
|
||||
props.getSecurity().setEnableLogin(true);
|
||||
store = new FileRunEventStore(new InMemoryFileRunEventRepository());
|
||||
failures =
|
||||
new FileRunEventService(
|
||||
store,
|
||||
new FailureActionRegistry(
|
||||
List.of(new AcknowledgeAction(store), new DismissAction(store))),
|
||||
authority,
|
||||
userService,
|
||||
props);
|
||||
controller = new NotificationController(new NotificationService(failures));
|
||||
|
||||
lenient().when(authority.currentUserTeamId()).thenReturn(TEAM);
|
||||
lenient().when(authority.canEditPolicies()).thenReturn(true);
|
||||
lenient().when(userService.getCurrentUsername()).thenReturn(ACTOR);
|
||||
}
|
||||
|
||||
private FileRunEvent given(FailureKind kind, String actor, String fileId) {
|
||||
return store.record(RecordFailure.forEditor(kind, TEAM, actor, fileId, "boom"));
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("the bell holds a prefixed id and nothing else")
|
||||
class Ids {
|
||||
|
||||
@Test
|
||||
void everyNotificationIsKeyedByItsSourceAndRowId() {
|
||||
FileRunEvent event = given(FailureKind.UNKNOWN, ACTOR, "f-1");
|
||||
|
||||
NotificationView notification = controller.list(null).notifications().getFirst();
|
||||
|
||||
assertThat(notification.id()).isEqualTo("failure:" + event.id());
|
||||
assertThat(notification.source()).isEqualTo(NotificationSource.FAILURE);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("what the bell is given to render")
|
||||
class Projection {
|
||||
|
||||
@Test
|
||||
void carriesTheKindOriginOwnershipAndTheQueuesClientActions() {
|
||||
FileRunEvent mine = given(FailureKind.INPUT_PASSWORD_PROTECTED, ACTOR, "f-1");
|
||||
|
||||
NotificationView notification = controller.list(null).notifications().getFirst();
|
||||
|
||||
assertThat(notification.kindId()).isEqualTo("INPUT_PASSWORD_PROTECTED");
|
||||
assertThat(notification.origin()).isEqualTo(FailureOrigin.TOOL);
|
||||
assertThat(notification.ownership()).isEqualTo(Ownership.MINE);
|
||||
assertThat(notification.severity()).isEqualTo(FailureSeverity.ERROR);
|
||||
assertThat(notification.status()).isEqualTo(FileRunEventStatus.NEW);
|
||||
assertThat(notification.fileId()).isEqualTo("f-1");
|
||||
assertThat(notification.policyId()).isNull();
|
||||
// How the client knows the fileId above is one of its own and worth looking up.
|
||||
assertThat(notification.sourceId()).isNull();
|
||||
assertThat(notification.defaultTitle()).isNotBlank();
|
||||
// The queue's own offers minus the server's: a bell offering different ones would lie.
|
||||
assertThat(notification.actions())
|
||||
.containsExactlyElementsOf(
|
||||
FileRunEventView.of(mine, failures.availableActions(mine))
|
||||
.actions()
|
||||
.stream()
|
||||
.filter(
|
||||
action ->
|
||||
action.execution()
|
||||
== FailureActionId.Execution.CLIENT)
|
||||
.toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void offersNoActionTheServerRunsBecauseDispositionsBelongToTheQueue() {
|
||||
// Deciding a failure's fate belongs to the review surface, not the panel.
|
||||
given(FailureKind.INPUT_PASSWORD_PROTECTED, ACTOR, "f-1");
|
||||
|
||||
assertThat(controller.list(null).notifications().getFirst().actions())
|
||||
.isNotEmpty()
|
||||
.allMatch(action -> action.execution() == FailureActionId.Execution.CLIENT);
|
||||
}
|
||||
|
||||
@Test
|
||||
void namesTheSourceThatFedAnUnattendedRunSoItsFileIdIsNotMistakenForAClientsOwn() {
|
||||
// Without the source a client looks up a hash it can never resolve and calls it
|
||||
// missing.
|
||||
store.record(
|
||||
RecordFailure.forRun(
|
||||
FailureKind.INPUT_PASSWORD_PROTECTED,
|
||||
TEAM,
|
||||
null,
|
||||
"policy-1",
|
||||
"run-1",
|
||||
"source-7",
|
||||
"hashed-identity",
|
||||
"boom"));
|
||||
|
||||
NotificationView notification = controller.list(null).notifications().getFirst();
|
||||
|
||||
assertThat(notification.sourceId()).isEqualTo("source-7");
|
||||
assertThat(notification.fileId()).isEqualTo("hashed-identity");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aColleaguesNotificationOffersTheReviewersActionsOnly() {
|
||||
// A leader sees the team's failures, so audience filtering has to reach the bell too.
|
||||
given(FailureKind.INPUT_PASSWORD_PROTECTED, "colleague@example.com", "f-1");
|
||||
|
||||
assertThat(controller.list(null).notifications().getFirst().actions())
|
||||
.extracting(FileRunEventView.ActionView::id)
|
||||
.containsExactly("VIEW_IN_PROCESSOR");
|
||||
}
|
||||
|
||||
@Test
|
||||
void carriesWhatAClientNeedsToRenderAnActionItDoesNotKnow() {
|
||||
given(FailureKind.INPUT_PASSWORD_PROTECTED, ACTOR, "f-1");
|
||||
|
||||
assertThat(controller.list(null).notifications().getFirst().actions())
|
||||
.isNotEmpty()
|
||||
.allSatisfy(
|
||||
action -> {
|
||||
assertThat(action.labelKey()).startsWith("portal.failures.action.");
|
||||
assertThat(action.defaultLabel()).isNotBlank();
|
||||
assertThat(action.execution()).isNotNull();
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
+272
@@ -0,0 +1,272 @@
|
||||
package stirling.software.proprietary.failure;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.core.io.ByteArrayResource;
|
||||
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.common.service.FileStorage;
|
||||
import stirling.software.common.service.InternalApiClient;
|
||||
import stirling.software.common.service.JobOwnershipService;
|
||||
import stirling.software.common.service.JobQueue;
|
||||
import stirling.software.common.service.ResourceMonitor;
|
||||
import stirling.software.common.service.TaskManager;
|
||||
import stirling.software.common.service.ToolMetadataService;
|
||||
import stirling.software.common.service.UserServiceInterface;
|
||||
import stirling.software.common.util.TempFileManager;
|
||||
import stirling.software.common.util.TempFileRegistry;
|
||||
import stirling.software.proprietary.policy.asset.InProcessPolicyAssetStore;
|
||||
import stirling.software.proprietary.policy.asset.PolicyAssetResolver;
|
||||
import stirling.software.proprietary.policy.config.PolicyManagementAuthority;
|
||||
import stirling.software.proprietary.policy.engine.PolicyEngine;
|
||||
import stirling.software.proprietary.policy.engine.PolicyExecutor;
|
||||
import stirling.software.proprietary.policy.engine.PolicyRunRegistry;
|
||||
import stirling.software.proprietary.policy.model.OutputSpec;
|
||||
import stirling.software.proprietary.policy.model.PipelineStep;
|
||||
import stirling.software.proprietary.policy.model.Policy;
|
||||
import stirling.software.proprietary.policy.model.PolicyInputs;
|
||||
import stirling.software.proprietary.policy.output.InlineOutputSink;
|
||||
import stirling.software.proprietary.policy.output.PolicyOutputResolver;
|
||||
import stirling.software.proprietary.policy.progress.PolicyProgressListener;
|
||||
import stirling.software.proprietary.policy.source.InProcessSourceStore;
|
||||
import stirling.software.proprietary.policy.store.PolicyStore;
|
||||
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/**
|
||||
* What a reader is offered on a real recorded row, every collaborator being the real one. Both
|
||||
* directions are asserted: offered to the wrong reader is either a dead button or a leaked
|
||||
* document.
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class PolicyFailureOwnershipTest {
|
||||
|
||||
private static final String ROTATE = "/api/v1/general/rotate-pdf";
|
||||
private static final Long TEAM = 3L;
|
||||
|
||||
@Mock private InternalApiClient internalApiClient;
|
||||
@Mock private ToolMetadataService toolMetadataService;
|
||||
@Mock private TaskManager taskManager;
|
||||
@Mock private FileStorage fileStorage;
|
||||
@Mock private JobOwnershipService jobOwnershipService;
|
||||
@Mock private ResourceMonitor resourceMonitor;
|
||||
@Mock private JobQueue jobQueue;
|
||||
@Mock private PolicyStore policyStore;
|
||||
@Mock private PolicyManagementAuthority authority;
|
||||
@Mock private UserServiceInterface userService;
|
||||
|
||||
@TempDir Path tempDir;
|
||||
|
||||
private PolicyEngine engine;
|
||||
private FileRunEventService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
ApplicationProperties props = new ApplicationProperties();
|
||||
props.getSecurity().setEnableLogin(true);
|
||||
props.getSystem().getTempFileManagement().setBaseTmpDir(tempDir.toString());
|
||||
props.getSystem().getTempFileManagement().setPrefix("failure-ownership-test-");
|
||||
|
||||
FileRunEventStore store = new FileRunEventStore(new InMemoryFileRunEventRepository());
|
||||
service =
|
||||
new FileRunEventService(
|
||||
store,
|
||||
new FailureActionRegistry(
|
||||
List.of(new AcknowledgeAction(store), new DismissAction(store))),
|
||||
authority,
|
||||
userService,
|
||||
props);
|
||||
|
||||
PolicyFailureRecorder recorder =
|
||||
new PolicyFailureRecorder(
|
||||
new FailureClassifier(JsonMapper.builder().build()), store, policyStore);
|
||||
PolicyExecutor executor =
|
||||
new PolicyExecutor(
|
||||
internalApiClient,
|
||||
toolMetadataService,
|
||||
new TempFileManager(new TempFileRegistry(), props),
|
||||
JsonMapper.builder().build());
|
||||
engine =
|
||||
new PolicyEngine(
|
||||
executor,
|
||||
taskManager,
|
||||
new PolicyRunRegistry(new ApplicationProperties()),
|
||||
recorder,
|
||||
fileStorage,
|
||||
jobOwnershipService,
|
||||
List.of(new InlineOutputSink(fileStorage)),
|
||||
new PolicyOutputResolver(new InProcessSourceStore()),
|
||||
resourceMonitor,
|
||||
jobQueue,
|
||||
new PolicyAssetResolver(new InProcessPolicyAssetStore()));
|
||||
|
||||
lenient()
|
||||
.when(jobOwnershipService.createScopedJobKey(anyString()))
|
||||
.thenAnswer(invocation -> invocation.getArgument(0));
|
||||
lenient().when(resourceMonitor.shouldQueueJob(anyInt())).thenReturn(false);
|
||||
lenient().when(toolMetadataService.isMultiInput(anyString())).thenReturn(false);
|
||||
// The team is resolved from the policy, so the recorded row lands in the reader's team.
|
||||
lenient().when(policyStore.get(anyString())).thenReturn(Optional.of(sharedPolicy()));
|
||||
lenient().when(authority.currentUserTeamId()).thenReturn(TEAM);
|
||||
}
|
||||
|
||||
/** Alice's policy, shared with her team. Bob is a member of it and does not own it. */
|
||||
private static Policy sharedPolicy() {
|
||||
return new Policy(
|
||||
"p1",
|
||||
"rotate",
|
||||
"alice",
|
||||
true,
|
||||
List.of(),
|
||||
List.of(new PipelineStep(ROTATE, Map.of())),
|
||||
OutputSpec.inline(),
|
||||
TEAM);
|
||||
}
|
||||
|
||||
/** Fails the policy's single tool step as {@code triggeredBy} (null = sweep). */
|
||||
private void runAndFail(String triggeredBy, String sourceId, String fileIdentity)
|
||||
throws Exception {
|
||||
when(internalApiClient.post(eq(ROTATE), any())).thenThrow(new RuntimeException("boom"));
|
||||
if (triggeredBy != null) {
|
||||
MDC.put("auditPrincipal", triggeredBy);
|
||||
}
|
||||
try {
|
||||
engine.runPolicy(
|
||||
sharedPolicy(),
|
||||
PolicyInputs.of(List.of(pdf())),
|
||||
PolicyProgressListener.NOOP,
|
||||
sourceId,
|
||||
fileIdentity)
|
||||
.completion()
|
||||
.get(10, TimeUnit.SECONDS);
|
||||
} finally {
|
||||
MDC.remove("auditPrincipal");
|
||||
}
|
||||
}
|
||||
|
||||
private static ByteArrayResource pdf() {
|
||||
return new ByteArrayResource("input".getBytes()) {
|
||||
@Override
|
||||
public String getFilename() {
|
||||
return "input.pdf";
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Lenient because a leader's scope and an UNOWNED check both answer without asking who reads,
|
||||
* so whether the name is consulted is the behaviour under test.
|
||||
*/
|
||||
private FileRunEvent asMember(String reader) {
|
||||
lenient().when(userService.getCurrentUsername()).thenReturn(reader);
|
||||
lenient().when(authority.canEditPolicies()).thenReturn(false);
|
||||
List<FileRunEvent> visible = service.list(null, null, 10);
|
||||
return visible.isEmpty() ? null : visible.getFirst();
|
||||
}
|
||||
|
||||
/** Read as a team leader, who reviews the whole team's incidents. See {@link #asMember}. */
|
||||
private FileRunEvent asReviewer(String reader) {
|
||||
lenient().when(userService.getCurrentUsername()).thenReturn(reader);
|
||||
lenient().when(authority.canEditPolicies()).thenReturn(true);
|
||||
return service.list(null, null, 10).getFirst();
|
||||
}
|
||||
|
||||
private List<FailureActionId> offeredTo(FileRunEvent event) {
|
||||
return service.availableActions(event).stream()
|
||||
.map(FileRunEventService.AvailableAction::id)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("a non-owner runs a shared policy on their own upload")
|
||||
class AttendedByANonOwner {
|
||||
|
||||
@Test
|
||||
void theTriggeringUserHoldsItAndIsOfferedTheDocument() throws Exception {
|
||||
runAndFail("bob", null, "bob-doc-1");
|
||||
|
||||
FileRunEvent mine = asMember("bob");
|
||||
assertThat(service.ownershipOf(mine)).isEqualTo(Ownership.MINE);
|
||||
assertThat(offeredTo(mine))
|
||||
.as("he is holding the document, so opening it is his to do")
|
||||
.contains(FailureActionId.VIEW_FILE);
|
||||
assertThat(service.availableActions(mine))
|
||||
.filteredOn(action -> action.id() == FailureActionId.VIEW_FILE)
|
||||
.singleElement()
|
||||
.satisfies(action -> assertThat(action.enabled()).isTrue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void thePolicyOwnerIsNotHandedADocumentSheNeverTouched() throws Exception {
|
||||
runAndFail("bob", null, "bob-doc-1");
|
||||
|
||||
// She owns the policy and pays for the run, and still has no copy of Bob's file.
|
||||
FileRunEvent theirs = asReviewer("alice");
|
||||
assertThat(service.ownershipOf(theirs)).isEqualTo(Ownership.THEIRS);
|
||||
assertThat(offeredTo(theirs)).doesNotContain(FailureActionId.VIEW_FILE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theReviewerIsStillOfferedWhatReviewingNeeds() throws Exception {
|
||||
runAndFail("bob", null, "bob-doc-1");
|
||||
|
||||
// Not her document, still her team's incident.
|
||||
assertThat(offeredTo(asReviewer("alice")))
|
||||
.contains(FailureActionId.VIEW_IN_PROCESSOR, FailureActionId.DISMISS);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("an unattended sweep pulls a file from a source")
|
||||
class UnattendedSweep {
|
||||
|
||||
@Test
|
||||
void theRowIsOwnedByNobodySoTheReviewerInheritsTheOwnerActions() throws Exception {
|
||||
runAndFail(null, "src-watched-folder", "file-hash-1");
|
||||
|
||||
FileRunEvent unattended = asReviewer("alice");
|
||||
assertThat(service.ownershipOf(unattended)).isEqualTo(Ownership.UNOWNED);
|
||||
// No browser holds this document, so the offer is stated and disabled, not dropped.
|
||||
assertThat(offeredTo(unattended)).contains(FailureActionId.VIEW_FILE);
|
||||
assertThat(service.availableActions(unattended))
|
||||
.filteredOn(action -> action.id() == FailureActionId.VIEW_FILE)
|
||||
.singleElement()
|
||||
.satisfies(
|
||||
action -> {
|
||||
assertThat(action.enabled()).isFalse();
|
||||
assertThat(action.disabledReasonKey())
|
||||
.isEqualTo("portal.failures.disabled.unattended");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void thePolicyOwnerDoesNotInheritItAsHerOwn() throws Exception {
|
||||
// Being billed for the sweep must not become ownership: she gets these as reviewer
|
||||
// only.
|
||||
runAndFail(null, "src-watched-folder", "file-hash-1");
|
||||
|
||||
assertThat(service.ownershipOf(asReviewer("alice"))).isNotEqualTo(Ownership.MINE);
|
||||
}
|
||||
}
|
||||
}
|
||||
+32
@@ -39,6 +39,7 @@ import tools.jackson.databind.json.JsonMapper;
|
||||
class PolicyFailureRecorderTest {
|
||||
|
||||
private static final Long TEAM = 11L;
|
||||
private static final String ACTOR = "dana@example.com";
|
||||
|
||||
@Mock private PolicyStore policyStore;
|
||||
|
||||
@@ -379,5 +380,36 @@ class PolicyFailureRecorderTest {
|
||||
|
||||
assertThat(store.list(TEAM, null, null, null, 10)).hasSize(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSameDocumentFailingInTwoAttendedRunsIsOneIncident() {
|
||||
// Every upload is a new run, so with no reference the run id stands in for the document
|
||||
// and the same broken file reads as a second incident rather than a second occurrence.
|
||||
when(policyStore.get("policy-1")).thenReturn(Optional.of(policy("policy-1", TEAM)));
|
||||
|
||||
recorder.recordRunFailure(
|
||||
"run-1", "policy-1", null, "editor-file-1", ACTOR, "locked", passwordFailure());
|
||||
recorder.recordRunFailure(
|
||||
"run-2", "policy-1", null, "editor-file-1", ACTOR, "locked", passwordFailure());
|
||||
|
||||
List<FileRunEvent> events = store.list(TEAM, null, null, null, 10);
|
||||
assertThat(events).hasSize(1);
|
||||
assertThat(events.getFirst().occurrences()).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void twoDocumentsFailingTheSameWayStaySeparateIncidents() {
|
||||
// Folding is per document, so neither row is credited with the other's occurrence.
|
||||
when(policyStore.get("policy-1")).thenReturn(Optional.of(policy("policy-1", TEAM)));
|
||||
|
||||
recorder.recordRunFailure(
|
||||
"run-1", "policy-1", null, "editor-file-1", ACTOR, "locked", passwordFailure());
|
||||
recorder.recordRunFailure(
|
||||
"run-2", "policy-1", null, "editor-file-2", ACTOR, "locked", passwordFailure());
|
||||
|
||||
assertThat(store.list(TEAM, null, null, null, 10))
|
||||
.hasSize(2)
|
||||
.allMatch(event -> event.occurrences() == 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+12
@@ -11,6 +11,8 @@ import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import stirling.software.proprietary.policy.controller.PolicyRunFiles;
|
||||
|
||||
/**
|
||||
* The privacy contract: a recorded failure carries no document identity of its own. There is no
|
||||
* name column and the dedup key is built only from opaque ids, so nothing here derives from what a
|
||||
@@ -53,6 +55,16 @@ class RecordFailurePrivacyTest {
|
||||
.doesNotContain("fileName");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theRunRequestThatSuppliesADocumentReferenceCarriesNoNameEither() {
|
||||
// The same discipline at the door as in the row: an id and nothing else, or a document name
|
||||
// reaches a table that deliberately has nowhere to put it.
|
||||
assertThat(List.of(PolicyRunFiles.class.getDeclaredFields()))
|
||||
.extracting(Field::getName)
|
||||
.contains("fileId")
|
||||
.doesNotContain("fileName", "documentName", "name");
|
||||
}
|
||||
|
||||
@Test
|
||||
void dedupKeyIsBuiltOnlyFromOpaqueIdentifiers() {
|
||||
// Two files under the same policy hash differently (so they stay separate incidents), but
|
||||
|
||||
+70
-3
@@ -29,6 +29,7 @@ import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
|
||||
@@ -39,6 +40,7 @@ import stirling.software.common.model.job.JobResponse;
|
||||
import stirling.software.common.model.tool.ToolDiagnostic;
|
||||
import stirling.software.common.service.JobOwnershipService;
|
||||
import stirling.software.common.util.TempFileManager;
|
||||
import stirling.software.common.util.TempFileRegistry;
|
||||
import stirling.software.proprietary.policy.config.PolicyAccessGuard;
|
||||
import stirling.software.proprietary.policy.config.PolicyManagementAuthority;
|
||||
import stirling.software.proprietary.policy.engine.PolicyRunHandle;
|
||||
@@ -87,7 +89,10 @@ class PolicyControllerTest {
|
||||
|
||||
@Mock private ProcessedLedger processedLedger;
|
||||
|
||||
@Mock private TempFileManager tempFileManager;
|
||||
// Real, not mocked: the run endpoints spool uploads through it.
|
||||
private final TempFileManager tempFileManager =
|
||||
new TempFileManager(new TempFileRegistry(), new ApplicationProperties());
|
||||
|
||||
@Mock private JobOwnershipService jobOwnershipService;
|
||||
|
||||
private ApplicationProperties applicationProperties;
|
||||
@@ -700,13 +705,46 @@ class PolicyControllerTest {
|
||||
@DisplayName("runStoredPolicy")
|
||||
class RunStoredPolicy {
|
||||
|
||||
/** What an editor sends: the documents, plus its own id for a single one of them. */
|
||||
private PolicyRunFiles filesWith(String fileId, int documents) {
|
||||
PolicyRunFiles files = new PolicyRunFiles();
|
||||
files.setFileId(fileId);
|
||||
files.setFileInput(
|
||||
java.util.stream.IntStream.range(0, documents)
|
||||
.mapToObj(
|
||||
i ->
|
||||
(org.springframework.web.multipart.MultipartFile)
|
||||
new MockMultipartFile(
|
||||
"fileInput",
|
||||
"doc" + i + ".pdf",
|
||||
"application/pdf",
|
||||
("pdf-" + i).getBytes()))
|
||||
.toList());
|
||||
return files;
|
||||
}
|
||||
|
||||
private String documentReferenceOf(PolicyRunFiles files) throws Exception {
|
||||
Policy p = policy("a", 1L);
|
||||
when(policyStore.get("a")).thenReturn(Optional.of(p));
|
||||
when(policyAccessGuard.canAccess(p)).thenReturn(true);
|
||||
when(policyRunner.runWith(eq(p), any(), eq(PolicyProgressListener.NOOP), any()))
|
||||
.thenReturn(handle("run-9"));
|
||||
|
||||
controller.runStoredPolicy("a", files);
|
||||
|
||||
ArgumentCaptor<String> reference = ArgumentCaptor.forClass(String.class);
|
||||
verify(policyRunner)
|
||||
.runWith(eq(p), any(), eq(PolicyProgressListener.NOOP), reference.capture());
|
||||
return reference.getValue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("runs a stored, accessible policy")
|
||||
void runsStored() throws Exception {
|
||||
Policy p = policy("a", 1L);
|
||||
when(policyStore.get("a")).thenReturn(Optional.of(p));
|
||||
when(policyAccessGuard.canAccess(p)).thenReturn(true);
|
||||
when(policyRunner.runWith(eq(p), any(), eq(PolicyProgressListener.NOOP)))
|
||||
when(policyRunner.runWith(eq(p), any(), eq(PolicyProgressListener.NOOP), any()))
|
||||
.thenReturn(handle("run-9"));
|
||||
|
||||
ResponseEntity<JobResponse<Void>> response =
|
||||
@@ -716,6 +754,35 @@ class PolicyControllerTest {
|
||||
assertThat(response.getBody().getJobId()).isEqualTo("run-9");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("records the caller's own id for a single-document run")
|
||||
void carriesTheCallersDocumentReference() throws Exception {
|
||||
// The point of the field: a failure names a document the client that started it can
|
||||
// resolve.
|
||||
assertThat(documentReferenceOf(filesWith("editor-file-1", 1)))
|
||||
.isEqualTo("editor-file-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("records nothing when the run carries several documents")
|
||||
void refusesToGuessWhichOfSeveralDocumentsItIs() throws Exception {
|
||||
// One incident, one reference: naming one of several would attribute it to whichever
|
||||
// bound first.
|
||||
assertThat(documentReferenceOf(filesWith("editor-file-1", 3))).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("records nothing when the caller sent no id")
|
||||
void toleratesACallerThatSendsNoReference() throws Exception {
|
||||
assertThat(documentReferenceOf(filesWith(null, 1))).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("records nothing for a blank id")
|
||||
void treatsABlankReferenceAsNone() throws Exception {
|
||||
assertThat(documentReferenceOf(filesWith(" ", 1))).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("not found when the stored policy is inaccessible")
|
||||
void notFound() {
|
||||
@@ -838,7 +905,7 @@ class PolicyControllerTest {
|
||||
Policy p = policy("a", 1L);
|
||||
when(policyStore.get("a")).thenReturn(Optional.of(p));
|
||||
when(policyAccessGuard.canAccess(p)).thenReturn(true);
|
||||
when(policyRunner.runWith(eq(p), any(), eq(PolicyProgressListener.NOOP)))
|
||||
when(policyRunner.runWith(eq(p), any(), eq(PolicyProgressListener.NOOP), any()))
|
||||
.thenReturn(handle("run-9"));
|
||||
|
||||
ResponseEntity<JobResponse<Void>> response =
|
||||
|
||||
+49
-4
@@ -32,6 +32,7 @@ import org.springframework.core.io.ByteArrayResource;
|
||||
import stirling.software.proprietary.policy.input.InputSource;
|
||||
import stirling.software.proprietary.policy.input.ResolveContext;
|
||||
import stirling.software.proprietary.policy.input.ResolvedInput;
|
||||
import stirling.software.proprietary.policy.ledger.IdentityHasher;
|
||||
import stirling.software.proprietary.policy.ledger.InProcessProcessedLedger;
|
||||
import stirling.software.proprietary.policy.ledger.ProcessedLedger;
|
||||
import stirling.software.proprietary.policy.model.InputSpec;
|
||||
@@ -293,13 +294,56 @@ class PolicyRunnerTest {
|
||||
Policy policy = policy(List.of(InputSpec.folder("/in")));
|
||||
PolicyInputs inputs = PolicyInputs.of(List.of());
|
||||
PolicyRunHandle handle = new PolicyRunHandle("r", new CompletableFuture<>());
|
||||
when(policyEngine.runPolicy(policy, inputs, PolicyProgressListener.NOOP))
|
||||
when(policyEngine.runPolicy(policy, inputs, PolicyProgressListener.NOOP, null, null))
|
||||
.thenReturn(handle);
|
||||
|
||||
assertSame(handle, runner.runWith(policy, inputs, PolicyProgressListener.NOOP));
|
||||
assertSame(handle, runner.runWith(policy, inputs, PolicyProgressListener.NOOP, null));
|
||||
verifyNoInteractions(folderSource);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAttendedRunCarriesTheClientsOwnDocumentReferenceAndNoSource() {
|
||||
// A failure of this run can then name the document the user is still holding, and the null
|
||||
// sourceId is what marks the reference as the client's own rather than a source's hash.
|
||||
Policy policy = policy(List.of());
|
||||
PolicyInputs inputs = PolicyInputs.of(List.of(new ByteArrayResource("a".getBytes())));
|
||||
when(policyEngine.runPolicy(
|
||||
policy, inputs, PolicyProgressListener.NOOP, null, "editor-file-1"))
|
||||
.thenReturn(new PolicyRunHandle("r", new CompletableFuture<>()));
|
||||
|
||||
runner.runWith(policy, inputs, PolicyProgressListener.NOOP, "editor-file-1");
|
||||
|
||||
verify(policyEngine)
|
||||
.runPolicy(policy, inputs, PolicyProgressListener.NOOP, null, "editor-file-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnattendedRunStillCarriesItsSourcesHashedIdentity() throws Exception {
|
||||
// The other id space, unchanged: a folder identity is a path, and a path is a filename, so
|
||||
// what reaches the run is the one-way hash and never the client-minted kind of reference.
|
||||
InputSpec spec = InputSpec.folder("/in");
|
||||
Policy policy = policy(List.of(spec));
|
||||
String sourceId = policy.inputs().getFirst().sourceId();
|
||||
when(folderSource.supports(spec)).thenReturn(true);
|
||||
when(folderSource.resolve(eq(spec), any()))
|
||||
.thenReturn(
|
||||
List.of(
|
||||
ResolvedInput.forFile(
|
||||
PolicyInputs.of(List.of()), "/in/doc.pdf", success -> {})));
|
||||
when(policyEngine.runPolicy(any(), any(), any(), any(), any()))
|
||||
.thenReturn(new PolicyRunHandle("r", new CompletableFuture<>()));
|
||||
|
||||
runner.run(policy);
|
||||
|
||||
verify(policyEngine)
|
||||
.runPolicy(
|
||||
eq(policy),
|
||||
any(),
|
||||
any(),
|
||||
eq(sourceId),
|
||||
eq(IdentityHasher.identityHash("/in/doc.pdf")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void runWithRecordsSuppliedDocsAgainstTheEditorSourceForThePolicyTeam() {
|
||||
Policy policy =
|
||||
@@ -317,10 +361,11 @@ class PolicyRunnerTest {
|
||||
List.of(
|
||||
new ByteArrayResource("a".getBytes()),
|
||||
new ByteArrayResource("b".getBytes())));
|
||||
when(policyEngine.runPolicy(policy, inputs, PolicyProgressListener.NOOP))
|
||||
when(policyEngine.runPolicy(
|
||||
policy, inputs, PolicyProgressListener.NOOP, null, "editor-file-1"))
|
||||
.thenReturn(new PolicyRunHandle("r", new CompletableFuture<>()));
|
||||
|
||||
runner.runWith(policy, inputs, PolicyProgressListener.NOOP);
|
||||
runner.runWith(policy, inputs, PolicyProgressListener.NOOP, "editor-file-1");
|
||||
|
||||
String key = EditorSource.counterKey(7L);
|
||||
assertEquals(2, docCounter.statsFor(List.of(key)).get(key).total());
|
||||
|
||||
Reference in New Issue
Block a user