From a19db93c372ef0662633d55cf7006460afab9e84 Mon Sep 17 00:00:00 2001 From: Ari Date: Tue, 17 May 2022 20:48:43 -0400 Subject: [PATCH] support for malformed automations --- .github/workflows/test.yml | 5 +- api/src/automations/loader.py | 17 ++- api/src/automations/types.py | 2 +- api/tests/samples/config/automations.yaml | 28 +++++ api/tests/unittests/api/test_automations.py | 14 +-- .../unittests/automations/test_manager.py | 12 +- webapp/package.json | 3 + .../src/components/AutomationEditor/index.css | 6 + .../AutomationEditor/index.stories.tsx | 60 +++++++++ .../src/components/AutomationEditor/index.tsx | 73 ++++++++++- .../src/components/AutomationEditor/state.ts | 57 ++++++--- .../AutomationList/AutomationList.stories.tsx | 54 ++++++++ .../AutomationList/AutomationListBox.tsx | 50 +++++--- webapp/src/components/DAGFlow/DAGCircle.tsx | 2 +- webapp/src/components/DAGFlow/flowDataMods.ts | 2 +- webapp/src/components/DAGFlow/index.tsx | 26 ++-- webapp/src/components/DAGFlow/safe.css | 4 + webapp/src/components/DAGFlow/safe.tsx | 84 +++++++++++++ .../components/DAGFlow/triggerConvertor.ts | 2 - webapp/src/components/Inputs/InputBoolean.tsx | 1 - webapp/src/components/Inputs/InputYaml.tsx | 2 +- .../NodeEditor/OptionManager/index.tsx | 4 - webapp/src/components/NodeEditor/constants.ts | 1 - webapp/src/types/automations/index.ts | 12 +- webapp/src/types/automations/triggers.ts | 85 +++---------- webapp/src/types/validators/actions.ts | 24 ++++ webapp/src/types/validators/autmation.ts | 12 ++ webapp/src/types/validators/common.ts | 9 ++ webapp/src/types/validators/helper.ts | 31 +++++ webapp/src/types/validators/index.test.ts | 24 ++++ webapp/src/types/validators/metadata.ts | 10 ++ webapp/src/types/validators/triggers.ts | 117 ++++++++++++++++++ webapp/src/utils/useDelay.ts | 2 +- webapp/src/utils/useWindowSize.ts | 4 +- webapp/yarn.lock | 5 + 35 files changed, 683 insertions(+), 161 deletions(-) create mode 100644 webapp/src/components/DAGFlow/safe.css create mode 100644 webapp/src/components/DAGFlow/safe.tsx create mode 100644 webapp/src/types/validators/actions.ts create mode 100644 webapp/src/types/validators/autmation.ts create mode 100644 webapp/src/types/validators/common.ts create mode 100644 webapp/src/types/validators/helper.ts create mode 100644 webapp/src/types/validators/index.test.ts create mode 100644 webapp/src/types/validators/metadata.ts create mode 100644 webapp/src/types/validators/triggers.ts diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index b88e47a..5ae4116 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -61,6 +61,9 @@ jobs: nodejs: name: "NodeJs Tests" runs-on: ubuntu-latest + strategy: + matrix: + action: [test:ci, tsc:ci, build] steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 @@ -71,7 +74,7 @@ jobs: - name: Install Dependencies run: cd webapp && yarn install - name: Run Tests - run: cd webapp && yarn test:ci + run: cd webapp && yarn ${{ matrix.action }} \ No newline at end of file diff --git a/api/src/automations/loader.py b/api/src/automations/loader.py index d2a3353..d9df413 100644 --- a/api/src/automations/loader.py +++ b/api/src/automations/loader.py @@ -1,4 +1,4 @@ -from typing import Iterator, Union +from typing import Any, Iterator, Union from pydantic.error_wrappers import ValidationError @@ -26,18 +26,27 @@ def load_automation( try: yield ExtenededAutomationData( metadata=AutomationMetdata.parse_obj(auto_raw), - condition=load_conditions(auto_raw.get("condition", [])), - sequence=load_conditions(auto_raw.get("action", [])), - trigger=normalize_obj(auto_raw.get("trigger", [])), + condition=ifempty_or_null_then_list(load_conditions(auto_raw.get("condition", []))), + sequence=ifempty_or_null_then_list(load_conditions(auto_raw.get("action", []))), + trigger=ifempty_or_null_then_list(normalize_obj(auto_raw.get("trigger", []))), tags=tags, ) except ValidationError as err: raise InvalidAutomationFile from err +def ifempty_or_null_then_list(obj: Any): + if not isinstance(obj, list): + return [] + else: + return obj + + def load_conditions(conditions: Union[dict, list, str]): if isinstance(conditions, list): return list(map(ensure_condition_dictionary, conditions)) + elif not conditions: + return [] else: return [ensure_condition_dictionary(conditions)] diff --git a/api/src/automations/types.py b/api/src/automations/types.py index 8b96fb6..a174ab0 100644 --- a/api/src/automations/types.py +++ b/api/src/automations/types.py @@ -9,7 +9,7 @@ class AutomationMetdata(BaseModel): alias: Optional[str] = None description: Optional[str] = None trigger_variables: Optional[Dict[str, Union[str, int, bool, float]]] = None - mode: Literal["single", "restart", "queued", "parallel"] = "single" + mode: str = "single" class AutomationData(BaseModel): diff --git a/api/tests/samples/config/automations.yaml b/api/tests/samples/config/automations.yaml index fa5e949..be943f6 100644 --- a/api/tests/samples/config/automations.yaml +++ b/api/tests/samples/config/automations.yaml @@ -811,3 +811,31 @@ device_id: das2qdasdasdasadaasd default: [] mode: single +- id: 'baddy-1' + alias: 'bad triggers' + description: '' + trigger: "" + condition: [] + action: [] + mode: single +- id: 'baddy-2' + alias: 'null things' + description: '' + trigger: + condition: + action: + mode: single +- id: 'baddy-3' + alias: 'big null things' + description: + trigger: + condition: + action: + mode: single +- id: 'bad mode' + alias: 'bade mode' + description: "" + trigger: [] + condition: [] + action: [] + mode: bad diff --git a/api/tests/unittests/api/test_automations.py b/api/tests/unittests/api/test_automations.py index 2cb2232..c8c3cc3 100644 --- a/api/tests/unittests/api/test_automations.py +++ b/api/tests/unittests/api/test_automations.py @@ -24,7 +24,7 @@ class BaseTestCase(TestCase): class automation_list_tests(BaseTestCase): - test_params = {"total": 28, "subtest2_found_items": 3, "subtest1_found_items": 10} + test_params = {"total": 32, "subtest2_found_items": 7, "subtest1_found_items": 10} def test_get_list_of_everything(self): data = self.client.post( @@ -106,18 +106,18 @@ class automation2_lists_tests(automation_list_tests): class automation_update_tests(BaseTestCase): def test_insert_new(self): resp = self.client.post("/automations/list", json={"limit": 1, "offset": 0}) - self.assertEqual(resp.json()["totalItems"], 28) + self.assertEqual(resp.json()["totalItems"], 32) resp = self.client.post( "/automations/item", json={ - "index": 29, + "index": 33, "data": AutomationData(metadata=AutomationMetdata(id="testme")).dict(), }, ) self.assertEqual(resp.status_code, 200) - resp = self.client.post("/automations/list", json={"limit": 1, "offset": 28}) + resp = self.client.post("/automations/list", json={"limit": 1, "offset": 32}) data = resp.json() - self.assertEqual(data["totalItems"], 29) + self.assertEqual(data["totalItems"], 33) self.assertEqual(data["data"][0]["metadata"]["id"], "testme") def test_update_some(self): @@ -324,7 +324,7 @@ class automation_update_tests(BaseTestCase): class automation_delete_tests(BaseTestCase): def test_delete_some(self): resp = self.client.post("/automations/list", json={"limit": 1, "offset": 0}) - self.assertEqual(resp.json()["totalItems"], 28) + self.assertEqual(resp.json()["totalItems"], 32) resp = self.client.delete( "/automations/item", json={ @@ -333,4 +333,4 @@ class automation_delete_tests(BaseTestCase): ) self.assertEqual(resp.status_code, 200) resp = self.client.post("/automations/list", json={"limit": 1, "offset": 0}) - self.assertEqual(resp.json()["totalItems"], 27) + self.assertEqual(resp.json()["totalItems"], 31) diff --git a/api/tests/unittests/automations/test_manager.py b/api/tests/unittests/automations/test_manager.py index a0e9816..d6accd6 100644 --- a/api/tests/unittests/automations/test_manager.py +++ b/api/tests/unittests/automations/test_manager.py @@ -24,11 +24,11 @@ class manager_tests(TestCase): _, _, loader = get_example_automation_loader() self.assertIsNone(loader.get(-1)) self.assertIsNone(loader.get(1_000)) - self.assertIsNone(loader.get(31)) + self.assertIsNone(loader.get(33)) def test_length(self): _, _, loader = get_example_automation_loader() - self.assertEqual(loader.get_total_items(), 28) + self.assertEqual(loader.get_total_items(), 32) def test_bad_automations_file(self): folder, _, manager = get_dummy_automation_loader( @@ -51,11 +51,11 @@ class manager_tests(TestCase): def test_create_automation_with_example_folder(self): _, _, manager = get_example_automation_loader() - self.assertEqual(manager.get_total_items(), 28) - manager.update(32, ExtenededAutomationData(metadata=AutomationMetdata(id="test1"))) - auto = manager.get(28) + self.assertEqual(manager.get_total_items(), 32) + manager.update(40, ExtenededAutomationData(metadata=AutomationMetdata(id="test1"))) + auto = manager.get(32) self.assertIsNotNone(auto) - self.assertEqual(manager.get_total_items(), 29) + self.assertEqual(manager.get_total_items(), 33) self.assertEqual(auto.metadata.id, "test1") # type: ignore def test_update_automation(self): diff --git a/webapp/package.json b/webapp/package.json index ed123fc..e9eb1d3 100644 --- a/webapp/package.json +++ b/webapp/package.json @@ -15,6 +15,7 @@ "react-jss": "^10.8.2", "react-router-dom": "6", "react-scripts": "4.0.3", + "superstruct": "^0.15.4", "theming": "^3.3.0", "typescript": "^4.1.2", "web-vitals": "^1.0.1", @@ -23,6 +24,8 @@ "scripts": { "start": "react-scripts start", "build": "react-scripts build", + "tsc": "tsc -w", + "tsc:ci": "tsc", "test:ci": "react-scripts test --ci=true --all --watchAll=false", "test": "react-scripts test", "test:debug": "react-scripts --inspect-brk test --runInBand --no-cache", diff --git a/webapp/src/components/AutomationEditor/index.css b/webapp/src/components/AutomationEditor/index.css index 8175605..9af6d83 100644 --- a/webapp/src/components/AutomationEditor/index.css +++ b/webapp/src/components/AutomationEditor/index.css @@ -5,6 +5,12 @@ height: 100%; } +.automation-editor-failures { + display: flex; + flex-direction: column; + padding: 1em; +} + .automation-editor--flow-wrapper { flex: 1; padding: 0 0.5em 0 0.5em; diff --git a/webapp/src/components/AutomationEditor/index.stories.tsx b/webapp/src/components/AutomationEditor/index.stories.tsx index 8b8de8d..c42fec2 100644 --- a/webapp/src/components/AutomationEditor/index.stories.tsx +++ b/webapp/src/components/AutomationEditor/index.stories.tsx @@ -111,3 +111,63 @@ EmptyStart.args = { sequence: [] } } + +export const BadAutomationInvalidMetadata = Template.bind({}) +BadAutomationInvalidMetadata.args = { + ...BadAutomationInvalidMetadata.args, + automation: { + condition: [], + tags: {}, + metadata: { + } as any, + trigger: [ + ], + sequence: [] + } +} + +export const BadAutomationInvalidTriggers = Template.bind({}) +BadAutomationInvalidTriggers.args = { + ...BadAutomationInvalidTriggers.args, + automation: { + condition: [], + tags: {}, + metadata: { + id: "random", + alias: "Random", + description: "Example Metadata", + trigger_variables: { + 'wowo': '!' + }, + mode: 'single', + }, + trigger: [ + "haha I am a string" + ] as any, + sequence: [] + } +} + +export const BadAutomationInvalidSequence = Template.bind({}) +BadAutomationInvalidSequence.args = { + ...BadAutomationInvalidSequence.args, + automation: { + condition: [], + tags: {}, + metadata: { + id: "random", + alias: "Bad Choose Sequence", + description: "Example Metadata", + trigger_variables: { + 'wowo': '!' + }, + mode: 'single', + }, + trigger: [], + sequence: [ + { + choose: {} + } + ] as any + } +} diff --git a/webapp/src/components/AutomationEditor/index.tsx b/webapp/src/components/AutomationEditor/index.tsx index b6ba10d..877d4b5 100644 --- a/webapp/src/components/AutomationEditor/index.tsx +++ b/webapp/src/components/AutomationEditor/index.tsx @@ -5,9 +5,11 @@ import { AutomationData } from "types/automations"; import { AutoInfoBox } from "./AutoInfoBox"; import { ButtonIcon } from "components/Icons/ButtonIcons"; import { Button } from "components/Inputs/Button"; -import { useAutomatioEditorState } from "./state"; -import { DAGAutomationFlow } from "components/DAGFlow"; +import { useAutomatioEditorState, EditorData } from './state'; +import { SafeDAGAutomationFlow } from "components/DAGFlow/safe"; import { DAGAutomationFlowDims } from "components/DAGFlow/types"; +import { MiniFailure } from 'types/validators/helper'; +import InputYaml from "components/Inputs/InputYaml"; interface Props { automation?: AutomationData; @@ -26,7 +28,9 @@ export const AutomationEditor: FC = ({ updateTrigger, updateMetadata, updateCondition, + validate, save, + saveAndUpdate, } = useAutomatioEditorState(propsAutos, propsOnUpdate); const [closeInfo, setCloseInfo] = useState(false); @@ -37,6 +41,14 @@ export const AutomationEditor: FC = ({ Loading... } + if (state.status === 'invalid') { + return + } return
= ({ Save
- = ({ } + + +export const ValidationBox: FC<{ + failures: MiniFailure[] + validate: (d: any) => MiniFailure[] | null, + data: EditorData, + onSave: (d: EditorData) => void, +}> = props => { + + const [{ failures, data }, setState] = useState({ + failures: props.failures, + data: props.data, + }); + + const makeSave = (k: K) => (d: EditorData[K]) => { + const newData = { + ...data, + [k]: d, + } + const newFails = props.validate(newData); + if (newFails) { + setState({ + failures: newFails, + data: newData, + }) + } else { + setState({ + failures: [], + data: newData, + }) + } + } + + return
+
    + {failures.map((f, i) => <> +
  • + {f.path}: +
      + {f.message.map((m, j) =>
    • + {m} +
    • )} +
    +
  • + )} +
+ Please correct the automation file manually and then continue! + + + + + + +
+} \ No newline at end of file diff --git a/webapp/src/components/AutomationEditor/state.ts b/webapp/src/components/AutomationEditor/state.ts index a92d7ce..37f3aee 100644 --- a/webapp/src/components/AutomationEditor/state.ts +++ b/webapp/src/components/AutomationEditor/state.ts @@ -1,6 +1,8 @@ import { useState, useEffect } from 'react'; import { AutomationData, AutomationMetadata } from "types/automations"; - +import * as v from "types/validators/autmation"; +import { getFailures } from "types/validators/helper"; +import { MiniFailure } from '../../types/validators/helper'; export type EditorData = ReturnType; export type EditorState = { @@ -8,6 +10,10 @@ export type EditorState = { data: EditorData } | { status: 'loading' +} | { + status: 'invalid', + failures: MiniFailure[], + data: EditorData, } export type EditorStatus = EditorState['status']; @@ -20,7 +26,7 @@ export const useAutomatioEditorState = ( }); const makeUpdate = (name: K) => ( data: D - ) => state.status !== 'loading' && update({ + ) => ((state.status === 'changed') || (state.status === 'unchanged')) && update({ status: 'changed', data: { ...state.data, @@ -28,21 +34,46 @@ export const useAutomatioEditorState = ( } }) + const saveAndUpdate = (data: EditorData) => { + const cleanData = { + ...data, + tags: data.tags.reduce((all, [tagName, tagValue]) => ({ + ...all, + [tagName.trim()]: tagValue.trim(), + }), {}) + }; + update({ + status: "loading", + }) + onSave(cleanData); + } + useEffect(() => { if (automation) { - update({ - status: 'unchanged', - data: genEditorData(automation), - }) + const failures = getFailures(automation, v.AutomationData); + if (failures) { + update({ + status: 'invalid', + failures, + data: genEditorData(automation), + }) + } else { + update({ + status: 'unchanged', + data: genEditorData(automation), + }) + } } }, [automation]); return { + validate: (data: any) => getFailures(data, v.AutomationData), updateTrigger: makeUpdate('trigger'), updateSequence: makeUpdate('sequence'), updateCondition: makeUpdate('condition'), + saveAndUpdate, updateMetadata: (metadata: AutomationMetadata, tags: Array<[string, string]>) => { - if (state.status !== 'loading') { + if ((state.status === 'changed') || (state.status === 'unchanged')) { update({ status: 'changed', data: { @@ -55,17 +86,7 @@ export const useAutomatioEditorState = ( }, save: () => { if (state.status !== 'loading') { - const data = { - ...state.data, - tags: state.data.tags.reduce((all, [tagName, tagValue]) => ({ - ...all, - [tagName]: tagValue, - }), {}) - }; - update({ - status: "loading", - }) - onSave(data); + saveAndUpdate(state.data) } }, get state() { diff --git a/webapp/src/components/AutomationList/AutomationList.stories.tsx b/webapp/src/components/AutomationList/AutomationList.stories.tsx index 9c727a3..e0d5d2e 100644 --- a/webapp/src/components/AutomationList/AutomationList.stories.tsx +++ b/webapp/src/components/AutomationList/AutomationList.stories.tsx @@ -64,3 +64,57 @@ FewAutos.args = { createMockAuto(), ], } + + + +export const BadAutmations = Template.bind({}) +BadAutmations.args = { + ...BadAutmations.args, + automations: [ + { + condition: [], + tags: {}, + metadata: { + id: "Bad Choose Sequence", + alias: "Bad Choose", + description: "Example Metadata", + trigger_variables: { + 'wowo': '!' + }, + mode: 'single', + }, + trigger: [], + sequence: [ + { + choose: {} + } + ] as any + }, + { + condition: [], + tags: {}, + metadata: { + id: "random", + alias: "Bad Trigger", + description: "Example Metadata", + trigger_variables: { + 'wowo': '!' + }, + mode: 'single', + }, + trigger: [ + "haha I am a string" + ] as any, + sequence: [] + }, + { + condition: [], + tags: {}, + metadata: { + } as any, + trigger: [ + ], + sequence: [] + } + ], +} diff --git a/webapp/src/components/AutomationList/AutomationListBox.tsx b/webapp/src/components/AutomationList/AutomationListBox.tsx index 3dd61f9..ebb09f3 100644 --- a/webapp/src/components/AutomationList/AutomationListBox.tsx +++ b/webapp/src/components/AutomationList/AutomationListBox.tsx @@ -1,6 +1,6 @@ import "./AutomationListBox.css"; import { FC, useState } from 'react'; -import { AutomationData } from "types/automations"; +import { AutomationData, AutomationMetadata } from "types/automations"; import InputMultiSelect from "components/Inputs/InputMultiSelect"; import InputText from "components/Inputs/InputText"; import { Button } from "components/Inputs/Button"; @@ -65,6 +65,9 @@ export const getTagList = (autos: AutomationData[]): string[] => Object.keys(aut }, {})) const filterAutomations = (autos: AutomationData[], searchText: string, selected: number[], tags: string[]): Array<[AutomationData, number]> => autos.map<[AutomationData, number]>((a, i) => [a, i]).filter(([a, i]) => { + if (!a.metadata) { + return true + } if (searchText.length > 0) { if ( !( @@ -130,25 +133,17 @@ const convertGroupsToItems = ( if (Array.isArray(groups)) { return groups.map(i => { const [auto, autoIndex] = autos[i]; + let title = "BadAuto<>" + if (auto.metadata) { + title = `Name = ${auto.metadata.alias}\nID = ${auto.metadata.id}\nDescription = ${auto.metadata.description}` + } return
onSelectAutomation(autoIndex)} > -
- {auto.metadata.alias.slice(0, 15)} ({auto.metadata.id.slice(0, 5)}) - {auto.metadata.description.slice(0, 25)} -
- {Object.keys(auto.tags).map(tagName => - {tagName}: {auto.tags[tagName]} - )} -
-
+
}) @@ -167,6 +162,31 @@ const convertGroupsToItems = ( } } +export const MetadataBox: FC<{ + metadata: AutomationMetadata, + tags: Record, +}> = (auto) => { + let title = {"BadAuto<>"} + if (auto.metadata) { + title = <> + {String(auto.metadata.alias).slice(0, 15)} ({String(auto.metadata.id).slice(0, 5)}) + {String(auto.metadata.description).slice(0, 25)} + + } + return
+ {title} +
+ {Object.keys(auto.tags).map(tagName => + {tagName}: {auto.tags[tagName]} + )} +
+
+} + const AutomationListBoxGroup: FC<{ groupName: string, diff --git a/webapp/src/components/DAGFlow/DAGCircle.tsx b/webapp/src/components/DAGFlow/DAGCircle.tsx index 76d64d5..093e5ac 100644 --- a/webapp/src/components/DAGFlow/DAGCircle.tsx +++ b/webapp/src/components/DAGFlow/DAGCircle.tsx @@ -1,5 +1,5 @@ import { FC } from "react"; -import { AddIcon, PencilIcon, TrashIcon } from '../Icons/index'; +import { AddIcon, TrashIcon } from '../Icons/index'; import { useCircleStyles } from './styles'; import { Handle, Position, XYPosition } from 'react-flow-renderer'; diff --git a/webapp/src/components/DAGFlow/flowDataMods.ts b/webapp/src/components/DAGFlow/flowDataMods.ts index 22db4fc..79b9c60 100644 --- a/webapp/src/components/DAGFlow/flowDataMods.ts +++ b/webapp/src/components/DAGFlow/flowDataMods.ts @@ -1,5 +1,5 @@ import { makeFlowCircle } from "./DAGCircle" -import { DAGAutomationFlowDims, FlowData } from "./types" +import { DAGAutomationFlowDims } from "./types" import { XYPosition } from 'react-flow-renderer'; export const makeAddButton = ( diff --git a/webapp/src/components/DAGFlow/index.tsx b/webapp/src/components/DAGFlow/index.tsx index 6292742..c48cd13 100644 --- a/webapp/src/components/DAGFlow/index.tsx +++ b/webapp/src/components/DAGFlow/index.tsx @@ -20,7 +20,18 @@ const nodeTypes = { 'dagcircle': DAGCircle, } -interface Props { +const makeOnEditAutomationConditions = ( + conditions: AutomationCondition[], + updateConditions: (c: AutomationCondition[]) => void, + openModal: UpdateModalState, +) => () => openModal({ + single: false, + node: conditions, + allowedTypes: ['condition'], + update: c => updateConditions(c as any), +}) + +export interface DAGAutomationFlowProps { className?: string; trigger: AutomationTrigger[]; condition: AutomationCondition[]; @@ -31,7 +42,7 @@ interface Props { onConditionUpdate: (s: AutomationCondition[]) => void; } -export const DAGAutomationFlow: FC = ({ +export const DAGAutomationFlow: FC = ({ className, trigger, condition, @@ -131,14 +142,3 @@ export const DAGAutomationFlow: FC = ({ ; } - -const makeOnEditAutomationConditions = ( - conditions: AutomationCondition[], - updateConditions: (c: AutomationCondition[]) => void, - openModal: UpdateModalState, -) => () => openModal({ - single: false, - node: conditions, - allowedTypes: ['condition'], - update: c => updateConditions(c as any), -}) \ No newline at end of file diff --git a/webapp/src/components/DAGFlow/safe.css b/webapp/src/components/DAGFlow/safe.css new file mode 100644 index 0000000..98196bd --- /dev/null +++ b/webapp/src/components/DAGFlow/safe.css @@ -0,0 +1,4 @@ +.dag-flow-safe { + height: 100%; + overflow: scroll; +} \ No newline at end of file diff --git a/webapp/src/components/DAGFlow/safe.tsx b/webapp/src/components/DAGFlow/safe.tsx new file mode 100644 index 0000000..5514a78 --- /dev/null +++ b/webapp/src/components/DAGFlow/safe.tsx @@ -0,0 +1,84 @@ +import "./safe.css"; +import { Component, ErrorInfo } from "react"; +import { DAGAutomationFlow, DAGAutomationFlowProps } from "."; +import { AutomationSequenceNode } from "types/automations"; +import { AutomationCondition } from "types/automations/conditions"; +import { AutomationTrigger } from 'types/automations/triggers'; +import InputYaml from "components/Inputs/InputYaml"; +import { Button } from "components/Inputs/Button"; + +type GoodState = { + hasError: false; +} +type FailedStateData = { + sequence: AutomationSequenceNode[], + condition: AutomationCondition[], + trigger: AutomationTrigger[], +} +type FailedState = { + hasError: true, + error: any, + errorInfo?: ErrorInfo, +} & FailedStateData +type State = GoodState | FailedState +export class SafeDAGAutomationFlow extends Component { + + state: State = { + hasError: false + } + + componentDidCatch(error: Error, errorInfo: ErrorInfo) { + this.setState({ + hasError: true, + error, + errorInfo, + sequence: this.props.sequence, + condition: this.props.condition, + trigger: this.props.trigger, + }) + } + + render() { + if (this.state.hasError) { + const makeSet = (k: K) => (d: FailedStateData[K]) => this.setState({ + ...this.state, + [k]: d, + }); + const makeSave = (k: K) => () => { + if (!this.state.hasError) { + return + } + if (k === 'condition') { + this.props.onConditionUpdate(this.state.condition) + } else if (k === 'sequence') { + this.props.onSequenceUpdate(this.state.sequence) + } else if (k === 'trigger') { + this.props.onTriggerUpdate(this.state.trigger) + } + } + return
+

An Error has occured.

+ +

Failed to Open Autmation!

+ Something is likely not configured in your automation properly. +
+

Error:

+

{String(this.state.error)}

+
+ {JSON.stringify(this.state.error, null, 4)} + {this.state.errorInfo && this.state.errorInfo.componentStack.split('\n').map((s, i) => <> + {s}
+ )} +

Automation YAML

+ + + + + + +
+ } + + return ; + } +} \ No newline at end of file diff --git a/webapp/src/components/DAGFlow/triggerConvertor.ts b/webapp/src/components/DAGFlow/triggerConvertor.ts index 530c5ba..b98a9af 100644 --- a/webapp/src/components/DAGFlow/triggerConvertor.ts +++ b/webapp/src/components/DAGFlow/triggerConvertor.ts @@ -1,6 +1,5 @@ import { AutomationTrigger } from 'types/automations/triggers'; import { DAGAutomationFlowDims, FlowData, TriggerMakerOptions } from './types'; -import { makeFlowCircle } from './DAGCircle'; import { makeAddButton } from './flowDataMods'; export const triggerToFlow = ( @@ -14,7 +13,6 @@ export const triggerToFlow = ( distanceFactor, nodeHeight, nodeWidth, - circleSize, padding, conditionHeight, } = dims; diff --git a/webapp/src/components/Inputs/InputBoolean.tsx b/webapp/src/components/Inputs/InputBoolean.tsx index 063b9d8..4482d6b 100644 --- a/webapp/src/components/Inputs/InputBoolean.tsx +++ b/webapp/src/components/Inputs/InputBoolean.tsx @@ -1,5 +1,4 @@ import "./InputBoolean.css"; -import InputWrapper from "./InputWrapper"; export interface Props { label: string; diff --git a/webapp/src/components/Inputs/InputYaml.tsx b/webapp/src/components/Inputs/InputYaml.tsx index 6b6ebff..bdedd4a 100644 --- a/webapp/src/components/Inputs/InputYaml.tsx +++ b/webapp/src/components/Inputs/InputYaml.tsx @@ -1,7 +1,7 @@ import * as yaml from "js-yaml"; import { useState } from "react"; import InputTextArea from "./InputTextArea"; -import { useDelayedFunction, useDelayEffect } from 'utils/useDelay'; +import { useDelayEffect } from 'utils/useDelay'; export interface Props { label: string; diff --git a/webapp/src/components/NodeEditor/OptionManager/index.tsx b/webapp/src/components/NodeEditor/OptionManager/index.tsx index db351ed..56b4fee 100644 --- a/webapp/src/components/NodeEditor/OptionManager/index.tsx +++ b/webapp/src/components/NodeEditor/OptionManager/index.tsx @@ -8,10 +8,6 @@ import InputYaml from 'components/Inputs/InputYaml'; type UseState = (s: S) => [S, Dispatch>] -const mockUseState: UseState = s => { - return [s, () => { }] -} - export const useEditorNodeState = (originalNode: AutomationNode, uState: UseState = useState) => { const [allState, setAllState] = uState({ node: originalNode, diff --git a/webapp/src/components/NodeEditor/constants.ts b/webapp/src/components/NodeEditor/constants.ts index 2639c87..b2ab365 100644 --- a/webapp/src/components/NodeEditor/constants.ts +++ b/webapp/src/components/NodeEditor/constants.ts @@ -1,5 +1,4 @@ import { AutomationNodeSubtype, AutomationNodeTypes } from "types/automations"; -import { ActionType } from "types/automations/actions"; import { AutomationNode } from '../../types/automations/index'; diff --git a/webapp/src/types/automations/index.ts b/webapp/src/types/automations/index.ts index 60add1d..fa781df 100644 --- a/webapp/src/types/automations/index.ts +++ b/webapp/src/types/automations/index.ts @@ -1,15 +1,11 @@ +import * as st from 'superstruct' + import { ActionType, AutomationAction } from "./actions"; import { AutomationCondition, ConditionType } from "./conditions"; import { AutomationTrigger, TriggerType } from "./triggers"; +import * as mv from "types/validators/metadata"; - -export interface AutomationMetadata { - id: string; - alias: string; - description: string; - trigger_variables?: Record; - mode: "single" | "restart" | "queued" | "parallel"; -} +export type AutomationMetadata = st.Infer export interface AutomationData { metadata: AutomationMetadata; trigger: AutomationTrigger[]; diff --git a/webapp/src/types/automations/triggers.ts b/webapp/src/types/automations/triggers.ts index 672c5a8..02c865b 100644 --- a/webapp/src/types/automations/triggers.ts +++ b/webapp/src/types/automations/triggers.ts @@ -1,79 +1,24 @@ +import * as st from 'superstruct' import { AutomationTime } from "./common"; +import * as v from "types/validators/triggers"; interface AutomationTriggerBase { alias?: string; } -export interface AutomationTriggerEvent extends AutomationTriggerBase { - platform: 'event'; - event_type: string | string[]; - event_data?: any; - context?: any; -} -export interface AutomationTriggerHA extends AutomationTriggerBase { - platform: 'homeassistant'; - event: 'start' | 'shutdown'; -} -export interface AutomationTriggerMQTT extends AutomationTriggerBase { - platform: 'mqtt'; - topic: string; - payload: string; - value_template: string; -} -export interface AutomationTriggerNumericState extends AutomationTriggerBase { - platform: 'numeric_state'; - entity_id: string | string[]; - attribute?: string; - value_template?: string; - above?: string; - below?: string; - for?: AutomationTime; -} -export interface AutomationTriggerState extends AutomationTriggerBase { - platform: 'state'; - entity_id: string | string[]; - attribute?: string; - from?: string; - to?: string; - for?: AutomationTime; -} -export interface AutomationTriggerTag extends AutomationTriggerBase { - platform: 'tag'; - tag_id: string; - device_id: string | string[]; -} -export interface AutomationTriggerTemplate extends AutomationTriggerBase { - platform: 'template'; - value_template: string; - for?: AutomationTime; -} -export interface AutomationTriggerTime extends AutomationTriggerBase { - platform: 'time'; - at: AutomationTime; -} -export interface AutomationTriggerTimePattern extends AutomationTriggerBase { - platform: 'time_pattern'; - hours?: string; - minutes?: string; - seconds?: string; -} -export interface AutomationTriggerWebhook extends AutomationTriggerBase { - platform: 'webhook'; - webhook_id: string; -} -export interface AutomationTriggerZone extends AutomationTriggerBase { - platform: 'zone'; - entity_id: string | string[]; - zone: string; - event: 'enter' | 'leave'; -} -export interface AutomationTriggerDevice extends AutomationTriggerBase { - platform: 'device'; - device_id: string; - domain: string; - type: string; - subtype: string; -} +export type AutomationTriggerEvent = st.Infer; +export type AutomationTriggerHA = st.Infer; +export type AutomationTriggerMQTT = st.Infer; +export type AutomationTriggerNumericState = st.Infer; +export type AutomationTriggerState = st.Infer; +export type AutomationTriggerTag = st.Infer; +export type AutomationTriggerTemplate = st.Infer; +export type AutomationTriggerTime = st.Infer; +export type AutomationTriggerTimePattern = st.Infer; +export type AutomationTriggerWebhook = st.Infer; +export type AutomationTriggerZone = st.Infer; +export type AutomationTriggerDevice = st.Infer; + export type AutomationTrigger = | AutomationTriggerEvent | AutomationTriggerHA diff --git a/webapp/src/types/validators/actions.ts b/webapp/src/types/validators/actions.ts new file mode 100644 index 0000000..d1b5f10 --- /dev/null +++ b/webapp/src/types/validators/actions.ts @@ -0,0 +1,24 @@ +import * as st from 'superstruct' + + +const AutomationActionNodeBase = { + alias: st.optional(st.string()), + variables: st.optional(st.record(st.string(), st.any())), +} + +export const ServiceAction = st.object({ + ...AutomationActionNodeBase, + data: st.any(), + target: st.any(), + service: st.string(), +}) + +export const RepeatAction = st.object({ + ...AutomationActionNodeBase, + repeat: st.object({ + count: st.number(), + sequence: st.array(), + }) +}) + + diff --git a/webapp/src/types/validators/autmation.ts b/webapp/src/types/validators/autmation.ts new file mode 100644 index 0000000..7258b38 --- /dev/null +++ b/webapp/src/types/validators/autmation.ts @@ -0,0 +1,12 @@ +import * as st from 'superstruct' +import { AutomationMetadata } from './metadata' +import { AutomationTrigger } from './triggers'; + + +export const AutomationData = st.object({ + metadata: AutomationMetadata, + trigger: st.array(AutomationTrigger), + condition: st.array(st.object()), + sequence: st.array(st.object()), + tags: st.record(st.string(), st.string()), +}) \ No newline at end of file diff --git a/webapp/src/types/validators/common.ts b/webapp/src/types/validators/common.ts new file mode 100644 index 0000000..aae2c6c --- /dev/null +++ b/webapp/src/types/validators/common.ts @@ -0,0 +1,9 @@ +import * as st from 'superstruct' + + +export const AutomationTime = st.object({ + hours: st.optional(st.number()), + minutes: st.optional(st.number()), + seconds: st.optional(st.number()), + milliseconds: st.optional(st.number()), +}) diff --git a/webapp/src/types/validators/helper.ts b/webapp/src/types/validators/helper.ts new file mode 100644 index 0000000..8ebaa55 --- /dev/null +++ b/webapp/src/types/validators/helper.ts @@ -0,0 +1,31 @@ +import * as st from 'superstruct'; + +export type MiniFailure = { + path: string, + message: string[], +} + +export const getFailures = (value: unknown, struct: st.Struct): MiniFailure[] | null => { + try { + st.assert(value, struct) + } catch (err) { + if (err instanceof st.StructError) { + const failureMap = err.failures().reduce((all: Record> = {}, next) => { + const path = next.path.join('.'); + if (all[path]) { + all[path].add(next.message) + } else { + all[path] = new Set([next.message]) + } + return all + }, {}) + return Object.keys(failureMap).map((path) => ({ + path, + message: Array.from(failureMap[path].values()) + })) + } + throw err + } + + return null +} \ No newline at end of file diff --git a/webapp/src/types/validators/index.test.ts b/webapp/src/types/validators/index.test.ts new file mode 100644 index 0000000..3bbc702 --- /dev/null +++ b/webapp/src/types/validators/index.test.ts @@ -0,0 +1,24 @@ +import * as st from "superstruct"; +import { AutomationMetadata } from "./metadata"; +import { AutomationData } from './autmation'; +import { getFailures } from './helper'; + +test('superstructure is', () => { + const badCheck = st.is({}, AutomationMetadata); + expect(badCheck).toBeFalsy() +}) + +test('getFailures returns failures', () => { + const failures = getFailures({ metadata: {} }, AutomationData); + expect(failures).toHaveLength(8) +}) + +test('getFailures returns null', () => { + const failures = getFailures({ + id: "test", + alias: "hey", + description: "wow", + mode: "single", + }, AutomationMetadata); + expect(failures).toBeNull() +}) \ No newline at end of file diff --git a/webapp/src/types/validators/metadata.ts b/webapp/src/types/validators/metadata.ts new file mode 100644 index 0000000..2e272a2 --- /dev/null +++ b/webapp/src/types/validators/metadata.ts @@ -0,0 +1,10 @@ +import * as st from 'superstruct' + + +export const AutomationMetadata = st.object({ + id: st.string(), + alias: st.string(), + description: st.string(), + trigger_variables: st.optional(st.nullable(st.record(st.string(), st.string()))), + mode: st.enums(["single", "restart", "queued", "parallel"]), +}) \ No newline at end of file diff --git a/webapp/src/types/validators/triggers.ts b/webapp/src/types/validators/triggers.ts new file mode 100644 index 0000000..4079dfa --- /dev/null +++ b/webapp/src/types/validators/triggers.ts @@ -0,0 +1,117 @@ +import * as st from 'superstruct' +import { AutomationTime } from './common' + + +const AutomationTriggerBase = { + alias: st.optional(st.string()) +} + +export const AutomationTriggerEvent = st.object({ + ...AutomationTriggerBase, + platform: st.literal('event'), + event_type: st.union([st.string(), st.array(st.string())]), + event_data: st.any(), + context: st.any(), +}) + +export const AutomationTriggerHA = st.object({ + ...AutomationTriggerBase, + platform: st.literal('homeassistant'), + event: st.enums(['start', 'shutdown']), +}) + +export const AutomationTriggerMQTT = st.object({ + ...AutomationTriggerBase, + platform: st.literal('mqtt'), + topic: st.string(), + payload: st.string(), + value_template: st.string(), +}) + +export const AutomationTriggerNumericState = st.object({ + ...AutomationTriggerBase, + platform: st.literal('numeric_state'), + entity_id: st.union([st.string(), st.array(st.string())]), + attribute: st.optional(st.string()), + value_template: st.optional(st.string()), + above: st.optional(st.string()), + below: st.optional(st.string()), + for: st.optional(AutomationTime), +}) + +export const AutomationTriggerState = st.object({ + ...AutomationTriggerBase, + platform: st.literal('state'), + entity_id: st.union([st.string(), st.array(st.string())]), + attribute: st.optional(st.string()), + from: st.optional(st.string()), + to: st.optional(st.string()), + for: st.optional(AutomationTime), +}) + +export const AutomationTriggerTag = st.object({ + ...AutomationTriggerBase, + platform: st.literal('tag'), + tag_id: st.string(), + device_id: st.union([st.string(), st.array(st.string())]), +}) + +export const AutomationTriggerTemplate = st.object({ + ...AutomationTriggerBase, + platform: st.literal('template'), + value_template: st.string(), + for: st.optional(AutomationTime), +}) + +export const AutomationTriggerTime = st.object({ + ...AutomationTriggerBase, + platform: st.literal('time'), + at: AutomationTime, +}) + +export const AutomationTriggerTimePattern = st.object({ + ...AutomationTriggerBase, + platform: st.literal('time_pattern'), + hours: st.optional(st.string()), + minutes: st.optional(st.string()), + seconds: st.optional(st.string()), +}) + +export const AutomationTriggerWebhook = st.object({ + ...AutomationTriggerBase, + platform: st.literal('webhook'), + webhook_id: st.string(), +}) + +export const AutomationTriggerZone = st.object({ + ...AutomationTriggerBase, + platform: st.literal('zone'), + entity_id: st.union([st.string(), st.array(st.string())]), + zone: st.string(), + event: st.enums(['enter', 'leave']) +}) + +export const AutomationTriggerDevice = st.object({ + ...AutomationTriggerBase, + platform: st.literal('device'), + device_id: st.string(), + domain: st.string(), + type: st.string(), + subtype: st.string(), +}) + + +export const AutomationTrigger = st.union([ + AutomationTriggerEvent, + AutomationTriggerHA, + AutomationTriggerMQTT, + AutomationTriggerNumericState, + AutomationTriggerState, + AutomationTriggerTag, + AutomationTriggerTemplate, + AutomationTriggerTime, + AutomationTriggerTimePattern, + AutomationTriggerWebhook, + AutomationTriggerZone, + AutomationTriggerDevice +]) \ No newline at end of file diff --git a/webapp/src/utils/useDelay.ts b/webapp/src/utils/useDelay.ts index 0221394..108356d 100644 --- a/webapp/src/utils/useDelay.ts +++ b/webapp/src/utils/useDelay.ts @@ -5,7 +5,7 @@ export const useDelayEffect = (cb: () => void, deps: any[], timeout: number) => const fcn = useDelayedFunction(cb, timeout); useEffect(() => { fcn() - }, [deps]) + }, deps) } export const useDelayedFunction = ( diff --git a/webapp/src/utils/useWindowSize.ts b/webapp/src/utils/useWindowSize.ts index 50c0f39..b0b5784 100644 --- a/webapp/src/utils/useWindowSize.ts +++ b/webapp/src/utils/useWindowSize.ts @@ -16,8 +16,6 @@ export default function useWindowSize(mobileRatioInd: number = 0.8): Size { const [windowSize, setWindowSize] = useState(makeUpdate(window, mobileRatioInd)); // alias - - useEffect(() => { // Handler to call on window resize function handleResize() { @@ -33,7 +31,7 @@ export default function useWindowSize(mobileRatioInd: number = 0.8): Size { // Remove event listener on cleanup return () => window.removeEventListener("resize", handleResize); - }, []); // Empty array ensures that effect is only run on mount + }, [mobileRatioInd]); // Empty array ensures that effect is only run on mount return windowSize; } diff --git a/webapp/yarn.lock b/webapp/yarn.lock index 70f621b..9eb346d 100644 --- a/webapp/yarn.lock +++ b/webapp/yarn.lock @@ -15937,6 +15937,11 @@ stylehacks@^4.0.0: postcss "^7.0.0" postcss-selector-parser "^3.0.0" +superstruct@^0.15.4: + version "0.15.4" + resolved "https://registry.yarnpkg.com/superstruct/-/superstruct-0.15.4.tgz#e3381dd84ca07e704e19f69eda74eee1a5efb1f9" + integrity sha512-eOoMeSbP9ZJChNOm/9RYjE+F36rYR966AAqeG3xhQB02j2sfAUXDp4EQ/7bAOqnlJnuFDB8yvOu50SocvKpUEw== + supports-color@^5.3.0: version "5.5.0" resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.5.0.tgz#e2e69a44ac8772f78a1ec0b35b689df6530efc8f"