All files / src/hooks/notifications useFlowsheetSubscriptions.ts

55.23% Statements 58/105
56% Branches 28/50
15.38% Functions 2/13
74.66% Lines 56/75

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202                                                                          3x       3x           20659x 20659x 20659x 20659x 20659x 20659x 20659x 20659x 20659x 20659x   20659x   243x 243x   26x         73x   71x     5x       88x     2x   2x         102510x   20659x   3x           3x       1x     1x     1x       2x           53383x   20659x   2x           2x 2x         53383x         20659x     20879x   20659x   343x 42475x   20659x           20769x   20659x     23x       3x 20879x   20659x   4x 12x         20879x   20659x   10x           20879x   20659x                         20879x    
import { toast } from "sonner";
import {
  TaskStatusEnum as StatusEnum,
  TaskTypeEnum,
} from "@/api/apiStore.gen.ts";
import { useBuildStateRefresh } from "@/hooks/cache/useBuildStateRefresh.ts";
import { useDiagnosticsRefresh } from "@/hooks/cache/useDiagnosticsRefresh.ts";
import { useFlowsheetRevisionRefresh } from "@/hooks/cache/useFlowsheetRevisionRefresh.ts";
import { useInvalidateChildTaskCache } from "@/hooks/cache/useInvalidateChildTaskCache.ts";
import { useMLTrainRefresh } from "@/hooks/cache/useMLTrainRefresh.ts";
import { useResultSummaryRefresh } from "@/hooks/cache/useResultSummaryRefresh.ts";
import { useSolveRefresh } from "@/hooks/cache/useSolveRefresh.ts";
import { useUpdateTaskCache } from "@/hooks/cache/useUpdateTaskCache.ts";
import type { BuildStateCompletionNotification } from "@/hooks/notifications/notificationSubscriptions.ts";
import {
  useAutoRevisionSkippedActiveTasksSubscription,
  useBuildStateCompletedSubscription,
  useResultSummaryAvailableSubscription,
  useResultSummaryCalculatingSubscription,
  useResultSummaryFailedSubscription,
  useTaskCancelledSubscription,
  useTaskCancellingSubscription,
  useTaskChildrenCancelledSubscription,
  useTaskCompletedSubscription,
  useTaskUpdatedSubscription,
} from "@/hooks/notifications/notificationSubscriptions.ts";
import { ContentTypes } from "../../pages/flowsheet-page/flowsheet/LeftSideBar/LeftSideBarTabDefinitions";
import { useSearchParam } from "../searchParams";
 
function handleBuildStateFailure(completion: BuildStateCompletionNotification) {
  if (completion.failure_kind === "delivery-failure") {
    console.warn("Build-state request delivery failed.", {
      context: completion.context,
    });
    return;
  }
 
  console.warn("Related property calculation failed.", {
    context: completion.context,
    error: completion.error,
  });
  toast.error("Related properties could not be updated", {
    description:
      "The stream property update was saved, but some related properties could not be calculated.",
  });
}
 
