Skip to content

Commit

Permalink
fix(status): rework statusData for live update
Browse files Browse the repository at this point in the history
  • Loading branch information
burgerni10 authored and Nicolas Burger committed Aug 18, 2022
1 parent 8ab9d80 commit e569611
Show file tree
Hide file tree
Showing 33 changed files with 242 additions and 373 deletions.
32 changes: 16 additions & 16 deletions src/HistoryQuery/HistoryQuery.class.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ class HistoryQuery {
this.filePattern = config.filePattern
this.cacheFolder = `${this.engine.cacheFolder}/${this.id}`
this.dataCacheFolder = `${this.engine.cacheFolder}/${this.id}/${HistoryQuery.DATA_FOLDER}`
this.statusData = { status: this.status }
this.statusData = {}
this.numberOfQueryParts = Math.round((this.endTime.getTime() - this.startTime.getTime()) / (1000 * this.config.settings.maxReadInterval))

if (!this.engine.eventEmitters[`/history/${this.id}/sse`]) {
Expand All @@ -53,8 +53,7 @@ class HistoryQuery {
}
this.engine.eventEmitters[`/history/${this.id}/sse`].events = new EventEmitter()
this.engine.eventEmitters[`/history/${this.id}/sse`].events.on('data', this.listener)
this.engine.eventEmitters[`/history/${this.id}/sse`].statusData = this.statusData
this.updateStatusDataStream()
this.updateStatusDataStream({ status: this.status })
}

/**
Expand Down Expand Up @@ -192,8 +191,7 @@ class HistoryQuery {
for (const scanGroup of this.south.scanGroups) {
const { scanMode } = scanGroup
if (scanGroup.points && scanGroup.points.length) {
this.statusData.scanGroup = `${scanGroup.scanMode} - ${scanGroup.aggregate}`
this.updateStatusDataStream()
this.updateStatusDataStream({ scanGroup: `${scanGroup.scanMode} - ${scanGroup.aggregate}` })
// eslint-disable-next-line no-await-in-loop
const exportResult = await this.exportScanMode(scanMode)
if (exportResult === -1) {
Expand All @@ -204,8 +202,7 @@ class HistoryQuery {
this.logger.error(`scanMode ${scanMode} ignored: scanGroup.points undefined or empty`)
}
}
this.statusData.scanGroup = null
this.updateStatusDataStream()
this.updateStatusDataStream({ scanGroup: null })
} else {
const exportResult = await this.exportScanMode(this.dataSource.scanMode)
if (exportResult === -1) {
Expand Down Expand Up @@ -283,9 +280,10 @@ class HistoryQuery {
} else {
intervalEndTime = this.endTime
}
this.statusData.currentTime = startTime.toISOString()
this.statusData.progress = Math.round((this.south.queryParts[scanMode] / this.numberOfQueryParts) * 10000) / 100
this.updateStatusDataStream()
this.updateStatusDataStream({
currentTime: startTime.toISOString(),
progress: Math.round((this.south.queryParts[scanMode] / this.numberOfQueryParts) * 10000) / 100,
})

// Wait between the read interval iterations
if (!firstIteration) {
Expand All @@ -312,9 +310,10 @@ class HistoryQuery {
this.south.queryParts[scanMode] = 0
// eslint-disable-next-line no-await-in-loop
await this.south.setConfig(`queryPart-${scanMode}`, this.south.queryParts[scanMode])
this.statusData.currentTime = startTime.toISOString()
this.statusData.progress = 100
this.updateStatusDataStream()
this.updateStatusDataStream({
currentTime: startTime.toISOString(),
progress: 100,
})
return 0
}

Expand All @@ -327,8 +326,7 @@ class HistoryQuery {
this.status = status
this.config.status = status
await this.engine.historyQueryRepository.update(this.config)
this.statusData.status = status
this.updateStatusDataStream()
this.updateStatusDataStream({ status })
}

/**
Expand Down Expand Up @@ -365,7 +363,9 @@ class HistoryQuery {
}
}

updateStatusDataStream() {
updateStatusDataStream(statusData = {}) {
this.statusData = { ...this.statusData, ...statusData }
this.engine.eventEmitters[`/history/${this.id}/sse`].statusData = this.statusData
this.engine.eventEmitters[`/history/${this.id}/sse`]?.events?.emit('data', this.statusData)
}
}
Expand Down
17 changes: 7 additions & 10 deletions src/HistoryQuery/HistoryQueryEngine.class.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,19 +59,19 @@ class HistoryQueryEngine extends BaseEngine {
* @returns {void}
*/
initializeStatusData() {
this.statusData = { ongoingHistoryQueryId: null }
if (!this.eventEmitters['/history/engine/sse']) {
this.eventEmitters['/history/engine/sse'] = {}
} else {
this.eventEmitters['/history/engine/sse'].events.removeAllListeners()
}
this.eventEmitters['/history/engine/sse'].events = new EventEmitter()
this.eventEmitters['/history/engine/sse'].events.on('data', this.listener)
this.eventEmitters['/history/engine/sse'].statusData = this.statusData
this.updateStatusDataStream()
this.updateStatusDataStream({ ongoingHistoryQueryId: null })
}

updateStatusDataStream() {
updateStatusDataStream(statusData = {}) {
this.statusData = { ...this.statusData, ...statusData }
this.eventEmitters['/history/engine/sse'].statusData = this.statusData
this.eventEmitters['/history/engine/sse']?.events?.emit('data', this.statusData)
}

Expand Down Expand Up @@ -149,8 +149,7 @@ class HistoryQueryEngine extends BaseEngine {

if (this.historyQuery) {
await this.historyQuery.stop()
this.statusData.ongoingHistorQueryId = null
this.updateStatusDataStream()
this.updateStatusDataStream({ ongoingHistoryQueryId: null })
this.eventEmitters['/history/engine/sse']?.events?.removeAllListeners()
this.eventEmitters['/history/engine/sse']?.stream?.destroy()
this.historyQuery = null
Expand Down Expand Up @@ -178,14 +177,12 @@ class HistoryQueryEngine extends BaseEngine {

if (dataSourceToUse && applicationToUse) {
this.historyQuery = new HistoryQuery(this, this.logger, historyQueryConfig, dataSourceToUse, applicationToUse)
this.statusData.ongoingHistoryQueryId = this.historyQuery.id
this.updateStatusDataStream()
this.updateStatusDataStream({ ongoingHistoryQueryId: this.historyQuery.id })
this.historyQuery.start()
}
} else {
this.logger.info('No HistoryQuery to execute')
this.statusData.ongoingHistoryQueryId = null
this.updateStatusDataStream()
this.updateStatusDataStream({ ongoingHistoryQueryId: null })
}
}

Expand Down
40 changes: 20 additions & 20 deletions src/client/About/About.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,20 @@ import { ConfigContext } from '../context/ConfigContext.jsx'
import logo from '../OIBus.png'

const About = () => {
const [staticStatus, setstaticStatus] = React.useState({})
const [dynamicStatus, setdynamicStatus] = React.useState({})
const [oibusInfo, setOibusInfo] = React.useState({})
const [oibusStatus, setOibusStatus] = React.useState({})
const { setAlert } = React.useContext(AlertContext)
const { activeConfig } = React.useContext(ConfigContext)

/**
* Acquire the status
* Retrieve OIBus info
* @returns {void}
*/
const fetchStatus = () => {
const fetchOIBusInfo = () => {
apis
.getStatus()
.getOIBusInfo()
.then((response) => {
setstaticStatus(response)
setOibusInfo(response)
})
.catch((error) => {
console.error(error)
Expand All @@ -35,7 +35,7 @@ const About = () => {
* @returns {void}
*/
React.useEffect(() => {
fetchStatus()
fetchOIBusInfo()
}, [])

/**
Expand All @@ -53,7 +53,7 @@ const About = () => {
source.onmessage = (event) => {
if (event && event.data) {
const myData = JSON.parse(event.data)
setdynamicStatus(myData)
setOibusStatus(myData)
}
}
return () => {
Expand All @@ -64,56 +64,56 @@ const About = () => {
return (
<div className="p-3">
<Container fluid>
{staticStatus && (
{oibusInfo && (
<ListGroup>
<ListGroupItem tag="a" href="https://optimistik.io/oibus">
<img src={logo} alt="logo" height="100px" />
</ListGroupItem>
<ListGroupItem>
<b className="me-1">Version:</b>
{staticStatus.version}
{oibusInfo.version}
</ListGroupItem>
<ListGroupItem>
<b className="me-1">Architecture:</b>
{staticStatus.architecture}
{oibusInfo.architecture}
</ListGroupItem>
<ListGroupItem>
<b className="me-1">currentDirectory:</b>
{staticStatus.currentDirectory}
{oibusInfo.currentDirectory}
</ListGroupItem>
<ListGroupItem>
<b className="me-1">nodeVersion:</b>
{staticStatus.nodeVersion}
{oibusInfo.nodeVersion}
</ListGroupItem>
<ListGroupItem>
<b className="me-1">Executable:</b>
{staticStatus.executable}
{oibusInfo.executable}
</ListGroupItem>
<ListGroupItem>
<b className="me-1">ConfigurationFile:</b>
{staticStatus.configurationFile}
{oibusInfo.configurationFile}
</ListGroupItem>
<ListGroupItem>
<b className="me-1">Hostname:</b>
{staticStatus.hostname}
{oibusInfo.hostname}
</ListGroupItem>
<ListGroupItem>
<b className="me-1">Operating System:</b>
{staticStatus.osType}
{oibusInfo.osType}
{' '}
{staticStatus.osRelease}
{oibusInfo.osRelease}
</ListGroupItem>
<ListGroupItem tag="a" href="https://optimistik.io/oibus">
Official site
</ListGroupItem>
<ListGroupItem>
Copyright:
{staticStatus.copyright}
{oibusInfo.copyright}
</ListGroupItem>
<ListGroupItem tag="a" href="https://joinup.ec.europa.eu/sites/default/files/custom-page/attachment/2020-03/EUPL-1.2%20EN.txt">
Licensed under the EUPL-1.2-or-later
</ListGroupItem>
{Object.entries(dynamicStatus)
{Object.entries(oibusStatus)
.map(([key, value]) => (
<ListGroupItem key={key}>
<div key={key}>
Expand Down
2 changes: 1 addition & 1 deletion src/client/About/About.spec.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ const status = {
let resolve
let reject
const setAlert = jest.fn()
apis.getStatus = () => new Promise((_resolve, _reject) => {
apis.getOIBusInfo = () => new Promise((_resolve, _reject) => {
resolve = _resolve
reject = _reject
})
Expand Down
8 changes: 4 additions & 4 deletions src/client/TopHeader.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const TopHeader = () => {
const { newConfig, activeConfig } = React.useContext(ConfigContext)
const [isOpen, setIsOpen] = React.useState(false)
const { setAlert } = React.useContext(AlertContext)
const [status, setStatus] = React.useState({})
const [oibusInfo, setOibusInfo] = React.useState({})
const location = useLocation()

React.useEffect(() => {
Expand All @@ -28,9 +28,9 @@ const TopHeader = () => {
*/
const fetchStatus = () => {
apis
.getStatus()
.getOIBusInfo()
.then((response) => {
setStatus(response)
setOibusInfo(response)
})
.catch((error) => {
console.error(error)
Expand Down Expand Up @@ -67,7 +67,7 @@ const TopHeader = () => {
About
</NavItem>
<NavItem className="oi-navname text-muted">
{`version ${status.version}`}
{`version ${oibusInfo.version}`}
</NavItem>
</Nav>
</Collapse>
Expand Down
4 changes: 2 additions & 2 deletions src/client/services/apis.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ const deleteHistoryQuery = async (id, position) => deleteRequest(`/history-queri
const getLastCompletedForHistoryQuery = async (id) => getRequest(`/history-queries/${id}/status`)

const getLogs = (fromDate, toDate, verbosity) => getRequest(`/logs?fromDate=${fromDate || ''}&toDate=${toDate || ''}&verbosity=[${verbosity}]`)
const getStatus = () => getRequest('/status')
const getOIBusInfo = () => getRequest('/info')
const getSouthStatus = (id) => getRequest(`/status/south/${id}`)
const getNorthStatus = (id) => getRequest(`/status/north/${id}`)

Expand All @@ -111,7 +111,7 @@ export default {
deleteHistoryQuery,
getLastCompletedForHistoryQuery,
getLogs,
getStatus,
getOIBusInfo,
getSouthStatus,
getNorthStatus,
reload,
Expand Down
4 changes: 2 additions & 2 deletions src/client/services/apis.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ global.fetch = jest.fn().mockImplementation((uri) => {
case '/config':
jsonString = JSON.stringify({ config: testConfig })
break
case '/status':
case '/info':
jsonString = JSON.stringify({ version: '1.0' })
break
default:
Expand Down Expand Up @@ -117,7 +117,7 @@ describe('apis', () => {
})

it('check getStatus', async () => {
const result = await apis.getStatus()
const result = await apis.getOIBusInfo()
expect(result).toEqual({ version: '1.0' })
})
})
6 changes: 3 additions & 3 deletions src/engine/HealthSignal.class.js
Original file line number Diff line number Diff line change
Expand Up @@ -92,12 +92,12 @@ class HealthSignal {
/**
* Retrieve status information from the engine
* @param {boolean} verbose - return only the id when false, return full status when true
* @returns {object} - the status of oibus
* @returns {object} - the status of OIBus
*/
async prepareStatus(verbose) {
let status = { version: this.engine.getVersion() }
let status = await this.engine.getOIBusInfo()
if (verbose) {
status = await this.engine.getStatus()
status = { ...status, ...this.engine.statusData }
}
return status
}
Expand Down
18 changes: 8 additions & 10 deletions src/engine/HealthSignal.class.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,7 @@ describe('HealthSignal', () => {
proxies: [proxy],
}
engine.configService = { getConfig: () => ({ engineConfig }) }
engine.getStatus = jest.fn()
engine.getVersion = jest.fn()
engine.getOIBusInfo = jest.fn()
engine.requestService = { httpSend: jest.fn() }

it('should be properly initialized', () => {
Expand Down Expand Up @@ -98,25 +97,24 @@ describe('HealthSignal', () => {

it('should prepare simple status info when verbose is not enabled', async () => {
const healthSignal = new HealthSignal(engine)
engine.getVersion.mockReturnValue('version')
engine.getOIBusInfo.mockReturnValue({ version: 'version' })
engine.statusData = { randomStatusData: 'test' }

const status = await healthSignal.prepareStatus(false)

expect(engine.getVersion).toHaveBeenCalledTimes(1)
expect(engine.getStatus).not.toHaveBeenCalled()
expect(engine.getOIBusInfo).toHaveBeenCalledTimes(1)
expect(status).toEqual({ version: 'version' })
})

it('should prepare full status info when verbose is enabled', async () => {
const healthSignal = new HealthSignal(engine)
engine.getVersion.mockReturnValue('ver')
engine.getStatus.mockReturnValue({ status: 'status', version: 'version' })
engine.getOIBusInfo.mockReturnValue({ status: 'status', version: 'version' })
engine.statusData = { randomStatusData: 'test' }

const status = await healthSignal.prepareStatus(true)

expect(engine.getVersion).toHaveBeenCalledTimes(1)
expect(engine.getStatus).toHaveBeenCalledTimes(1)
expect(status).toEqual({ status: 'status', version: 'version' })
expect(engine.getOIBusInfo).toHaveBeenCalledTimes(1)
expect(status).toEqual({ status: 'status', version: 'version', randomStatusData: 'test' })
})

it('should call RequestService httpSend()', async () => {
Expand Down
Loading

0 comments on commit e569611

Please sign in to comment.