Skip to content

Commit 79a9245

Browse files
committed
listening and fetching configs from OpenHIM
1 parent 3fb3fba commit 79a9245

9 files changed

+264
-85
lines changed

package-lock.json

+56
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

+1
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
},
4242
"dependencies": {
4343
"@clickhouse/client": "^1.8.0",
44+
"axios": "^1.7.7",
4445
"dotenv": "^16.4.5",
4546
"express": "^4.18.2",
4647
"express-async-handler": "^1.2.0",

src/index.ts

+14-10
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,29 @@
11
import express from 'express';
22
import path from 'path';
3-
import { readFile } from 'fs/promises';
43
import { getConfig } from './config/config';
54
import logger from './logger';
65
import routes from './routes/index';
7-
import { setupMediator } from './openhim/openhim';
8-
import {
9-
createMinioBucketListeners,
10-
} from './utils/minioClient';
6+
import { getRegisterBuckets, setupMediator } from './openhim/openhim';
7+
import { createMinioBucketListeners, ensureBucketExists } from './utils/minioClient';
118

129
const app = express();
1310

1411
app.use('/', routes);
1512

16-
createMinioBucketListeners();
17-
18-
app.listen(getConfig().port, async() => {
13+
app.listen(getConfig().port, async () => {
1914
logger.info(`Server is running on port - ${getConfig().port}`);
2015

2116
if (getConfig().runningMode !== 'testing' && getConfig().registerMediator) {
22-
setupMediator(path.resolve(__dirname, './openhim/mediatorConfig.json'));
17+
setupMediator();
2318
}
24-
});
2519

20+
const buckets = await getRegisterBuckets();
21+
22+
buckets.length === 0 && logger.warn('No buckets specified in the configuration');
23+
24+
for await (const { bucket, region } of buckets) {
25+
await ensureBucketExists(bucket, region);
26+
}
27+
28+
createMinioBucketListeners(buckets.map((bucket) => bucket.bucket));
29+
});

src/openhim/mediatorConfig.json

+21-9
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,8 @@
2020
"instant"
2121
],
2222
"methods": [
23-
"POST", "GET"
23+
"POST",
24+
"GET"
2425
],
2526
"type": "http"
2627
}
@@ -35,15 +36,26 @@
3536
"type": "http"
3637
}
3738
],
38-
"configDefs": [{
39-
"param": "minio_buckets_registry",
39+
"configDefs": [
40+
{
41+
"param": "minio_buckets_registry",
4042
"displayName": "Minio Buckets Registry",
4143
"description": "The available Minio buckets and their configurations",
4244
"type": "struct",
4345
"array": true,
44-
"template":[{
45-
"param": "bucket",
46-
"type": "string"
47-
}]
48-
}]
49-
}
46+
"template": [
47+
{
48+
"param": "bucket",
49+
"displayName": "Bucket",
50+
"type": "string"
51+
},
52+
{
53+
"param": "region",
54+
"displayName": "Region (optional)",
55+
"type": "string",
56+
"optional": true
57+
}
58+
]
59+
}
60+
]
61+
}

src/openhim/openhim.ts

+87-7
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,28 @@ import logger from '../logger';
22
import { MediatorConfig } from '../types/mediatorConfig';
33
import { RequestOptions } from '../types/request';
44
import { getConfig } from '../config/config';
5-
import { activateHeartbeat, fetchConfig, registerMediator } from 'openhim-mediator-utils';
5+
import axios, { AxiosError } from 'axios';
6+
import https from 'https';
7+
import {
8+
activateHeartbeat,
9+
fetchConfig,
10+
registerMediator,
11+
authenticate,
12+
genAuthHeaders,
13+
} from 'openhim-mediator-utils';
14+
import { Bucket, createMinioBucketListeners, ensureBucketExists } from '../utils/minioClient';
15+
import path from 'path';
616

7-
const { openhimUsername, openhimPassword, openhimMediatorUrl, trustSelfSigned } = getConfig();
17+
const { openhimUsername, openhimPassword, openhimMediatorUrl, trustSelfSigned, runningMode } =
18+
getConfig();
819