export function useFlowsheetSubscriptions(enabled = true) {
  const { refreshSolveDependencies } = useSolveRefresh();
  const { refreshRevisionList } = useFlowsheetRevisionRefresh();
  const { refreshBuildStateDependencies } = useBuildStateRefresh();
  const { refreshDiagnostics } = useDiagnosticsRefresh();
  const { refreshMLTrainDependencies } = useMLTrainRefresh();
  const { refreshResultSummaries } = useResultSummaryRefresh();
  const updateTaskCache = useUpdateTaskCache();
  const invalidateChildTaskCache = useInvalidateChildTaskCache();
  const [, setContent] = useSearchParam("content");
 
  useTaskCompletedSubscription((completedTask) => {
    Iif (!enabled) return;
    refreshDiagnostics();
    updateTaskCache(completedTask);
 
    Iif (completedTask.task_type === TaskTypeEnum.BuildState) return;
 
    // Process completion for non-child tasks
    if (completedTask.parent == null) {
      if (completedTask.task_type == TaskTypeEnum.Solve) {
        refreshSolveDependencies(completedTask.id);
        if (completedTask.status == StatusEnum.Completed) {
          refreshRevisionList();
        }
      } else if (completedTask.task_type == TaskTypeEnum.MlTraining) {
        refreshMLTrainDependencies();
      }
 
      if (completedTask.status == StatusEnum.Completed)
        toast.success(`${completedTask.task_type} completed successfully`);
      else {
        if (completedTask.task_type == TaskTypeEnum.Solve) {
          setContent(ContentTypes.solverLogs); // so the user can see the logs immediately
        }
        toast.error(`${completedTask.task_type} failed`, {
          description: `The ${completedTask.task_type} task did not complete successfully. See the logs for more details.`,
        });
      }
    }
  });
 
  useTaskCancelledSubscription((cancelledTask) => {
    Iif (!enabled) return;
    updateTaskCache(cancelledTask);
 
    Iif (cancelledTask.task_type === TaskTypeEnum.BuildState) return;
 
    // Process completion for non-child tasks
    if (cancelledTask.parent == null) {
      refreshSolveDependencies(cancelledTask.id);
      if (cancelledTask.debug?.timed_out) {
        // Timeout metadata is persisted on the task debug payload by Django,
        // so users see the exact configured timeout value in the toast.
        const timeoutSeconds = Number(
          cancelledTask.debug?.solve_timeout_seconds,
        );
        const timeoutDescription = Number.isFinite(timeoutSeconds)
          ? `The solve exceeded its timeout of ${timeoutSeconds} seconds and was cancelled. See the logs for more details.`
          : "The solve exceeded its timeout and was cancelled. See the logs for more details.";
        toast.error("Solve timed out", {
          description: timeoutDescription,
        });
      } else {
        toast.error("Solve cancelled", {
          description:
            "The solve task is cancelled. See the logs for more details.",
        });
      }
    }
  });
 
  useTaskCancellingSubscription((cancelledTask) => {
    Iif (!enabled) return;
    updateTaskCache(cancelledTask);
 
    Iif (cancelledTask.task_type === TaskTypeEnum.BuildState) return;
 
    // Process completion for non-child tasks
    if (cancelledTask.parent == null) {
      refreshSolveDependencies(cancelledTask.id);
      toast.info("Solve cancelling", {
        description:
          "The solve task is cancelling. See the logs for more details.",
      });
    }
  });
 
  // When a parent task's children are cancelled en-masse, drop all locally
  // cached child-task pages so they are refetched on demand rather than
  // processing individual updates for potentially thousands of children.
  useTaskChildrenCancelledSubscription((parentTask) => {
    Iif (!enabled) return;
    invalidateChildTaskCache(parentTask.id);
  });
 
  useTaskUpdatedSubscription((updatedTask) => {
    Iif (!enabled) return;
    updateTaskCache(updatedTask);
  });
 
  useAutoRevisionSkippedActiveTasksSubscription(() => {
    Iif (!enabled) return;
    toast.warning("Automatic version not created", {
      description:
        "Another task was still running when the solve finished. You can save a version after active tasks finish.",
    });
  });
 
  useBuildStateCompletedSubscription((completion) => {
    Iif (!enabled) return;
    if (completion.status === "success") {
      refreshBuildStateDependencies();
      return;
    }
 
    handleBuildStateFailure(completion);
  });
 
  useResultSummaryCalculatingSubscription((notification) => {
    Iif (!enabled) return;
    refreshResultSummaries(
      notification.simulation_object_ids.map((simulationObjectId) => ({
        scenarioId: notification.scenario_id,
        simulationObjectId,
      })),
    );
  });
 
  useResultSummaryAvailableSubscription((notification) => {
    Iif (!enabled) return;
    refreshResultSummaries([
      {
        scenarioId: notification.scenario_id,
        simulationObjectId: notification.simulation_object_id,
      },
    ]);
  });
 
  useResultSummaryFailedSubscription((notification) => {
    Iif (!enabled) return;
    refreshResultSummaries([
      {
        scenarioId: notification.scenario_id,
        simulationObjectId: notification.simulation_object_id,
      },
    ]);
    toast.error("Aggregate results could not be calculated", {
      description:
        notification.errors[0]?.message ??
        "Open the solver logs for more detail.",
    });
  });
}