Skip to content
This repository was archived by the owner on Jan 14, 2025. It is now read-only.

Commit 190a754

Browse files
authored
[ORCT-118] Extract find or create period (#229)
1 parent 8e3dd23 commit 190a754

7 files changed

Lines changed: 202 additions & 154 deletions

File tree

app/lib/alimonitor-services/BookkeepingService.js

Lines changed: 23 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,11 @@ const { databaseManager: {
2121
repositories: {
2222
RunRepository,
2323
DetectorSubsystemRepository,
24-
PeriodRepository,
25-
BeamTypeRepository,
2624
RunDetectorsRepository,
2725
},
26+
sequelize,
2827
} } = require('../database/DatabaseManager.js');
28+
const { createOrForceUpdate } = require('../services/periods/findOrUpdateOrCreatePeriod.js');
2929

3030
/**
3131
* BookkeepingService used to synchronize runs
@@ -127,52 +127,27 @@ class BookkeepingService extends AbstractServiceSynchronizer {
127127
const period = extractPeriod(periodName, beamType);
128128
const { detectorsNameToId } = this;
129129

130-
return await BeamTypeRepository.T.findOrCreate({
131-
where: {
132-
name: beamType,
133-
},
134-
})
135-
.then(async ([beamType, _]) => await PeriodRepository.T.findOrCreate({
136-
where: {
137-
name: period.name,
138-
},
139-
defaults: {
140-
name: period.name,
141-
year: period.year,
142-
BeamTypeId: beamType.id,
143-
},
144-
}))
145-
.catch((e) => {
146-
throw new Error('Find or create period failed', {
147-
cause: {
148-
error: e.message,
149-
meta: {
150-
explicitValues: {
151-
name: period.name,
152-
year: period.year,
153-
BeamTypeId: beamType.id,
154-
},
155-
implicitValues: {
156-
BeamType: beamType,
157-
},
158-
},
159-
},
160-
});
161-
})
162-
.then(async ([period, _]) => await RunRepository.T.upsert({
163-
PeriodId: period.id,
164-
...run,
165-
}))
166-
.then(async ([run, _]) => {
167-
const d = detectorNames?.map((detectorName, i) => ({
168-
run_number: run.runNumber,
169-
detector_id: detectorsNameToId[detectorName],
170-
quality: detectorQualities[i] }));
171-
172-
await RunDetectorsRepository.T.bulkCreate(
173-
d, { updateOnDuplicate: ['quality'] },
174-
);
175-
});
130+
const upsertRun = async ([dbPeriod, _]) => await RunRepository.upsert({
131+
PeriodId: dbPeriod.id,
132+
...run,
133+
});
134+
135+
const bulkCreateRunDetectors = async ([run, _]) => {
136+
const d = detectorNames?.map((detectorName, i) => ({
137+
run_number: run.runNumber,
138+
detector_id: detectorsNameToId[detectorName],
139+
quality: detectorQualities[i] }));
140+
141+
await RunDetectorsRepository.bulkCreate(
142+
d, { updateOnDuplicate: ['quality'] },
143+
);
144+
};
145+
146+
const pipeline = async () => await createOrForceUpdate(period)
147+
.then(upsertRun)
148+
.then(bulkCreateRunDetectors);
149+
150+
return await sequelize.transaction(async () => await pipeline());
176151
}
177152

178153
/**

app/lib/alimonitor-services/MonalisaService.js

Lines changed: 6 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,11 @@ const config = require('../config/configProvider.js');
2727

2828
const { databaseManager: {
2929
repositories: {
30-
BeamTypeRepository,
31-
PeriodRepository,
3230
DataPassRepository,
3331
},
3432
sequelize,
3533
} } = require('../database/DatabaseManager.js');
34+
const { findOrCreatePeriod } = require('../services/periods/findOrUpdateOrCreatePeriod.js');
3635

3736
class MonalisaService extends AbstractServiceSynchronizer {
3837
constructor() {
@@ -93,40 +92,14 @@ class MonalisaService extends AbstractServiceSynchronizer {
9392

9493
async executeDbAction(dataPass) {
9594
const { period } = dataPass;
96-
97-
return await BeamTypeRepository.T.findOrCreate({
98-
where: {
99-
name: period.beamType,
100-
},
101-
})
102-
.then(async ([beamType, _]) => await PeriodRepository.T.findOrCreate({
103-
where: {
104-
name: period.name,
105-
},
106-
defaults: {
107-
name: period.name,
108-
year: period.year,
109-
BeamTypeId: beamType.id,
110-
},
111-
}))
112-
.catch((e) => {
113-
throw new Error('Find or create period failed', {
114-
cause: {
115-
error: e.message,
116-
meta: {
117-
explicitValues: {
118-
name: period.name,
119-
year: period.year,
120-
},
121-
},
122-
},
123-
});
124-
})
125-
.then(async ([period, _]) => await DataPassRepository.T.upsert({
95+
const act = async () => findOrCreatePeriod(period)
96+
.then(async ([period, _]) => await DataPassRepository.upsert({
12697
PeriodId: period.id,
12798
...dataPass,
12899
}))
129-
.then(async ([dataPass, _]) => await this.monalisaServiceDetails.setSyncTask({ parentDataUnit: dataPass }));
100+
.then(async ([dbDataPass, _]) => await this.monalisaServiceDetails.setSyncTask({ parentDataUnit: dbDataPass }));
101+
102+
return await sequelize.transaction(async (_t1) => await act());
130103
}
131104
}
132105

app/lib/alimonitor-services/MonalisaServiceDetails.js

Lines changed: 57 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -15,15 +15,15 @@
1515

1616
const AbstractServiceSynchronizer = require('./AbstractServiceSynchronizer.js');
1717
const Utils = require('../utils');
18-
const { ServicesEndpointsFormatter } = require('./helpers');
18+
const { ServicesEndpointsFormatter, ServicesDataCommons: { PERIOD_NAME_REGEX } } = require('./helpers');
19+
const { findOrCreatePeriod } = require('../services/periods/findOrUpdateOrCreatePeriod.js');
1920

2021
const { databaseManager: {
2122
repositories: {
2223
RunRepository,
23-
PeriodRepository,
2424
},
25-
sequelize,
2625
} } = require('../database/DatabaseManager.js');
26+
const { extractPeriod } = require('./helpers/ServicesDataCommons.js');
2727

2828
class MonalisaServiceDetails extends AbstractServiceSynchronizer {
2929
constructor() {
@@ -32,7 +32,7 @@ class MonalisaServiceDetails extends AbstractServiceSynchronizer {
3232

3333
this.ketpFields = {
3434
run_no: 'runNumber',
35-
raw_partition: 'period',
35+
raw_partition: 'periodName',
3636
};
3737
}
3838

@@ -52,59 +52,74 @@ class MonalisaServiceDetails extends AbstractServiceSynchronizer {
5252
}
5353

5454
adjustDataUnit(dataPassDetails) {
55-
return Utils.filterObject(dataPassDetails, this.ketpFields);
55+
dataPassDetails = Utils.filterObject(dataPassDetails, this.ketpFields);
56+
const { periodName } = dataPassDetails;
57+
dataPassDetails.period = PERIOD_NAME_REGEX.test(periodName) ? extractPeriod(periodName) : undefined;
58+
return dataPassDetails;
5659
}
5760

5861
isDataUnitValid() {
5962
return true;
6063
}
6164

6265
async executeDbAction(dataPassDetails, forUrlMetaStore) {
63-
const { parentDataUnit: dataPass } = forUrlMetaStore;
64-
return (async () => {
65-
if (/LHC[0-9]{2}[a-z]+/.test(dataPassDetails.period)) {
66-
return await PeriodRepository.T.findOrCreate({
67-
where: {
68-
name: dataPassDetails.period,
69-
},
70-
});
66+
const { parentDataUnit: dbDataPass } = forUrlMetaStore;
67+
68+
const getPresumedPeriod = async () => {
69+
if (dataPassDetails.period) {
70+
return await findOrCreatePeriod(dataPassDetails.period);
7171
} else {
72-
// eslint-disable-next-line max-len
73-
this.logger.warn(`Incorrect period from monalisa ${dataPassDetails.period} for run ${dataPassDetails.runNumber} in data pass ${dataPass.name}`);
72+
this.logger.warn(`Incorrect period name from monalisa ${dataPassDetails.periodName}
73+
for run ${dataPassDetails.runNumber} in details of data pass ${dbDataPass.name}`);
7474
return [undefined, undefined];
7575
}
76-
})()
77-
.then(async ([period, _]) => {
78-
dataPassDetails.PeriodId = period?.id;
79-
return await RunRepository.T.findOrCreate({
80-
where: {
81-
runNumber: dataPassDetails.runNumber,
82-
},
83-
defualt: {
84-
runNumber: dataPassDetails.runNumber,
85-
PeriodId: dataPassDetails.PeriodId,
86-
},
87-
});
76+
};
77+
78+
const findOrCreateRun = async ([dbPeriod, _]) => {
79+
dataPassDetails.PeriodId = dbPeriod?.id;
80+
return await RunRepository.findOrCreate({
81+
where: {
82+
runNumber: dataPassDetails.runNumber,
83+
},
84+
defualt: {
85+
runNumber: dataPassDetails.runNumber,
86+
PeriodId: dataPassDetails.PeriodId,
87+
},
8888
})
89-
.catch(async (e) => {
90-
throw new Error('Find or create run failed', {
91-
cause: {
92-
error: e.message,
93-
meta: {
94-
actualValueInDB: await RunRepository.findOne({ where: { runNumber: dataPassDetails.runNumber } }, { raw: true }),
95-
inQueryValues: {
96-
runNumber: dataPassDetails.runNumber,
97-
PeriodId: dataPassDetails.PeriodId,
89+
.catch(async (e) => {
90+
throw new Error('Find or create run failed', {
91+
cause: {
92+
error: {
93+
error: e.message,
94+
cause: e.cause,
9895
},
99-
sourceValues: {
100-
runNumber: dataPassDetails.runNumber,
101-
periodName: dataPassDetails.period,
96+
meta: {
97+
actualValueInDB: await RunRepository.findOne(
98+
{ where: { runNumber: dataPassDetails.runNumber } },
99+
{ raw: true },
100+
).catch((error) => `ERROR RETRIVING ADDITIONAL INFO FROM DB: ${error.message}`),
101+
102+
inQueryValues: {
103+
runNumber: dataPassDetails.runNumber,
104+
PeriodId: dataPassDetails.PeriodId,
105+
},
106+
sourceValues: {
107+
runNumber: dataPassDetails.runNumber,
108+
periodName: dataPassDetails.period,
109+
},
102110
},
103111
},
104-
},
112+
});
105113
});
106-
})
107-
.then(async ([run, _]) => await sequelize.transaction(() => run.addDataPasses(dataPass.id, { ignoreDuplicates: true })));
114+
};
115+
116+
const addRunToDataPass = async ([dbRun, _]) => await dbRun.addDataPasses(dbDataPass.id, { ignoreDuplicates: true });
117+
118+
const pipeline = async () => await getPresumedPeriod()
119+
.then(findOrCreateRun)
120+
.then(addRunToDataPass);
121+
122+
return await pipeline();
108123
}
109124
}
110125

app/lib/alimonitor-services/MonalisaServiceMC.js

Lines changed: 10 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,13 @@ const config = require('../config/configProvider.js');
2020

2121
const { databaseManager: {
2222
repositories: {
23-
BeamTypeRepository,
24-
PeriodRepository,
2523
SimulationPassRepository,
2624
DataPassRepository,
2725
RunRepository,
2826
},
2927
sequelize,
3028
} } = require('../database/DatabaseManager.js');
29+
const { findOrCreatePeriod } = require('../services/periods/findOrUpdateOrCreatePeriod.js');
3130

3231
class MonalisaServiceMC extends AbstractServiceSynchronizer {
3332
constructor() {
@@ -114,37 +113,20 @@ class MonalisaServiceMC extends AbstractServiceSynchronizer {
114113
requestedEvents: simulationPass.requestedEvents,
115114
outputSize: simulationPass.outputSize,
116115
})
117-
.then(async ([simulationPassDBInstance, _]) => {
116+
.then(async ([dbSimulationPass, _]) => {
118117
await Promise.all(simulationPass.anchoredPeriods.map(async (period) =>
119-
this.findOrCreatePeriod(period)
118+
findOrCreatePeriod(period)
120119
.then(async ([period, _]) => {
121-
const periodAddPromise = simulationPassDBInstance.addPeriod(period.id, { ignoreDuplicates: true });
122-
const dataPassPipelinePromises = this.findOrCreateAndAddDataPasses(simulationPass, simulationPassDBInstance, period);
123-
const runsAddPipeline = this.findOrCreateAndAddRuns(simulationPass, simulationPassDBInstance, period);
120+
const periodAddPromise = dbSimulationPass.addPeriod(period.id, { ignoreDuplicates: true });
121+
const dataPassPipelinePromises = this.findOrCreateAndAddDataPasses(simulationPass, dbSimulationPass, period);
122+
const runsAddPipeline = this.findOrCreateAndAddRuns(simulationPass, dbSimulationPass, period);
124123

125124
await Promise.all([periodAddPromise, dataPassPipelinePromises, runsAddPipeline]);
126125
})));
127126
});
128127
}
129128

130-
async findOrCreatePeriod({ name: periodName, year: periodYear, beamType }) {
131-
return await sequelize.transaction(async () => PeriodRepository.findOrCreate({
132-
where: {
133-
name: periodName,
134-
},
135-
defaults: {
136-
name: periodName,
137-
year: periodYear,
138-
BeamTypeId: !beamType ? undefined : (await BeamTypeRepository.findOrCreate({
139-
where: {
140-
name: beamType,
141-
},
142-
}))[0]?.id,
143-
},
144-
}));
145-
}
146-
147-
async findOrCreateAndAddDataPasses(simulationPass, simulationPassDBInstance, period) {
129+
async findOrCreateAndAddDataPasses(simulationPass, dbSimulationPass, period) {
148130
const promises = simulationPass.anchoredPasses
149131
.map((passSuffix) => sequelize.transaction(
150132
() => DataPassRepository.findOrCreate({
@@ -155,13 +137,13 @@ class MonalisaServiceMC extends AbstractServiceSynchronizer {
155137
name: `${period.name}_${passSuffix}`,
156138
PeriodId: period.id,
157139
},
158-
}).then(([dataPass, _]) => simulationPassDBInstance.addDataPass(dataPass.id,
140+
}).then(([dataPass, _]) => dbSimulationPass.addDataPass(dataPass.id,
159141
{ ignoreDuplicates: true })),
160142
));
161143
return await Promise.all(promises);
162144
}
163145

164-
async findOrCreateAndAddRuns(simulationPass, simulationPassDBInstance, period) {
146+
async findOrCreateAndAddRuns(simulationPass, dbSimulationPass, period) {
165147
const promises = simulationPass.runs.map((runNumber) => sequelize.transaction(async () => {
166148
const insertWithoutPeriod = simulationPass.anchoredPeriods.length > 1;
167149
await RunRepository.findOrCreate({
@@ -174,7 +156,7 @@ class MonalisaServiceMC extends AbstractServiceSynchronizer {
174156
},
175157
});
176158

177-
return await simulationPassDBInstance.addRun(runNumber, { ignoreDuplicates: true });
159+
return await dbSimulationPass.addRun(runNumber, { ignoreDuplicates: true });
178160
}));
179161

180162
return await Promise.all(promises);

app/lib/database/DatabaseManager.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,8 @@ class DatabaseManager {
2727
constructor() {
2828
this.logger = new Log(DatabaseManager.name);
2929
this.schema = 'public';
30-
const o2rct_namespace = cls.createNamespace('o2rct-namespace');
31-
Sequelize.useCLS(o2rct_namespace);
30+
this.o2rct_namespace = cls.createNamespace('o2rct-namespace');
31+
Sequelize.useCLS(this.o2rct_namespace);
3232

3333
this.sequelize = new Sequelize({
3434
...config.database,

app/lib/database/repositories/Repository.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ class Repository {
8989
* @return {Promise<boolean>} promise that resolves when the patch has been applied
9090
*/
9191
async updateOne(dbOject, patch) {
92-
return dbOject.update(patch);
92+
return await dbOject.update(patch);
9393
}
9494

9595
/**

0 commit comments

Comments
 (0)