9-
const resolveMediatorConfig = (mediatorConfigFilePath: string): MediatorConfig => {
20+
const mediatorConfigFilePath = path.resolve(__dirname, './mediatorConfig.json');
21+
22+
const resolveMediatorConfig = (): MediatorConfig => {
1023
let mediatorConfigFile;
1124

1225
try {
26+
logger.info(`Loading mediator config from: ${mediatorConfigFilePath}`);
1327
mediatorConfigFile = require(mediatorConfigFilePath);
1428
} catch (error) {
1529
logger.error(`Failed to parse JSON: ${error}`);
@@ -29,9 +43,9 @@ const resolveOpenhimConfig = (urn: string): RequestOptions => {
2943
};
3044
};
3145

32-
export const setupMediator = (mediatorConfigFilePath: string) => {
46+
export const setupMediator = () => {
3347
try {
34-
const mediatorConfig = resolveMediatorConfig(mediatorConfigFilePath);
48+
const mediatorConfig = resolveMediatorConfig();
3549
const openhimConfig = resolveOpenhimConfig(mediatorConfig.urn);
3650

3751
registerMediator(openhimConfig, mediatorConfig, (error: Error) => {
@@ -54,12 +68,78 @@ export const setupMediator = (mediatorConfigFilePath: string) => {
5468
logger.error(`Heartbeat failed: ${JSON.stringify(err)}`);
5569
});
5670

57-
emitter.on('config', (config: any) => {
58-
logger.info(`Config: ${JSON.stringify(config)}`);
71+
emitter.on('config', async (config: any) => {
72+
logger.info('Received config from OpenHIM');
73+
74+
const buckets = config.minio_buckets_registry as Bucket[];
75+
76+
for await (const { bucket, region } of buckets) {
77+
await ensureBucketExists(bucket, region);
78+
}
79+
80+
createMinioBucketListeners(buckets.map((bucket) => bucket.bucket));
5981
});
6082
});
6183
});
6284
} catch (err) {
6385
logger.error('Unable to register mediator', err);
6486
}
6587
};
88+
89+
//TODO: Add Typing and error handling.
90+
async function getMediatorConfig() {
91+
logger.info('Fetching mediator config from OpenHIM');
92+
const mediatorConfig = resolveMediatorConfig();
93+
const openhimConfig = resolveOpenhimConfig(mediatorConfig.urn);
94+
95+
const { apiURL, urn, username, password, trustSelfSigned } = openhimConfig;
96+
97+
try {
98+
const request = await axios.get(`${apiURL}/mediators/urn:mediator:climate-mediator`, {
99+
auth: {
100+
username,
101+
password,
102+
},
103+
httpsAgent: new https.Agent({
104+
rejectUnauthorized: !trustSelfSigned,
105+
}),
106+
});
107+
108+
return request.data;
109+
} catch (e) {
110+
const error = e as AxiosError;
111+
logger.error(`Failed to fetch mediator config: ${JSON.stringify(error)}`);
112+
error.status === 404 && logger.warn('Mediator config not found in OpenHIM, ');
113+
return null;
114+
}
115+
}
116+
117+
export async function getRegisterBuckets(): Promise<Bucket[]> {
118+
if (runningMode !== 'testing') {
119+
logger.info('Fetching registered buckets from OpenHIM');
120+
const mediatorConfig = await getMediatorConfig();
121+
122+
//TODO: Handle errors, and undefined response.
123+
const buckets = mediatorConfig.config?.minio_buckets_registry as Bucket[];
124+
if (!buckets) {
125+
return [];
126+
}
127+
return buckets;
128+
} else {
129+
logger.info('Running in testing mode, reading buckets from ENV');
130+
const buckets = getConfig().minio.buckets.split(',');
131+
return buckets.map((bucket) => ({ bucket, region: '' }));
132+
}
133+
}
134+
135+
export async function registerBucket(bucket: string, region?: string) {
136+
if (runningMode !== 'testing') {
137+
return true;
138+
}
139+
const mediatorConfig = await getMediatorConfig();
140+
const existingBuckets = mediatorConfig.config?.minio_buckets_registry;
141+
142+
if (!existingBuckets) {
143+
return [];
144+
}
145+
}

0 commit comments

Comments
 (0)