Skip to content

Commit

Permalink
fix(south/north): rename init into start and create stop method
Browse files Browse the repository at this point in the history
  • Loading branch information
burgerni10 authored and Nicolas Burger committed Nov 20, 2022
1 parent 57f6389 commit 753cd6b
Show file tree
Hide file tree
Showing 40 changed files with 218 additions and 187 deletions.
1 change: 1 addition & 0 deletions src/engine/health-signal.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@ describe('HealthSignal', () => {
})

it('should forward health signal', async () => {
utils.createProxyAgent.mockImplementation(() => null)
const data = { status: 'status' }
healthSignal.http.enabled = true
await healthSignal.forwardRequest(data)
Expand Down
10 changes: 5 additions & 5 deletions src/engine/history-query/history-query.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,14 +64,14 @@ class HistoryQuery {

this.overwriteConnectorsSettings()

await this.north.init(
await this.north.start(
path.resolve(this.cacheFolder, `north-${this.north.id}`),
this.engine.oibusName,
this.engine.defaultLogParameters,
)
await this.north.connect()

await this.south.init(
await this.south.start(
path.resolve(this.cacheFolder, `south-${this.south.id}`),
this.engine.oibusName,
this.engine.defaultLogParameters,
Expand All @@ -86,7 +86,7 @@ class HistoryQuery {
this.setStatus(HistoryQuery.STATUS_RUNNING)
this.statusService.updateStatusDataStream({ status: HistoryQuery.STATUS_RUNNING })

// In the south.init method, queryParts is set for each scanMode to 0
// In the south.start method, queryParts is set for each scanMode to 0
// Because of scan groups, associated to aggregates, each scan mode must be queried independently
// Map each scanMode to a history query and run each query sequentially
await Object.keys(this.south.queryParts).reduce((promise, scanMode) => promise.then(
Expand All @@ -104,11 +104,11 @@ class HistoryQuery {
}
if (this.south) {
this.logger.info(`Stopping South connector "${this.southConfiguration.name}".`)
await this.south.disconnect()
await this.south.stop()
}
if (this.north) {
this.logger.info(`Stopping North connector "${this.northConfiguration.name}".`)
await this.north.disconnect()
await this.north.stop()
}
this.statusService.stop()
}
Expand Down
11 changes: 4 additions & 7 deletions src/engine/oibus-engine.js
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ class OIBusEngine extends BaseEngine {
await Promise.allSettled(this.activeSouths.map((south) => {
const initAndConnect = async () => {
try {
await south.init(this.cacheFolder, this.oibusName, this.defaultLogParameters)
await south.start(this.cacheFolder, this.oibusName, this.defaultLogParameters)
await south.connect()
} catch (error) {
this.logger.error(error)
Expand All @@ -201,7 +201,7 @@ class OIBusEngine extends BaseEngine {
await Promise.allSettled(this.activeNorths.map((north) => {
const initAndConnect = async () => {
try {
await north.init(this.cacheFolder, this.oibusName, this.defaultLogParameters)
await north.start(this.cacheFolder, this.oibusName, this.defaultLogParameters)
await north.connect()
} catch (error) {
this.logger.error(error)
Expand Down Expand Up @@ -269,16 +269,13 @@ class OIBusEngine extends BaseEngine {
this.scanLists = {}

// Stop South connectors
await Promise.allSettled(this.activeSouths.map((south) => {
this.logger.info(`Stopping South "${south.name}" (${south.id}).`)
return south.disconnect()
}))
await Promise.allSettled(this.activeSouths.map((south) => south.stop()))
this.activeSouths = []

// Stop North connectors
await Promise.allSettled(this.activeNorths.map((north) => {
this.logger.info(`Stopping North "${north.name}" (${north.id}).`)
return north.disconnect()
return north.stop()
}))
this.activeNorths = []

Expand Down
6 changes: 3 additions & 3 deletions src/north/north-amazon-s3/north-amazon-s3.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,14 +50,14 @@ class NorthAmazonS3 extends NorthConnector {
}

/**
* Initialize services (logger, certificate, status data)
* Initialize services (logger, certificate, status data) at startup
* @param {String} baseFolder - The base cache folder
* @param {String} oibusName - The OIBus name
* @param {Object} defaultLogParameters - The default logs parameters
* @returns {Promise<void>} - The result promise
*/
async init(baseFolder, oibusName, defaultLogParameters) {
await super.init(baseFolder, oibusName, defaultLogParameters)
async start(baseFolder, oibusName, defaultLogParameters) {
await super.start(baseFolder, oibusName, defaultLogParameters)

this.s3 = new S3Client({
region: this.region,
Expand Down
6 changes: 3 additions & 3 deletions src/north/north-amazon-s3/north-amazon-s3.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ describe('NorthAmazonS3', () => {
subscribedTo: [],
}
north = new AmazonS3(configuration, [])
await north.init('baseFolder', 'oibusName', {})
await north.start('baseFolder', 'oibusName', {})
})

it('should be properly initialized', () => {
Expand Down Expand Up @@ -122,7 +122,7 @@ describe('NorthAmazonS3', () => {
NodeHttpHandler.mockReturnValueOnce(expectedAgent)

const amazonS3WithProxy = new AmazonS3(amazonS3WithProxyConfig, proxies)
await amazonS3WithProxy.init('baseFolder', 'oibusName', {})
await amazonS3WithProxy.start('baseFolder', 'oibusName', {})

expect(amazonS3WithProxy.bucket).toEqual(amazonS3WithProxyConfig.settings.bucket)
expect(amazonS3WithProxy.folder).toEqual(amazonS3WithProxyConfig.settings.folder)
Expand Down Expand Up @@ -159,7 +159,7 @@ describe('NorthAmazonS3', () => {
NodeHttpHandler.mockReturnValueOnce(expectedAgent)

const amazonS3WithProxy = new AmazonS3(amazonS3WithProxyConfig, proxies)
await amazonS3WithProxy.init('baseFolder', 'oibusName', {})
await amazonS3WithProxy.start('baseFolder', 'oibusName', {})

expect(amazonS3WithProxy.bucket).toEqual(amazonS3WithProxyConfig.settings.bucket)
expect(amazonS3WithProxy.folder).toEqual(amazonS3WithProxyConfig.settings.folder)
Expand Down
51 changes: 30 additions & 21 deletions src/north/north-connector.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,13 +79,13 @@ class NorthConnector {
}

/**
* Initialize services (logger, certificate, status data)
* Initialize services (logger, certificate, status data) at startup
* @param {String} baseFolder - The base cache folder
* @param {String} oibusName - The OIBus name
* @param {Object} defaultLogParameters - The default logs parameters
* @returns {Promise<void>} - The result promise
*/
async init(baseFolder, oibusName, defaultLogParameters) {
async start(baseFolder, oibusName, defaultLogParameters) {
this.baseFolder = path.resolve(baseFolder, `north-${this.id}`)

this.statusService = new StatusService()
Expand Down Expand Up @@ -129,6 +129,34 @@ class NorthConnector {
this.proxyAgent = await this.getProxy(this.proxySettings)
}

/**
* Stop services and timer
* @returns {Promise<void>} - The result promise
*/
async stop() {
this.logger.info(`Stopping North "${this.name}" (${this.id}).`)
await this.disconnect()

this.numberOfSentValues = 0
this.valuesRetryCount = 0
this.sendingValuesInProgress = false
this.resendValuesImmediately = false

this.numberOfSentFiles = 0
this.filesRetryCount = 0
this.sendingFilesInProgress = false
this.resendFilesImmediately = false

if (this.valuesTimeout) {
clearTimeout(this.valuesTimeout)
}
if (this.filesTimeout) {
clearTimeout(this.filesTimeout)
}
this.fileCache.stop()
this.valueCache.stop()
}

/**
* Method called by Engine to initialize a North connector. This method can be surcharged in the
* North connector implementation to allow connection to a third party application for example.
Expand All @@ -154,25 +182,6 @@ class NorthConnector {
this.connected = false
this.statusService.updateStatusDataStream({ 'Connected at': 'Not connected' })
this.logger.info(`North connector "${this.name}" (${this.id}) disconnected.`)

this.numberOfSentValues = 0
this.valuesRetryCount = 0
this.sendingValuesInProgress = false
this.resendValuesImmediately = false

this.numberOfSentFiles = 0
this.filesRetryCount = 0
this.sendingFilesInProgress = false
this.resendFilesImmediately = false

if (this.valuesTimeout) {
clearTimeout(this.valuesTimeout)
}
if (this.filesTimeout) {
clearTimeout(this.filesTimeout)
}
this.fileCache.stop()
this.valueCache.stop()
}

/**
Expand Down
22 changes: 15 additions & 7 deletions src/north/north-connector.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ describe('NorthConnector', () => {
},
}
north = new NorthConnector(configuration, [{ name: 'proxyTest' }])
await north.init('baseFolder', 'oibusName', {})
await north.start('baseFolder', 'oibusName', {})
})

afterEach(() => {
Expand All @@ -58,7 +58,7 @@ describe('NorthConnector', () => {

north.canHandleFiles = true
north.canHandleValues = true
await north.init('baseFolder', 'oibusName', {})
await north.start('baseFolder', 'oibusName', {})
expect(north.statusService.updateStatusDataStream).toHaveBeenCalledWith({
'Number of values sent since OIBus has started': 0,
'Number of files sent since OIBus has started': 0,
Expand All @@ -78,27 +78,35 @@ describe('NorthConnector', () => {
north.resetFilesTimeout = jest.fn()
north.caching.sendInterval = 0

await north.init('baseFolder', 'oibusName', {})
await north.start('baseFolder', 'oibusName', {})
expect(north.resetValuesTimeout).not.toHaveBeenCalled()
expect(north.resetFilesTimeout).not.toHaveBeenCalled()
expect(north.logger.warn).toHaveBeenCalledWith('No send interval. No values or files will be sent.')
})

it('should properly disconnect', async () => {
const clearTimeoutSpy = jest.spyOn(global, 'clearTimeout')
await north.connect()
expect(north.connected).toBeTruthy()

await north.disconnect()
expect(north.connected).toBeFalsy()
expect(north.logger.info).toHaveBeenCalledWith('North connector "north" (id) disconnected.')
})

it('should properly stop', async () => {
const clearTimeoutSpy = jest.spyOn(global, 'clearTimeout')
north.disconnect = jest.fn()

await north.stop()

expect(north.logger.info).toHaveBeenCalledWith('Stopping North "north" (id).')
expect(north.disconnect).toHaveBeenCalledTimes(1)
expect(clearTimeoutSpy).toHaveBeenCalledTimes(2)

clearTimeoutSpy.mockClear()

north.valuesTimeout = null
north.filesTimeout = null
await north.disconnect()
await north.stop()
expect(clearTimeoutSpy).toHaveBeenCalledTimes(0)
})

Expand Down Expand Up @@ -128,8 +136,8 @@ describe('NorthConnector', () => {
it('should get proxy', async () => {
utils.createProxyAgent.mockImplementation(() => ({ proxyAgent: 'a field' }))
expect(await north.getProxy()).toBeNull()

expect(await north.getProxy('proxyTest')).toEqual({ proxyAgent: 'a field' })
expect(await north.getProxy('anotherProxy')).toBeNull()
})

it('should not retrieve values if already sending it', async () => {
Expand Down
4 changes: 2 additions & 2 deletions src/north/north-console/north-console.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ beforeEach(async () => {
},
}
north = new Console(configuration, [])
await north.init('baseFolder', 'oibusName', {})
await north.start('baseFolder', 'oibusName', {})
})

describe('North Console', () => {
Expand All @@ -51,7 +51,7 @@ describe('North Console', () => {
})

it('should properly handle values in non verbose mode', async () => {
await north.init('baseFolder', 'oibusName', {})
await north.start('baseFolder', 'oibusName', {})
const values = [
{
pointId: 'pointId',
Expand Down
10 changes: 5 additions & 5 deletions src/north/north-csv-to-http/north-csv-to-http.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,14 +79,14 @@ describe('NorthCsvToHttp', () => {
})

it('should be properly initialized', async () => {
await north.init('baseFolder', 'oibusName', {})
await north.start('baseFolder', 'oibusName', {})

expect(north.canHandleValues).toBeFalsy()
expect(north.canHandleFiles).toBeTruthy()
})

it('should properly reject file if type is other than csv', async () => {
await north.init('baseFolder', 'oibusName', {})
await north.start('baseFolder', 'oibusName', {})

await expect(north.handleFile('filePath')).rejects
.toThrowError('Invalid file format: .csv file expected. File "filePath" skipped.')
Expand All @@ -107,15 +107,15 @@ describe('NorthCsvToHttp', () => {
['5', '2020-12-17 05:00'],
])

await north.init('baseFolder', 'oibusName', {})
await north.start('baseFolder', 'oibusName', {})

await north.handleFile('csvToHttpTest.csv')

expect(serviceUtils.httpSend).toHaveBeenCalledTimes(1)
})

it('should properly test validity of header', async () => {
await north.init('baseFolder', 'oibusName', {})
await north.start('baseFolder', 'oibusName', {})

const jsonObject = {}

Expand All @@ -140,7 +140,7 @@ describe('NorthCsvToHttp', () => {
})

it('should properly send data (body.length <= bodyMaxLength)', async () => {
await north.init('baseFolder', 'oibusName', {})
await north.start('baseFolder', 'oibusName', {})

const httpBody = []
for (let i = 0; i < north.bodyMaxLength - 1; i += 1) {
Expand Down
2 changes: 1 addition & 1 deletion src/north/north-file-writer/north-file-writer.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ describe('NorthFileWriter', () => {
subscribedTo: [],
}
north = new FileWriter(configuration, [])
await north.init('baseFolder', 'oibusName', {})
await north.start('baseFolder', 'oibusName', {})
})

it('should be properly initialized', () => {
Expand Down
10 changes: 5 additions & 5 deletions src/north/north-influx-db/north-influx-db.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ describe('North InfluxDB', () => {
})

it('should call makeRequest and manage error', async () => {
await north.init('baseFolder', 'oibusName', {})
await north.start('baseFolder', 'oibusName', {})

serviceUtils.httpSend.mockImplementation(() => {
throw new Error('http error')
Expand All @@ -81,7 +81,7 @@ describe('North InfluxDB', () => {
})

it('should log error when there are not enough groups for placeholders in measurement', async () => {
await north.init('baseFolder', 'oibusName', {})
await north.start('baseFolder', 'oibusName', {})

north.measurement = '%5$s'

Expand All @@ -91,7 +91,7 @@ describe('North InfluxDB', () => {
})

it('should log error when there are not enough groups for placeholders in tags', async () => {
await north.init('baseFolder', 'oibusName', {})
await north.start('baseFolder', 'oibusName', {})

north.tags = 'site=%2$s,unit=%3$s,sensor=%5$s'
await north.handleValues(values)
Expand All @@ -100,7 +100,7 @@ describe('North InfluxDB', () => {
})

it('should properly handle values with useDataKeyValue', async () => {
await north.init('baseFolder', 'oibusName', {})
await north.start('baseFolder', 'oibusName', {})

const valueWithDataLevel = [{
pointId: 'ANA/BL1RCP05',
Expand Down Expand Up @@ -183,7 +183,7 @@ describe('North InfluxDB', () => {
})

it('should properly retrieve timestamp with timestampPathInDataValue', async () => {
await north.init('baseFolder', 'oibusName', {})
await north.start('baseFolder', 'oibusName', {})

north.timestampPathInDataValue = 'associatedTimestamp.timestamp'
north.useDataKeyValue = true
Expand Down
Loading

0 comments on commit 753cd6b

Please sign in to comment.