From 1ce8bf170cda2afab334cd330325cd4fbb97dab4 Mon Sep 17 00:00:00 2001 From: Fabian Mastenbroek Date: Wed, 7 Jul 2021 11:46:57 +0200 Subject: ui: Split App container into separate components This change splits the App container into separate pages, as a starting point for removing much of the unnecessary state from Redux. --- opendc-web/opendc-web-ui/src/api/topologies.js | 2 +- .../src/components/app/map/MapStageComponent.js | 11 +- opendc-web/opendc-web-ui/src/containers/app/App.js | 111 --------------------- .../app/sidebars/project/PortfolioListContainer.js | 7 +- .../app/sidebars/project/ScenarioListContainer.js | 11 +- .../app/sidebars/project/TopologyListContainer.js | 4 +- opendc-web/opendc-web-ui/src/data/project.js | 7 ++ .../src/pages/projects/[project]/index.js | 16 +-- .../projects/[project]/portfolios/[portfolio].js | 45 +++++++-- .../projects/[project]/topologies/[topology].js | 81 +++++++++++++++ 10 files changed, 149 insertions(+), 146 deletions(-) delete mode 100644 opendc-web/opendc-web-ui/src/containers/app/App.js create mode 100644 opendc-web/opendc-web-ui/src/pages/projects/[project]/topologies/[topology].js diff --git a/opendc-web/opendc-web-ui/src/api/topologies.js b/opendc-web/opendc-web-ui/src/api/topologies.js index 802be4bb..40685094 100644 --- a/opendc-web/opendc-web-ui/src/api/topologies.js +++ b/opendc-web/opendc-web-ui/src/api/topologies.js @@ -31,7 +31,7 @@ export function getTopology(auth, topologyId) { } export function updateTopology(auth, topology) { - const { _id, ...data } = topology; + const { _id, ...data } = topology return request(auth, `topologies/${topology._id}`, 'PUT', { topology: data }) } diff --git a/opendc-web/opendc-web-ui/src/components/app/map/MapStageComponent.js b/opendc-web/opendc-web-ui/src/components/app/map/MapStageComponent.js index 07b2d8f0..a8e156ec 100644 --- a/opendc-web/opendc-web-ui/src/components/app/map/MapStageComponent.js +++ b/opendc-web/opendc-web-ui/src/components/app/map/MapStageComponent.js @@ -1,3 +1,4 @@ +/* eslint-disable react-hooks/exhaustive-deps */ import PropTypes from 'prop-types' import React, { useEffect, useRef, useState } from 'react' import { HotKeys } from 'react-hotkeys' @@ -37,10 +38,12 @@ function MapStageComponent({ setPos([mousePos.x, mousePos.y]) } - useEffect(() => { - const updateDimensions = () => setMapDimensions(window.innerWidth, window.innerHeight - NAVBAR_HEIGHT) - const updateScale = (e) => zoomInOnPosition(e.deltaY < 0, x, y) + const updateDimensions = () => setMapDimensions(window.innerWidth, window.innerHeight - NAVBAR_HEIGHT) + const updateScale = (e) => zoomInOnPosition(e.deltaY < 0, x, y) + // We explicitly do not specify any dependencies to prevent infinitely dispatching updateDimensions commands + // eslint-disable-next-line react-hooks/exhaustive-deps + useEffect(() => { updateDimensions() window.addEventListener('resize', updateDimensions) @@ -57,7 +60,7 @@ function MapStageComponent({ window.removeEventListener('resize', updateDimensions) window.removeEventListener('wheel', updateScale) } - }, [x, y, setMapDimensions, zoomInOnPosition]) + }, []) const store = useStore() diff --git a/opendc-web/opendc-web-ui/src/containers/app/App.js b/opendc-web/opendc-web-ui/src/containers/app/App.js deleted file mode 100644 index ec9714ce..00000000 --- a/opendc-web/opendc-web-ui/src/containers/app/App.js +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (c) 2021 AtLarge Research - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -import PropTypes from 'prop-types' -import React, { useEffect } from 'react' -import Head from 'next/head' -import { HotKeys } from 'react-hotkeys' -import { useDispatch, useSelector } from 'react-redux' -import { openPortfolioSucceeded } from '../../redux/actions/portfolios' -import { openProjectSucceeded } from '../../redux/actions/projects' -import ToolPanelComponent from '../../components/app/map/controls/ToolPanelComponent' -import LoadingScreen from '../../components/app/map/LoadingScreen' -import ScaleIndicatorContainer from '../../containers/app/map/controls/ScaleIndicatorContainer' -import MapStage from '../../containers/app/map/MapStage' -import TopologySidebarContainer from '../../containers/app/sidebars/topology/TopologySidebarContainer' -import AppNavbarContainer from '../../containers/navigation/AppNavbarContainer' -import ProjectSidebarContainer from '../../containers/app/sidebars/project/ProjectSidebarContainer' -import { openScenarioSucceeded } from '../../redux/actions/scenarios' -import PortfolioResultsContainer from '../../containers/app/results/PortfolioResultsContainer' -import { KeymapConfiguration } from '../../hotkeys' -import { useRequireAuth } from '../../auth' -import { useActiveProject } from '../../data/project' - -const App = ({ projectId, portfolioId, scenarioId }) => { - useRequireAuth() - - const projectName = useActiveProject()?.name - const topologyIsLoading = useSelector((state) => state.currentTopologyId === '-1') - - const dispatch = useDispatch() - useEffect(() => { - if (scenarioId) { - dispatch(openScenarioSucceeded(projectId, portfolioId, scenarioId)) - } else if (portfolioId) { - dispatch(openPortfolioSucceeded(projectId, portfolioId)) - } else { - dispatch(openProjectSucceeded(projectId)) - } - }, [projectId, portfolioId, scenarioId, dispatch]) - - const constructionElements = topologyIsLoading ? ( -
- -
- ) : ( -
- - - - - -
- ) - - const portfolioElements = ( -
- -
- -
-
- ) - - const scenarioElements = ( -
- -
-

Scenario loading

-
-
- ) - - const title = projectName ? projectName + ' - OpenDC' : 'Simulation - OpenDC' - - return ( - - - {title} - - - {scenarioId ? scenarioElements : portfolioId ? portfolioElements : constructionElements} - - ) -} - -App.propTypes = { - projectId: PropTypes.string.isRequired, - portfolioId: PropTypes.string, - scenarioId: PropTypes.string, -} - -export default App diff --git a/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/PortfolioListContainer.js b/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/PortfolioListContainer.js index a36997ff..28d7f0d1 100644 --- a/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/PortfolioListContainer.js +++ b/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/PortfolioListContainer.js @@ -6,16 +6,15 @@ import { addPortfolio, deletePortfolio, setCurrentPortfolio } from '../../../../ import { getState } from '../../../../util/state-utils' import { setCurrentTopology } from '../../../../redux/actions/topology/building' import NewPortfolioModalComponent from '../../../../components/modals/custom-components/NewPortfolioModalComponent' -import { useActivePortfolio, useActiveProject, usePortfolios } from '../../../../data/project' +import { usePortfolios } from '../../../../data/project' const PortfolioListContainer = () => { - const currentProjectId = useActiveProject()?._id - const currentPortfolioId = useActivePortfolio()?._id + const router = useRouter() + const { project: currentProjectId, portfolio: currentPortfolioId } = router.query const portfolios = usePortfolios(currentProjectId) const dispatch = useDispatch() const [isVisible, setVisible] = useState(false) - const router = useRouter() const actions = { onNewPortfolio: () => setVisible(true), onChoosePortfolio: (portfolioId) => { diff --git a/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/ScenarioListContainer.js b/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/ScenarioListContainer.js index e1be51dc..10743401 100644 --- a/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/ScenarioListContainer.js +++ b/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/ScenarioListContainer.js @@ -1,3 +1,4 @@ +import PropTypes from 'prop-types' import React, { useState } from 'react' import { useDispatch } from 'react-redux' import ScenarioListComponent from '../../../../components/app/sidebars/project/ScenarioListComponent' @@ -5,11 +6,13 @@ import { addScenario, deleteScenario, setCurrentScenario } from '../../../../red import { setCurrentPortfolio } from '../../../../redux/actions/portfolios' import NewScenarioModalComponent from '../../../../components/modals/custom-components/NewScenarioModalComponent' import { useProjectTopologies } from '../../../../data/topology' -import { useActiveScenario, useActiveProject, useScenarios } from '../../../../data/project' +import { useActiveScenario, useScenarios } from '../../../../data/project' import { useSchedulers, useTraces } from '../../../../data/experiments' +import { useRouter } from 'next/router' const ScenarioListContainer = ({ portfolioId }) => { - const currentProjectId = useActiveProject()?._id + const router = useRouter() + const { project: currentProjectId } = router.query const currentScenarioId = useActiveScenario()?._id const scenarios = useScenarios(portfolioId) const topologies = useProjectTopologies() @@ -71,4 +74,8 @@ const ScenarioListContainer = ({ portfolioId }) => { ) } +ScenarioListContainer.propTypes = { + portfolioId: PropTypes.string.isRequired, +} + export default ScenarioListContainer diff --git a/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/TopologyListContainer.js b/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/TopologyListContainer.js index 266ca495..648c4500 100644 --- a/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/TopologyListContainer.js +++ b/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/TopologyListContainer.js @@ -18,14 +18,14 @@ const TopologyListContainer = () => { const onChooseTopology = async (id) => { dispatch(setCurrentTopology(id)) const state = await getState(dispatch) - router.push(`/projects/${state.currentProjectId}`) + await router.push(`/projects/${state.currentProjectId}/topologies/${id}`) } const onDeleteTopology = async (id) => { if (id) { const state = await getState(dispatch) dispatch(deleteTopology(id)) dispatch(setCurrentTopology(state.objects.project[state.currentProjectId].topologyIds[0])) - router.push(`/projects/${state.currentProjectId}`) + await router.push(`/projects/${state.currentProjectId}`) } } const onCreateTopology = (name) => { diff --git a/opendc-web/opendc-web-ui/src/data/project.js b/opendc-web/opendc-web-ui/src/data/project.js index de2bc0d3..d4c95370 100644 --- a/opendc-web/opendc-web-ui/src/data/project.js +++ b/opendc-web/opendc-web-ui/src/data/project.js @@ -29,6 +29,13 @@ export function useProjects() { return useSelector((state) => state.projects) } +/** + * Return the project with the specified identifier. + */ +export function useProject(projectId) { + return useSelector((state) => state.projects[projectId]) +} + /** * Return the current active project. */ diff --git a/opendc-web/opendc-web-ui/src/pages/projects/[project]/index.js b/opendc-web/opendc-web-ui/src/pages/projects/[project]/index.js index 72316bc9..cce887aa 100644 --- a/opendc-web/opendc-web-ui/src/pages/projects/[project]/index.js +++ b/opendc-web/opendc-web-ui/src/pages/projects/[project]/index.js @@ -20,18 +20,6 @@ * SOFTWARE. */ -import { useRouter } from 'next/router' -import App from '../../../containers/app/App' +import Topology from './topologies/[topology]' -function Project() { - const router = useRouter() - const { project } = router.query - - if (project) { - return - } - - return
-} - -export default Project +export default Topology diff --git a/opendc-web/opendc-web-ui/src/pages/projects/[project]/portfolios/[portfolio].js b/opendc-web/opendc-web-ui/src/pages/projects/[project]/portfolios/[portfolio].js index 76a8d23b..b21db44c 100644 --- a/opendc-web/opendc-web-ui/src/pages/projects/[project]/portfolios/[portfolio].js +++ b/opendc-web/opendc-web-ui/src/pages/projects/[project]/portfolios/[portfolio].js @@ -21,17 +21,46 @@ */ import { useRouter } from 'next/router' -import App from '../../../../containers/app/App' +import Head from 'next/head' +import AppNavbarContainer from '../../../../containers/navigation/AppNavbarContainer' +import React, { useEffect } from 'react' +import { useProject } from '../../../../data/project' +import ProjectSidebarContainer from '../../../../containers/app/sidebars/project/ProjectSidebarContainer' +import PortfolioResultsContainer from '../../../../containers/app/results/PortfolioResultsContainer' +import { useDispatch } from 'react-redux' +import { openPortfolioSucceeded } from '../../../../redux/actions/portfolios' -function Project() { +/** + * Page that displays the results in a portfolio. + */ +function Portfolio() { const router = useRouter() - const { project, portfolio } = router.query + const { project: projectId, portfolio: portfolioId } = router.query + + const project = useProject(projectId) + const title = project?.name ? project?.name + ' - OpenDC' : 'Simulation - OpenDC' - if (project && portfolio) { - return - } + const dispatch = useDispatch() + useEffect(() => { + if (portfolioId) { + dispatch(openPortfolioSucceeded(projectId, portfolioId)) + } + }, [projectId, portfolioId, dispatch]) - return
+ return ( +
+ + {title} + + +
+ +
+ +
+
+
+ ) } -export default Project +export default Portfolio diff --git a/opendc-web/opendc-web-ui/src/pages/projects/[project]/topologies/[topology].js b/opendc-web/opendc-web-ui/src/pages/projects/[project]/topologies/[topology].js new file mode 100644 index 00000000..28db1531 --- /dev/null +++ b/opendc-web/opendc-web-ui/src/pages/projects/[project]/topologies/[topology].js @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2021 AtLarge Research + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import { useRouter } from 'next/router' +import { useProject } from '../../../../data/project' +import { useDispatch, useSelector } from 'react-redux' +import React, { useEffect } from 'react' +import { openProjectSucceeded } from '../../../../redux/actions/projects' +import { HotKeys } from 'react-hotkeys' +import { KeymapConfiguration } from '../../../../hotkeys' +import Head from 'next/head' +import AppNavbarContainer from '../../../../containers/navigation/AppNavbarContainer' +import LoadingScreen from '../../../../components/app/map/LoadingScreen' +import MapStage from '../../../../containers/app/map/MapStage' +import ScaleIndicatorContainer from '../../../../containers/app/map/controls/ScaleIndicatorContainer' +import ToolPanelComponent from '../../../../components/app/map/controls/ToolPanelComponent' +import ProjectSidebarContainer from '../../../../containers/app/sidebars/project/ProjectSidebarContainer' +import TopologySidebarContainer from '../../../../containers/app/sidebars/topology/TopologySidebarContainer' + +/** + * Page that displays a datacenter topology. + */ +function Topology() { + const router = useRouter() + const { project: projectId, topology: topologyId } = router.query + + const project = useProject(projectId) + const title = project?.name ? project?.name + ' - OpenDC' : 'Simulation - OpenDC' + + const dispatch = useDispatch() + useEffect(() => { + if (projectId) { + dispatch(openProjectSucceeded(projectId)) + } + }, [projectId, topologyId, dispatch]) + + const topologyIsLoading = useSelector((state) => state.currentTopologyId === '-1') + + return ( + + + {title} + + + {topologyIsLoading ? ( +
+ +
+ ) : ( +
+ + + + + +
+ )} +
+ ) +} + +export default Topology -- cgit v1.2.3 From aa788a3ad18badfac8beaabdaffc88b9e52f9306 Mon Sep 17 00:00:00 2001 From: Fabian Mastenbroek Date: Wed, 7 Jul 2021 15:07:11 +0200 Subject: ui: Remove current ids state from Redux This change removes the current active identifiers from the Redux state. Instead, we use the router query to track the active project, portfolio and topology. --- .../app/sidebars/project/PortfolioListComponent.js | 2 +- .../app/sidebars/project/ScenarioListComponent.js | 38 ++--------------- .../app/results/PortfolioResultsContainer.js | 13 +++--- .../app/sidebars/project/PortfolioListContainer.js | 12 +++--- .../app/sidebars/project/ScenarioListContainer.js | 14 ++----- .../app/sidebars/project/TopologyListContainer.js | 14 +++---- opendc-web/opendc-web-ui/src/data/project.js | 21 ++-------- opendc-web/opendc-web-ui/src/data/topology.js | 7 +++- .../opendc-web-ui/src/redux/actions/portfolios.js | 11 +---- .../opendc-web-ui/src/redux/actions/scenarios.js | 9 ---- .../opendc-web-ui/src/redux/actions/topologies.js | 3 +- .../src/redux/reducers/current-ids.js | 44 -------------------- .../opendc-web-ui/src/redux/reducers/index.js | 5 +-- .../opendc-web-ui/src/redux/sagas/portfolios.js | 48 +++++++++++----------- .../opendc-web-ui/src/redux/sagas/projects.js | 2 +- .../opendc-web-ui/src/redux/sagas/scenarios.js | 8 ++-- .../opendc-web-ui/src/redux/sagas/topology.js | 28 +++++-------- 17 files changed, 80 insertions(+), 199 deletions(-) diff --git a/opendc-web/opendc-web-ui/src/components/app/sidebars/project/PortfolioListComponent.js b/opendc-web/opendc-web-ui/src/components/app/sidebars/project/PortfolioListComponent.js index ce271819..b948b747 100644 --- a/opendc-web/opendc-web-ui/src/components/app/sidebars/project/PortfolioListComponent.js +++ b/opendc-web/opendc-web-ui/src/components/app/sidebars/project/PortfolioListComponent.js @@ -61,7 +61,7 @@ function PortfolioListComponent({ PortfolioListComponent.propTypes = { portfolios: PropTypes.arrayOf(Portfolio), - currentProjectId: PropTypes.string.isRequired, + currentProjectId: PropTypes.string, currentPortfolioId: PropTypes.string, onNewPortfolio: PropTypes.func.isRequired, onChoosePortfolio: PropTypes.func.isRequired, diff --git a/opendc-web/opendc-web-ui/src/components/app/sidebars/project/ScenarioListComponent.js b/opendc-web/opendc-web-ui/src/components/app/sidebars/project/ScenarioListComponent.js index f990dfcb..e81d2b78 100644 --- a/opendc-web/opendc-web-ui/src/components/app/sidebars/project/ScenarioListComponent.js +++ b/opendc-web/opendc-web-ui/src/components/app/sidebars/project/ScenarioListComponent.js @@ -1,48 +1,19 @@ import PropTypes from 'prop-types' import React from 'react' import { Scenario } from '../../../../shapes' -import Link from 'next/link' import { Button, Col, Row } from 'reactstrap' -import classNames from 'classnames' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' -import { faPlus, faPlay, faTrash } from '@fortawesome/free-solid-svg-icons' +import { faPlus, faTrash } from '@fortawesome/free-solid-svg-icons' -function ScenarioListComponent({ - scenarios, - portfolioId, - currentProjectId, - currentScenarioId, - onNewScenario, - onChooseScenario, - onDeleteScenario, -}) { +function ScenarioListComponent({ scenarios, portfolioId, onNewScenario, onDeleteScenario }) { return ( <> {scenarios.map((scenario, idx) => ( - + {scenario.name} - - - - {portfolios.map((portfolio, idx) => ( + {portfolios.map((portfolio) => (
{ const router = useRouter() const { project: currentProjectId, portfolio: currentPortfolioId } = router.query + const { data: currentProject } = useProject(currentProjectId) const portfolios = usePortfolios(currentProjectId) const dispatch = useDispatch() @@ -24,7 +25,7 @@ const PortfolioListContainer = () => { if (id) { const state = await getState(dispatch) dispatch(deletePortfolio(id)) - dispatch(setCurrentTopology(state.objects.project[currentProjectId].topologyIds[0])) + dispatch(setCurrentTopology(currentProject.topologyIds[0])) await router.push(`/projects/${currentProjectId}`) } }, diff --git a/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/ScenarioListContainer.js b/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/ScenarioListContainer.js index 0eb61026..c474c56e 100644 --- a/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/ScenarioListContainer.js +++ b/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/ScenarioListContainer.js @@ -7,11 +7,8 @@ import NewScenarioModalComponent from '../../../../components/modals/custom-comp import { useProjectTopologies } from '../../../../data/topology' import { useScenarios } from '../../../../data/project' import { useSchedulers, useTraces } from '../../../../data/experiments' -import { useRouter } from 'next/router' const ScenarioListContainer = ({ portfolioId }) => { - const router = useRouter() - const { project: currentProjectId } = router.query const scenarios = useScenarios(portfolioId) const topologies = useProjectTopologies() const traces = useTraces() @@ -23,7 +20,6 @@ const ScenarioListContainer = ({ portfolioId }) => { const onNewScenario = (currentPortfolioId) => { setVisible(true) } - const onChooseScenario = (portfolioId, scenarioId) => {} const onDeleteScenario = (id) => { if (id) { dispatch(deleteScenario(id)) @@ -67,7 +63,7 @@ const ScenarioListContainer = ({ portfolioId }) => { } ScenarioListContainer.propTypes = { - portfolioId: PropTypes.string.isRequired, + portfolioId: PropTypes.string, } export default ScenarioListContainer diff --git a/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/TopologyListContainer.js b/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/TopologyListContainer.js index 69367b5f..55f8bd00 100644 --- a/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/TopologyListContainer.js +++ b/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/TopologyListContainer.js @@ -6,11 +6,13 @@ import { useRouter } from 'next/router' import { addTopology, deleteTopology } from '../../../../redux/actions/topologies' import NewTopologyModalComponent from '../../../../components/modals/custom-components/NewTopologyModalComponent' import { useActiveTopology, useProjectTopologies } from '../../../../data/topology' +import { useProject } from '../../../../data/project' const TopologyListContainer = () => { const dispatch = useDispatch() const router = useRouter() const { project: currentProjectId } = router.query + const { data: currentProject } = useProject(currentProjectId) const topologies = useProjectTopologies() const currentTopologyId = useActiveTopology()?._id const [isVisible, setVisible] = useState(false) @@ -22,7 +24,7 @@ const TopologyListContainer = () => { const onDeleteTopology = async (id) => { if (id) { dispatch(deleteTopology(id)) - dispatch(setCurrentTopology(state.objects.project[currentProjectId].topologyIds[0])) + dispatch(setCurrentTopology(currentProject.topologyIds[0])) await router.push(`/projects/${currentProjectId}`) } } diff --git a/opendc-web/opendc-web-ui/src/containers/navigation/AppNavbarContainer.js b/opendc-web/opendc-web-ui/src/containers/navigation/AppNavbarContainer.js index 6742bc26..ff9f9fe7 100644 --- a/opendc-web/opendc-web-ui/src/containers/navigation/AppNavbarContainer.js +++ b/opendc-web/opendc-web-ui/src/containers/navigation/AppNavbarContainer.js @@ -1,9 +1,10 @@ import React from 'react' import AppNavbarComponent from '../../components/navigation/AppNavbarComponent' -import { useActiveProject } from '../../data/project' +import { useActiveProjectId, useProject } from '../../data/project' const AppNavbarContainer = (props) => { - const project = useActiveProject() + const projectId = useActiveProjectId() + const { data: project } = useProject(projectId) return } diff --git a/opendc-web/opendc-web-ui/src/containers/projects/NewProjectContainer.js b/opendc-web/opendc-web-ui/src/containers/projects/NewProjectContainer.js index e03b5c07..c844fe2d 100644 --- a/opendc-web/opendc-web-ui/src/containers/projects/NewProjectContainer.js +++ b/opendc-web/opendc-web-ui/src/containers/projects/NewProjectContainer.js @@ -1,20 +1,25 @@ import React, { useState } from 'react' -import { useDispatch } from 'react-redux' -import { addProject } from '../../redux/actions/projects' import TextInputModal from '../../components/modals/TextInputModal' import { Button } from 'reactstrap' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faPlus } from '@fortawesome/free-solid-svg-icons' +import { useMutation, useQueryClient } from 'react-query' +import { addProject } from '../../api/projects' +import { useAuth } from '../../auth' /** * A container for creating a new project. */ const NewProjectContainer = () => { const [isVisible, setVisible] = useState(false) - const dispatch = useDispatch() + const auth = useAuth() + const queryClient = useQueryClient() + const mutation = useMutation((data) => addProject(auth, data), { + onSuccess: (result) => queryClient.setQueryData('projects', (old) => [...(old || []), result]), + }) const callback = (text) => { if (text) { - dispatch(addProject(text)) + mutation.mutate({ name: text }) } setVisible(false) } diff --git a/opendc-web/opendc-web-ui/src/containers/projects/ProjectActions.js b/opendc-web/opendc-web-ui/src/containers/projects/ProjectActions.js index bdb422dc..eba388d6 100644 --- a/opendc-web/opendc-web-ui/src/containers/projects/ProjectActions.js +++ b/opendc-web/opendc-web-ui/src/containers/projects/ProjectActions.js @@ -1,13 +1,18 @@ import React from 'react' -import { useDispatch } from 'react-redux' -import { deleteProject } from '../../redux/actions/projects' import ProjectActionButtons from '../../components/projects/ProjectActionButtons' +import { useMutation, useQueryClient } from 'react-query' +import { useAuth } from '../../auth' +import { deleteProject } from '../../api/projects' const ProjectActions = (props) => { - const dispatch = useDispatch() + const auth = useAuth() + const queryClient = useQueryClient() + const mutation = useMutation((projectId) => deleteProject(auth, projectId), { + onSuccess: () => queryClient.invalidateQueries('projects'), + }) const actions = { onViewUsers: (id) => {}, // TODO implement user viewing - onDelete: (id) => dispatch(deleteProject(id)), + onDelete: (id) => mutation.mutate(id), } return } diff --git a/opendc-web/opendc-web-ui/src/containers/projects/ProjectListContainer.js b/opendc-web/opendc-web-ui/src/containers/projects/ProjectListContainer.js index 6632a8b5..91e8ac5a 100644 --- a/opendc-web/opendc-web-ui/src/containers/projects/ProjectListContainer.js +++ b/opendc-web/opendc-web-ui/src/containers/projects/ProjectListContainer.js @@ -3,6 +3,7 @@ import PropTypes from 'prop-types' import ProjectList from '../../components/projects/ProjectList' import { useAuth } from '../../auth' import { useProjects } from '../../data/project' +import { useQueryClient } from 'react-query' const getVisibleProjects = (projects, filter, userId) => { switch (filter) { @@ -23,8 +24,8 @@ const getVisibleProjects = (projects, filter, userId) => { const ProjectListContainer = ({ filter }) => { const { user } = useAuth() - const projects = useProjects() - return + const { data: projects } = useProjects() + return } ProjectListContainer.propTypes = { diff --git a/opendc-web/opendc-web-ui/src/data/project.js b/opendc-web/opendc-web-ui/src/data/project.js index 30b36efa..308930e5 100644 --- a/opendc-web/opendc-web-ui/src/data/project.js +++ b/opendc-web/opendc-web-ui/src/data/project.js @@ -21,39 +21,43 @@ */ import { useSelector } from 'react-redux' +import { useQuery } from 'react-query' +import { fetchProject, fetchProjects } from '../api/projects' +import { useAuth } from '../auth' import { useRouter } from 'next/router' /** * Return the available projects. */ export function useProjects() { - return useSelector((state) => state.projects) + const auth = useAuth() + return useQuery('projects', () => fetchProjects(auth)) } /** * Return the project with the specified identifier. */ export function useProject(projectId) { - return useSelector((state) => state.projects[projectId]) + const auth = useAuth() + return useQuery(`projects/${projectId}`, () => fetchProject(auth, projectId), { enabled: !!projectId }) } /** - * Return the current active project. + * Return the current active project identifier. */ -export function useActiveProject() { +export function useActiveProjectId() { const router = useRouter() - const { project: projectId } = router.query - return useSelector((state) => state.objects.project[projectId]) + const { project } = router.query + return project } /** * Return the portfolios for the specified project id. */ export function usePortfolios(projectId) { + const { data: project } = useProject(projectId) return useSelector((state) => { - let portfolios = state.objects.project[projectId] - ? state.objects.project[projectId].portfolioIds.map((t) => state.objects.portfolio[t]) - : [] + let portfolios = project?.portfolioIds?.map((t) => state.objects.portfolio[t]) ?? [] if (portfolios.filter((t) => !t).length > 0) { portfolios = [] } diff --git a/opendc-web/opendc-web-ui/src/data/topology.js b/opendc-web/opendc-web-ui/src/data/topology.js index f6ce1672..4c746a7e 100644 --- a/opendc-web/opendc-web-ui/src/data/topology.js +++ b/opendc-web/opendc-web-ui/src/data/topology.js @@ -21,7 +21,7 @@ */ import { useSelector } from 'react-redux' -import { useRouter } from 'next/router' +import { useActiveProjectId, useProject } from './project' /** * Return the current active topology. @@ -34,14 +34,14 @@ export function useActiveTopology() { * Return the topologies for the active project. */ export function useProjectTopologies() { - const router = useRouter() - const { project: currentProjectId } = router.query + const projectId = useActiveProjectId() + const { data: project } = useProject(projectId) return useSelector(({ objects }) => { - if (!currentProjectId || !objects.project[currentProjectId]) { + if (!project) { return [] } - const topologies = objects.project[currentProjectId].topologyIds.map((t) => objects.topology[t]) + const topologies = project.topologyIds.map((t) => objects.topology[t]) if (topologies.filter((t) => !t).length > 0) { return [] diff --git a/opendc-web/opendc-web-ui/src/pages/_app.js b/opendc-web/opendc-web-ui/src/pages/_app.js index c1adbd6e..7b4dcb3e 100644 --- a/opendc-web/opendc-web-ui/src/pages/_app.js +++ b/opendc-web/opendc-web-ui/src/pages/_app.js @@ -28,15 +28,20 @@ import '../index.scss' import { AuthProvider, useAuth } from '../auth' import * as Sentry from '@sentry/react' import { Integrations } from '@sentry/tracing' +import { QueryClient, QueryClientProvider } from 'react-query' +import { useMemo } from 'react' // This setup is necessary to forward the Auth0 context to the Redux context const Inner = ({ Component, pageProps }) => { const auth = useAuth() - const store = useStore(pageProps.initialReduxState, { auth }) + const queryClient = useMemo(() => new QueryClient(), []) + const store = useStore(pageProps.initialReduxState, { auth, queryClient }) return ( - - - + + + + + ) } diff --git a/opendc-web/opendc-web-ui/src/pages/projects/[project]/topologies/[topology].js b/opendc-web/opendc-web-ui/src/pages/projects/[project]/topologies/[topology].js index 28db1531..a9dfdb19 100644 --- a/opendc-web/opendc-web-ui/src/pages/projects/[project]/topologies/[topology].js +++ b/opendc-web/opendc-web-ui/src/pages/projects/[project]/topologies/[topology].js @@ -24,7 +24,6 @@ import { useRouter } from 'next/router' import { useProject } from '../../../../data/project' import { useDispatch, useSelector } from 'react-redux' import React, { useEffect } from 'react' -import { openProjectSucceeded } from '../../../../redux/actions/projects' import { HotKeys } from 'react-hotkeys' import { KeymapConfiguration } from '../../../../hotkeys' import Head from 'next/head' @@ -35,6 +34,7 @@ import ScaleIndicatorContainer from '../../../../containers/app/map/controls/Sca import ToolPanelComponent from '../../../../components/app/map/controls/ToolPanelComponent' import ProjectSidebarContainer from '../../../../containers/app/sidebars/project/ProjectSidebarContainer' import TopologySidebarContainer from '../../../../containers/app/sidebars/topology/TopologySidebarContainer' +import { openProjectSucceeded } from '../../../../redux/actions/projects' /** * Page that displays a datacenter topology. @@ -43,7 +43,7 @@ function Topology() { const router = useRouter() const { project: projectId, topology: topologyId } = router.query - const project = useProject(projectId) + const { data: project } = useProject(projectId) const title = project?.name ? project?.name + ' - OpenDC' : 'Simulation - OpenDC' const dispatch = useDispatch() diff --git a/opendc-web/opendc-web-ui/src/pages/projects/index.js b/opendc-web/opendc-web-ui/src/pages/projects/index.js index 958ca622..2d8e6de7 100644 --- a/opendc-web/opendc-web-ui/src/pages/projects/index.js +++ b/opendc-web/opendc-web-ui/src/pages/projects/index.js @@ -1,22 +1,17 @@ -import React, { useEffect, useState } from 'react' +import React, { useState } from 'react' import Head from 'next/head' -import { useDispatch } from 'react-redux' import ProjectFilterPanel from '../../components/projects/FilterPanel' import NewProjectContainer from '../../containers/projects/NewProjectContainer' import ProjectListContainer from '../../containers/projects/ProjectListContainer' import AppNavbarContainer from '../../containers/navigation/AppNavbarContainer' import { useRequireAuth } from '../../auth' import { Container } from 'reactstrap' -import { fetchProjects } from '../../redux/actions/projects' function Projects() { useRequireAuth() - const dispatch = useDispatch() const [filter, setFilter] = useState('SHOW_ALL') - useEffect(() => dispatch(fetchProjects()), [dispatch]) - return ( <> diff --git a/opendc-web/opendc-web-ui/src/redux/actions/projects.js b/opendc-web/opendc-web-ui/src/redux/actions/projects.js index a6324c43..4fe6f6a8 100644 --- a/opendc-web/opendc-web-ui/src/redux/actions/projects.js +++ b/opendc-web/opendc-web-ui/src/redux/actions/projects.js @@ -1,52 +1,5 @@ -export const FETCH_PROJECTS = 'FETCH_PROJECTS' -export const FETCH_PROJECTS_SUCCEEDED = 'FETCH_PROJECTS_SUCCEEDED' -export const ADD_PROJECT = 'ADD_PROJECT' -export const ADD_PROJECT_SUCCEEDED = 'ADD_PROJECT_SUCCEEDED' -export const DELETE_PROJECT = 'DELETE_PROJECT' -export const DELETE_PROJECT_SUCCEEDED = 'DELETE_PROJECT_SUCCEEDED' export const OPEN_PROJECT_SUCCEEDED = 'OPEN_PROJECT_SUCCEEDED' -export function fetchProjects() { - return { - type: FETCH_PROJECTS, - } -} - -export function fetchProjectsSucceeded(projects) { - return { - type: FETCH_PROJECTS_SUCCEEDED, - projects, - } -} - -export function addProject(name) { - return { - type: ADD_PROJECT, - name, - } -} - -export function addProjectSucceeded(project) { - return { - type: ADD_PROJECT_SUCCEEDED, - project, - } -} - -export function deleteProject(id) { - return { - type: DELETE_PROJECT, - id, - } -} - -export function deleteProjectSucceeded(id) { - return { - type: DELETE_PROJECT_SUCCEEDED, - id, - } -} - export function openProjectSucceeded(id) { return { type: OPEN_PROJECT_SUCCEEDED, diff --git a/opendc-web/opendc-web-ui/src/redux/reducers/index.js b/opendc-web/opendc-web-ui/src/redux/reducers/index.js index 9f556d18..1b17a206 100644 --- a/opendc-web/opendc-web-ui/src/redux/reducers/index.js +++ b/opendc-web/opendc-web-ui/src/redux/reducers/index.js @@ -4,11 +4,9 @@ import { currentTopologyId } from './current-ids' import { interactionLevel } from './interaction-level' import { map } from './map' import { objects } from './objects' -import { projects } from './projects' const rootReducer = combineReducers({ objects, - projects, construction, map, currentTopologyId, diff --git a/opendc-web/opendc-web-ui/src/redux/reducers/interaction-level.js b/opendc-web/opendc-web-ui/src/redux/reducers/interaction-level.js index eafcb269..8bf81b98 100644 --- a/opendc-web/opendc-web-ui/src/redux/reducers/interaction-level.js +++ b/opendc-web/opendc-web-ui/src/redux/reducers/interaction-level.js @@ -5,7 +5,6 @@ import { GO_FROM_RACK_TO_MACHINE, GO_FROM_ROOM_TO_RACK, } from '../actions/interaction-level' -import { OPEN_PROJECT_SUCCEEDED } from '../actions/projects' import { SET_CURRENT_TOPOLOGY } from '../actions/topology/building' import { OPEN_SCENARIO_SUCCEEDED } from '../actions/scenarios' @@ -13,7 +12,6 @@ export function interactionLevel(state = { mode: 'BUILDING' }, action) { switch (action.type) { case OPEN_PORTFOLIO_SUCCEEDED: case OPEN_SCENARIO_SUCCEEDED: - case OPEN_PROJECT_SUCCEEDED: case SET_CURRENT_TOPOLOGY: return { mode: 'BUILDING', diff --git a/opendc-web/opendc-web-ui/src/redux/reducers/projects.js b/opendc-web/opendc-web-ui/src/redux/reducers/projects.js deleted file mode 100644 index a920e47f..00000000 --- a/opendc-web/opendc-web-ui/src/redux/reducers/projects.js +++ /dev/null @@ -1,14 +0,0 @@ -import { ADD_PROJECT_SUCCEEDED, DELETE_PROJECT_SUCCEEDED, FETCH_PROJECTS_SUCCEEDED } from '../actions/projects' - -export function projects(state = [], action) { - switch (action.type) { - case FETCH_PROJECTS_SUCCEEDED: - return action.projects - case ADD_PROJECT_SUCCEEDED: - return [...state, action.project] - case DELETE_PROJECT_SUCCEEDED: - return state.filter((project) => project._id !== action.id) - default: - return state - } -} diff --git a/opendc-web/opendc-web-ui/src/redux/sagas/index.js b/opendc-web/opendc-web-ui/src/redux/sagas/index.js index a8f44843..939be691 100644 --- a/opendc-web/opendc-web-ui/src/redux/sagas/index.js +++ b/opendc-web/opendc-web-ui/src/redux/sagas/index.js @@ -11,7 +11,7 @@ import { ADD_UNIT, DELETE_MACHINE, DELETE_UNIT } from '../actions/topology/machi import { ADD_MACHINE, DELETE_RACK, EDIT_RACK_NAME } from '../actions/topology/rack' import { ADD_RACK_TO_TILE, DELETE_ROOM, EDIT_ROOM_NAME } from '../actions/topology/room' import { onAddPortfolio, onDeletePortfolio, onOpenPortfolioSucceeded, onUpdatePortfolio } from './portfolios' -import { onFetchProjects, onOpenProjectSucceeded, onProjectAdd, onProjectDelete } from './projects' +import { onOpenProjectSucceeded } from './projects' import { onAddMachine, onAddRackToTile, @@ -36,10 +36,6 @@ import { onAddPrefab } from './prefabs' import { ADD_PREFAB } from '../actions/prefabs' export default function* rootSaga() { - yield takeEvery(FETCH_PROJECTS, onFetchProjects) - yield takeEvery(ADD_PROJECT, onProjectAdd) - yield takeEvery(DELETE_PROJECT, onProjectDelete) - yield takeEvery(OPEN_PROJECT_SUCCEEDED, onOpenProjectSucceeded) yield takeEvery(OPEN_PORTFOLIO_SUCCEEDED, onOpenPortfolioSucceeded) yield takeEvery(OPEN_SCENARIO_SUCCEEDED, onOpenScenarioSucceeded) diff --git a/opendc-web/opendc-web-ui/src/redux/sagas/objects.js b/opendc-web/opendc-web-ui/src/redux/sagas/objects.js index e5fd092d..5523dd57 100644 --- a/opendc-web/opendc-web-ui/src/redux/sagas/objects.js +++ b/opendc-web/opendc-web-ui/src/redux/sagas/objects.js @@ -1,13 +1,11 @@ import { call, put, select, getContext } from 'redux-saga/effects' import { addToStore } from '../actions/objects' import { getAllSchedulers } from '../../api/schedulers' -import { getProject } from '../../api/projects' import { getAllTraces } from '../../api/traces' import { getTopology, updateTopology } from '../../api/topologies' import { uuid } from 'uuidv4' export const OBJECT_SELECTORS = { - project: (state) => state.objects.project, user: (state) => state.objects.user, authorization: (state) => state.objects.authorization, portfolio: (state) => state.objects.portfolio, @@ -41,11 +39,6 @@ function* fetchAndStoreObjects(objectType, apiCall) { return objects } -export const fetchAndStoreProject = function* (id) { - const auth = yield getContext('auth') - return yield fetchAndStoreObject('project', id, call(getProject, auth, id)) -} - export const fetchAndStoreTopology = function* (id) { const topologyStore = yield select(OBJECT_SELECTORS['topology']) const roomStore = yield select(OBJECT_SELECTORS['room']) diff --git a/opendc-web/opendc-web-ui/src/redux/sagas/portfolios.js b/opendc-web/opendc-web-ui/src/redux/sagas/portfolios.js index 48d1ad3e..c32fcdc0 100644 --- a/opendc-web/opendc-web-ui/src/redux/sagas/portfolios.js +++ b/opendc-web/opendc-web-ui/src/redux/sagas/portfolios.js @@ -1,7 +1,7 @@ import { call, put, select, delay, getContext } from 'redux-saga/effects' -import { addPropToStoreObject, addToStore } from '../actions/objects' +import { addToStore } from '../actions/objects' import { addPortfolio, deletePortfolio, getPortfolio, updatePortfolio } from '../../api/portfolios' -import { getProject } from '../../api/projects' +import { fetchProject } from '../../api/projects' import { fetchAndStoreAllSchedulers, fetchAndStoreAllTraces } from './objects' import { fetchAndStoreAllTopologiesOfProject } from './topology' import { getScenario } from '../../api/scenarios' @@ -9,9 +9,11 @@ import { getScenario } from '../../api/scenarios' export function* onOpenPortfolioSucceeded(action) { try { const auth = yield getContext('auth') - const project = yield call(getProject, auth, action.projectId) - yield put(addToStore('project', project)) - yield fetchAndStoreAllTopologiesOfProject(project._id) + const queryClient = yield getContext('queryClient') + const project = yield call(() => + queryClient.fetchQuery(`projects/${action.projectId}`, () => fetchProject(auth, action.projectId)) + ) + yield fetchAndStoreAllTopologiesOfProject(action.projectId) yield fetchPortfoliosOfProject(project) yield fetchAndStoreAllSchedulers() yield fetchAndStoreAllTraces() @@ -94,13 +96,6 @@ export function* onAddPortfolio(action) { }) ) yield put(addToStore('portfolio', portfolio)) - - const portfolioIds = yield select((state) => state.objects.project[projectId].portfolioIds) - yield put( - addPropToStoreObject('project', projectId, { - portfolioIds: portfolioIds.concat([portfolio._id]), - }) - ) } catch (error) { console.error(error) } @@ -119,17 +114,7 @@ export function* onUpdatePortfolio(action) { export function* onDeletePortfolio(action) { try { const auth = yield getContext('auth') - const portfolio = yield select((state) => state.objects.portfolio[action.id]) - yield call(deletePortfolio, auth, action.id) - - const portfolioIds = yield select((state) => state.objects.project[portfolio.projectId].portfolioIds) - - yield put( - addPropToStoreObject('project', portfolio.projectId, { - portfolioIds: portfolioIds.filter((id) => id !== action.id), - }) - ) } catch (error) { console.error(error) } diff --git a/opendc-web/opendc-web-ui/src/redux/sagas/projects.js b/opendc-web/opendc-web-ui/src/redux/sagas/projects.js index 0689090a..96a4323c 100644 --- a/opendc-web/opendc-web-ui/src/redux/sagas/projects.js +++ b/opendc-web/opendc-web-ui/src/redux/sagas/projects.js @@ -1,16 +1,16 @@ -import { call, put, getContext } from 'redux-saga/effects' -import { addToStore } from '../actions/objects' -import { addProjectSucceeded, deleteProjectSucceeded, fetchProjectsSucceeded } from '../actions/projects' -import { addProject, deleteProject, getProject, getProjects } from '../../api/projects' +import { call, getContext } from 'redux-saga/effects' import { fetchAndStoreAllTopologiesOfProject } from './topology' import { fetchAndStoreAllSchedulers, fetchAndStoreAllTraces } from './objects' import { fetchPortfoliosOfProject } from './portfolios' +import { fetchProject } from '../../api/projects' export function* onOpenProjectSucceeded(action) { try { const auth = yield getContext('auth') - const project = yield call(getProject, auth, action.id) - yield put(addToStore('project', project)) + const queryClient = yield getContext('queryClient') + const project = yield call(() => + queryClient.fetchQuery(`projects/${action.id}`, () => fetchProject(auth, action.id)) + ) yield fetchAndStoreAllTopologiesOfProject(action.id, true) yield fetchPortfoliosOfProject(project) @@ -20,34 +20,3 @@ export function* onOpenProjectSucceeded(action) { console.error(error) } } - -export function* onProjectAdd(action) { - try { - const auth = yield getContext('auth') - const project = yield call(addProject, auth, { name: action.name }) - yield put(addToStore('project', project)) - yield put(addProjectSucceeded(project)) - } catch (error) { - console.error(error) - } -} - -export function* onProjectDelete(action) { - try { - const auth = yield getContext('auth') - yield call(deleteProject, auth, action.id) - yield put(deleteProjectSucceeded(action.id)) - } catch (error) { - console.error(error) - } -} - -export function* onFetchProjects(action) { - try { - const auth = yield getContext('auth') - const projects = yield call(getProjects, auth) - yield put(fetchProjectsSucceeded(projects)) - } catch (error) { - console.error(error) - } -} diff --git a/opendc-web/opendc-web-ui/src/redux/sagas/scenarios.js b/opendc-web/opendc-web-ui/src/redux/sagas/scenarios.js index b2979636..3fe12981 100644 --- a/opendc-web/opendc-web-ui/src/redux/sagas/scenarios.js +++ b/opendc-web/opendc-web-ui/src/redux/sagas/scenarios.js @@ -1,6 +1,6 @@ import { call, put, select, getContext } from 'redux-saga/effects' import { addPropToStoreObject, addToStore } from '../actions/objects' -import { getProject } from '../../api/projects' +import { fetchProject } from '../../api/projects' import { fetchAndStoreAllSchedulers, fetchAndStoreAllTraces } from './objects' import { fetchAndStoreAllTopologiesOfProject } from './topology' import { addScenario, deleteScenario, updateScenario } from '../../api/scenarios' @@ -9,7 +9,10 @@ import { fetchPortfolioWithScenarios, watchForPortfolioResults } from './portfol export function* onOpenScenarioSucceeded(action) { try { const auth = yield getContext('auth') - const project = yield call(getProject, auth, action.projectId) + const queryClient = yield getContext('queryClient') + const project = yield call(() => + queryClient.fetchQuery(`projects/${action.projectId}`, () => fetchProject(auth, action.projectId)) + ) yield put(addToStore('project', project)) yield fetchAndStoreAllTopologiesOfProject(project._id) yield fetchAndStoreAllSchedulers() diff --git a/opendc-web/opendc-web-ui/src/redux/sagas/topology.js b/opendc-web/opendc-web-ui/src/redux/sagas/topology.js index 4f7bc8db..3f41e1d4 100644 --- a/opendc-web/opendc-web-ui/src/redux/sagas/topology.js +++ b/opendc-web/opendc-web-ui/src/redux/sagas/topology.js @@ -19,10 +19,15 @@ import { import { fetchAndStoreTopology, getTopologyAsObject, updateTopologyOnServer } from './objects' import { uuid } from 'uuidv4' import { addTopology, deleteTopology } from '../../api/topologies' +import { fetchProject } from '../../api/projects' export function* fetchAndStoreAllTopologiesOfProject(projectId, setTopology = false) { try { - const project = yield select((state) => state.objects.project[projectId]) + const auth = yield getContext('auth') + const queryClient = yield getContext('queryClient') + const project = yield call(() => + queryClient.fetchQuery(`projects/${projectId}`, () => fetchProject(auth, projectId)) + ) for (let i in project.topologyIds) { yield fetchAndStoreTopology(project.topologyIds[i]) @@ -51,13 +56,6 @@ export function* onAddTopology(action) { const auth = yield getContext('auth') const topology = yield call(addTopology, auth, { ...topologyToBeCreated, projectId }) yield fetchAndStoreTopology(topology._id) - - const topologyIds = yield select((state) => state.objects.project[projectId].topologyIds) - yield put( - addPropToStoreObject('project', projectId, { - topologyIds: topologyIds.concat([topology._id]), - }) - ) yield put(setCurrentTopology(topology._id)) } catch (error) { console.error(error) @@ -66,21 +64,19 @@ export function* onAddTopology(action) { export function* onDeleteTopology(action) { try { - const topology = yield select((state) => state.objects.topologies[action.id]) - const topologyIds = yield select((state) => state.objects.project[topology.projectId].topologyIds) + const auth = yield getContext('auth') + const queryClient = yield getContext('queryClient') + const project = yield call(() => + queryClient.fetchQuery(`projects/${action.projectId}`, () => fetchProject(auth, action.projectId)) + ) + const topologyIds = project?.topologyIds ?? [] + const currentTopologyId = yield select((state) => state.currentTopologyId) if (currentTopologyId === action.id) { yield put(setCurrentTopology(topologyIds.filter((t) => t !== action.id)[0])) } - const auth = yield getContext('auth') yield call(deleteTopology, auth, action.id) - - yield put( - addPropToStoreObject('project', topology.projectId, { - topologyIds: topologyIds.filter((id) => id !== action.id), - }) - ) } catch (error) { console.error(error) } diff --git a/opendc-web/opendc-web-ui/yarn.lock b/opendc-web/opendc-web-ui/yarn.lock index 60a48d32..630f38db 100644 --- a/opendc-web/opendc-web-ui/yarn.lock +++ b/opendc-web/opendc-web-ui/yarn.lock @@ -64,6 +64,13 @@ dependencies: regenerator-runtime "^0.13.4" +"@babel/runtime@^7.5.5", "@babel/runtime@^7.6.2", "@babel/runtime@^7.7.2": + version "7.14.6" + resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.14.6.tgz#535203bc0892efc7dec60bdc27b2ecf6e409062d" + integrity sha512-/PCB2uJ7oM44tz8YhC4Z/6PeOKXp4K588f+5M3clr1M4zbqztlo0XEfJ2LEzj/FgwfgGcIdl8n7YYjTCI0BYwg== + dependencies: + regenerator-runtime "^0.13.4" + "@babel/types@7.8.3": version "7.8.3" resolved "https://registry.yarnpkg.com/@babel/types/-/types-7.8.3.tgz#5a383dffa5416db1b73dedffd311ffd0788fb31c" @@ -660,6 +667,11 @@ base64-js@^1.0.2: resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-1.5.1.tgz#1b1b440160a5bf7ad40b650f095963481903930a" integrity sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA== +big-integer@^1.6.16: + version "1.6.48" + resolved "https://registry.yarnpkg.com/big-integer/-/big-integer-1.6.48.tgz#8fd88bd1632cba4a1c8c3e3d7159f08bb95b4b9e" + integrity sha512-j51egjPa7/i+RdiRuJbPdJ2FIUYYPhvYLjzoYbcMMm62ooO6F94fETG4MTs46zPAF9Brs04OajboA/qTGuz78w== + big.js@^5.2.2: version "5.2.2" resolved "https://registry.yarnpkg.com/big.js/-/big.js-5.2.2.tgz#65f0af382f578bcdc742bd9c281e9cb2d7768328" @@ -700,6 +712,20 @@ braces@^3.0.1, braces@~3.0.2: dependencies: fill-range "^7.0.1" +broadcast-channel@^3.4.1: + version "3.7.0" + resolved "https://registry.yarnpkg.com/broadcast-channel/-/broadcast-channel-3.7.0.tgz#2dfa5c7b4289547ac3f6705f9c00af8723889937" + integrity sha512-cIAKJXAxGJceNZGTZSBzMxzyOn72cVgPnKx4dc6LRjQgbaJUQqhy5rzL3zbMxkMWsGKkv2hSFkPRMEXfoMZ2Mg== + dependencies: + "@babel/runtime" "^7.7.2" + detect-node "^2.1.0" + js-sha3 "0.8.0" + microseconds "0.2.0" + nano-time "1.0.0" + oblivious-set "1.0.0" + rimraf "3.0.2" + unload "2.2.0" + brorand@^1.0.1, brorand@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/brorand/-/brorand-1.1.0.tgz#12c25efe40a45e3c323eb8675a0a0ce57b22371f" @@ -1260,6 +1286,11 @@ des.js@^1.0.0: inherits "^2.0.1" minimalistic-assert "^1.0.0" +detect-node@^2.0.4, detect-node@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/detect-node/-/detect-node-2.1.0.tgz#c9c70775a49c3d03bc2c06d9a73be550f978f8b1" + integrity sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g== + diffie-hellman@^5.0.0: version "5.0.3" resolved "https://registry.yarnpkg.com/diffie-hellman/-/diffie-hellman-5.0.3.tgz#40e8ee98f55a2149607146921c63e1ae5f3d2875" @@ -2268,6 +2299,11 @@ jest-worker@27.0.0-next.5: merge-stream "^2.0.0" supports-color "^8.0.0" +js-sha3@0.8.0: + version "0.8.0" + resolved "https://registry.yarnpkg.com/js-sha3/-/js-sha3-0.8.0.tgz#b9b7a5da73afad7dedd0f8c463954cbde6818840" + integrity sha512-gF1cRrHhIzNfToc802P800N8PpXS+evLLXfsVpowqmAFR9uwbi89WvXg2QspOmXL8QL86J4T1EpFu+yUkwJY3Q== + "js-tokens@^3.0.0 || ^4.0.0", js-tokens@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-4.0.0.tgz#19203fb59991df98e3a287050d4647cdeaf32499" @@ -2482,6 +2518,14 @@ make-dir@^3.0.2: dependencies: semver "^6.0.0" +match-sorter@^6.0.2: + version "6.3.0" + resolved "https://registry.yarnpkg.com/match-sorter/-/match-sorter-6.3.0.tgz#454a1b31ed218cddbce6231a0ecb5fdc549fed01" + integrity sha512-efYOf/wUpNb8FgNY+cOD2EIJI1S5I7YPKsw0LBp7wqPh5pmMS6i/wr3ZWwfwrAw1NvqTA2KUReVRWDX84lUcOQ== + dependencies: + "@babel/runtime" "^7.12.5" + remove-accents "0.4.2" + mathjs@~7.6.0: version "7.6.0" resolved "https://registry.yarnpkg.com/mathjs/-/mathjs-7.6.0.tgz#f0b7579e0756b13422995d0c4f29bd17d65d4dcc" @@ -2523,6 +2567,11 @@ micromatch@^4.0.2: braces "^3.0.1" picomatch "^2.2.3" +microseconds@0.2.0: + version "0.2.0" + resolved "https://registry.yarnpkg.com/microseconds/-/microseconds-0.2.0.tgz#233b25f50c62a65d861f978a4a4f8ec18797dc39" + integrity sha512-n7DHHMjR1avBbSpsTBj6fmMGh2AGrifVV4e+WYc3Q9lO+xnSZ3NyhcBND3vzzatt05LFhoKFRxrIyklmLlUtyA== + miller-rabin@^4.0.0: version "4.0.1" resolved "https://registry.yarnpkg.com/miller-rabin/-/miller-rabin-4.0.1.tgz#f080351c865b0dc562a8462966daa53543c78a4d" @@ -2573,6 +2622,13 @@ ms@^2.1.1: resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.3.tgz#574c8138ce1d2b5861f0b44579dbadd60c6615b2" integrity sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA== +nano-time@1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/nano-time/-/nano-time-1.0.0.tgz#b0554f69ad89e22d0907f7a12b0993a5d96137ef" + integrity sha1-sFVPaa2J4i0JB/ehKwmTpdlhN+8= + dependencies: + big-integer "^1.6.16" + nanoid@^3.1.22: version "3.1.22" resolved "https://registry.yarnpkg.com/nanoid/-/nanoid-3.1.22.tgz#b35f8fb7d151990a8aebd5aa5015c03cf726f844" @@ -2775,6 +2831,11 @@ object.values@^1.1.3, object.values@^1.1.4: define-properties "^1.1.3" es-abstract "^1.18.2" +oblivious-set@1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/oblivious-set/-/oblivious-set-1.0.0.tgz#c8316f2c2fb6ff7b11b6158db3234c49f733c566" + integrity sha512-z+pI07qxo4c2CulUHCDf9lcqDlMSo72N/4rLUpRXf6fu+q8vjt8y0xS+Tlf8NTJDdTXHbdeO1n3MlbctwEoXZw== + once@^1.3.0, once@^1.3.1, once@^1.4.0: version "1.4.0" resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" @@ -3226,6 +3287,15 @@ react-popper@^1.3.6: typed-styles "^0.0.7" warning "^4.0.2" +react-query@^3.18.1: + version "3.18.1" + resolved "https://registry.yarnpkg.com/react-query/-/react-query-3.18.1.tgz#893b5475a7b4add099e007105317446f7a2cd310" + integrity sha512-17lv3pQxU9n+cB5acUv0/cxNTjo9q8G+RsedC6Ax4V9D8xEM7Q5xf9xAbCPdEhDrrnzPjTls9fQEABKRSi7OJA== + dependencies: + "@babel/runtime" "^7.5.5" + broadcast-channel "^3.4.1" + match-sorter "^6.0.2" + react-reconciler@~0.26.1: version "0.26.2" resolved "https://registry.yarnpkg.com/react-reconciler/-/react-reconciler-0.26.2.tgz#bbad0e2d1309423f76cf3c3309ac6c96e05e9d91" @@ -3432,6 +3502,11 @@ regexpp@^3.1.0: resolved "https://registry.yarnpkg.com/regexpp/-/regexpp-3.1.0.tgz#206d0ad0a5648cffbdb8ae46438f3dc51c9f78e2" integrity sha512-ZOIzd8yVsQQA7j8GCSlPGXwg5PfmA1mrq0JP4nGhh54LaKN3xdai/vHUDu74pKwV8OxseMS65u2NImosQcSD0Q== +remove-accents@0.4.2: + version "0.4.2" + resolved "https://registry.yarnpkg.com/remove-accents/-/remove-accents-0.4.2.tgz#0a43d3aaae1e80db919e07ae254b285d9e1c7bb5" + integrity sha1-CkPTqq4egNuRngeuJUsoXZ4ce7U= + require-from-string@^2.0.2: version "2.0.2" resolved "https://registry.yarnpkg.com/require-from-string/-/require-from-string-2.0.2.tgz#89a7fdd938261267318eafe14f9c32e598c36909" @@ -3476,7 +3551,7 @@ reusify@^1.0.4: resolved "https://registry.yarnpkg.com/reusify/-/reusify-1.0.4.tgz#90da382b1e126efc02146e90845a88db12925d76" integrity sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw== -rimraf@^3.0.2: +rimraf@3.0.2, rimraf@^3.0.2: version "3.0.2" resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-3.0.2.tgz#f1a5402ba6220ad52cc1282bac1ae3aa49fd061a" integrity sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA== @@ -4066,6 +4141,14 @@ unfetch@^4.2.0: resolved "https://registry.yarnpkg.com/unfetch/-/unfetch-4.2.0.tgz#7e21b0ef7d363d8d9af0fb929a5555f6ef97a3be" integrity sha512-F9p7yYCn6cIW9El1zi0HI6vqpeIvBsr3dSuRO6Xuppb1u5rXpCPmMvLSyECLhybr9isec8Ohl0hPekMVrEinDA== +unload@2.2.0: + version "2.2.0" + resolved "https://registry.yarnpkg.com/unload/-/unload-2.2.0.tgz#ccc88fdcad345faa06a92039ec0f80b488880ef7" + integrity sha512-B60uB5TNBLtN6/LsgAf3udH9saB5p7gqJwcFfbOEZ8BcBHnGwCf6G/TGiEqkRAxX7zAFIUtzdrXQSdL3Q/wqNA== + dependencies: + "@babel/runtime" "^7.6.2" + detect-node "^2.0.4" + unpipe@1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/unpipe/-/unpipe-1.0.0.tgz#b2bf4ee8514aae6165b4817829d21b2ef49904ec" -- cgit v1.2.3 From d28a2f194a75eb86095485ae4f88be349bcc18b6 Mon Sep 17 00:00:00 2001 From: Fabian Mastenbroek Date: Wed, 7 Jul 2021 16:36:54 +0200 Subject: ui: Fetch schedulers and traces using React Query This change updates the OpenDC frontend to fetch schedulers and traces using React Query, removing its dependency on Redux. --- opendc-web/opendc-web-ui/src/api/schedulers.js | 2 +- opendc-web/opendc-web-ui/src/api/traces.js | 2 +- .../app/sidebars/project/ScenarioListContainer.js | 4 ++-- opendc-web/opendc-web-ui/src/data/experiments.js | 11 ++++++++--- .../opendc-web-ui/src/redux/reducers/objects.js | 2 -- opendc-web/opendc-web-ui/src/redux/sagas/objects.js | 19 ++----------------- .../opendc-web-ui/src/redux/sagas/portfolios.js | 7 ------- opendc-web/opendc-web-ui/src/redux/sagas/projects.js | 3 --- opendc-web/opendc-web-ui/src/redux/sagas/scenarios.js | 3 --- 9 files changed, 14 insertions(+), 39 deletions(-) diff --git a/opendc-web/opendc-web-ui/src/api/schedulers.js b/opendc-web/opendc-web-ui/src/api/schedulers.js index 1b69f1a1..0b8b8153 100644 --- a/opendc-web/opendc-web-ui/src/api/schedulers.js +++ b/opendc-web/opendc-web-ui/src/api/schedulers.js @@ -22,6 +22,6 @@ import { request } from './index' -export function getAllSchedulers(auth) { +export function fetchSchedulers(auth) { return request(auth, 'schedulers/') } diff --git a/opendc-web/opendc-web-ui/src/api/traces.js b/opendc-web/opendc-web-ui/src/api/traces.js index df03a2dd..fd637ac3 100644 --- a/opendc-web/opendc-web-ui/src/api/traces.js +++ b/opendc-web/opendc-web-ui/src/api/traces.js @@ -22,6 +22,6 @@ import { request } from './index' -export function getAllTraces(auth) { +export function fetchTraces(auth) { return request(auth, 'traces/') } diff --git a/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/ScenarioListContainer.js b/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/ScenarioListContainer.js index c474c56e..7acc13ee 100644 --- a/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/ScenarioListContainer.js +++ b/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/ScenarioListContainer.js @@ -11,8 +11,8 @@ import { useSchedulers, useTraces } from '../../../../data/experiments' const ScenarioListContainer = ({ portfolioId }) => { const scenarios = useScenarios(portfolioId) const topologies = useProjectTopologies() - const traces = useTraces() - const schedulers = useSchedulers() + const traces = useTraces().data ?? [] + const schedulers = useSchedulers().data ?? [] const dispatch = useDispatch() const [isVisible, setVisible] = useState(false) diff --git a/opendc-web/opendc-web-ui/src/data/experiments.js b/opendc-web/opendc-web-ui/src/data/experiments.js index aef512e5..4797bacb 100644 --- a/opendc-web/opendc-web-ui/src/data/experiments.js +++ b/opendc-web/opendc-web-ui/src/data/experiments.js @@ -20,18 +20,23 @@ * SOFTWARE. */ -import { useSelector } from 'react-redux' +import { useQuery } from 'react-query' +import { fetchTraces } from '../api/traces' +import { useAuth } from '../auth' +import { fetchSchedulers } from '../api/schedulers' /** * Return the available traces to experiment with. */ export function useTraces() { - return useSelector((state) => Object.values(state.objects.trace)) + const auth = useAuth() + return useQuery('traces', () => fetchTraces(auth)) } /** * Return the available schedulers to experiment with. */ export function useSchedulers() { - return useSelector((state) => Object.values(state.objects.scheduler)) + const auth = useAuth() + return useQuery('schedulers', () => fetchSchedulers(auth)) } diff --git a/opendc-web/opendc-web-ui/src/redux/reducers/objects.js b/opendc-web/opendc-web-ui/src/redux/reducers/objects.js index a2483b43..f8f577ac 100644 --- a/opendc-web/opendc-web-ui/src/redux/reducers/objects.js +++ b/opendc-web/opendc-web-ui/src/redux/reducers/objects.js @@ -20,8 +20,6 @@ export const objects = combineReducers({ tile: object('tile'), room: object('room'), topology: object('topology'), - trace: object('trace'), - scheduler: object('scheduler'), portfolio: object('portfolio'), scenario: object('scenario'), prefab: object('prefab'), diff --git a/opendc-web/opendc-web-ui/src/redux/sagas/objects.js b/opendc-web/opendc-web-ui/src/redux/sagas/objects.js index 5523dd57..fe826014 100644 --- a/opendc-web/opendc-web-ui/src/redux/sagas/objects.js +++ b/opendc-web/opendc-web-ui/src/redux/sagas/objects.js @@ -1,7 +1,7 @@ import { call, put, select, getContext } from 'redux-saga/effects' import { addToStore } from '../actions/objects' -import { getAllSchedulers } from '../../api/schedulers' -import { getAllTraces } from '../../api/traces' +import { fetchSchedulers } from '../../api/schedulers' +import { fetchTraces } from '../../api/traces' import { getTopology, updateTopology } from '../../api/topologies' import { uuid } from 'uuidv4' @@ -210,18 +210,3 @@ export const getRackById = function* (id, keepIds) { })), } } - -export const fetchAndStoreAllTraces = function* () { - const auth = yield getContext('auth') - return yield fetchAndStoreObjects('trace', call(getAllTraces, auth)) -} - -export const fetchAndStoreAllSchedulers = function* () { - const auth = yield getContext('auth') - const objects = yield call(getAllSchedulers, auth) - for (let object of objects) { - object._id = object.name - yield put(addToStore('scheduler', object)) - } - return objects -} diff --git a/opendc-web/opendc-web-ui/src/redux/sagas/portfolios.js b/opendc-web/opendc-web-ui/src/redux/sagas/portfolios.js index c32fcdc0..68956225 100644 --- a/opendc-web/opendc-web-ui/src/redux/sagas/portfolios.js +++ b/opendc-web/opendc-web-ui/src/redux/sagas/portfolios.js @@ -2,8 +2,6 @@ import { call, put, select, delay, getContext } from 'redux-saga/effects' import { addToStore } from '../actions/objects' import { addPortfolio, deletePortfolio, getPortfolio, updatePortfolio } from '../../api/portfolios' import { fetchProject } from '../../api/projects' -import { fetchAndStoreAllSchedulers, fetchAndStoreAllTraces } from './objects' -import { fetchAndStoreAllTopologiesOfProject } from './topology' import { getScenario } from '../../api/scenarios' export function* onOpenPortfolioSucceeded(action) { @@ -15,8 +13,6 @@ export function* onOpenPortfolioSucceeded(action) { ) yield fetchAndStoreAllTopologiesOfProject(action.projectId) yield fetchPortfoliosOfProject(project) - yield fetchAndStoreAllSchedulers() - yield fetchAndStoreAllTraces() yield watchForPortfolioResults(action.portfolioId) } catch (error) { @@ -55,9 +51,6 @@ export function* getCurrentUnfinishedScenarios(portfolioId) { export function* fetchPortfoliosOfProject(project) { try { - yield fetchAndStoreAllSchedulers() - yield fetchAndStoreAllTraces() - for (const i in project.portfolioIds) { yield fetchPortfolioWithScenarios(project.portfolioIds[i]) } diff --git a/opendc-web/opendc-web-ui/src/redux/sagas/projects.js b/opendc-web/opendc-web-ui/src/redux/sagas/projects.js index 96a4323c..6dc3c682 100644 --- a/opendc-web/opendc-web-ui/src/redux/sagas/projects.js +++ b/opendc-web/opendc-web-ui/src/redux/sagas/projects.js @@ -1,6 +1,5 @@ import { call, getContext } from 'redux-saga/effects' import { fetchAndStoreAllTopologiesOfProject } from './topology' -import { fetchAndStoreAllSchedulers, fetchAndStoreAllTraces } from './objects' import { fetchPortfoliosOfProject } from './portfolios' import { fetchProject } from '../../api/projects' @@ -14,8 +13,6 @@ export function* onOpenProjectSucceeded(action) { yield fetchAndStoreAllTopologiesOfProject(action.id, true) yield fetchPortfoliosOfProject(project) - yield fetchAndStoreAllSchedulers() - yield fetchAndStoreAllTraces() } catch (error) { console.error(error) } diff --git a/opendc-web/opendc-web-ui/src/redux/sagas/scenarios.js b/opendc-web/opendc-web-ui/src/redux/sagas/scenarios.js index 3fe12981..10ab3547 100644 --- a/opendc-web/opendc-web-ui/src/redux/sagas/scenarios.js +++ b/opendc-web/opendc-web-ui/src/redux/sagas/scenarios.js @@ -1,7 +1,6 @@ import { call, put, select, getContext } from 'redux-saga/effects' import { addPropToStoreObject, addToStore } from '../actions/objects' import { fetchProject } from '../../api/projects' -import { fetchAndStoreAllSchedulers, fetchAndStoreAllTraces } from './objects' import { fetchAndStoreAllTopologiesOfProject } from './topology' import { addScenario, deleteScenario, updateScenario } from '../../api/scenarios' import { fetchPortfolioWithScenarios, watchForPortfolioResults } from './portfolios' @@ -15,8 +14,6 @@ export function* onOpenScenarioSucceeded(action) { ) yield put(addToStore('project', project)) yield fetchAndStoreAllTopologiesOfProject(project._id) - yield fetchAndStoreAllSchedulers() - yield fetchAndStoreAllTraces() yield fetchPortfolioWithScenarios(action.portfolioId) // TODO Fetch scenario-specific metrics -- cgit v1.2.3 From 9c8a987556d0fb0cdf0eb67e0c191a8dcc5593b9 Mon Sep 17 00:00:00 2001 From: Fabian Mastenbroek Date: Wed, 7 Jul 2021 17:30:15 +0200 Subject: ui: Fetch scenarios and portfolios using React Query --- opendc-web/opendc-web-ui/src/api/portfolios.js | 8 +- opendc-web/opendc-web-ui/src/api/scenarios.js | 8 +- .../app/results/PortfolioResultsContainer.js | 27 +---- .../app/sidebars/project/PortfolioListContainer.js | 40 +++++--- .../app/sidebars/project/ScenarioListContainer.js | 48 ++++++--- opendc-web/opendc-web-ui/src/data/project.js | 62 +++++------ .../projects/[project]/portfolios/[portfolio].js | 8 +- .../opendc-web-ui/src/redux/actions/portfolios.js | 34 ------ .../opendc-web-ui/src/redux/actions/scenarios.js | 34 ------ .../src/redux/middleware/viewport-adjustment.js | 2 +- .../src/redux/reducers/construction-mode.js | 6 -- .../src/redux/reducers/interaction-level.js | 4 - opendc-web/opendc-web-ui/src/redux/sagas/index.js | 16 +-- .../opendc-web-ui/src/redux/sagas/objects.js | 30 ++---- .../opendc-web-ui/src/redux/sagas/portfolios.js | 114 --------------------- .../opendc-web-ui/src/redux/sagas/projects.js | 10 -- .../opendc-web-ui/src/redux/sagas/scenarios.js | 69 ------------- .../opendc-web-ui/src/redux/sagas/topology.js | 8 +- 18 files changed, 120 insertions(+), 408 deletions(-) delete mode 100644 opendc-web/opendc-web-ui/src/redux/actions/portfolios.js delete mode 100644 opendc-web/opendc-web-ui/src/redux/actions/scenarios.js delete mode 100644 opendc-web/opendc-web-ui/src/redux/sagas/portfolios.js delete mode 100644 opendc-web/opendc-web-ui/src/redux/sagas/scenarios.js diff --git a/opendc-web/opendc-web-ui/src/api/portfolios.js b/opendc-web/opendc-web-ui/src/api/portfolios.js index 28898e6a..36709b36 100644 --- a/opendc-web/opendc-web-ui/src/api/portfolios.js +++ b/opendc-web/opendc-web-ui/src/api/portfolios.js @@ -22,12 +22,12 @@ import { request } from './index' -export function addPortfolio(auth, projectId, portfolio) { - return request(auth, `projects/${projectId}/portfolios`, 'POST', { portfolio }) +export function fetchPortfolio(auth, portfolioId) { + return request(auth, `portfolios/${portfolioId}`) } -export function getPortfolio(auth, portfolioId) { - return request(auth, `portfolios/${portfolioId}`) +export function addPortfolio(auth, portfolio) { + return request(auth, `projects/${portfolio.projectId}/portfolios`, 'POST', { portfolio }) } export function updatePortfolio(auth, portfolioId, portfolio) { diff --git a/opendc-web/opendc-web-ui/src/api/scenarios.js b/opendc-web/opendc-web-ui/src/api/scenarios.js index 095aa788..3a7c7e6f 100644 --- a/opendc-web/opendc-web-ui/src/api/scenarios.js +++ b/opendc-web/opendc-web-ui/src/api/scenarios.js @@ -22,12 +22,12 @@ import { request } from './index' -export function addScenario(auth, portfolioId, scenario) { - return request(auth, `portfolios/${portfolioId}/scenarios`, 'POST', { scenario }) +export function fetchScenario(auth, scenarioId) { + return request(auth, `scenarios/${scenarioId}`) } -export function getScenario(auth, scenarioId) { - return request(auth, `scenarios/${scenarioId}`) +export function addScenario(auth, scenario) { + return request(auth, `portfolios/${scenario.portfolioId}/scenarios`, 'POST', { scenario }) } export function updateScenario(auth, scenarioId, scenario) { diff --git a/opendc-web/opendc-web-ui/src/containers/app/results/PortfolioResultsContainer.js b/opendc-web/opendc-web-ui/src/containers/app/results/PortfolioResultsContainer.js index ce7d5514..f9a380cb 100644 --- a/opendc-web/opendc-web-ui/src/containers/app/results/PortfolioResultsContainer.js +++ b/opendc-web/opendc-web-ui/src/containers/app/results/PortfolioResultsContainer.js @@ -1,32 +1,15 @@ import React from 'react' -import { useSelector } from 'react-redux' import PortfolioResultsComponent from '../../../components/app/results/PortfolioResultsComponent' import { useRouter } from 'next/router' +import { usePortfolio, useScenarios } from '../../../data/project' const PortfolioResultsContainer = (props) => { const router = useRouter() const { portfolio: currentPortfolioId } = router.query - const { scenarios, portfolio } = useSelector((state) => { - if ( - !currentPortfolioId || - !state.objects.portfolio[currentPortfolioId] || - state.objects.portfolio[currentPortfolioId].scenarioIds - .map((scenarioId) => state.objects.scenario[scenarioId]) - .some((s) => s === undefined) - ) { - return { - portfolio: undefined, - scenarios: [], - } - } - - return { - portfolio: state.objects.portfolio[currentPortfolioId], - scenarios: state.objects.portfolio[currentPortfolioId].scenarioIds.map( - (scenarioId) => state.objects.scenario[scenarioId] - ), - } - }) + const { data: portfolio } = usePortfolio(currentPortfolioId) + const scenarios = useScenarios(portfolio?.scenarioIds ?? []) + .filter((res) => res.data) + .map((res) => res.data) return } diff --git a/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/PortfolioListContainer.js b/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/PortfolioListContainer.js index 1b539b8f..01183724 100644 --- a/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/PortfolioListContainer.js +++ b/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/PortfolioListContainer.js @@ -2,17 +2,36 @@ import React, { useState } from 'react' import { useDispatch } from 'react-redux' import { useRouter } from 'next/router' import PortfolioListComponent from '../../../../components/app/sidebars/project/PortfolioListComponent' -import { addPortfolio, deletePortfolio } from '../../../../redux/actions/portfolios' -import { getState } from '../../../../util/state-utils' -import { setCurrentTopology } from '../../../../redux/actions/topology/building' import NewPortfolioModalComponent from '../../../../components/modals/custom-components/NewPortfolioModalComponent' -import { useActivePortfolioId, useActiveProjectId, usePortfolios, useProject } from '../../../../data/project' +import { usePortfolios, useProject } from '../../../../data/project' +import { useMutation, useQueryClient } from 'react-query' +import { addPortfolio, deletePortfolio } from '../../../../api/portfolios' +import { useAuth } from '../../../../auth' const PortfolioListContainer = () => { const router = useRouter() const { project: currentProjectId, portfolio: currentPortfolioId } = router.query const { data: currentProject } = useProject(currentProjectId) - const portfolios = usePortfolios(currentProjectId) + const portfolios = usePortfolios(currentProject?.portfolioIds ?? []) + .filter((res) => res.data) + .map((res) => res.data) + + const auth = useAuth() + const queryClient = useQueryClient() + const addMutation = useMutation((data) => addPortfolio(auth, data), { + onSuccess: async (result) => { + await queryClient.invalidateQueries(['projects', currentProjectId]) + }, + }) + const deleteMutation = useMutation((id) => deletePortfolio(auth, id), { + onSuccess: async (result) => { + queryClient.setQueryData(['projects', currentProjectId], (old) => ({ + ...old, + portfolioIds: old.portfolioIds.filter((id) => id !== result._id), + })) + queryClient.removeQueries(['portfolios', result._id]) + }, + }) const dispatch = useDispatch() const [isVisible, setVisible] = useState(false) @@ -23,21 +42,14 @@ const PortfolioListContainer = () => { }, onDeletePortfolio: async (id) => { if (id) { - const state = await getState(dispatch) - dispatch(deletePortfolio(id)) - dispatch(setCurrentTopology(currentProject.topologyIds[0])) + await deleteMutation.mutateAsync(id) await router.push(`/projects/${currentProjectId}`) } }, } const callback = (name, targets) => { if (name) { - dispatch( - addPortfolio(currentProjectId, { - name, - targets, - }) - ) + addMutation.mutate({ projectId: currentProjectId, name, targets }) } setVisible(false) } diff --git a/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/ScenarioListContainer.js b/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/ScenarioListContainer.js index 7acc13ee..6bfc8599 100644 --- a/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/ScenarioListContainer.js +++ b/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/ScenarioListContainer.js @@ -1,20 +1,40 @@ import PropTypes from 'prop-types' import React, { useState } from 'react' -import { useDispatch } from 'react-redux' import ScenarioListComponent from '../../../../components/app/sidebars/project/ScenarioListComponent' -import { addScenario, deleteScenario } from '../../../../redux/actions/scenarios' import NewScenarioModalComponent from '../../../../components/modals/custom-components/NewScenarioModalComponent' import { useProjectTopologies } from '../../../../data/topology' -import { useScenarios } from '../../../../data/project' +import { usePortfolio, useScenarios } from '../../../../data/project' import { useSchedulers, useTraces } from '../../../../data/experiments' +import { useAuth } from '../../../../auth' +import { useMutation, useQueryClient } from 'react-query' +import { addScenario, deleteScenario } from '../../../../api/scenarios' const ScenarioListContainer = ({ portfolioId }) => { - const scenarios = useScenarios(portfolioId) + const { data: portfolio } = usePortfolio(portfolioId) + const scenarios = useScenarios(portfolio?.scenarioIds ?? []) + .filter((res) => res.data) + .map((res) => res.data) const topologies = useProjectTopologies() const traces = useTraces().data ?? [] const schedulers = useSchedulers().data ?? [] - const dispatch = useDispatch() + const auth = useAuth() + const queryClient = useQueryClient() + const addMutation = useMutation((data) => addScenario(auth, data), { + onSuccess: async (result) => { + await queryClient.invalidateQueries(['portfolios', portfolioId]) + }, + }) + const deleteMutation = useMutation((id) => deleteScenario(auth, id), { + onSuccess: async (result) => { + queryClient.setQueryData(['portfolios', portfolioId], (old) => ({ + ...old, + scenarioIds: old.scenarioIds.filter((id) => id !== result._id), + })) + queryClient.removeQueries(['scenarios', result._id]) + }, + }) + const [isVisible, setVisible] = useState(false) const onNewScenario = (currentPortfolioId) => { @@ -22,20 +42,18 @@ const ScenarioListContainer = ({ portfolioId }) => { } const onDeleteScenario = (id) => { if (id) { - dispatch(deleteScenario(id)) + deleteMutation.mutate(id) } } const callback = (name, portfolioId, trace, topology, operational) => { if (name) { - dispatch( - addScenario({ - portfolioId, - name, - trace, - topology, - operational, - }) - ) + addMutation.mutate({ + portfolioId, + name, + trace, + topology, + operational, + }) } setVisible(false) diff --git a/opendc-web/opendc-web-ui/src/data/project.js b/opendc-web/opendc-web-ui/src/data/project.js index 308930e5..5cf620da 100644 --- a/opendc-web/opendc-web-ui/src/data/project.js +++ b/opendc-web/opendc-web-ui/src/data/project.js @@ -20,11 +20,12 @@ * SOFTWARE. */ -import { useSelector } from 'react-redux' -import { useQuery } from 'react-query' +import { useQueries, useQuery } from 'react-query' import { fetchProject, fetchProjects } from '../api/projects' import { useAuth } from '../auth' import { useRouter } from 'next/router' +import { fetchPortfolio } from '../api/portfolios' +import { fetchScenario } from '../api/scenarios' /** * Return the available projects. @@ -39,45 +40,48 @@ export function useProjects() { */ export function useProject(projectId) { const auth = useAuth() - return useQuery(`projects/${projectId}`, () => fetchProject(auth, projectId), { enabled: !!projectId }) + return useQuery(['projects', projectId], () => fetchProject(auth, projectId), { enabled: !!projectId }) } /** - * Return the current active project identifier. + * Return the portfolio with the specified identifier. */ -export function useActiveProjectId() { - const router = useRouter() - const { project } = router.query - return project +export function usePortfolio(portfolioId) { + const auth = useAuth() + return useQuery(['portfolios', portfolioId], () => fetchPortfolio(auth, portfolioId), { enabled: !!portfolioId }) } /** * Return the portfolios for the specified project id. */ -export function usePortfolios(projectId) { - const { data: project } = useProject(projectId) - return useSelector((state) => { - let portfolios = project?.portfolioIds?.map((t) => state.objects.portfolio[t]) ?? [] - if (portfolios.filter((t) => !t).length > 0) { - portfolios = [] - } - - return portfolios - }) +export function usePortfolios(portfolioIds) { + const auth = useAuth() + return useQueries( + portfolioIds.map((portfolioId) => ({ + queryKey: ['portfolios', portfolioId], + queryFn: () => fetchPortfolio(auth, portfolioId), + })) + ) } /** - * Return the scenarios for the specified portfolio id. + * Return the scenarios with the specified identifiers. */ -export function useScenarios(portfolioId) { - return useSelector((state) => { - let scenarios = state.objects.portfolio[portfolioId] - ? state.objects.portfolio[portfolioId].scenarioIds.map((t) => state.objects.scenario[t]) - : [] - if (scenarios.filter((t) => !t).length > 0) { - scenarios = [] - } +export function useScenarios(scenarioIds) { + const auth = useAuth() + return useQueries( + scenarioIds.map((scenarioId) => ({ + queryKey: ['scenario', scenarioId], + queryFn: () => fetchScenario(auth, scenarioId), + })) + ) +} - return scenarios - }) +/** + * Return the current active project identifier. + */ +export function useActiveProjectId() { + const router = useRouter() + const { project } = router.query + return project } diff --git a/opendc-web/opendc-web-ui/src/pages/projects/[project]/portfolios/[portfolio].js b/opendc-web/opendc-web-ui/src/pages/projects/[project]/portfolios/[portfolio].js index b21db44c..d3d61271 100644 --- a/opendc-web/opendc-web-ui/src/pages/projects/[project]/portfolios/[portfolio].js +++ b/opendc-web/opendc-web-ui/src/pages/projects/[project]/portfolios/[portfolio].js @@ -23,12 +23,11 @@ import { useRouter } from 'next/router' import Head from 'next/head' import AppNavbarContainer from '../../../../containers/navigation/AppNavbarContainer' -import React, { useEffect } from 'react' +import React from 'react' import { useProject } from '../../../../data/project' import ProjectSidebarContainer from '../../../../containers/app/sidebars/project/ProjectSidebarContainer' import PortfolioResultsContainer from '../../../../containers/app/results/PortfolioResultsContainer' import { useDispatch } from 'react-redux' -import { openPortfolioSucceeded } from '../../../../redux/actions/portfolios' /** * Page that displays the results in a portfolio. @@ -41,11 +40,6 @@ function Portfolio() { const title = project?.name ? project?.name + ' - OpenDC' : 'Simulation - OpenDC' const dispatch = useDispatch() - useEffect(() => { - if (portfolioId) { - dispatch(openPortfolioSucceeded(projectId, portfolioId)) - } - }, [projectId, portfolioId, dispatch]) return (
diff --git a/opendc-web/opendc-web-ui/src/redux/actions/portfolios.js b/opendc-web/opendc-web-ui/src/redux/actions/portfolios.js deleted file mode 100644 index 923cd217..00000000 --- a/opendc-web/opendc-web-ui/src/redux/actions/portfolios.js +++ /dev/null @@ -1,34 +0,0 @@ -export const ADD_PORTFOLIO = 'ADD_PORTFOLIO' -export const UPDATE_PORTFOLIO = 'UPDATE_PORTFOLIO' -export const DELETE_PORTFOLIO = 'DELETE_PORTFOLIO' -export const OPEN_PORTFOLIO_SUCCEEDED = 'OPEN_PORTFOLIO_SUCCEEDED' - -export function addPortfolio(projectId, portfolio) { - return { - type: ADD_PORTFOLIO, - projectId, - portfolio, - } -} - -export function updatePortfolio(portfolio) { - return { - type: UPDATE_PORTFOLIO, - portfolio, - } -} - -export function deletePortfolio(id) { - return { - type: DELETE_PORTFOLIO, - id, - } -} - -export function openPortfolioSucceeded(projectId, portfolioId) { - return { - type: OPEN_PORTFOLIO_SUCCEEDED, - projectId, - portfolioId, - } -} diff --git a/opendc-web/opendc-web-ui/src/redux/actions/scenarios.js b/opendc-web/opendc-web-ui/src/redux/actions/scenarios.js deleted file mode 100644 index 644933d6..00000000 --- a/opendc-web/opendc-web-ui/src/redux/actions/scenarios.js +++ /dev/null @@ -1,34 +0,0 @@ -export const ADD_SCENARIO = 'ADD_SCENARIO' -export const UPDATE_SCENARIO = 'UPDATE_SCENARIO' -export const DELETE_SCENARIO = 'DELETE_SCENARIO' -export const OPEN_SCENARIO_SUCCEEDED = 'OPEN_SCENARIO_SUCCEEDED' - -export function addScenario(scenario) { - return { - type: ADD_SCENARIO, - scenario, - } -} - -export function updateScenario(scenario) { - return { - type: UPDATE_SCENARIO, - scenario, - } -} - -export function deleteScenario(id) { - return { - type: DELETE_SCENARIO, - id, - } -} - -export function openScenarioSucceeded(projectId, portfolioId, scenarioId) { - return { - type: OPEN_SCENARIO_SUCCEEDED, - projectId, - portfolioId, - scenarioId, - } -} diff --git a/opendc-web/opendc-web-ui/src/redux/middleware/viewport-adjustment.js b/opendc-web/opendc-web-ui/src/redux/middleware/viewport-adjustment.js index 6b22eb80..bee6becd 100644 --- a/opendc-web/opendc-web-ui/src/redux/middleware/viewport-adjustment.js +++ b/opendc-web/opendc-web-ui/src/redux/middleware/viewport-adjustment.js @@ -22,7 +22,7 @@ export const viewportAdjustmentMiddleware = (store) => (next) => (action) => { mapDimensions = { width: action.width, height: action.height } } - if (topologyId !== '-1') { + if (topologyId && topologyId !== '-1') { const roomIds = state.objects.topology[topologyId].roomIds const rooms = roomIds.map((id) => Object.assign({}, state.objects.room[id])) rooms.forEach((room) => (room.tiles = room.tileIds.map((tileId) => state.objects.tile[tileId]))) diff --git a/opendc-web/opendc-web-ui/src/redux/reducers/construction-mode.js b/opendc-web/opendc-web-ui/src/redux/reducers/construction-mode.js index 257dddd2..5bac7fea 100644 --- a/opendc-web/opendc-web-ui/src/redux/reducers/construction-mode.js +++ b/opendc-web/opendc-web-ui/src/redux/reducers/construction-mode.js @@ -9,8 +9,6 @@ import { START_ROOM_EDIT, } from '../actions/topology/building' import { DELETE_ROOM, START_RACK_CONSTRUCTION, STOP_RACK_CONSTRUCTION } from '../actions/topology/room' -import { OPEN_PORTFOLIO_SUCCEEDED } from '../actions/portfolios' -import { OPEN_SCENARIO_SUCCEEDED } from '../actions/scenarios' export function currentRoomInConstruction(state = '-1', action) { switch (action.type) { @@ -20,8 +18,6 @@ export function currentRoomInConstruction(state = '-1', action) { return action.roomId case CANCEL_NEW_ROOM_CONSTRUCTION_SUCCEEDED: case FINISH_NEW_ROOM_CONSTRUCTION: - case OPEN_PORTFOLIO_SUCCEEDED: - case OPEN_SCENARIO_SUCCEEDED: case FINISH_ROOM_EDIT: case SET_CURRENT_TOPOLOGY: case DELETE_ROOM: @@ -36,8 +32,6 @@ export function inRackConstructionMode(state = false, action) { case START_RACK_CONSTRUCTION: return true case STOP_RACK_CONSTRUCTION: - case OPEN_PORTFOLIO_SUCCEEDED: - case OPEN_SCENARIO_SUCCEEDED: case SET_CURRENT_TOPOLOGY: case GO_DOWN_ONE_INTERACTION_LEVEL: return false diff --git a/opendc-web/opendc-web-ui/src/redux/reducers/interaction-level.js b/opendc-web/opendc-web-ui/src/redux/reducers/interaction-level.js index 8bf81b98..9f23949f 100644 --- a/opendc-web/opendc-web-ui/src/redux/reducers/interaction-level.js +++ b/opendc-web/opendc-web-ui/src/redux/reducers/interaction-level.js @@ -1,4 +1,3 @@ -import { OPEN_PORTFOLIO_SUCCEEDED } from '../actions/portfolios' import { GO_DOWN_ONE_INTERACTION_LEVEL, GO_FROM_BUILDING_TO_ROOM, @@ -6,12 +5,9 @@ import { GO_FROM_ROOM_TO_RACK, } from '../actions/interaction-level' import { SET_CURRENT_TOPOLOGY } from '../actions/topology/building' -import { OPEN_SCENARIO_SUCCEEDED } from '../actions/scenarios' export function interactionLevel(state = { mode: 'BUILDING' }, action) { switch (action.type) { - case OPEN_PORTFOLIO_SUCCEEDED: - case OPEN_SCENARIO_SUCCEEDED: case SET_CURRENT_TOPOLOGY: return { mode: 'BUILDING', diff --git a/opendc-web/opendc-web-ui/src/redux/sagas/index.js b/opendc-web/opendc-web-ui/src/redux/sagas/index.js index 939be691..74d9efb6 100644 --- a/opendc-web/opendc-web-ui/src/redux/sagas/index.js +++ b/opendc-web/opendc-web-ui/src/redux/sagas/index.js @@ -1,6 +1,5 @@ import { takeEvery } from 'redux-saga/effects' -import { ADD_PORTFOLIO, DELETE_PORTFOLIO, OPEN_PORTFOLIO_SUCCEEDED, UPDATE_PORTFOLIO } from '../actions/portfolios' -import { ADD_PROJECT, DELETE_PROJECT, FETCH_PROJECTS, OPEN_PROJECT_SUCCEEDED } from '../actions/projects' +import { OPEN_PROJECT_SUCCEEDED } from '../actions/projects' import { ADD_TILE, CANCEL_NEW_ROOM_CONSTRUCTION, @@ -10,7 +9,6 @@ import { import { ADD_UNIT, DELETE_MACHINE, DELETE_UNIT } from '../actions/topology/machine' import { ADD_MACHINE, DELETE_RACK, EDIT_RACK_NAME } from '../actions/topology/rack' import { ADD_RACK_TO_TILE, DELETE_ROOM, EDIT_ROOM_NAME } from '../actions/topology/room' -import { onAddPortfolio, onDeletePortfolio, onOpenPortfolioSucceeded, onUpdatePortfolio } from './portfolios' import { onOpenProjectSucceeded } from './projects' import { onAddMachine, @@ -30,15 +28,11 @@ import { onStartNewRoomConstruction, } from './topology' import { ADD_TOPOLOGY, DELETE_TOPOLOGY } from '../actions/topologies' -import { ADD_SCENARIO, DELETE_SCENARIO, OPEN_SCENARIO_SUCCEEDED, UPDATE_SCENARIO } from '../actions/scenarios' -import { onAddScenario, onDeleteScenario, onOpenScenarioSucceeded, onUpdateScenario } from './scenarios' import { onAddPrefab } from './prefabs' import { ADD_PREFAB } from '../actions/prefabs' export default function* rootSaga() { yield takeEvery(OPEN_PROJECT_SUCCEEDED, onOpenProjectSucceeded) - yield takeEvery(OPEN_PORTFOLIO_SUCCEEDED, onOpenPortfolioSucceeded) - yield takeEvery(OPEN_SCENARIO_SUCCEEDED, onOpenScenarioSucceeded) yield takeEvery(ADD_TOPOLOGY, onAddTopology) yield takeEvery(DELETE_TOPOLOGY, onDeleteTopology) @@ -56,13 +50,5 @@ export default function* rootSaga() { yield takeEvery(ADD_UNIT, onAddUnit) yield takeEvery(DELETE_UNIT, onDeleteUnit) - yield takeEvery(ADD_PORTFOLIO, onAddPortfolio) - yield takeEvery(UPDATE_PORTFOLIO, onUpdatePortfolio) - yield takeEvery(DELETE_PORTFOLIO, onDeletePortfolio) - - yield takeEvery(ADD_SCENARIO, onAddScenario) - yield takeEvery(UPDATE_SCENARIO, onUpdateScenario) - yield takeEvery(DELETE_SCENARIO, onDeleteScenario) - yield takeEvery(ADD_PREFAB, onAddPrefab) } diff --git a/opendc-web/opendc-web-ui/src/redux/sagas/objects.js b/opendc-web/opendc-web-ui/src/redux/sagas/objects.js index fe826014..88f71fe4 100644 --- a/opendc-web/opendc-web-ui/src/redux/sagas/objects.js +++ b/opendc-web/opendc-web-ui/src/redux/sagas/objects.js @@ -1,7 +1,5 @@ import { call, put, select, getContext } from 'redux-saga/effects' import { addToStore } from '../actions/objects' -import { fetchSchedulers } from '../../api/schedulers' -import { fetchTraces } from '../../api/traces' import { getTopology, updateTopology } from '../../api/topologies' import { uuid } from 'uuidv4' @@ -21,24 +19,9 @@ export const OBJECT_SELECTORS = { topology: (state) => state.objects.topology, } -function* fetchAndStoreObject(objectType, id, apiCall) { - const objectStore = yield select(OBJECT_SELECTORS[objectType]) - let object = objectStore[id] - if (!object) { - object = yield apiCall - yield put(addToStore(objectType, object)) - } - return object -} - -function* fetchAndStoreObjects(objectType, apiCall) { - const objects = yield apiCall - for (let object of objects) { - yield put(addToStore(objectType, object)) - } - return objects -} - +/** + * Fetches and normalizes the topology with the specified identifier. + */ export const fetchAndStoreTopology = function* (id) { const topologyStore = yield select(OBJECT_SELECTORS['topology']) const roomStore = yield select(OBJECT_SELECTORS['room']) @@ -135,12 +118,15 @@ const generateIdIfNotPresent = (obj) => { } export const updateTopologyOnServer = function* (id) { - const topology = yield getTopologyAsObject(id, true) + const topology = yield denormalizeTopology(id, true) const auth = yield getContext('auth') yield call(updateTopology, auth, topology) } -export const getTopologyAsObject = function* (id, keepIds) { +/** + * Denormalizes the topology representation in order to be stored on the server. + */ +export const denormalizeTopology = function* (id, keepIds) { const topologyStore = yield select(OBJECT_SELECTORS['topology']) const rooms = yield getAllRooms(topologyStore[id].roomIds, keepIds) return { diff --git a/opendc-web/opendc-web-ui/src/redux/sagas/portfolios.js b/opendc-web/opendc-web-ui/src/redux/sagas/portfolios.js deleted file mode 100644 index 68956225..00000000 --- a/opendc-web/opendc-web-ui/src/redux/sagas/portfolios.js +++ /dev/null @@ -1,114 +0,0 @@ -import { call, put, select, delay, getContext } from 'redux-saga/effects' -import { addToStore } from '../actions/objects' -import { addPortfolio, deletePortfolio, getPortfolio, updatePortfolio } from '../../api/portfolios' -import { fetchProject } from '../../api/projects' -import { getScenario } from '../../api/scenarios' - -export function* onOpenPortfolioSucceeded(action) { - try { - const auth = yield getContext('auth') - const queryClient = yield getContext('queryClient') - const project = yield call(() => - queryClient.fetchQuery(`projects/${action.projectId}`, () => fetchProject(auth, action.projectId)) - ) - yield fetchAndStoreAllTopologiesOfProject(action.projectId) - yield fetchPortfoliosOfProject(project) - - yield watchForPortfolioResults(action.portfolioId) - } catch (error) { - console.error(error) - } -} - -export function* watchForPortfolioResults(portfolioId) { - try { - let unfinishedScenarios = yield getCurrentUnfinishedScenarios(portfolioId) - - while (unfinishedScenarios.length > 0) { - yield delay(3000) - yield fetchPortfolioWithScenarios(portfolioId) - unfinishedScenarios = yield getCurrentUnfinishedScenarios(portfolioId) - } - } catch (error) { - console.error(error) - } -} - -export function* getCurrentUnfinishedScenarios(portfolioId) { - try { - if (!portfolioId) { - return [] - } - - const scenarioIds = yield select((state) => state.objects.portfolio[portfolioId].scenarioIds) - const scenarioObjects = yield select((state) => state.objects.scenario) - const scenarios = scenarioIds.map((s) => scenarioObjects[s]) - return scenarios.filter((s) => !s || s.simulation.state === 'QUEUED' || s.simulation.state === 'RUNNING') - } catch (error) { - console.error(error) - } -} - -export function* fetchPortfoliosOfProject(project) { - try { - for (const i in project.portfolioIds) { - yield fetchPortfolioWithScenarios(project.portfolioIds[i]) - } - } catch (error) { - console.error(error) - } -} - -export function* fetchPortfolioWithScenarios(portfolioId) { - try { - const auth = yield getContext('auth') - const portfolio = yield call(getPortfolio, auth, portfolioId) - yield put(addToStore('portfolio', portfolio)) - - for (let i in portfolio.scenarioIds) { - const scenario = yield call(getScenario, auth, portfolio.scenarioIds[i]) - yield put(addToStore('scenario', scenario)) - } - return portfolio - } catch (error) { - console.error(error) - } -} - -export function* onAddPortfolio(action) { - try { - const { projectId } = action - const auth = yield getContext('auth') - const portfolio = yield call( - addPortfolio, - auth, - projectId, - Object.assign({}, action.portfolio, { - projectId: projectId, - scenarioIds: [], - }) - ) - yield put(addToStore('portfolio', portfolio)) - } catch (error) { - console.error(error) - } -} - -export function* onUpdatePortfolio(action) { - try { - const auth = yield getContext('auth') - const portfolio = yield call(updatePortfolio, auth, action.portfolio._id, action.portfolio) - yield put(addToStore('portfolio', portfolio)) - } catch (error) { - console.error(error) - } -} - -export function* onDeletePortfolio(action) { - try { - const auth = yield getContext('auth') - yield call(deletePortfolio, auth, action.id) - } catch (error) { - console.error(error) - } -} diff --git a/opendc-web/opendc-web-ui/src/redux/sagas/projects.js b/opendc-web/opendc-web-ui/src/redux/sagas/projects.js index 6dc3c682..5809d4d2 100644 --- a/opendc-web/opendc-web-ui/src/redux/sagas/projects.js +++ b/opendc-web/opendc-web-ui/src/redux/sagas/projects.js @@ -1,18 +1,8 @@ -import { call, getContext } from 'redux-saga/effects' import { fetchAndStoreAllTopologiesOfProject } from './topology' -import { fetchPortfoliosOfProject } from './portfolios' -import { fetchProject } from '../../api/projects' export function* onOpenProjectSucceeded(action) { try { - const auth = yield getContext('auth') - const queryClient = yield getContext('queryClient') - const project = yield call(() => - queryClient.fetchQuery(`projects/${action.id}`, () => fetchProject(auth, action.id)) - ) - yield fetchAndStoreAllTopologiesOfProject(action.id, true) - yield fetchPortfoliosOfProject(project) } catch (error) { console.error(error) } diff --git a/opendc-web/opendc-web-ui/src/redux/sagas/scenarios.js b/opendc-web/opendc-web-ui/src/redux/sagas/scenarios.js deleted file mode 100644 index 10ab3547..00000000 --- a/opendc-web/opendc-web-ui/src/redux/sagas/scenarios.js +++ /dev/null @@ -1,69 +0,0 @@ -import { call, put, select, getContext } from 'redux-saga/effects' -import { addPropToStoreObject, addToStore } from '../actions/objects' -import { fetchProject } from '../../api/projects' -import { fetchAndStoreAllTopologiesOfProject } from './topology' -import { addScenario, deleteScenario, updateScenario } from '../../api/scenarios' -import { fetchPortfolioWithScenarios, watchForPortfolioResults } from './portfolios' - -export function* onOpenScenarioSucceeded(action) { - try { - const auth = yield getContext('auth') - const queryClient = yield getContext('queryClient') - const project = yield call(() => - queryClient.fetchQuery(`projects/${action.projectId}`, () => fetchProject(auth, action.projectId)) - ) - yield put(addToStore('project', project)) - yield fetchAndStoreAllTopologiesOfProject(project._id) - yield fetchPortfolioWithScenarios(action.portfolioId) - - // TODO Fetch scenario-specific metrics - } catch (error) { - console.error(error) - } -} - -export function* onAddScenario(action) { - try { - const auth = yield getContext('auth') - const scenario = yield call(addScenario, auth, action.scenario.portfolioId, action.scenario) - yield put(addToStore('scenario', scenario)) - - const scenarioIds = yield select((state) => state.objects.portfolio[action.scenario.portfolioId].scenarioIds) - yield put( - addPropToStoreObject('portfolio', action.scenario.portfolioId, { - scenarioIds: scenarioIds.concat([scenario._id]), - }) - ) - yield watchForPortfolioResults(action.scenario.portfolioId) - } catch (error) { - console.error(error) - } -} - -export function* onUpdateScenario(action) { - try { - const auth = yield getContext('auth') - const scenario = yield call(updateScenario, auth, action.scenario._id, action.scenario) - yield put(addToStore('scenario', scenario)) - } catch (error) { - console.error(error) - } -} - -export function* onDeleteScenario(action) { - try { - const auth = yield getContext('auth') - const scenario = yield select((state) => state.objects.scenario[action.id]) - yield call(deleteScenario, auth, action.id) - - const scenarioIds = yield select((state) => state.objects.portfolio[scenario.portfolioId].scenarioIds) - - yield put( - addPropToStoreObject('scenario', scenario.portfolioId, { - scenarioIds: scenarioIds.filter((id) => id !== action.id), - }) - ) - } catch (error) { - console.error(error) - } -} diff --git a/opendc-web/opendc-web-ui/src/redux/sagas/topology.js b/opendc-web/opendc-web-ui/src/redux/sagas/topology.js index 3f41e1d4..efa125c6 100644 --- a/opendc-web/opendc-web-ui/src/redux/sagas/topology.js +++ b/opendc-web/opendc-web-ui/src/redux/sagas/topology.js @@ -16,7 +16,7 @@ import { DEFAULT_RACK_SLOT_CAPACITY, MAX_NUM_UNITS_PER_MACHINE, } from '../../components/app/map/MapConstants' -import { fetchAndStoreTopology, getTopologyAsObject, updateTopologyOnServer } from './objects' +import { fetchAndStoreTopology, denormalizeTopology, updateTopologyOnServer } from './objects' import { uuid } from 'uuidv4' import { addTopology, deleteTopology } from '../../api/topologies' import { fetchProject } from '../../api/projects' @@ -26,7 +26,7 @@ export function* fetchAndStoreAllTopologiesOfProject(projectId, setTopology = fa const auth = yield getContext('auth') const queryClient = yield getContext('queryClient') const project = yield call(() => - queryClient.fetchQuery(`projects/${projectId}`, () => fetchProject(auth, projectId)) + queryClient.fetchQuery(['projects', projectId], () => fetchProject(auth, projectId)) ) for (let i in project.topologyIds) { @@ -47,7 +47,7 @@ export function* onAddTopology(action) { let topologyToBeCreated if (duplicateId) { - topologyToBeCreated = yield getTopologyAsObject(duplicateId, false) + topologyToBeCreated = yield denormalizeTopology(duplicateId, false) topologyToBeCreated = { ...topologyToBeCreated, name } } else { topologyToBeCreated = { name: action.name, rooms: [] } @@ -67,7 +67,7 @@ export function* onDeleteTopology(action) { const auth = yield getContext('auth') const queryClient = yield getContext('queryClient') const project = yield call(() => - queryClient.fetchQuery(`projects/${action.projectId}`, () => fetchProject(auth, action.projectId)) + queryClient.fetchQuery(['projects', action.projectId], () => fetchProject(auth, action.projectId)) ) const topologyIds = project?.topologyIds ?? [] -- cgit v1.2.3 From 02a2f0f89cb1f39a5f8856bca1971a4e1b12374f Mon Sep 17 00:00:00 2001 From: Fabian Mastenbroek Date: Wed, 7 Jul 2021 20:13:30 +0200 Subject: ui: Use React Query defaults to reduce duplication --- opendc-web/opendc-web-ui/src/api/topologies.js | 8 +- .../src/components/app/map/MapStageComponent.js | 4 +- .../app/sidebars/project/PortfolioListContainer.js | 28 ++----- .../app/sidebars/project/ScenarioListContainer.js | 43 +++------- .../app/sidebars/project/TopologyListContainer.js | 14 ++-- .../src/containers/projects/NewProjectContainer.js | 12 +-- .../src/containers/projects/ProjectActions.js | 12 +-- .../containers/projects/ProjectListContainer.js | 1 - opendc-web/opendc-web-ui/src/data/experiments.js | 15 ++-- opendc-web/opendc-web-ui/src/data/project.js | 96 ++++++++++++++++++---- opendc-web/opendc-web-ui/src/data/topology.js | 55 +++++++++---- opendc-web/opendc-web-ui/src/pages/_app.js | 12 ++- .../opendc-web-ui/src/redux/actions/topologies.js | 8 -- opendc-web/opendc-web-ui/src/redux/sagas/index.js | 4 +- .../opendc-web-ui/src/redux/sagas/objects.js | 4 +- .../opendc-web-ui/src/redux/sagas/topology.js | 28 +------ 16 files changed, 181 insertions(+), 163 deletions(-) diff --git a/opendc-web/opendc-web-ui/src/api/topologies.js b/opendc-web/opendc-web-ui/src/api/topologies.js index 40685094..74fc1977 100644 --- a/opendc-web/opendc-web-ui/src/api/topologies.js +++ b/opendc-web/opendc-web-ui/src/api/topologies.js @@ -22,12 +22,12 @@ import { request } from './index' -export function addTopology(auth, topology) { - return request(auth, `projects/${topology.projectId}/topologies`, 'POST', { topology }) +export function fetchTopology(auth, topologyId) { + return request(auth, `topologies/${topologyId}`) } -export function getTopology(auth, topologyId) { - return request(auth, `topologies/${topologyId}`) +export function addTopology(auth, topology) { + return request(auth, `projects/${topology.projectId}/topologies`, 'POST', { topology }) } export function updateTopology(auth, topology) { diff --git a/opendc-web/opendc-web-ui/src/components/app/map/MapStageComponent.js b/opendc-web/opendc-web-ui/src/components/app/map/MapStageComponent.js index a8e156ec..c3177fe1 100644 --- a/opendc-web/opendc-web-ui/src/components/app/map/MapStageComponent.js +++ b/opendc-web/opendc-web-ui/src/components/app/map/MapStageComponent.js @@ -1,4 +1,3 @@ -/* eslint-disable react-hooks/exhaustive-deps */ import PropTypes from 'prop-types' import React, { useEffect, useRef, useState } from 'react' import { HotKeys } from 'react-hotkeys' @@ -42,7 +41,6 @@ function MapStageComponent({ const updateScale = (e) => zoomInOnPosition(e.deltaY < 0, x, y) // We explicitly do not specify any dependencies to prevent infinitely dispatching updateDimensions commands - // eslint-disable-next-line react-hooks/exhaustive-deps useEffect(() => { updateDimensions() @@ -60,7 +58,7 @@ function MapStageComponent({ window.removeEventListener('resize', updateDimensions) window.removeEventListener('wheel', updateScale) } - }, []) + }, []) // eslint-disable-line react-hooks/exhaustive-deps const store = useStore() diff --git a/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/PortfolioListContainer.js b/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/PortfolioListContainer.js index 01183724..1fb88253 100644 --- a/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/PortfolioListContainer.js +++ b/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/PortfolioListContainer.js @@ -1,12 +1,9 @@ import React, { useState } from 'react' -import { useDispatch } from 'react-redux' import { useRouter } from 'next/router' import PortfolioListComponent from '../../../../components/app/sidebars/project/PortfolioListComponent' import NewPortfolioModalComponent from '../../../../components/modals/custom-components/NewPortfolioModalComponent' import { usePortfolios, useProject } from '../../../../data/project' -import { useMutation, useQueryClient } from 'react-query' -import { addPortfolio, deletePortfolio } from '../../../../api/portfolios' -import { useAuth } from '../../../../auth' +import { useMutation } from 'react-query' const PortfolioListContainer = () => { const router = useRouter() @@ -16,24 +13,9 @@ const PortfolioListContainer = () => { .filter((res) => res.data) .map((res) => res.data) - const auth = useAuth() - const queryClient = useQueryClient() - const addMutation = useMutation((data) => addPortfolio(auth, data), { - onSuccess: async (result) => { - await queryClient.invalidateQueries(['projects', currentProjectId]) - }, - }) - const deleteMutation = useMutation((id) => deletePortfolio(auth, id), { - onSuccess: async (result) => { - queryClient.setQueryData(['projects', currentProjectId], (old) => ({ - ...old, - portfolioIds: old.portfolioIds.filter((id) => id !== result._id), - })) - queryClient.removeQueries(['portfolios', result._id]) - }, - }) + const { mutate: addPortfolio } = useMutation('addPortfolio') + const { mutateAsync: deletePortfolio } = useMutation('deletePortfolio') - const dispatch = useDispatch() const [isVisible, setVisible] = useState(false) const actions = { onNewPortfolio: () => setVisible(true), @@ -42,14 +24,14 @@ const PortfolioListContainer = () => { }, onDeletePortfolio: async (id) => { if (id) { - await deleteMutation.mutateAsync(id) + await deletePortfolio(id) await router.push(`/projects/${currentProjectId}`) } }, } const callback = (name, targets) => { if (name) { - addMutation.mutate({ projectId: currentProjectId, name, targets }) + addPortfolio({ projectId: currentProjectId, name, targets }) } setVisible(false) } diff --git a/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/ScenarioListContainer.js b/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/ScenarioListContainer.js index 6bfc8599..62761583 100644 --- a/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/ScenarioListContainer.js +++ b/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/ScenarioListContainer.js @@ -2,52 +2,33 @@ import PropTypes from 'prop-types' import React, { useState } from 'react' import ScenarioListComponent from '../../../../components/app/sidebars/project/ScenarioListComponent' import NewScenarioModalComponent from '../../../../components/modals/custom-components/NewScenarioModalComponent' -import { useProjectTopologies } from '../../../../data/topology' -import { usePortfolio, useScenarios } from '../../../../data/project' +import { useTopologies } from '../../../../data/topology' +import { usePortfolio, useProject, useScenarios } from '../../../../data/project' import { useSchedulers, useTraces } from '../../../../data/experiments' -import { useAuth } from '../../../../auth' -import { useMutation, useQueryClient } from 'react-query' -import { addScenario, deleteScenario } from '../../../../api/scenarios' +import { useMutation } from 'react-query' const ScenarioListContainer = ({ portfolioId }) => { const { data: portfolio } = usePortfolio(portfolioId) + const { data: project } = useProject(portfolio?.projectId) const scenarios = useScenarios(portfolio?.scenarioIds ?? []) .filter((res) => res.data) .map((res) => res.data) - const topologies = useProjectTopologies() + const topologies = useTopologies(project?.topologyIds ?? []) + .filter((res) => res.data) + .map((res) => res.data) const traces = useTraces().data ?? [] const schedulers = useSchedulers().data ?? [] - const auth = useAuth() - const queryClient = useQueryClient() - const addMutation = useMutation((data) => addScenario(auth, data), { - onSuccess: async (result) => { - await queryClient.invalidateQueries(['portfolios', portfolioId]) - }, - }) - const deleteMutation = useMutation((id) => deleteScenario(auth, id), { - onSuccess: async (result) => { - queryClient.setQueryData(['portfolios', portfolioId], (old) => ({ - ...old, - scenarioIds: old.scenarioIds.filter((id) => id !== result._id), - })) - queryClient.removeQueries(['scenarios', result._id]) - }, - }) + const { mutate: addScenario } = useMutation('addScenario') + const { mutate: deleteScenario } = useMutation('deleteScenario') const [isVisible, setVisible] = useState(false) - const onNewScenario = (currentPortfolioId) => { - setVisible(true) - } - const onDeleteScenario = (id) => { - if (id) { - deleteMutation.mutate(id) - } - } + const onNewScenario = () => setVisible(true) + const onDeleteScenario = (id) => id && deleteScenario(id) const callback = (name, portfolioId, trace, topology, operational) => { if (name) { - addMutation.mutate({ + addScenario({ portfolioId, name, trace, diff --git a/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/TopologyListContainer.js b/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/TopologyListContainer.js index 55f8bd00..78db166c 100644 --- a/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/TopologyListContainer.js +++ b/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/TopologyListContainer.js @@ -3,28 +3,32 @@ import { useDispatch } from 'react-redux' import TopologyListComponent from '../../../../components/app/sidebars/project/TopologyListComponent' import { setCurrentTopology } from '../../../../redux/actions/topology/building' import { useRouter } from 'next/router' -import { addTopology, deleteTopology } from '../../../../redux/actions/topologies' +import { addTopology } from '../../../../redux/actions/topologies' import NewTopologyModalComponent from '../../../../components/modals/custom-components/NewTopologyModalComponent' -import { useActiveTopology, useProjectTopologies } from '../../../../data/topology' +import { useActiveTopology, useTopologies } from '../../../../data/topology' import { useProject } from '../../../../data/project' +import { useMutation } from 'react-query' const TopologyListContainer = () => { const dispatch = useDispatch() const router = useRouter() const { project: currentProjectId } = router.query const { data: currentProject } = useProject(currentProjectId) - const topologies = useProjectTopologies() + const topologies = useTopologies(currentProject?.topologyIds ?? []) + .filter((res) => res.data) + .map((res) => res.data) const currentTopologyId = useActiveTopology()?._id const [isVisible, setVisible] = useState(false) + const { mutate: deleteTopology } = useMutation('deleteTopology') + const onChooseTopology = async (id) => { dispatch(setCurrentTopology(id)) await router.push(`/projects/${currentProjectId}/topologies/${id}`) } const onDeleteTopology = async (id) => { if (id) { - dispatch(deleteTopology(id)) - dispatch(setCurrentTopology(currentProject.topologyIds[0])) + deleteTopology(id) await router.push(`/projects/${currentProjectId}`) } } diff --git a/opendc-web/opendc-web-ui/src/containers/projects/NewProjectContainer.js b/opendc-web/opendc-web-ui/src/containers/projects/NewProjectContainer.js index c844fe2d..ac0edae4 100644 --- a/opendc-web/opendc-web-ui/src/containers/projects/NewProjectContainer.js +++ b/opendc-web/opendc-web-ui/src/containers/projects/NewProjectContainer.js @@ -3,23 +3,17 @@ import TextInputModal from '../../components/modals/TextInputModal' import { Button } from 'reactstrap' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faPlus } from '@fortawesome/free-solid-svg-icons' -import { useMutation, useQueryClient } from 'react-query' -import { addProject } from '../../api/projects' -import { useAuth } from '../../auth' +import { useMutation } from 'react-query' /** * A container for creating a new project. */ const NewProjectContainer = () => { const [isVisible, setVisible] = useState(false) - const auth = useAuth() - const queryClient = useQueryClient() - const mutation = useMutation((data) => addProject(auth, data), { - onSuccess: (result) => queryClient.setQueryData('projects', (old) => [...(old || []), result]), - }) + const { mutate: addProject } = useMutation('addProject') const callback = (text) => { if (text) { - mutation.mutate({ name: text }) + addProject({ name: text }) } setVisible(false) } diff --git a/opendc-web/opendc-web-ui/src/containers/projects/ProjectActions.js b/opendc-web/opendc-web-ui/src/containers/projects/ProjectActions.js index eba388d6..62985742 100644 --- a/opendc-web/opendc-web-ui/src/containers/projects/ProjectActions.js +++ b/opendc-web/opendc-web-ui/src/containers/projects/ProjectActions.js @@ -1,18 +1,12 @@ import React from 'react' import ProjectActionButtons from '../../components/projects/ProjectActionButtons' -import { useMutation, useQueryClient } from 'react-query' -import { useAuth } from '../../auth' -import { deleteProject } from '../../api/projects' +import { useMutation } from 'react-query' const ProjectActions = (props) => { - const auth = useAuth() - const queryClient = useQueryClient() - const mutation = useMutation((projectId) => deleteProject(auth, projectId), { - onSuccess: () => queryClient.invalidateQueries('projects'), - }) + const { mutate: deleteProject } = useMutation('deleteProject') const actions = { onViewUsers: (id) => {}, // TODO implement user viewing - onDelete: (id) => mutation.mutate(id), + onDelete: (id) => deleteProject(id), } return } diff --git a/opendc-web/opendc-web-ui/src/containers/projects/ProjectListContainer.js b/opendc-web/opendc-web-ui/src/containers/projects/ProjectListContainer.js index 91e8ac5a..b5c5dd68 100644 --- a/opendc-web/opendc-web-ui/src/containers/projects/ProjectListContainer.js +++ b/opendc-web/opendc-web-ui/src/containers/projects/ProjectListContainer.js @@ -3,7 +3,6 @@ import PropTypes from 'prop-types' import ProjectList from '../../components/projects/ProjectList' import { useAuth } from '../../auth' import { useProjects } from '../../data/project' -import { useQueryClient } from 'react-query' const getVisibleProjects = (projects, filter, userId) => { switch (filter) { diff --git a/opendc-web/opendc-web-ui/src/data/experiments.js b/opendc-web/opendc-web-ui/src/data/experiments.js index 4797bacb..a76ea53f 100644 --- a/opendc-web/opendc-web-ui/src/data/experiments.js +++ b/opendc-web/opendc-web-ui/src/data/experiments.js @@ -22,21 +22,26 @@ import { useQuery } from 'react-query' import { fetchTraces } from '../api/traces' -import { useAuth } from '../auth' import { fetchSchedulers } from '../api/schedulers' +/** + * Configure the query defaults for the experiment endpoints. + */ +export function configureExperimentClient(queryClient, auth) { + queryClient.setQueryDefaults('traces', { queryFn: () => fetchTraces(auth) }) + queryClient.setQueryDefaults('schedulers', { queryFn: () => fetchSchedulers(auth) }) +} + /** * Return the available traces to experiment with. */ export function useTraces() { - const auth = useAuth() - return useQuery('traces', () => fetchTraces(auth)) + return useQuery('traces') } /** * Return the available schedulers to experiment with. */ export function useSchedulers() { - const auth = useAuth() - return useQuery('schedulers', () => fetchSchedulers(auth)) + return useQuery('schedulers') } diff --git a/opendc-web/opendc-web-ui/src/data/project.js b/opendc-web/opendc-web-ui/src/data/project.js index 5cf620da..256203a3 100644 --- a/opendc-web/opendc-web-ui/src/data/project.js +++ b/opendc-web/opendc-web-ui/src/data/project.js @@ -21,45 +21,113 @@ */ import { useQueries, useQuery } from 'react-query' -import { fetchProject, fetchProjects } from '../api/projects' -import { useAuth } from '../auth' +import { addProject, deleteProject, fetchProject, fetchProjects } from '../api/projects' import { useRouter } from 'next/router' -import { fetchPortfolio } from '../api/portfolios' -import { fetchScenario } from '../api/scenarios' +import { addPortfolio, deletePortfolio, fetchPortfolio } from '../api/portfolios' +import { addScenario, deleteScenario, fetchScenario } from '../api/scenarios' + +/** + * Configure the query defaults for the project endpoints. + */ +export function configureProjectClient(queryClient, auth) { + queryClient.setQueryDefaults('projects', { + queryFn: ({ queryKey }) => (queryKey.length === 1 ? fetchProjects(auth) : fetchProject(auth, queryKey[1])), + }) + + queryClient.setMutationDefaults('addProject', { + mutationFn: (data) => addProject(auth, data), + onSuccess: async (result) => { + queryClient.setQueryData('projects', (old = []) => [...old, result]) + }, + }) + queryClient.setMutationDefaults('deleteProject', { + mutationFn: (id) => deleteProject(auth, id), + onSuccess: async (result) => { + queryClient.setQueryData('projects', (old = []) => old.filter((project) => project._id !== result._id)) + queryClient.removeQueries(['projects', result._id]) + }, + }) + + queryClient.setQueryDefaults('portfolios', { + queryFn: ({ queryKey }) => fetchPortfolio(auth, queryKey[1]), + }) + queryClient.setMutationDefaults('addPortfolio', { + mutationFn: (data) => addPortfolio(auth, data), + onSuccess: async (result) => { + queryClient.setQueryData(['projects', result.projectId], (old) => ({ + ...old, + portfolioIds: [...old.portfolioIds, result._id], + })) + queryClient.setQueryData(['portfolios', result._id], result) + }, + }) + queryClient.setMutationDefaults('deletePortfolio', { + mutationFn: (id) => deletePortfolio(auth, id), + onSuccess: async (result) => { + queryClient.setQueryData(['projects', result.projectId], (old) => ({ + ...old, + portfolioIds: old.portfolioIds.filter((id) => id !== result._id), + })) + queryClient.removeQueries(['portfolios', result._id]) + }, + }) + + queryClient.setQueryDefaults('scenarios', { + queryFn: ({ queryKey }) => fetchScenario(auth, queryKey[1]), + }) + queryClient.setMutationDefaults('addScenario', { + mutationFn: (data) => addScenario(auth, data), + onSuccess: async (result) => { + // Register updated scenario in cache + queryClient.setQueryData(['scenarios', result._id], result) + + // Add scenario id to portfolio + queryClient.setQueryData(['portfolios', result.portfolioId], (old) => ({ + ...old, + scenarioIds: [...old.scenarioIds, result._id], + })) + }, + }) + queryClient.setMutationDefaults('deleteScenario', { + mutationFn: (id) => deleteScenario(auth, id), + onSuccess: async (result) => { + queryClient.setQueryData(['portfolios', result.portfolioId], (old) => ({ + ...old, + scenarioIds: old.scenarioIds.filter((id) => id !== result._id), + })) + queryClient.removeQueries(['scenarios', result._id]) + }, + }) +} /** * Return the available projects. */ export function useProjects() { - const auth = useAuth() - return useQuery('projects', () => fetchProjects(auth)) + return useQuery('projects') } /** * Return the project with the specified identifier. */ export function useProject(projectId) { - const auth = useAuth() - return useQuery(['projects', projectId], () => fetchProject(auth, projectId), { enabled: !!projectId }) + return useQuery(['projects', projectId], { enabled: !!projectId }) } /** * Return the portfolio with the specified identifier. */ export function usePortfolio(portfolioId) { - const auth = useAuth() - return useQuery(['portfolios', portfolioId], () => fetchPortfolio(auth, portfolioId), { enabled: !!portfolioId }) + return useQuery(['portfolios', portfolioId], { enabled: !!portfolioId }) } /** * Return the portfolios for the specified project id. */ export function usePortfolios(portfolioIds) { - const auth = useAuth() return useQueries( portfolioIds.map((portfolioId) => ({ queryKey: ['portfolios', portfolioId], - queryFn: () => fetchPortfolio(auth, portfolioId), })) ) } @@ -68,11 +136,9 @@ export function usePortfolios(portfolioIds) { * Return the scenarios with the specified identifiers. */ export function useScenarios(scenarioIds) { - const auth = useAuth() return useQueries( scenarioIds.map((scenarioId) => ({ - queryKey: ['scenario', scenarioId], - queryFn: () => fetchScenario(auth, scenarioId), + queryKey: ['scenarios', scenarioId], })) ) } diff --git a/opendc-web/opendc-web-ui/src/data/topology.js b/opendc-web/opendc-web-ui/src/data/topology.js index 4c746a7e..92911a70 100644 --- a/opendc-web/opendc-web-ui/src/data/topology.js +++ b/opendc-web/opendc-web-ui/src/data/topology.js @@ -21,7 +21,40 @@ */ import { useSelector } from 'react-redux' -import { useActiveProjectId, useProject } from './project' +import { useQueries } from 'react-query' +import { addTopology, deleteTopology, fetchTopology, updateTopology } from '../api/topologies' + +/** + * Configure the query defaults for the topology endpoints. + */ +export function configureTopologyClient(queryClient, auth) { + queryClient.setQueryDefaults('topologies', { queryFn: ({ queryKey }) => fetchTopology(auth, queryKey[1]) }) + + queryClient.setMutationDefaults('addTopology', { + mutationFn: (data) => addTopology(auth, data), + onSuccess: async (result) => { + queryClient.setQueryData(['projects', result.projectId], (old) => ({ + ...old, + topologyIds: [...old.topologyIds, result._id], + })) + queryClient.setQueryData(['topologies', result._id], result) + }, + }) + queryClient.setMutationDefaults('updateTopology', { + mutationFn: (data) => updateTopology(auth, data), + onSuccess: async (result) => queryClient.setQueryData(['topologies', result._id], result), + }) + queryClient.setMutationDefaults('deleteTopology', { + mutationFn: (id) => deleteTopology(auth, id), + onSuccess: async (result) => { + queryClient.setQueryData(['projects', result.projectId], (old) => ({ + ...old, + topologyIds: old.topologyIds.filter((id) => id !== result._id), + })) + queryClient.removeQueries(['topologies', result._id]) + }, + }) +} /** * Return the current active topology. @@ -31,22 +64,8 @@ export function useActiveTopology() { } /** - * Return the topologies for the active project. + * Return the scenarios with the specified identifiers. */ -export function useProjectTopologies() { - const projectId = useActiveProjectId() - const { data: project } = useProject(projectId) - return useSelector(({ objects }) => { - if (!project) { - return [] - } - - const topologies = project.topologyIds.map((t) => objects.topology[t]) - - if (topologies.filter((t) => !t).length > 0) { - return [] - } - - return topologies - }) +export function useTopologies(topologyIds) { + return useQueries(topologyIds.map((topologyId) => ({ queryKey: ['topologies', topologyId] }))) } diff --git a/opendc-web/opendc-web-ui/src/pages/_app.js b/opendc-web/opendc-web-ui/src/pages/_app.js index 7b4dcb3e..6a7200d5 100644 --- a/opendc-web/opendc-web-ui/src/pages/_app.js +++ b/opendc-web/opendc-web-ui/src/pages/_app.js @@ -30,11 +30,21 @@ import * as Sentry from '@sentry/react' import { Integrations } from '@sentry/tracing' import { QueryClient, QueryClientProvider } from 'react-query' import { useMemo } from 'react' +import { configureProjectClient } from '../data/project' +import { configureExperimentClient } from '../data/experiments' +import { configureTopologyClient } from '../data/topology' // This setup is necessary to forward the Auth0 context to the Redux context const Inner = ({ Component, pageProps }) => { const auth = useAuth() - const queryClient = useMemo(() => new QueryClient(), []) + + const queryClient = useMemo(() => { + const client = new QueryClient() + configureProjectClient(client, auth) + configureExperimentClient(client, auth) + configureTopologyClient(client, auth) + return client + }, []) // eslint-disable-line react-hooks/exhaustive-deps const store = useStore(pageProps.initialReduxState, { auth, queryClient }) return ( diff --git a/opendc-web/opendc-web-ui/src/redux/actions/topologies.js b/opendc-web/opendc-web-ui/src/redux/actions/topologies.js index abfded7e..e19a7f21 100644 --- a/opendc-web/opendc-web-ui/src/redux/actions/topologies.js +++ b/opendc-web/opendc-web-ui/src/redux/actions/topologies.js @@ -1,5 +1,4 @@ export const ADD_TOPOLOGY = 'ADD_TOPOLOGY' -export const DELETE_TOPOLOGY = 'DELETE_TOPOLOGY' export function addTopology(projectId, name, duplicateId) { return { @@ -9,10 +8,3 @@ export function addTopology(projectId, name, duplicateId) { duplicateId, } } - -export function deleteTopology(id) { - return { - type: DELETE_TOPOLOGY, - id, - } -} diff --git a/opendc-web/opendc-web-ui/src/redux/sagas/index.js b/opendc-web/opendc-web-ui/src/redux/sagas/index.js index 74d9efb6..318f0afb 100644 --- a/opendc-web/opendc-web-ui/src/redux/sagas/index.js +++ b/opendc-web/opendc-web-ui/src/redux/sagas/index.js @@ -21,13 +21,12 @@ import { onDeleteRack, onDeleteRoom, onDeleteTile, - onDeleteTopology, onDeleteUnit, onEditRackName, onEditRoomName, onStartNewRoomConstruction, } from './topology' -import { ADD_TOPOLOGY, DELETE_TOPOLOGY } from '../actions/topologies' +import { ADD_TOPOLOGY } from '../actions/topologies' import { onAddPrefab } from './prefabs' import { ADD_PREFAB } from '../actions/prefabs' @@ -35,7 +34,6 @@ export default function* rootSaga() { yield takeEvery(OPEN_PROJECT_SUCCEEDED, onOpenProjectSucceeded) yield takeEvery(ADD_TOPOLOGY, onAddTopology) - yield takeEvery(DELETE_TOPOLOGY, onDeleteTopology) yield takeEvery(START_NEW_ROOM_CONSTRUCTION, onStartNewRoomConstruction) yield takeEvery(CANCEL_NEW_ROOM_CONSTRUCTION, onCancelNewRoomConstruction) yield takeEvery(ADD_TILE, onAddTile) diff --git a/opendc-web/opendc-web-ui/src/redux/sagas/objects.js b/opendc-web/opendc-web-ui/src/redux/sagas/objects.js index 88f71fe4..99082df0 100644 --- a/opendc-web/opendc-web-ui/src/redux/sagas/objects.js +++ b/opendc-web/opendc-web-ui/src/redux/sagas/objects.js @@ -1,6 +1,6 @@ import { call, put, select, getContext } from 'redux-saga/effects' import { addToStore } from '../actions/objects' -import { getTopology, updateTopology } from '../../api/topologies' +import { fetchTopology, updateTopology } from '../../api/topologies' import { uuid } from 'uuidv4' export const OBJECT_SELECTORS = { @@ -32,7 +32,7 @@ export const fetchAndStoreTopology = function* (id) { let topology = topologyStore[id] if (!topology) { - const fullTopology = yield call(getTopology, auth, id) + const fullTopology = yield call(fetchTopology, auth, id) for (let roomIdx in fullTopology.rooms) { const fullRoom = fullTopology.rooms[roomIdx] diff --git a/opendc-web/opendc-web-ui/src/redux/sagas/topology.js b/opendc-web/opendc-web-ui/src/redux/sagas/topology.js index efa125c6..0ed40131 100644 --- a/opendc-web/opendc-web-ui/src/redux/sagas/topology.js +++ b/opendc-web/opendc-web-ui/src/redux/sagas/topology.js @@ -18,16 +18,12 @@ import { } from '../../components/app/map/MapConstants' import { fetchAndStoreTopology, denormalizeTopology, updateTopologyOnServer } from './objects' import { uuid } from 'uuidv4' -import { addTopology, deleteTopology } from '../../api/topologies' -import { fetchProject } from '../../api/projects' +import { addTopology } from '../../api/topologies' export function* fetchAndStoreAllTopologiesOfProject(projectId, setTopology = false) { try { - const auth = yield getContext('auth') const queryClient = yield getContext('queryClient') - const project = yield call(() => - queryClient.fetchQuery(['projects', projectId], () => fetchProject(auth, projectId)) - ) + const project = yield call(() => queryClient.fetchQuery(['projects', projectId])) for (let i in project.topologyIds) { yield fetchAndStoreTopology(project.topologyIds[i]) @@ -62,26 +58,6 @@ export function* onAddTopology(action) { } } -export function* onDeleteTopology(action) { - try { - const auth = yield getContext('auth') - const queryClient = yield getContext('queryClient') - const project = yield call(() => - queryClient.fetchQuery(['projects', action.projectId], () => fetchProject(auth, action.projectId)) - ) - const topologyIds = project?.topologyIds ?? [] - - const currentTopologyId = yield select((state) => state.currentTopologyId) - if (currentTopologyId === action.id) { - yield put(setCurrentTopology(topologyIds.filter((t) => t !== action.id)[0])) - } - - yield call(deleteTopology, auth, action.id) - } catch (error) { - console.error(error) - } -} - export function* onStartNewRoomConstruction() { try { const topologyId = yield select((state) => state.currentTopologyId) -- cgit v1.2.3 From 5ec19973eb3d23046d874b097275857a58c23082 Mon Sep 17 00:00:00 2001 From: Fabian Mastenbroek Date: Wed, 7 Jul 2021 20:45:06 +0200 Subject: api: Add endpoints for accessing project relations This change adds additional endpoints to the REST API to access the project relations, the portfolios and topologies that belong to a project. --- opendc-web/opendc-web-api/opendc/api/portfolios.py | 14 ++ opendc-web/opendc-web-api/opendc/api/projects.py | 27 ++- opendc-web/opendc-web-api/opendc/auth.py | 5 +- opendc-web/opendc-web-api/opendc/exts.py | 7 +- .../opendc-web-api/opendc/models/portfolio.py | 7 + .../opendc-web-api/opendc/models/scenario.py | 6 + .../opendc-web-api/opendc/models/topology.py | 7 + opendc-web/opendc-web-api/static/schema.yml | 182 ++++++++++++++++++++- .../opendc-web-api/tests/api/test_portfolios.py | 16 ++ .../opendc-web-api/tests/api/test_projects.py | 30 ++++ 10 files changed, 291 insertions(+), 10 deletions(-) diff --git a/opendc-web/opendc-web-api/opendc/api/portfolios.py b/opendc-web/opendc-web-api/opendc/api/portfolios.py index eea82289..4d8f54fd 100644 --- a/opendc-web/opendc-web-api/opendc/api/portfolios.py +++ b/opendc-web/opendc-web-api/opendc/api/portfolios.py @@ -103,6 +103,20 @@ class PortfolioScenarios(Resource): """ method_decorators = [requires_auth] + def get(self, portfolio_id): + """ + Get all scenarios belonging to a portfolio. + """ + portfolio = PortfolioModel.from_id(portfolio_id) + + portfolio.check_exists() + portfolio.check_user_access(current_user['sub'], True) + + scenarios = Scenario.get_for_portfolio(portfolio_id) + + data = ScenarioSchema().dump(scenarios, many=True) + return {'data': data} + def post(self, portfolio_id): """ Add a new scenario to this portfolio diff --git a/opendc-web/opendc-web-api/opendc/api/projects.py b/opendc-web/opendc-web-api/opendc/api/projects.py index 05f02a84..2b47c12e 100644 --- a/opendc-web/opendc-web-api/opendc/api/projects.py +++ b/opendc-web/opendc-web-api/opendc/api/projects.py @@ -132,6 +132,18 @@ class ProjectTopologies(Resource): """ method_decorators = [requires_auth] + def get(self, project_id): + """Get all topologies belonging to the project.""" + project = ProjectModel.from_id(project_id) + + project.check_exists() + project.check_user_access(current_user['sub'], True) + + topologies = Topology.get_for_project(project_id) + data = TopologySchema().dump(topologies, many=True) + + return {'data': data} + def post(self, project_id): """Add a new Topology to the specified project and return it""" schema = ProjectTopologies.PutSchema() @@ -170,6 +182,18 @@ class ProjectPortfolios(Resource): """ method_decorators = [requires_auth] + def get(self, project_id): + """Get all portfolios belonging to the project.""" + project = ProjectModel.from_id(project_id) + + project.check_exists() + project.check_user_access(current_user['sub'], True) + + portfolios = Portfolio.get_for_project(project_id) + data = PortfolioSchema().dump(portfolios, many=True) + + return {'data': data} + def post(self, project_id): """Add a new Portfolio for this Project.""" schema = ProjectPortfolios.PutSchema() @@ -190,7 +214,8 @@ class ProjectPortfolios(Resource): project.obj['portfolioIds'].append(portfolio.get_id()) project.update() - return {'data': portfolio.obj} + data = PortfolioSchema().dump(portfolio.obj) + return {'data': data} class PutSchema(Schema): """ diff --git a/opendc-web/opendc-web-api/opendc/auth.py b/opendc-web/opendc-web-api/opendc/auth.py index 6db06fb1..d5da6ee5 100644 --- a/opendc-web/opendc-web-api/opendc/auth.py +++ b/opendc-web/opendc-web-api/opendc/auth.py @@ -40,10 +40,7 @@ def get_token(): parts = auth.split() if parts[0].lower() != "bearer": - raise AuthError({ - "code": "invalid_header", - "description": "Authorization header must start with Bearer" - }, 401) + raise AuthError({"code": "invalid_header", "description": "Authorization header must start with Bearer"}, 401) if len(parts) == 1: raise AuthError({"code": "invalid_header", "description": "Token not found"}, 401) if len(parts) > 2: diff --git a/opendc-web/opendc-web-api/opendc/exts.py b/opendc-web/opendc-web-api/opendc/exts.py index 17dacd5e..3ee8babb 100644 --- a/opendc-web/opendc-web-api/opendc/exts.py +++ b/opendc-web/opendc-web-api/opendc/exts.py @@ -83,10 +83,9 @@ def requires_scope(required_scope): @wraps(f) def decorated(*args, **kwargs): if not has_scope(required_scope): - raise AuthError({ - "code": "Unauthorized", - "description": "You don't have access to this resource" - }, 403) + raise AuthError({"code": "Unauthorized", "description": "You don't have access to this resource"}, 403) return f(*args, **kwargs) + return decorated + return decorator diff --git a/opendc-web/opendc-web-api/opendc/models/portfolio.py b/opendc-web/opendc-web-api/opendc/models/portfolio.py index 1643e23e..eb016947 100644 --- a/opendc-web/opendc-web-api/opendc/models/portfolio.py +++ b/opendc-web/opendc-web-api/opendc/models/portfolio.py @@ -1,5 +1,7 @@ +from bson import ObjectId from marshmallow import Schema, fields +from opendc.exts import db from opendc.models.project import Project from opendc.models.model import Model @@ -38,3 +40,8 @@ class Portfolio(Model): """ project = Project.from_id(self.obj['projectId']) project.check_user_access(user_id, edit_access) + + @classmethod + def get_for_project(cls, project_id): + """Get all portfolios for the specified project id.""" + return db.fetch_all({'projectId': ObjectId(project_id)}, cls.collection_name) diff --git a/opendc-web/opendc-web-api/opendc/models/scenario.py b/opendc-web/opendc-web-api/opendc/models/scenario.py index 0fb6c453..63160448 100644 --- a/opendc-web/opendc-web-api/opendc/models/scenario.py +++ b/opendc-web/opendc-web-api/opendc/models/scenario.py @@ -1,5 +1,6 @@ from datetime import datetime +from bson import ObjectId from marshmallow import Schema, fields from opendc.exts import db @@ -65,6 +66,11 @@ class Scenario(Model): """ return cls(db.fetch_all({'simulation.state': 'QUEUED'}, cls.collection_name)) + @classmethod + def get_for_portfolio(cls, portfolio_id): + """Get all scenarios for the specified portfolio id.""" + return db.fetch_all({'portfolioId': ObjectId(portfolio_id)}, cls.collection_name) + def update_state(self, new_state, results=None): """Atomically update the state of the Scenario. """ diff --git a/opendc-web/opendc-web-api/opendc/models/topology.py b/opendc-web/opendc-web-api/opendc/models/topology.py index 71d2cade..7d2349ab 100644 --- a/opendc-web/opendc-web-api/opendc/models/topology.py +++ b/opendc-web/opendc-web-api/opendc/models/topology.py @@ -1,5 +1,7 @@ +from bson import ObjectId from marshmallow import Schema, fields +from opendc.exts import db from opendc.models.project import Project from opendc.models.model import Model @@ -93,3 +95,8 @@ class Topology(Model): """ project = Project.from_id(self.obj['projectId']) project.check_user_access(user_id, edit_access) + + @classmethod + def get_for_project(cls, project_id): + """Get all topologies for the specified project id.""" + return db.fetch_all({'projectId': ObjectId(project_id)}, cls.collection_name) diff --git a/opendc-web/opendc-web-api/static/schema.yml b/opendc-web/opendc-web-api/static/schema.yml index 6a07ae52..56cf58e7 100644 --- a/opendc-web/opendc-web-api/static/schema.yml +++ b/opendc-web/opendc-web-api/static/schema.yml @@ -222,6 +222,49 @@ paths: schema: $ref: "#/components/schemas/NotFound" "/projects/{projectId}/topologies": + get: + tags: + - projects + description: Get Project Topologies. + parameters: + - name: projectId + in: path + description: Project's ID. + required: true + schema: + type: string + responses: + "200": + description: Successfully retrieved Project Topologies. + content: + "application/json": + schema: + type: object + required: + - data + properties: + data: + type: array + items: + $ref: "#/components/schemas/Topology" + "401": + description: Unauthorized. + content: + "application/json": + schema: + $ref: "#/components/schemas/Unauthorized" + "403": + description: Forbidden from retrieving Project. + content: + "application/json": + schema: + $ref: "#/components/schemas/Forbidden" + "404": + description: Project not found. + content: + "application/json": + schema: + $ref: "#/components/schemas/NotFound" post: tags: - projects @@ -273,9 +316,52 @@ paths: schema: $ref: "#/components/schemas/NotFound" "/projects/{projectId}/portfolios": + get: + tags: + - projects + description: Get Project Portfolios. + parameters: + - name: projectId + in: path + description: Project's ID. + required: true + schema: + type: string + responses: + "200": + description: Successfully retrieved Project Portfolios. + content: + "application/json": + schema: + type: object + required: + - data + properties: + data: + type: array + items: + $ref: "#/components/schemas/Portfolio" + "401": + description: Unauthorized. + content: + "application/json": + schema: + $ref: "#/components/schemas/Unauthorized" + "403": + description: Forbidden from retrieving Project. + content: + "application/json": + schema: + $ref: "#/components/schemas/Forbidden" + "404": + description: Project not found. + content: + "application/json": + schema: + $ref: "#/components/schemas/NotFound" post: tags: - - portfolios + - projects description: Add a Portfolio. parameters: - name: projectId @@ -611,6 +697,100 @@ paths: "application/json": schema: $ref: "#/components/schemas/NotFound" + "/portfolios/{portfolioId}/scenarios": + get: + tags: + - portfolios + description: Get Portfolio Scenarios. + parameters: + - name: portfolioId + in: path + description: Portfolio's ID. + required: true + schema: + type: string + responses: + "200": + description: Successfully retrieved Portfolio Scenarios. + content: + "application/json": + schema: + type: object + required: + - data + properties: + data: + type: array + items: + $ref: "#/components/schemas/Scenario" + "401": + description: Unauthorized. + content: + "application/json": + schema: + $ref: "#/components/schemas/Unauthorized" + "403": + description: Forbidden from retrieving Portfolio. + content: + "application/json": + schema: + $ref: "#/components/schemas/Forbidden" + "404": + description: Portfolio not found. + content: + "application/json": + schema: + $ref: "#/components/schemas/NotFound" + post: + tags: + - portfolios + description: Add a Scenario. + parameters: + - name: portfolioId + in: path + description: Portfolio's ID. + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + properties: + topology: + $ref: "#/components/schemas/Scenario" + description: The new Scenario. + required: true + responses: + "200": + description: Successfully added Scenario. + content: + "application/json": + schema: + type: object + required: + - data + properties: + data: + $ref: "#/components/schemas/Scenario" + "400": + description: Missing or incorrectly typed parameter. + content: + "application/json": + schema: + $ref: "#/components/schemas/Invalid" + "401": + description: Unauthorized. + content: + "application/json": + schema: + $ref: "#/components/schemas/Unauthorized" + "404": + description: Portfolio not found. + content: + "application/json": + schema: + $ref: "#/components/schemas/NotFound" "/scenarios/{scenarioId}": get: tags: diff --git a/opendc-web/opendc-web-api/tests/api/test_portfolios.py b/opendc-web/opendc-web-api/tests/api/test_portfolios.py index da7991f6..196fcb1c 100644 --- a/opendc-web/opendc-web-api/tests/api/test_portfolios.py +++ b/opendc-web/opendc-web-api/tests/api/test_portfolios.py @@ -322,3 +322,19 @@ def test_add_portfolio(client, mocker): assert 'projectId' in res.json['data'] assert 'scenarioIds' in res.json['data'] assert '200' in res.status + + +def test_get_portfolio_scenarios(client, mocker): + mocker.patch.object(db, + 'fetch_one', + return_value={ + 'projectId': test_id, + '_id': test_id, + 'authorizations': [{ + 'userId': 'test', + 'level': 'EDIT' + }] + }) + mocker.patch.object(db, 'fetch_all', return_value=[{'_id': test_id}]) + res = client.get(f'/portfolios/{test_id}/scenarios') + assert '200' in res.status diff --git a/opendc-web/opendc-web-api/tests/api/test_projects.py b/opendc-web/opendc-web-api/tests/api/test_projects.py index c4c82e0d..1cfe4c52 100644 --- a/opendc-web/opendc-web-api/tests/api/test_projects.py +++ b/opendc-web/opendc-web-api/tests/api/test_projects.py @@ -30,6 +30,36 @@ def test_get_user_projects(client, mocker): assert '200' in res.status +def test_get_user_topologies(client, mocker): + mocker.patch.object(db, + 'fetch_one', + return_value={ + '_id': test_id, + 'authorizations': [{ + 'userId': 'test', + 'level': 'EDIT' + }] + }) + mocker.patch.object(db, 'fetch_all', return_value=[{'_id': test_id}]) + res = client.get(f'/projects/{test_id}/topologies') + assert '200' in res.status + + +def test_get_user_portfolios(client, mocker): + mocker.patch.object(db, + 'fetch_one', + return_value={ + '_id': test_id, + 'authorizations': [{ + 'userId': 'test', + 'level': 'EDIT' + }] + }) + mocker.patch.object(db, 'fetch_all', return_value=[{'_id': test_id}]) + res = client.get(f'/projects/{test_id}/portfolios') + assert '200' in res.status + + def test_add_project_missing_parameter(client): assert '400' in client.post('/projects/').status -- cgit v1.2.3 From 1157cc3c56c0f8d36be277bd1ea633f03dd7abbf Mon Sep 17 00:00:00 2001 From: Fabian Mastenbroek Date: Thu, 8 Jul 2021 11:45:06 +0200 Subject: api: Re-expose simulation results from scenario endpoint This change updates the OpenDC API to re-expose the simulation results as they are necessary for the frontend to display the results. --- opendc-web/opendc-web-api/opendc/models/scenario.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/opendc-web/opendc-web-api/opendc/models/scenario.py b/opendc-web/opendc-web-api/opendc/models/scenario.py index 63160448..47771e06 100644 --- a/opendc-web/opendc-web-api/opendc/models/scenario.py +++ b/opendc-web/opendc-web-api/opendc/models/scenario.py @@ -8,6 +8,13 @@ from opendc.models.model import Model from opendc.models.portfolio import Portfolio +class SimulationSchema(Schema): + """ + Simulation details. + """ + state = fields.String() + + class TraceSchema(Schema): """ Schema for specifying the trace of a scenario. @@ -42,6 +49,8 @@ class ScenarioSchema(Schema): trace = fields.Nested(TraceSchema) topology = fields.Nested(TopologySchema) operational = fields.Nested(OperationalSchema) + simulation = fields.Nested(SimulationSchema, dump_only=True) + results = fields.Dict(dump_only=True) class Scenario(Model): -- cgit v1.2.3 From 29196842447d841d2e21462adcfc8c2ed1d851ad Mon Sep 17 00:00:00 2001 From: Fabian Mastenbroek Date: Thu, 8 Jul 2021 13:15:28 +0200 Subject: ui: Simplify normalization of topology This change updates the OpenDC frontend to use the normalizr library for normalizing the user topology. --- .../opendc-web-api/opendc/models/topology.py | 2 +- opendc-web/opendc-web-ui/package.json | 1 + .../src/components/app/map/groups/RoomGroup.js | 8 +- .../src/components/app/map/groups/TileGroup.js | 2 +- .../src/components/app/map/groups/TopologyGroup.js | 6 +- .../app/sidebars/topology/machine/UnitComponent.js | 2 +- .../sidebars/topology/machine/UnitListComponent.js | 22 ++- .../app/sidebars/topology/rack/MachineComponent.js | 10 +- .../sidebars/topology/rack/MachineListComponent.js | 19 ++- .../containers/app/map/RackEnergyFillContainer.js | 12 +- .../containers/app/map/RackSpaceFillContainer.js | 2 +- .../src/containers/app/map/RoomContainer.js | 5 + .../src/containers/app/map/TileContainer.js | 2 +- .../src/containers/app/map/WallContainer.js | 2 +- .../containers/app/map/layers/ObjectHoverLayer.js | 4 +- .../containers/app/map/layers/RoomHoverLayer.js | 6 +- .../app/sidebars/project/ScenarioListContainer.js | 2 +- .../app/sidebars/project/TopologyListContainer.js | 2 +- .../topology/machine/MachineSidebarContainer.js | 2 +- .../app/sidebars/topology/machine/UnitContainer.js | 14 -- .../sidebars/topology/machine/UnitListContainer.js | 33 +++- .../sidebars/topology/rack/EmptySlotContainer.js | 12 -- .../app/sidebars/topology/rack/MachineContainer.js | 14 -- .../sidebars/topology/rack/MachineListContainer.js | 27 ++- .../sidebars/topology/rack/RackNameContainer.js | 2 +- .../sidebars/topology/rack/RackSidebarContainer.js | 2 +- opendc-web/opendc-web-ui/src/pages/_document.js | 2 +- .../opendc-web-ui/src/redux/actions/topologies.js | 8 + .../src/redux/actions/topology/building.js | 13 +- .../src/redux/actions/topology/room.js | 2 +- .../src/redux/middleware/viewport-adjustment.js | 4 +- .../opendc-web-ui/src/redux/reducers/objects.js | 18 +- .../opendc-web-ui/src/redux/sagas/objects.js | 186 ++------------------- .../opendc-web-ui/src/redux/sagas/prefabs.js | 11 +- .../opendc-web-ui/src/redux/sagas/topology.js | 74 ++++---- opendc-web/opendc-web-ui/src/shapes.js | 31 +--- .../opendc-web-ui/src/util/topology-schema.js | 47 ++++++ opendc-web/opendc-web-ui/yarn.lock | 5 + 38 files changed, 254 insertions(+), 362 deletions(-) delete mode 100644 opendc-web/opendc-web-ui/src/containers/app/sidebars/topology/machine/UnitContainer.js delete mode 100644 opendc-web/opendc-web-ui/src/containers/app/sidebars/topology/rack/EmptySlotContainer.js delete mode 100644 opendc-web/opendc-web-ui/src/containers/app/sidebars/topology/rack/MachineContainer.js create mode 100644 opendc-web/opendc-web-ui/src/util/topology-schema.js diff --git a/opendc-web/opendc-web-api/opendc/models/topology.py b/opendc-web/opendc-web-api/opendc/models/topology.py index 7d2349ab..592f82c5 100644 --- a/opendc-web/opendc-web-api/opendc/models/topology.py +++ b/opendc-web/opendc-web-api/opendc/models/topology.py @@ -75,7 +75,7 @@ class TopologySchema(Schema): Schema representing a datacenter topology. """ _id = fields.String(dump_only=True) - projectId = fields.String(dump_only=True) + projectId = fields.String() name = fields.String(required=True) rooms = fields.List(fields.Nested(RoomSchema), required=True) diff --git a/opendc-web/opendc-web-ui/package.json b/opendc-web/opendc-web-ui/package.json index e9570879..1a906acd 100644 --- a/opendc-web/opendc-web-ui/package.json +++ b/opendc-web/opendc-web-ui/package.json @@ -32,6 +32,7 @@ "lint-staged": "~10.2.2", "mathjs": "~7.6.0", "next": "^11.0.1", + "normalizr": "^3.6.1", "prettier": "~2.0.5", "prop-types": "~15.7.2", "react": "^17.0.2", diff --git a/opendc-web/opendc-web-ui/src/components/app/map/groups/RoomGroup.js b/opendc-web/opendc-web-ui/src/components/app/map/groups/RoomGroup.js index e67d54fc..42d20ff1 100644 --- a/opendc-web/opendc-web-ui/src/components/app/map/groups/RoomGroup.js +++ b/opendc-web/opendc-web-ui/src/components/app/map/groups/RoomGroup.js @@ -10,7 +10,7 @@ const RoomGroup = ({ room, interactionLevel, currentRoomInConstruction, onClick if (currentRoomInConstruction === room._id) { return ( - {room.tileIds.map((tileId) => ( + {room.tiles.map((tileId) => ( ))} @@ -25,16 +25,16 @@ const RoomGroup = ({ room, interactionLevel, currentRoomInConstruction, onClick interactionLevel.roomId === room._id ) { return [ - room.tileIds + room.tiles .filter((tileId) => tileId !== interactionLevel.tileId) .map((tileId) => ), , - room.tileIds + room.tiles .filter((tileId) => tileId === interactionLevel.tileId) .map((tileId) => ), ] } else { - return room.tileIds.map((tileId) => ) + return room.tiles.map((tileId) => ) } })()} diff --git a/opendc-web/opendc-web-ui/src/components/app/map/groups/TileGroup.js b/opendc-web/opendc-web-ui/src/components/app/map/groups/TileGroup.js index 2a108b93..ce5e4a6b 100644 --- a/opendc-web/opendc-web-ui/src/components/app/map/groups/TileGroup.js +++ b/opendc-web/opendc-web-ui/src/components/app/map/groups/TileGroup.js @@ -8,7 +8,7 @@ import RoomTile from '../elements/RoomTile' const TileGroup = ({ tile, newTile, onClick }) => { let tileObject - if (tile.rackId) { + if (tile.rack) { tileObject = } else { tileObject = null diff --git a/opendc-web/opendc-web-ui/src/components/app/map/groups/TopologyGroup.js b/opendc-web/opendc-web-ui/src/components/app/map/groups/TopologyGroup.js index 57107768..d4c6db7d 100644 --- a/opendc-web/opendc-web-ui/src/components/app/map/groups/TopologyGroup.js +++ b/opendc-web/opendc-web-ui/src/components/app/map/groups/TopologyGroup.js @@ -12,7 +12,7 @@ const TopologyGroup = ({ topology, interactionLevel }) => { if (interactionLevel.mode === 'BUILDING') { return ( - {topology.roomIds.map((roomId) => ( + {topology.rooms.map((roomId) => ( ))} @@ -21,13 +21,13 @@ const TopologyGroup = ({ topology, interactionLevel }) => { return ( - {topology.roomIds + {topology.rooms .filter((roomId) => roomId !== interactionLevel.roomId) .map((roomId) => ( ))} {interactionLevel.mode === 'ROOM' ? : null} - {topology.roomIds + {topology.rooms .filter((roomId) => roomId === interactionLevel.roomId) .map((roomId) => ( diff --git a/opendc-web/opendc-web-ui/src/components/app/sidebars/topology/machine/UnitComponent.js b/opendc-web/opendc-web-ui/src/components/app/sidebars/topology/machine/UnitComponent.js index 03b92459..46c639bd 100644 --- a/opendc-web/opendc-web-ui/src/components/app/sidebars/topology/machine/UnitComponent.js +++ b/opendc-web/opendc-web-ui/src/components/app/sidebars/topology/machine/UnitComponent.js @@ -60,7 +60,7 @@ function UnitComponent({ index, unitType, unit, onDelete }) { UnitComponent.propTypes = { index: PropTypes.number, unitType: PropTypes.string, - unit: PropTypes.oneOf([ProcessingUnit, StorageUnit]), + unit: PropTypes.oneOfType([ProcessingUnit, StorageUnit]), onDelete: PropTypes.func, } diff --git a/opendc-web/opendc-web-ui/src/components/app/sidebars/topology/machine/UnitListComponent.js b/opendc-web/opendc-web-ui/src/components/app/sidebars/topology/machine/UnitListComponent.js index b7da74a1..54c1a6cc 100644 --- a/opendc-web/opendc-web-ui/src/components/app/sidebars/topology/machine/UnitListComponent.js +++ b/opendc-web/opendc-web-ui/src/components/app/sidebars/topology/machine/UnitListComponent.js @@ -1,12 +1,19 @@ import PropTypes from 'prop-types' import React from 'react' -import UnitContainer from '../../../../../containers/app/sidebars/topology/machine/UnitContainer' +import { ProcessingUnit, StorageUnit } from '../../../../../shapes' +import UnitComponent from './UnitComponent' -const UnitListComponent = ({ unitType, unitIds }) => ( +const UnitListComponent = ({ unitType, units, onDelete }) => (
    - {unitIds.length !== 0 ? ( - unitIds.map((unitId, index) => ( - + {units.length !== 0 ? ( + units.map((unit, index) => ( + onDelete(unit, unitType)} + index={index} + key={index} + /> )) ) : (
    @@ -19,8 +26,9 @@ const UnitListComponent = ({ unitType, unitIds }) => ( ) UnitListComponent.propTypes = { - unitType: PropTypes.string, - unitIds: PropTypes.array, + unitType: PropTypes.string.isRequired, + units: PropTypes.arrayOf(PropTypes.oneOfType([ProcessingUnit, StorageUnit])).isRequired, + onDelete: PropTypes.func, } export default UnitListComponent diff --git a/opendc-web/opendc-web-ui/src/components/app/sidebars/topology/rack/MachineComponent.js b/opendc-web/opendc-web-ui/src/components/app/sidebars/topology/rack/MachineComponent.js index f91202ba..b71918da 100644 --- a/opendc-web/opendc-web-ui/src/components/app/sidebars/topology/rack/MachineComponent.js +++ b/opendc-web/opendc-web-ui/src/components/app/sidebars/topology/rack/MachineComponent.js @@ -23,7 +23,7 @@ UnitIcon.propTypes = { const MachineComponent = ({ position, machine, onClick }) => { const hasNoUnits = - machine.cpuIds.length + machine.gpuIds.length + machine.memoryIds.length + machine.storageIds.length === 0 + machine.cpus.length + machine.gpus.length + machine.memories.length + machine.storages.length === 0 return ( { {position}
    - {machine.cpuIds.length > 0 ? : undefined} - {machine.gpuIds.length > 0 ? : undefined} - {machine.memoryIds.length > 0 ? : undefined} - {machine.storageIds.length > 0 ? : undefined} + {machine.cpus.length > 0 ? : undefined} + {machine.gpus.length > 0 ? : undefined} + {machine.memories.length > 0 ? : undefined} + {machine.storages.length > 0 ? : undefined} {hasNoUnits ? Machine with no units : undefined}
    diff --git a/opendc-web/opendc-web-ui/src/components/app/sidebars/topology/rack/MachineListComponent.js b/opendc-web/opendc-web-ui/src/components/app/sidebars/topology/rack/MachineListComponent.js index d0958c28..e024a417 100644 --- a/opendc-web/opendc-web-ui/src/components/app/sidebars/topology/rack/MachineListComponent.js +++ b/opendc-web/opendc-web-ui/src/components/app/sidebars/topology/rack/MachineListComponent.js @@ -1,17 +1,18 @@ import PropTypes from 'prop-types' import React from 'react' -import EmptySlotContainer from '../../../../../containers/app/sidebars/topology/rack/EmptySlotContainer' -import MachineContainer from '../../../../../containers/app/sidebars/topology/rack/MachineContainer' import { machineList } from './MachineListComponent.module.scss' +import MachineComponent from './MachineComponent' +import { Machine } from '../../../../../shapes' +import EmptySlotComponent from './EmptySlotComponent' -const MachineListComponent = ({ machineIds }) => { +const MachineListComponent = ({ machines = [], onSelect, onAdd }) => { return (
      - {machineIds.map((machineId, index) => { - if (machineId === null) { - return + {machines.map((machine, index) => { + if (machine === null) { + return onAdd(index + 1)} /> } else { - return + return onSelect(index + 1)} machine={machine} /> } })}
    @@ -19,7 +20,9 @@ const MachineListComponent = ({ machineIds }) => { } MachineListComponent.propTypes = { - machineIds: PropTypes.array, + machines: PropTypes.arrayOf(Machine), + onSelect: PropTypes.func.isRequired, + onAdd: PropTypes.func.isRequired, } export default MachineListComponent diff --git a/opendc-web/opendc-web-ui/src/containers/app/map/RackEnergyFillContainer.js b/opendc-web/opendc-web-ui/src/containers/app/map/RackEnergyFillContainer.js index 00d3152f..d22317a5 100644 --- a/opendc-web/opendc-web-ui/src/containers/app/map/RackEnergyFillContainer.js +++ b/opendc-web/opendc-web-ui/src/containers/app/map/RackEnergyFillContainer.js @@ -5,17 +5,17 @@ import RackFillBar from '../../../components/app/map/elements/RackFillBar' const RackSpaceFillContainer = (props) => { const state = useSelector((state) => { let energyConsumptionTotal = 0 - const rack = state.objects.rack[state.objects.tile[props.tileId].rackId] - const machineIds = rack.machineIds + const rack = state.objects.rack[state.objects.tile[props.tileId].rack] + const machineIds = rack.machines machineIds.forEach((machineId) => { if (machineId !== null) { const machine = state.objects.machine[machineId] - machine.cpuIds.forEach((id) => (energyConsumptionTotal += state.objects.cpu[id].energyConsumptionW)) - machine.gpuIds.forEach((id) => (energyConsumptionTotal += state.objects.gpu[id].energyConsumptionW)) - machine.memoryIds.forEach( + machine.cpus.forEach((id) => (energyConsumptionTotal += state.objects.cpu[id].energyConsumptionW)) + machine.gpus.forEach((id) => (energyConsumptionTotal += state.objects.gpu[id].energyConsumptionW)) + machine.memories.forEach( (id) => (energyConsumptionTotal += state.objects.memory[id].energyConsumptionW) ) - machine.storageIds.forEach( + machine.storages.forEach( (id) => (energyConsumptionTotal += state.objects.storage[id].energyConsumptionW) ) } diff --git a/opendc-web/opendc-web-ui/src/containers/app/map/RackSpaceFillContainer.js b/opendc-web/opendc-web-ui/src/containers/app/map/RackSpaceFillContainer.js index dc5119fd..8d6f61e0 100644 --- a/opendc-web/opendc-web-ui/src/containers/app/map/RackSpaceFillContainer.js +++ b/opendc-web/opendc-web-ui/src/containers/app/map/RackSpaceFillContainer.js @@ -4,7 +4,7 @@ import RackFillBar from '../../../components/app/map/elements/RackFillBar' const RackSpaceFillContainer = (props) => { const state = useSelector((state) => { - const machineIds = state.objects.rack[state.objects.tile[props.tileId].rackId].machineIds + const machineIds = state.objects.rack[state.objects.tile[props.tileId].rack].machines return { type: 'space', fillFraction: machineIds.filter((id) => id !== null).length / machineIds.length, diff --git a/opendc-web/opendc-web-ui/src/containers/app/map/RoomContainer.js b/opendc-web/opendc-web-ui/src/containers/app/map/RoomContainer.js index 52d48317..0a9e1503 100644 --- a/opendc-web/opendc-web-ui/src/containers/app/map/RoomContainer.js +++ b/opendc-web/opendc-web-ui/src/containers/app/map/RoomContainer.js @@ -1,3 +1,4 @@ +import PropTypes from 'prop-types' import React from 'react' import { useDispatch, useSelector } from 'react-redux' import { goFromBuildingToRoom } from '../../../redux/actions/interaction-level' @@ -15,4 +16,8 @@ const RoomContainer = (props) => { return dispatch(goFromBuildingToRoom(props.roomId))} /> } +RoomContainer.propTypes = { + roomId: PropTypes.string, +} + export default RoomContainer diff --git a/opendc-web/opendc-web-ui/src/containers/app/map/TileContainer.js b/opendc-web/opendc-web-ui/src/containers/app/map/TileContainer.js index f97e89a1..50a2abfd 100644 --- a/opendc-web/opendc-web-ui/src/containers/app/map/TileContainer.js +++ b/opendc-web/opendc-web-ui/src/containers/app/map/TileContainer.js @@ -9,7 +9,7 @@ const TileContainer = (props) => { const dispatch = useDispatch() const onClick = (tile) => { - if (tile.rackId) { + if (tile.rack) { dispatch(goFromRoomToRack(tile._id)) } } diff --git a/opendc-web/opendc-web-ui/src/containers/app/map/WallContainer.js b/opendc-web/opendc-web-ui/src/containers/app/map/WallContainer.js index 2a469860..67f36396 100644 --- a/opendc-web/opendc-web-ui/src/containers/app/map/WallContainer.js +++ b/opendc-web/opendc-web-ui/src/containers/app/map/WallContainer.js @@ -4,7 +4,7 @@ import WallGroup from '../../../components/app/map/groups/WallGroup' const WallContainer = (props) => { const tiles = useSelector((state) => - state.objects.room[props.roomId].tileIds.map((tileId) => state.objects.tile[tileId]) + state.objects.room[props.roomId].tiles.map((tileId) => state.objects.tile[tileId]) ) return } diff --git a/opendc-web/opendc-web-ui/src/containers/app/map/layers/ObjectHoverLayer.js b/opendc-web/opendc-web-ui/src/containers/app/map/layers/ObjectHoverLayer.js index 8e934a01..e9a64545 100644 --- a/opendc-web/opendc-web-ui/src/containers/app/map/layers/ObjectHoverLayer.js +++ b/opendc-web/opendc-web-ui/src/containers/app/map/layers/ObjectHoverLayer.js @@ -16,10 +16,10 @@ const ObjectHoverLayer = (props) => { } const currentRoom = state.objects.room[state.interactionLevel.roomId] - const tiles = currentRoom.tileIds.map((tileId) => state.objects.tile[tileId]) + const tiles = currentRoom.tiles.map((tileId) => state.objects.tile[tileId]) const tile = findTileWithPosition(tiles, x, y) - return !(tile === null || tile.rackId) + return !(tile === null || tile.rack) }, } }) diff --git a/opendc-web/opendc-web-ui/src/containers/app/map/layers/RoomHoverLayer.js b/opendc-web/opendc-web-ui/src/containers/app/map/layers/RoomHoverLayer.js index 1bfadb6d..4070c766 100644 --- a/opendc-web/opendc-web-ui/src/containers/app/map/layers/RoomHoverLayer.js +++ b/opendc-web/opendc-web-ui/src/containers/app/map/layers/RoomHoverLayer.js @@ -23,14 +23,14 @@ const RoomHoverLayer = (props) => { .map((id) => Object.assign({}, state.objects.room[id])) .filter( (room) => - state.objects.topology[state.currentTopologyId].roomIds.indexOf(room._id) !== -1 && + state.objects.topology[state.currentTopologyId].rooms.indexOf(room._id) !== -1 && room._id !== state.construction.currentRoomInConstruction ) ;[...oldRooms, newRoom].forEach((room) => { - room.tiles = room.tileIds.map((tileId) => state.objects.tile[tileId]) + room.tiles = room.tiles.map((tileId) => state.objects.tile[tileId]) }) - if (newRoom.tileIds.length === 0) { + if (newRoom.tiles.length === 0) { return findPositionInRooms(oldRooms, x, y) === -1 } diff --git a/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/ScenarioListContainer.js b/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/ScenarioListContainer.js index 62761583..fd55582f 100644 --- a/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/ScenarioListContainer.js +++ b/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/ScenarioListContainer.js @@ -15,7 +15,7 @@ const ScenarioListContainer = ({ portfolioId }) => { .map((res) => res.data) const topologies = useTopologies(project?.topologyIds ?? []) .filter((res) => res.data) - .map((res) => res.data) + .map((res) => ({ _id: res.data._id, name: res.data.name })) const traces = useTraces().data ?? [] const schedulers = useSchedulers().data ?? [] diff --git a/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/TopologyListContainer.js b/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/TopologyListContainer.js index 78db166c..55eab23a 100644 --- a/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/TopologyListContainer.js +++ b/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/TopologyListContainer.js @@ -16,7 +16,7 @@ const TopologyListContainer = () => { const { data: currentProject } = useProject(currentProjectId) const topologies = useTopologies(currentProject?.topologyIds ?? []) .filter((res) => res.data) - .map((res) => res.data) + .map((res) => ({ _id: res.data._id, name: res.data.name })) const currentTopologyId = useActiveTopology()?._id const [isVisible, setVisible] = useState(false) diff --git a/opendc-web/opendc-web-ui/src/containers/app/sidebars/topology/machine/MachineSidebarContainer.js b/opendc-web/opendc-web-ui/src/containers/app/sidebars/topology/machine/MachineSidebarContainer.js index cb7ec8f9..7553c2fe 100644 --- a/opendc-web/opendc-web-ui/src/containers/app/sidebars/topology/machine/MachineSidebarContainer.js +++ b/opendc-web/opendc-web-ui/src/containers/app/sidebars/topology/machine/MachineSidebarContainer.js @@ -5,7 +5,7 @@ import MachineSidebarComponent from '../../../../../components/app/sidebars/topo const MachineSidebarContainer = (props) => { const machineId = useSelector( (state) => - state.objects.rack[state.objects.tile[state.interactionLevel.tileId].rackId].machineIds[ + state.objects.rack[state.objects.tile[state.interactionLevel.tileId].rack].machines[ state.interactionLevel.position - 1 ] ) diff --git a/opendc-web/opendc-web-ui/src/containers/app/sidebars/topology/machine/UnitContainer.js b/opendc-web/opendc-web-ui/src/containers/app/sidebars/topology/machine/UnitContainer.js deleted file mode 100644 index acb16a21..00000000 --- a/opendc-web/opendc-web-ui/src/containers/app/sidebars/topology/machine/UnitContainer.js +++ /dev/null @@ -1,14 +0,0 @@ -import React from 'react' -import { useDispatch, useSelector } from 'react-redux' -import { deleteUnit } from '../../../../../redux/actions/topology/machine' -import UnitComponent from '../../../../../components/app/sidebars/topology/machine/UnitComponent' - -const UnitContainer = ({ unitId, unitType }) => { - const dispatch = useDispatch() - const unit = useSelector((state) => state.objects[unitType][unitId]) - const onDelete = () => dispatch(deleteUnit(unitType, unitId)) - - return -} - -export default UnitContainer diff --git a/opendc-web/opendc-web-ui/src/containers/app/sidebars/topology/machine/UnitListContainer.js b/opendc-web/opendc-web-ui/src/containers/app/sidebars/topology/machine/UnitListContainer.js index c5c9444d..cdd7e268 100644 --- a/opendc-web/opendc-web-ui/src/containers/app/sidebars/topology/machine/UnitListContainer.js +++ b/opendc-web/opendc-web-ui/src/containers/app/sidebars/topology/machine/UnitListContainer.js @@ -1,17 +1,34 @@ +import PropTypes from 'prop-types' import React from 'react' -import { useSelector } from 'react-redux' +import { useDispatch, useSelector } from 'react-redux' import UnitListComponent from '../../../../../components/app/sidebars/topology/machine/UnitListComponent' +import { deleteUnit } from '../../../../../redux/actions/topology/machine' -const UnitListContainer = (props) => { - const unitIds = useSelector( - (state) => +const unitMapping = { + cpu: 'cpus', + gpu: 'gpus', + memory: 'memories', + storage: 'storages', +} + +const UnitListContainer = ({ unitType, ...props }) => { + const dispatch = useDispatch() + const units = useSelector((state) => { + const machine = state.objects.machine[ - state.objects.rack[state.objects.tile[state.interactionLevel.tileId].rackId].machineIds[ + state.objects.rack[state.objects.tile[state.interactionLevel.tileId].rack].machines[ state.interactionLevel.position - 1 ] - ][props.unitType + 'Ids'] - ) - return + ] + return machine[unitMapping[unitType]].map((id) => state.objects[unitType][id]) + }) + const onDelete = (unit, unitType) => dispatch(deleteUnit(unitType, unit._id)) + + return +} + +UnitListContainer.propTypes = { + unitType: PropTypes.string.isRequired, } export default UnitListContainer diff --git a/opendc-web/opendc-web-ui/src/containers/app/sidebars/topology/rack/EmptySlotContainer.js b/opendc-web/opendc-web-ui/src/containers/app/sidebars/topology/rack/EmptySlotContainer.js deleted file mode 100644 index 2134e411..00000000 --- a/opendc-web/opendc-web-ui/src/containers/app/sidebars/topology/rack/EmptySlotContainer.js +++ /dev/null @@ -1,12 +0,0 @@ -import React from 'react' -import { useDispatch } from 'react-redux' -import { addMachine } from '../../../../../redux/actions/topology/rack' -import EmptySlotComponent from '../../../../../components/app/sidebars/topology/rack/EmptySlotComponent' - -const EmptySlotContainer = (props) => { - const dispatch = useDispatch() - const onAdd = () => dispatch(addMachine(props.position)) - return -} - -export default EmptySlotContainer diff --git a/opendc-web/opendc-web-ui/src/containers/app/sidebars/topology/rack/MachineContainer.js b/opendc-web/opendc-web-ui/src/containers/app/sidebars/topology/rack/MachineContainer.js deleted file mode 100644 index 7d8e32c1..00000000 --- a/opendc-web/opendc-web-ui/src/containers/app/sidebars/topology/rack/MachineContainer.js +++ /dev/null @@ -1,14 +0,0 @@ -import React from 'react' -import { useDispatch, useSelector } from 'react-redux' -import { goFromRackToMachine } from '../../../../../redux/actions/interaction-level' -import MachineComponent from '../../../../../components/app/sidebars/topology/rack/MachineComponent' - -const MachineContainer = (props) => { - const machine = useSelector((state) => state.objects.machine[props.machineId]) - const dispatch = useDispatch() - return ( - dispatch(goFromRackToMachine(props.position))} machine={machine} /> - ) -} - -export default MachineContainer diff --git a/opendc-web/opendc-web-ui/src/containers/app/sidebars/topology/rack/MachineListContainer.js b/opendc-web/opendc-web-ui/src/containers/app/sidebars/topology/rack/MachineListContainer.js index b45300fc..2118d915 100644 --- a/opendc-web/opendc-web-ui/src/containers/app/sidebars/topology/rack/MachineListContainer.js +++ b/opendc-web/opendc-web-ui/src/containers/app/sidebars/topology/rack/MachineListContainer.js @@ -1,12 +1,29 @@ -import React from 'react' -import { useSelector } from 'react-redux' +import React, { useMemo } from 'react' +import { useDispatch, useSelector } from 'react-redux' import MachineListComponent from '../../../../../components/app/sidebars/topology/rack/MachineListComponent' +import { goFromRackToMachine } from '../../../../../redux/actions/interaction-level' +import { addMachine } from '../../../../../redux/actions/topology/rack' const MachineListContainer = (props) => { - const machineIds = useSelector( - (state) => state.objects.rack[state.objects.tile[state.interactionLevel.tileId].rackId].machineIds + const rack = useSelector((state) => state.objects.rack[state.objects.tile[state.interactionLevel.tileId].rack]) + const machines = useSelector((state) => rack.machines.map((id) => state.objects.machine[id])) + const machinesNull = useMemo(() => { + const res = Array(rack.capacity).fill(null) + for (const machine of machines) { + res[machine.position - 1] = machine + } + return res + }, [rack, machines]) + const dispatch = useDispatch() + + return ( + dispatch(addMachine(index))} + onSelect={(index) => dispatch(goFromRackToMachine(index))} + /> ) - return } export default MachineListContainer diff --git a/opendc-web/opendc-web-ui/src/containers/app/sidebars/topology/rack/RackNameContainer.js b/opendc-web/opendc-web-ui/src/containers/app/sidebars/topology/rack/RackNameContainer.js index eaa1e78e..2c39cf9f 100644 --- a/opendc-web/opendc-web-ui/src/containers/app/sidebars/topology/rack/RackNameContainer.js +++ b/opendc-web/opendc-web-ui/src/containers/app/sidebars/topology/rack/RackNameContainer.js @@ -7,7 +7,7 @@ import { editRackName } from '../../../../../redux/actions/topology/rack' const RackNameContainer = () => { const [isVisible, setVisible] = useState(false) const rackName = useSelector( - (state) => state.objects.rack[state.objects.tile[state.interactionLevel.tileId].rackId].name + (state) => state.objects.rack[state.objects.tile[state.interactionLevel.tileId].rack].name ) const dispatch = useDispatch() const callback = (name) => { diff --git a/opendc-web/opendc-web-ui/src/containers/app/sidebars/topology/rack/RackSidebarContainer.js b/opendc-web/opendc-web-ui/src/containers/app/sidebars/topology/rack/RackSidebarContainer.js index b8fc3bfb..34777125 100644 --- a/opendc-web/opendc-web-ui/src/containers/app/sidebars/topology/rack/RackSidebarContainer.js +++ b/opendc-web/opendc-web-ui/src/containers/app/sidebars/topology/rack/RackSidebarContainer.js @@ -3,7 +3,7 @@ import { useSelector } from 'react-redux' import RackSidebarComponent from '../../../../../components/app/sidebars/topology/rack/RackSidebarComponent' const RackSidebarContainer = (props) => { - const rackId = useSelector((state) => state.objects.tile[state.interactionLevel.tileId].rackId) + const rackId = useSelector((state) => state.objects.tile[state.interactionLevel.tileId].rack) return } diff --git a/opendc-web/opendc-web-ui/src/pages/_document.js b/opendc-web/opendc-web-ui/src/pages/_document.js index 8e4680c0..51d8d3e0 100644 --- a/opendc-web/opendc-web-ui/src/pages/_document.js +++ b/opendc-web/opendc-web-ui/src/pages/_document.js @@ -25,7 +25,7 @@ import Document, { Html, Head, Main, NextScript } from 'next/document' class OpenDCDocument extends Document { render() { return ( - + diff --git a/opendc-web/opendc-web-ui/src/redux/actions/topologies.js b/opendc-web/opendc-web-ui/src/redux/actions/topologies.js index e19a7f21..529e8663 100644 --- a/opendc-web/opendc-web-ui/src/redux/actions/topologies.js +++ b/opendc-web/opendc-web-ui/src/redux/actions/topologies.js @@ -1,4 +1,5 @@ export const ADD_TOPOLOGY = 'ADD_TOPOLOGY' +export const STORE_TOPOLOGY = 'STORE_TOPOLOGY' export function addTopology(projectId, name, duplicateId) { return { @@ -8,3 +9,10 @@ export function addTopology(projectId, name, duplicateId) { duplicateId, } } + +export function storeTopology(entities) { + return { + type: STORE_TOPOLOGY, + entities, + } +} diff --git a/opendc-web/opendc-web-ui/src/redux/actions/topology/building.js b/opendc-web/opendc-web-ui/src/redux/actions/topology/building.js index 72deda6f..f1a7d569 100644 --- a/opendc-web/opendc-web-ui/src/redux/actions/topology/building.js +++ b/opendc-web/opendc-web-ui/src/redux/actions/topology/building.js @@ -32,7 +32,7 @@ export function startNewRoomConstructionSucceeded(roomId) { export function finishNewRoomConstruction() { return (dispatch, getState) => { const { objects, construction } = getState() - if (objects.room[construction.currentRoomInConstruction].tileIds.length === 0) { + if (objects.room[construction.currentRoomInConstruction].tiles.length === 0) { dispatch(cancelNewRoomConstruction()) return } @@ -75,13 +75,10 @@ export function toggleTileAtLocation(positionX, positionY) { return (dispatch, getState) => { const { objects, construction } = getState() - const tileIds = objects.room[construction.currentRoomInConstruction].tileIds - for (let index in tileIds) { - if ( - objects.tile[tileIds[index]].positionX === positionX && - objects.tile[tileIds[index]].positionY === positionY - ) { - dispatch(deleteTile(tileIds[index])) + const tileIds = objects.room[construction.currentRoomInConstruction].tiles + for (const tileId of tileIds) { + if (objects.tile[tileId].positionX === positionX && objects.tile[tileId].positionY === positionY) { + dispatch(deleteTile(tileId)) return } } diff --git a/opendc-web/opendc-web-ui/src/redux/actions/topology/room.js b/opendc-web/opendc-web-ui/src/redux/actions/topology/room.js index 61eea7fe..80ef7c5e 100644 --- a/opendc-web/opendc-web-ui/src/redux/actions/topology/room.js +++ b/opendc-web/opendc-web-ui/src/redux/actions/topology/room.js @@ -29,7 +29,7 @@ export function addRackToTile(positionX, positionY) { return (dispatch, getState) => { const { objects, interactionLevel } = getState() const currentRoom = objects.room[interactionLevel.roomId] - const tiles = currentRoom.tileIds.map((tileId) => objects.tile[tileId]) + const tiles = currentRoom.tiles.map((tileId) => objects.tile[tileId]) const tile = findTileWithPosition(tiles, positionX, positionY) if (tile !== null) { diff --git a/opendc-web/opendc-web-ui/src/redux/middleware/viewport-adjustment.js b/opendc-web/opendc-web-ui/src/redux/middleware/viewport-adjustment.js index bee6becd..c2fc5004 100644 --- a/opendc-web/opendc-web-ui/src/redux/middleware/viewport-adjustment.js +++ b/opendc-web/opendc-web-ui/src/redux/middleware/viewport-adjustment.js @@ -23,9 +23,9 @@ export const viewportAdjustmentMiddleware = (store) => (next) => (action) => { } if (topologyId && topologyId !== '-1') { - const roomIds = state.objects.topology[topologyId].roomIds + const roomIds = state.objects.topology[topologyId].rooms const rooms = roomIds.map((id) => Object.assign({}, state.objects.room[id])) - rooms.forEach((room) => (room.tiles = room.tileIds.map((tileId) => state.objects.tile[tileId]))) + rooms.forEach((room) => (room.tiles = room.tiles.map((tileId) => state.objects.tile[tileId]))) let hasNoTiles = true for (let i in rooms) { diff --git a/opendc-web/opendc-web-ui/src/redux/reducers/objects.js b/opendc-web/opendc-web-ui/src/redux/reducers/objects.js index f8f577ac..11f6d353 100644 --- a/opendc-web/opendc-web-ui/src/redux/reducers/objects.js +++ b/opendc-web/opendc-web-ui/src/redux/reducers/objects.js @@ -6,11 +6,9 @@ import { REMOVE_ID_FROM_STORE_OBJECT_LIST_PROP, } from '../actions/objects' import { CPU_UNITS, GPU_UNITS, MEMORY_UNITS, STORAGE_UNITS } from '../../util/unit-specifications' +import { STORE_TOPOLOGY } from '../actions/topologies' export const objects = combineReducers({ - project: object('project'), - user: object('user'), - authorization: objectWithId('authorization', (object) => [object.userId, object.projectId]), cpu: object('cpu', CPU_UNITS), gpu: object('gpu', GPU_UNITS), memory: object('memory', MEMORY_UNITS), @@ -20,8 +18,6 @@ export const objects = combineReducers({ tile: object('tile'), room: object('room'), topology: object('topology'), - portfolio: object('portfolio'), - scenario: object('scenario'), prefab: object('prefab'), }) @@ -31,18 +27,16 @@ function object(type, defaultState = {}) { function objectWithId(type, getId, defaultState = {}) { return (state = defaultState, action) => { - if (action.objectType !== type) { + if (action.type === STORE_TOPOLOGY) { + return { ...state, ...action.entities[type] } + } else if (action.objectType !== type) { return state } if (action.type === ADD_TO_STORE) { - return Object.assign({}, state, { - [getId(action.object)]: action.object, - }) + return { ...state, [getId(action.object)]: action.object } } else if (action.type === ADD_PROP_TO_STORE_OBJECT) { - return Object.assign({}, state, { - [action.objectId]: Object.assign({}, state[action.objectId], action.propObject), - }) + return { ...state, [action.objectId]: { ...state[action.objectId], ...action.propObject } } } else if (action.type === ADD_ID_TO_STORE_OBJECT_LIST_PROP) { return Object.assign({}, state, { [action.objectId]: Object.assign({}, state[action.objectId], { diff --git a/opendc-web/opendc-web-ui/src/redux/sagas/objects.js b/opendc-web/opendc-web-ui/src/redux/sagas/objects.js index 99082df0..9b4f8094 100644 --- a/opendc-web/opendc-web-ui/src/redux/sagas/objects.js +++ b/opendc-web/opendc-web-ui/src/redux/sagas/objects.js @@ -1,124 +1,27 @@ import { call, put, select, getContext } from 'redux-saga/effects' -import { addToStore } from '../actions/objects' import { fetchTopology, updateTopology } from '../../api/topologies' -import { uuid } from 'uuidv4' - -export const OBJECT_SELECTORS = { - user: (state) => state.objects.user, - authorization: (state) => state.objects.authorization, - portfolio: (state) => state.objects.portfolio, - scenario: (state) => state.objects.scenario, - cpu: (state) => state.objects.cpu, - gpu: (state) => state.objects.gpu, - memory: (state) => state.objects.memory, - storage: (state) => state.objects.storage, - machine: (state) => state.objects.machine, - rack: (state) => state.objects.rack, - tile: (state) => state.objects.tile, - room: (state) => state.objects.room, - topology: (state) => state.objects.topology, -} +import { Topology } from '../../util/topology-schema' +import { denormalize, normalize } from 'normalizr' +import { storeTopology } from '../actions/topologies' /** * Fetches and normalizes the topology with the specified identifier. */ export const fetchAndStoreTopology = function* (id) { - const topologyStore = yield select(OBJECT_SELECTORS['topology']) - const roomStore = yield select(OBJECT_SELECTORS['room']) - const tileStore = yield select(OBJECT_SELECTORS['tile']) - const rackStore = yield select(OBJECT_SELECTORS['rack']) - const machineStore = yield select(OBJECT_SELECTORS['machine']) const auth = yield getContext('auth') - let topology = topologyStore[id] + let topology = yield select((state) => state.objects.topology[id]) if (!topology) { - const fullTopology = yield call(fetchTopology, auth, id) - - for (let roomIdx in fullTopology.rooms) { - const fullRoom = fullTopology.rooms[roomIdx] - - generateIdIfNotPresent(fullRoom) - - if (!roomStore[fullRoom._id]) { - for (let tileIdx in fullRoom.tiles) { - const fullTile = fullRoom.tiles[tileIdx] - - generateIdIfNotPresent(fullTile) - - if (!tileStore[fullTile._id]) { - if (fullTile.rack) { - const fullRack = fullTile.rack - - generateIdIfNotPresent(fullRack) - - if (!rackStore[fullRack._id]) { - for (let machineIdx in fullRack.machines) { - const fullMachine = fullRack.machines[machineIdx] - - generateIdIfNotPresent(fullMachine) - - if (!machineStore[fullMachine._id]) { - let machine = (({ _id, position, cpus, gpus, memories, storages }) => ({ - _id, - rackId: fullRack._id, - position, - cpuIds: cpus.map((u) => u._id), - gpuIds: gpus.map((u) => u._id), - memoryIds: memories.map((u) => u._id), - storageIds: storages.map((u) => u._id), - }))(fullMachine) - yield put(addToStore('machine', machine)) - } - } - - const filledSlots = new Array(fullRack.capacity).fill(null) - fullRack.machines.forEach( - (machine) => (filledSlots[machine.position - 1] = machine._id) - ) - let rack = (({ _id, name, capacity, powerCapacityW }) => ({ - _id, - name, - capacity, - powerCapacityW, - machineIds: filledSlots, - }))(fullRack) - yield put(addToStore('rack', rack)) - } - } - - let tile = (({ _id, positionX, positionY, rack }) => ({ - _id, - roomId: fullRoom._id, - positionX, - positionY, - rackId: rack ? rack._id : undefined, - }))(fullTile) - yield put(addToStore('tile', tile)) - } - } - - let room = (({ _id, name, tiles }) => ({ _id, name, tileIds: tiles.map((t) => t._id) }))(fullRoom) - yield put(addToStore('room', room)) - } - } - - topology = (({ _id, name, rooms }) => ({ _id, name, roomIds: rooms.map((r) => r._id) }))(fullTopology) - yield put(addToStore('topology', topology)) - - // TODO consider pushing the IDs + const newTopology = yield call(fetchTopology, auth, id) + const { entities } = normalize(newTopology, Topology) + yield put(storeTopology(entities)) } return topology } -const generateIdIfNotPresent = (obj) => { - if (!obj._id) { - obj._id = uuid() - } -} - export const updateTopologyOnServer = function* (id) { - const topology = yield denormalizeTopology(id, true) + const topology = yield denormalizeTopology(id) const auth = yield getContext('auth') yield call(updateTopology, auth, topology) } @@ -126,73 +29,8 @@ export const updateTopologyOnServer = function* (id) { /** * Denormalizes the topology representation in order to be stored on the server. */ -export const denormalizeTopology = function* (id, keepIds) { - const topologyStore = yield select(OBJECT_SELECTORS['topology']) - const rooms = yield getAllRooms(topologyStore[id].roomIds, keepIds) - return { - _id: keepIds ? id : undefined, - name: topologyStore[id].name, - rooms: rooms, - } -} - -export const getAllRooms = function* (roomIds, keepIds) { - const roomStore = yield select(OBJECT_SELECTORS['room']) - - let rooms = [] - - for (let id of roomIds) { - let tiles = yield getAllRoomTiles(roomStore[id], keepIds) - rooms.push({ - _id: keepIds ? id : undefined, - name: roomStore[id].name, - tiles: tiles, - }) - } - return rooms -} - -export const getAllRoomTiles = function* (roomStore, keepIds) { - let tiles = [] - - for (let id of roomStore.tileIds) { - tiles.push(yield getTileById(id, keepIds)) - } - return tiles -} - -export const getTileById = function* (id, keepIds) { - const tileStore = yield select(OBJECT_SELECTORS['tile']) - return { - _id: keepIds ? id : undefined, - positionX: tileStore[id].positionX, - positionY: tileStore[id].positionY, - rack: !tileStore[id].rackId ? undefined : yield getRackById(tileStore[id].rackId, keepIds), - } -} - -export const getRackById = function* (id, keepIds) { - const rackStore = yield select(OBJECT_SELECTORS['rack']) - const machineStore = yield select(OBJECT_SELECTORS['machine']) - const cpuStore = yield select(OBJECT_SELECTORS['cpu']) - const gpuStore = yield select(OBJECT_SELECTORS['gpu']) - const memoryStore = yield select(OBJECT_SELECTORS['memory']) - const storageStore = yield select(OBJECT_SELECTORS['storage']) - - return { - _id: keepIds ? rackStore[id]._id : undefined, - name: rackStore[id].name, - capacity: rackStore[id].capacity, - powerCapacityW: rackStore[id].powerCapacityW, - machines: rackStore[id].machineIds - .filter((m) => m !== null) - .map((machineId) => ({ - _id: keepIds ? machineId : undefined, - position: machineStore[machineId].position, - cpus: machineStore[machineId].cpuIds.map((id) => cpuStore[id]), - gpus: machineStore[machineId].gpuIds.map((id) => gpuStore[id]), - memories: machineStore[machineId].memoryIds.map((id) => memoryStore[id]), - storages: machineStore[machineId].storageIds.map((id) => storageStore[id]), - })), - } +export const denormalizeTopology = function* (id) { + const objects = yield select((state) => state.objects) + const topology = objects.topology[id] + return denormalize(topology, Topology, objects) } diff --git a/opendc-web/opendc-web-ui/src/redux/sagas/prefabs.js b/opendc-web/opendc-web-ui/src/redux/sagas/prefabs.js index ec679391..91b03bf6 100644 --- a/opendc-web/opendc-web-ui/src/redux/sagas/prefabs.js +++ b/opendc-web/opendc-web-ui/src/redux/sagas/prefabs.js @@ -1,14 +1,17 @@ import { call, put, select, getContext } from 'redux-saga/effects' import { addToStore } from '../actions/objects' import { addPrefab } from '../../api/prefabs' -import { getRackById } from './objects' +import { Rack } from '../../util/topology-schema' +import { denormalize } from 'normalizr' export function* onAddPrefab(action) { try { - const currentRackId = yield select((state) => state.objects.tile[state.interactionLevel.tileId].rackId) - const currentRackJson = yield getRackById(currentRackId, false) + const interactionLevel = yield select((state) => state.interactionLevel) + const objects = yield select((state) => state.objects) + const rack = objects.rack[objects.tile[interactionLevel.tileId].rack] + const prefabRack = denormalize(rack, Rack, objects) const auth = yield getContext('auth') - const prefab = yield call(addPrefab, auth, { name: action.name, rack: currentRackJson }) + const prefab = yield call(() => addPrefab(auth, { name: action.name, rack: prefabRack })) yield put(addToStore('prefab', prefab)) } catch (error) { console.error(error) diff --git a/opendc-web/opendc-web-ui/src/redux/sagas/topology.js b/opendc-web/opendc-web-ui/src/redux/sagas/topology.js index 0ed40131..5d9154fd 100644 --- a/opendc-web/opendc-web-ui/src/redux/sagas/topology.js +++ b/opendc-web/opendc-web-ui/src/redux/sagas/topology.js @@ -25,8 +25,8 @@ export function* fetchAndStoreAllTopologiesOfProject(projectId, setTopology = fa const queryClient = yield getContext('queryClient') const project = yield call(() => queryClient.fetchQuery(['projects', projectId])) - for (let i in project.topologyIds) { - yield fetchAndStoreTopology(project.topologyIds[i]) + for (const id of project.topologyIds) { + yield fetchAndStoreTopology(id) } if (setTopology) { @@ -43,8 +43,9 @@ export function* onAddTopology(action) { let topologyToBeCreated if (duplicateId) { - topologyToBeCreated = yield denormalizeTopology(duplicateId, false) + topologyToBeCreated = yield denormalizeTopology(duplicateId) topologyToBeCreated = { ...topologyToBeCreated, name } + delete topologyToBeCreated._id } else { topologyToBeCreated = { name: action.name, rooms: [] } } @@ -65,10 +66,10 @@ export function* onStartNewRoomConstruction() { _id: uuid(), name: 'Room', topologyId, - tileIds: [], + tiles: [], } yield put(addToStore('room', room)) - yield put(addIdToStoreObjectListProp('topology', topologyId, 'roomIds', room._id)) + yield put(addIdToStoreObjectListProp('topology', topologyId, 'rooms', room._id)) yield updateTopologyOnServer(topologyId) yield put(startNewRoomConstructionSucceeded(room._id)) } catch (error) { @@ -80,7 +81,7 @@ export function* onCancelNewRoomConstruction() { try { const topologyId = yield select((state) => state.currentTopologyId) const roomId = yield select((state) => state.construction.currentRoomInConstruction) - yield put(removeIdFromStoreObjectListProp('topology', topologyId, 'roomIds', roomId)) + yield put(removeIdFromStoreObjectListProp('topology', topologyId, 'rooms', roomId)) // TODO remove room from store, too yield updateTopologyOnServer(topologyId) yield put(cancelNewRoomConstructionSucceeded()) @@ -100,7 +101,7 @@ export function* onAddTile(action) { positionY: action.positionY, } yield put(addToStore('tile', tile)) - yield put(addIdToStoreObjectListProp('room', roomId, 'tileIds', tile._id)) + yield put(addIdToStoreObjectListProp('room', roomId, 'tiles', tile._id)) yield updateTopologyOnServer(topologyId) } catch (error) { console.error(error) @@ -111,7 +112,7 @@ export function* onDeleteTile(action) { try { const topologyId = yield select((state) => state.currentTopologyId) const roomId = yield select((state) => state.construction.currentRoomInConstruction) - yield put(removeIdFromStoreObjectListProp('room', roomId, 'tileIds', action.tileId)) + yield put(removeIdFromStoreObjectListProp('room', roomId, 'tiles', action.tileId)) yield updateTopologyOnServer(topologyId) } catch (error) { console.error(error) @@ -136,7 +137,7 @@ export function* onDeleteRoom() { const topologyId = yield select((state) => state.currentTopologyId) const roomId = yield select((state) => state.interactionLevel.roomId) yield put(goDownOneInteractionLevel()) - yield put(removeIdFromStoreObjectListProp('topology', topologyId, 'roomIds', roomId)) + yield put(removeIdFromStoreObjectListProp('topology', topologyId, 'rooms', roomId)) yield updateTopologyOnServer(topologyId) } catch (error) { console.error(error) @@ -146,7 +147,7 @@ export function* onDeleteRoom() { export function* onEditRackName(action) { try { const topologyId = yield select((state) => state.currentTopologyId) - const rackId = yield select((state) => state.objects.tile[state.interactionLevel.tileId].rackId) + const rackId = yield select((state) => state.objects.tile[state.interactionLevel.tileId].rack) const rack = Object.assign({}, yield select((state) => state.objects.rack[rackId])) rack.name = action.name yield put(addPropToStoreObject('rack', rackId, { name: action.name })) @@ -161,7 +162,7 @@ export function* onDeleteRack() { const topologyId = yield select((state) => state.currentTopologyId) const tileId = yield select((state) => state.interactionLevel.tileId) yield put(goDownOneInteractionLevel()) - yield put(addPropToStoreObject('tile', tileId, { rackId: undefined })) + yield put(addPropToStoreObject('tile', tileId, { rack: undefined })) yield updateTopologyOnServer(topologyId) } catch (error) { console.error(error) @@ -176,10 +177,10 @@ export function* onAddRackToTile(action) { name: 'Rack', capacity: DEFAULT_RACK_SLOT_CAPACITY, powerCapacityW: DEFAULT_RACK_POWER_CAPACITY, + machines: [], } - rack.machineIds = new Array(rack.capacity).fill(null) yield put(addToStore('rack', rack)) - yield put(addPropToStoreObject('tile', action.tileId, { rackId: rack._id })) + yield put(addPropToStoreObject('tile', action.tileId, { rack: rack._id })) yield updateTopologyOnServer(topologyId) } catch (error) { console.error(error) @@ -189,23 +190,21 @@ export function* onAddRackToTile(action) { export function* onAddMachine(action) { try { const topologyId = yield select((state) => state.currentTopologyId) - const rackId = yield select((state) => state.objects.tile[state.interactionLevel.tileId].rackId) + const rackId = yield select((state) => state.objects.tile[state.interactionLevel.tileId].rack) const rack = yield select((state) => state.objects.rack[rackId]) const machine = { _id: uuid(), - rackId, position: action.position, - cpuIds: [], - gpuIds: [], - memoryIds: [], - storageIds: [], + cpus: [], + gpus: [], + memories: [], + storages: [], } yield put(addToStore('machine', machine)) - const machineIds = [...rack.machineIds] - machineIds[machine.position - 1] = machine._id - yield put(addPropToStoreObject('rack', rackId, { machineIds })) + const machineIds = [...rack.machines, machine._id] + yield put(addPropToStoreObject('rack', rackId, { machines: machineIds })) yield updateTopologyOnServer(topologyId) } catch (error) { console.error(error) @@ -217,35 +216,41 @@ export function* onDeleteMachine() { const topologyId = yield select((state) => state.currentTopologyId) const tileId = yield select((state) => state.interactionLevel.tileId) const position = yield select((state) => state.interactionLevel.position) - const rack = yield select((state) => state.objects.rack[state.objects.tile[tileId].rackId]) - const machineIds = [...rack.machineIds] - machineIds[position - 1] = null + const rack = yield select((state) => state.objects.rack[state.objects.tile[tileId].rack]) yield put(goDownOneInteractionLevel()) - yield put(addPropToStoreObject('rack', rack._id, { machineIds })) + yield put( + addPropToStoreObject('rack', rack._id, { machines: rack.machines.filter((_, idx) => idx !== position - 1) }) + ) yield updateTopologyOnServer(topologyId) } catch (error) { console.error(error) } } +const unitMapping = { + cpu: 'cpus', + gpu: 'gpus', + memory: 'memories', + storage: 'storages', +} + export function* onAddUnit(action) { try { const topologyId = yield select((state) => state.currentTopologyId) const tileId = yield select((state) => state.interactionLevel.tileId) const position = yield select((state) => state.interactionLevel.position) const machine = yield select( - (state) => - state.objects.machine[state.objects.rack[state.objects.tile[tileId].rackId].machineIds[position - 1]] + (state) => state.objects.machine[state.objects.rack[state.objects.tile[tileId].rack].machines[position - 1]] ) - if (machine[action.unitType + 'Ids'].length >= MAX_NUM_UNITS_PER_MACHINE) { + if (machine[unitMapping[action.unitType]].length >= MAX_NUM_UNITS_PER_MACHINE) { return } - const units = [...machine[action.unitType + 'Ids'], action.id] + const units = [...machine[unitMapping[action.unitType]], action.id] yield put( addPropToStoreObject('machine', machine._id, { - [action.unitType + 'Ids']: units, + [unitMapping[action.unitType]]: units, }) ) yield updateTopologyOnServer(topologyId) @@ -260,15 +265,14 @@ export function* onDeleteUnit(action) { const tileId = yield select((state) => state.interactionLevel.tileId) const position = yield select((state) => state.interactionLevel.position) const machine = yield select( - (state) => - state.objects.machine[state.objects.rack[state.objects.tile[tileId].rackId].machineIds[position - 1]] + (state) => state.objects.machine[state.objects.rack[state.objects.tile[tileId].rack].machines[position - 1]] ) - const unitIds = machine[action.unitType + 'Ids'].slice() + const unitIds = machine[unitMapping[action.unitType]].slice() unitIds.splice(action.index, 1) yield put( addPropToStoreObject('machine', machine._id, { - [action.unitType + 'Ids']: unitIds, + [unitMapping[action.unitType]]: unitIds, }) ) yield updateTopologyOnServer(topologyId) diff --git a/opendc-web/opendc-web-ui/src/shapes.js b/opendc-web/opendc-web-ui/src/shapes.js index 6c29eab0..3c27ad11 100644 --- a/opendc-web/opendc-web-ui/src/shapes.js +++ b/opendc-web/opendc-web-ui/src/shapes.js @@ -40,14 +40,6 @@ export const Project = PropTypes.shape({ portfolioIds: PropTypes.array.isRequired, }) -export const Authorization = PropTypes.shape({ - userId: PropTypes.string.isRequired, - user: User, - projectId: PropTypes.string.isRequired, - project: Project, - level: PropTypes.string.isRequired, -}) - export const ProcessingUnit = PropTypes.shape({ _id: PropTypes.string.isRequired, name: PropTypes.string.isRequired, @@ -66,44 +58,37 @@ export const StorageUnit = PropTypes.shape({ export const Machine = PropTypes.shape({ _id: PropTypes.string.isRequired, - rackId: PropTypes.string.isRequired, position: PropTypes.number.isRequired, - cpuIds: PropTypes.arrayOf(PropTypes.string.isRequired), - cpus: PropTypes.arrayOf(ProcessingUnit), - gpuIds: PropTypes.arrayOf(PropTypes.string.isRequired), - gpus: PropTypes.arrayOf(ProcessingUnit), - memoryIds: PropTypes.arrayOf(PropTypes.string.isRequired), - memories: PropTypes.arrayOf(StorageUnit), - storageIds: PropTypes.arrayOf(PropTypes.string.isRequired), - storages: PropTypes.arrayOf(StorageUnit), + cpus: PropTypes.arrayOf(PropTypes.string), + gpus: PropTypes.arrayOf(PropTypes.string), + memories: PropTypes.arrayOf(PropTypes.string), + storages: PropTypes.arrayOf(PropTypes.string), }) export const Rack = PropTypes.shape({ _id: PropTypes.string.isRequired, capacity: PropTypes.number.isRequired, powerCapacityW: PropTypes.number.isRequired, - machines: PropTypes.arrayOf(Machine), + machines: PropTypes.arrayOf(PropTypes.string), }) export const Tile = PropTypes.shape({ _id: PropTypes.string.isRequired, - roomId: PropTypes.string.isRequired, positionX: PropTypes.number.isRequired, positionY: PropTypes.number.isRequired, - rackId: PropTypes.string, - rack: Rack, + rack: PropTypes.string, }) export const Room = PropTypes.shape({ _id: PropTypes.string.isRequired, name: PropTypes.string.isRequired, - tiles: PropTypes.arrayOf(Tile), + tiles: PropTypes.arrayOf(PropTypes.string), }) export const Topology = PropTypes.shape({ _id: PropTypes.string.isRequired, name: PropTypes.string.isRequired, - rooms: PropTypes.arrayOf(Room), + rooms: PropTypes.arrayOf(PropTypes.string), }) export const Scheduler = PropTypes.shape({ diff --git a/opendc-web/opendc-web-ui/src/util/topology-schema.js b/opendc-web/opendc-web-ui/src/util/topology-schema.js new file mode 100644 index 00000000..9acd688b --- /dev/null +++ b/opendc-web/opendc-web-ui/src/util/topology-schema.js @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2021 AtLarge Research + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import { schema } from 'normalizr' + +const Cpu = new schema.Entity('cpu', {}, { idAttribute: '_id' }) +const Gpu = new schema.Entity('gpu', {}, { idAttribute: '_id' }) +const Memory = new schema.Entity('memory', {}, { idAttribute: '_id' }) +const Storage = new schema.Entity('storage', {}, { idAttribute: '_id' }) + +export const Machine = new schema.Entity( + 'machine', + { + cpus: [Cpu], + gpus: [Gpu], + memories: [Memory], + storages: [Storage], + }, + { idAttribute: '_id' } +) + +export const Rack = new schema.Entity('rack', { machines: [Machine] }, { idAttribute: '_id' }) + +export const Tile = new schema.Entity('tile', { rack: Rack }, { idAttribute: '_id' }) + +export const Room = new schema.Entity('room', { tiles: [Tile] }, { idAttribute: '_id' }) + +export const Topology = new schema.Entity('topology', { rooms: [Room] }, { idAttribute: '_id' }) diff --git a/opendc-web/opendc-web-ui/yarn.lock b/opendc-web/opendc-web-ui/yarn.lock index 630f38db..bf4c419e 100644 --- a/opendc-web/opendc-web-ui/yarn.lock +++ b/opendc-web/opendc-web-ui/yarn.lock @@ -2763,6 +2763,11 @@ normalize-path@^3.0.0, normalize-path@~3.0.0: resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-3.0.0.tgz#0dcd69ff23a1c9b11fd0978316644a0388216a65" integrity sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA== +normalizr@^3.6.1: + version "3.6.1" + resolved "https://registry.yarnpkg.com/normalizr/-/normalizr-3.6.1.tgz#d367ab840e031ff382141b8d81ce279292ff69fe" + integrity sha512-8iEmqXmPtll8PwbEFrbPoDxVw7MKnNvt3PZzR2Xvq9nggEEOgBlNICPXYzyZ4w4AkHUzCU998mdatER3n2VaMA== + npm-run-path@^4.0.0: version "4.0.1" resolved "https://registry.yarnpkg.com/npm-run-path/-/npm-run-path-4.0.1.tgz#b7ecd1e5ed53da8e37a55e1c2269e0b97ed748ea" -- cgit v1.2.3 From 2c8d675c2cf140eac05988065a9d20fd2773399a Mon Sep 17 00:00:00 2001 From: Fabian Mastenbroek Date: Thu, 8 Jul 2021 13:36:39 +0200 Subject: ui: Combine fetching of project relations This change updates the OpenDC frontend to combine the fetching of project relations. This means that for a single project, we make only one additional request to retrieve all its topologies. --- opendc-web/opendc-web-ui/src/api/portfolios.js | 4 ++++ opendc-web/opendc-web-ui/src/api/scenarios.js | 4 ++++ opendc-web/opendc-web-ui/src/api/topologies.js | 4 ++++ .../app/results/PortfolioResultsContainer.js | 7 ++---- .../app/sidebars/project/PortfolioListContainer.js | 7 ++---- .../app/sidebars/project/ScenarioListContainer.js | 17 +++++++------- .../app/sidebars/project/TopologyListContainer.js | 10 ++++---- opendc-web/opendc-web-ui/src/data/project.js | 27 ++++++++++++++-------- opendc-web/opendc-web-ui/src/data/topology.js | 13 +++++++---- 9 files changed, 54 insertions(+), 39 deletions(-) diff --git a/opendc-web/opendc-web-ui/src/api/portfolios.js b/opendc-web/opendc-web-ui/src/api/portfolios.js index 36709b36..82ac0ced 100644 --- a/opendc-web/opendc-web-ui/src/api/portfolios.js +++ b/opendc-web/opendc-web-ui/src/api/portfolios.js @@ -26,6 +26,10 @@ export function fetchPortfolio(auth, portfolioId) { return request(auth, `portfolios/${portfolioId}`) } +export function fetchPortfoliosOfProject(auth, projectId) { + return request(auth, `projects/${projectId}/portfolios`) +} + export function addPortfolio(auth, portfolio) { return request(auth, `projects/${portfolio.projectId}/portfolios`, 'POST', { portfolio }) } diff --git a/opendc-web/opendc-web-ui/src/api/scenarios.js b/opendc-web/opendc-web-ui/src/api/scenarios.js index 3a7c7e6f..88516caa 100644 --- a/opendc-web/opendc-web-ui/src/api/scenarios.js +++ b/opendc-web/opendc-web-ui/src/api/scenarios.js @@ -26,6 +26,10 @@ export function fetchScenario(auth, scenarioId) { return request(auth, `scenarios/${scenarioId}`) } +export function fetchScenariosOfPortfolio(auth, portfolioId) { + return request(auth, `portfolios/${portfolioId}/scenarios`) +} + export function addScenario(auth, scenario) { return request(auth, `portfolios/${scenario.portfolioId}/scenarios`, 'POST', { scenario }) } diff --git a/opendc-web/opendc-web-ui/src/api/topologies.js b/opendc-web/opendc-web-ui/src/api/topologies.js index 74fc1977..0b8864e0 100644 --- a/opendc-web/opendc-web-ui/src/api/topologies.js +++ b/opendc-web/opendc-web-ui/src/api/topologies.js @@ -26,6 +26,10 @@ export function fetchTopology(auth, topologyId) { return request(auth, `topologies/${topologyId}`) } +export function fetchTopologiesOfProject(auth, projectId) { + return request(auth, `projects/${projectId}/topologies`) +} + export function addTopology(auth, topology) { return request(auth, `projects/${topology.projectId}/topologies`, 'POST', { topology }) } diff --git a/opendc-web/opendc-web-ui/src/containers/app/results/PortfolioResultsContainer.js b/opendc-web/opendc-web-ui/src/containers/app/results/PortfolioResultsContainer.js index f9a380cb..a75f15ae 100644 --- a/opendc-web/opendc-web-ui/src/containers/app/results/PortfolioResultsContainer.js +++ b/opendc-web/opendc-web-ui/src/containers/app/results/PortfolioResultsContainer.js @@ -1,16 +1,13 @@ import React from 'react' import PortfolioResultsComponent from '../../../components/app/results/PortfolioResultsComponent' import { useRouter } from 'next/router' -import { usePortfolio, useScenarios } from '../../../data/project' +import { usePortfolio, usePortfolioScenarios } from '../../../data/project' const PortfolioResultsContainer = (props) => { const router = useRouter() const { portfolio: currentPortfolioId } = router.query const { data: portfolio } = usePortfolio(currentPortfolioId) - const scenarios = useScenarios(portfolio?.scenarioIds ?? []) - .filter((res) => res.data) - .map((res) => res.data) - + const scenarios = usePortfolioScenarios(currentPortfolioId).data ?? [] return } diff --git a/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/PortfolioListContainer.js b/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/PortfolioListContainer.js index 1fb88253..60ac666c 100644 --- a/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/PortfolioListContainer.js +++ b/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/PortfolioListContainer.js @@ -2,16 +2,13 @@ import React, { useState } from 'react' import { useRouter } from 'next/router' import PortfolioListComponent from '../../../../components/app/sidebars/project/PortfolioListComponent' import NewPortfolioModalComponent from '../../../../components/modals/custom-components/NewPortfolioModalComponent' -import { usePortfolios, useProject } from '../../../../data/project' +import { useProjectPortfolios } from '../../../../data/project' import { useMutation } from 'react-query' const PortfolioListContainer = () => { const router = useRouter() const { project: currentProjectId, portfolio: currentPortfolioId } = router.query - const { data: currentProject } = useProject(currentProjectId) - const portfolios = usePortfolios(currentProject?.portfolioIds ?? []) - .filter((res) => res.data) - .map((res) => res.data) + const portfolios = useProjectPortfolios(currentProjectId).data ?? [] const { mutate: addPortfolio } = useMutation('addPortfolio') const { mutateAsync: deletePortfolio } = useMutation('deletePortfolio') diff --git a/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/ScenarioListContainer.js b/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/ScenarioListContainer.js index fd55582f..3b68df38 100644 --- a/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/ScenarioListContainer.js +++ b/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/ScenarioListContainer.js @@ -2,20 +2,19 @@ import PropTypes from 'prop-types' import React, { useState } from 'react' import ScenarioListComponent from '../../../../components/app/sidebars/project/ScenarioListComponent' import NewScenarioModalComponent from '../../../../components/modals/custom-components/NewScenarioModalComponent' -import { useTopologies } from '../../../../data/topology' -import { usePortfolio, useProject, useScenarios } from '../../../../data/project' +import { useProjectTopologies } from '../../../../data/topology' +import { usePortfolio, usePortfolioScenarios } from '../../../../data/project' import { useSchedulers, useTraces } from '../../../../data/experiments' import { useMutation } from 'react-query' const ScenarioListContainer = ({ portfolioId }) => { const { data: portfolio } = usePortfolio(portfolioId) - const { data: project } = useProject(portfolio?.projectId) - const scenarios = useScenarios(portfolio?.scenarioIds ?? []) - .filter((res) => res.data) - .map((res) => res.data) - const topologies = useTopologies(project?.topologyIds ?? []) - .filter((res) => res.data) - .map((res) => ({ _id: res.data._id, name: res.data.name })) + const scenarios = usePortfolioScenarios(portfolioId).data ?? [] + const topologies = + useProjectTopologies(portfolio?.projectId).data?.map((topology) => ({ + _id: topology._id, + name: topology.name, + })) ?? [] const traces = useTraces().data ?? [] const schedulers = useSchedulers().data ?? [] diff --git a/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/TopologyListContainer.js b/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/TopologyListContainer.js index 55eab23a..a2244a30 100644 --- a/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/TopologyListContainer.js +++ b/opendc-web/opendc-web-ui/src/containers/app/sidebars/project/TopologyListContainer.js @@ -5,18 +5,16 @@ import { setCurrentTopology } from '../../../../redux/actions/topology/building' import { useRouter } from 'next/router' import { addTopology } from '../../../../redux/actions/topologies' import NewTopologyModalComponent from '../../../../components/modals/custom-components/NewTopologyModalComponent' -import { useActiveTopology, useTopologies } from '../../../../data/topology' -import { useProject } from '../../../../data/project' +import { useActiveTopology, useProjectTopologies } from '../../../../data/topology' import { useMutation } from 'react-query' const TopologyListContainer = () => { const dispatch = useDispatch() const router = useRouter() const { project: currentProjectId } = router.query - const { data: currentProject } = useProject(currentProjectId) - const topologies = useTopologies(currentProject?.topologyIds ?? []) - .filter((res) => res.data) - .map((res) => ({ _id: res.data._id, name: res.data.name })) + const topologies = + useProjectTopologies(currentProjectId).data?.map((topology) => ({ _id: topology._id, name: topology.name })) ?? + [] const currentTopologyId = useActiveTopology()?._id const [isVisible, setVisible] = useState(false) diff --git a/opendc-web/opendc-web-ui/src/data/project.js b/opendc-web/opendc-web-ui/src/data/project.js index 256203a3..9bdcfb93 100644 --- a/opendc-web/opendc-web-ui/src/data/project.js +++ b/opendc-web/opendc-web-ui/src/data/project.js @@ -23,8 +23,8 @@ import { useQueries, useQuery } from 'react-query' import { addProject, deleteProject, fetchProject, fetchProjects } from '../api/projects' import { useRouter } from 'next/router' -import { addPortfolio, deletePortfolio, fetchPortfolio } from '../api/portfolios' -import { addScenario, deleteScenario, fetchScenario } from '../api/scenarios' +import { addPortfolio, deletePortfolio, fetchPortfolio, fetchPortfoliosOfProject } from '../api/portfolios' +import { addScenario, deleteScenario, fetchScenario, fetchScenariosOfPortfolio } from '../api/scenarios' /** * Configure the query defaults for the project endpoints. @@ -51,6 +51,9 @@ export function configureProjectClient(queryClient, auth) { queryClient.setQueryDefaults('portfolios', { queryFn: ({ queryKey }) => fetchPortfolio(auth, queryKey[1]), }) + queryClient.setQueryDefaults('project-portfolios', { + queryFn: ({ queryKey }) => fetchPortfoliosOfProject(auth, queryKey[1]), + }) queryClient.setMutationDefaults('addPortfolio', { mutationFn: (data) => addPortfolio(auth, data), onSuccess: async (result) => { @@ -75,6 +78,9 @@ export function configureProjectClient(queryClient, auth) { queryClient.setQueryDefaults('scenarios', { queryFn: ({ queryKey }) => fetchScenario(auth, queryKey[1]), }) + queryClient.setQueryDefaults('portfolio-scenarios', { + queryFn: ({ queryKey }) => fetchScenariosOfPortfolio(auth, queryKey[1]), + }) queryClient.setMutationDefaults('addScenario', { mutationFn: (data) => addScenario(auth, data), onSuccess: async (result) => { @@ -122,14 +128,10 @@ export function usePortfolio(portfolioId) { } /** - * Return the portfolios for the specified project id. + * Return the portfolios of the specified project. */ -export function usePortfolios(portfolioIds) { - return useQueries( - portfolioIds.map((portfolioId) => ({ - queryKey: ['portfolios', portfolioId], - })) - ) +export function useProjectPortfolios(projectId) { + return useQuery(['project-portfolios', projectId], { enabled: !!projectId }) } /** @@ -143,6 +145,13 @@ export function useScenarios(scenarioIds) { ) } +/** + * Return the scenarios of the specified portfolio. + */ +export function usePortfolioScenarios(portfolioId) { + return useQuery(['portfolio-scenarios', portfolioId], { enabled: !!portfolioId }) +} + /** * Return the current active project identifier. */ diff --git a/opendc-web/opendc-web-ui/src/data/topology.js b/opendc-web/opendc-web-ui/src/data/topology.js index 92911a70..8db75877 100644 --- a/opendc-web/opendc-web-ui/src/data/topology.js +++ b/opendc-web/opendc-web-ui/src/data/topology.js @@ -21,14 +21,17 @@ */ import { useSelector } from 'react-redux' -import { useQueries } from 'react-query' -import { addTopology, deleteTopology, fetchTopology, updateTopology } from '../api/topologies' +import { useQueries, useQuery } from 'react-query' +import { addTopology, deleteTopology, fetchTopologiesOfProject, fetchTopology, updateTopology } from '../api/topologies' /** * Configure the query defaults for the topology endpoints. */ export function configureTopologyClient(queryClient, auth) { queryClient.setQueryDefaults('topologies', { queryFn: ({ queryKey }) => fetchTopology(auth, queryKey[1]) }) + queryClient.setQueryDefaults('project-topologies', { + queryFn: ({ queryKey }) => fetchTopologiesOfProject(auth, queryKey[1]), + }) queryClient.setMutationDefaults('addTopology', { mutationFn: (data) => addTopology(auth, data), @@ -64,8 +67,8 @@ export function useActiveTopology() { } /** - * Return the scenarios with the specified identifiers. + * Return the topologies of the specified project. */ -export function useTopologies(topologyIds) { - return useQueries(topologyIds.map((topologyId) => ({ queryKey: ['topologies', topologyId] }))) +export function useProjectTopologies(projectId) { + return useQuery(['project-topologies', projectId], { enabled: !!projectId }) } -- cgit v1.2.3