-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathDefaultTransferProcessRunner.java
More file actions
227 lines (194 loc) · 8.07 KB
/
DefaultTransferProcessRunner.java
File metadata and controls
227 lines (194 loc) · 8.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
package care.smith.fts.cda;
import static care.smith.fts.util.JsonLogFormatter.asJson;
import static care.smith.fts.util.NanoIdUtils.nanoId;
import static java.util.stream.Stream.concat;
import care.smith.fts.api.ConsentedPatient;
import care.smith.fts.api.ConsentedPatientBundle;
import care.smith.fts.api.TransportBundle;
import care.smith.fts.api.cda.BundleSender.Result;
import care.smith.fts.cda.TransferProcessStatus.Step;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Slf4j
@Component
public class DefaultTransferProcessRunner implements TransferProcessRunner {
private final Map<String, TransferProcessInstance> instances = new HashMap<>();
private final Queue<TransferProcessInstance> queued = new LinkedList<>() {};
private final TransferProcessRunnerConfig config;
private final ObjectMapper om;
public DefaultTransferProcessRunner(
@Autowired ObjectMapper om, @Autowired TransferProcessRunnerConfig config) {
this.om = om;
this.config = config;
}
@Override
public String start(TransferProcessDefinition process, List<String> identifiers) {
var processId = nanoId(6);
log.info("[Process {}] Created, config: {}", processId, asJson(om, process.rawConfig()));
var transferProcessInstance = new TransferProcessInstance(process, processId, identifiers);
startOrQueue(processId, transferProcessInstance);
return processId;
}
private synchronized void startOrQueue(
String processId, TransferProcessInstance transferProcessInstance) {
removeOldProcesses();
if (runningInstances() < config.maxConcurrentProcesses) {
transferProcessInstance.execute();
instances.put(processId, transferProcessInstance);
} else {
log.info("[Process {}] Queued", processId);
queued.add(transferProcessInstance);
}
}
private synchronized long runningInstances() {
return instances.values().stream().filter(TransferProcessInstance::isRunning).count();
}
private synchronized void removeOldProcesses() {
var removeBefore = LocalDateTime.now().minus(config.processTtl);
var forRemoval =
instances.values().stream()
.filter(inst -> inst.status().mayBeRemoved(removeBefore))
.toList();
forRemoval.forEach(p -> instances.remove(p.processId()));
}
@Override
public synchronized Mono<List<TransferProcessStatus>> statuses() {
removeOldProcesses();
var statuses =
concat(
instances.values().stream().map(TransferProcessInstance::status),
queued.stream().map(TransferProcessInstance::status))
.toList();
return Mono.just(statuses);
}
@Override
public synchronized Mono<TransferProcessStatus> status(String processId) {
var transferProcessInstance = instances.get(processId);
if (transferProcessInstance != null) {
return Mono.just(transferProcessInstance.status());
} else {
return Mono.justOrEmpty(
queued.stream().filter(q -> q.processId().equals(processId)).findFirst())
.map(TransferProcessInstance::status)
.switchIfEmpty(
Mono.error(
new IllegalStateException("No transfer process with processId: " + processId)));
}
}
private synchronized void onComplete() {
var next = queued.poll();
if (next != null) {
next.execute();
instances.put(next.processId(), next);
}
}
public class TransferProcessInstance {
private final TransferProcessDefinition process;
private final AtomicReference<TransferProcessStatus> status;
private final List<String> identifiers;
public TransferProcessInstance(
TransferProcessDefinition process, String processId, List<String> identifiers) {
this.process = process;
status = new AtomicReference<>(TransferProcessStatus.create(processId));
this.identifiers = identifiers;
}
public void execute() {
status.updateAndGet(s -> s.setPhase(Phase.RUNNING));
selectCohort(identifiers)
.transform(this::selectData)
.transform(this::deidentify)
.transform(this::sendBundles)
.doOnComplete(this::onComplete)
.doOnComplete(DefaultTransferProcessRunner.this::onComplete)
.subscribe();
log.info("[Process {}] Started", processId());
}
private Flux<ConsentedPatient> selectCohort(List<String> identifiers) {
return process
.cohortSelector()
.selectCohort(identifiers)
.doOnNext(b -> status.updateAndGet(TransferProcessStatus::incTotalPatients))
.doOnError(e -> status.updateAndGet(s -> s.setPhase(Phase.FATAL)))
.onErrorComplete();
}
private Flux<ConsentedPatientBundle> selectData(Flux<ConsentedPatient> cohortSelection) {
return cohortSelection
.flatMap(this::selectDataForPatient)
.doOnNext(b -> status.updateAndGet(TransferProcessStatus::incTotalBundles));
}
private Flux<ConsentedPatientBundle> selectDataForPatient(ConsentedPatient patient) {
return process
.dataSelector()
.select(patient)
.onErrorResume(e -> handlePatientError(patient.identifier(), Step.SELECT_DATA, e));
}
private <T> Mono<T> handlePatientError(String patientId, Step step, Throwable e) {
logError(step, patientId, e);
status.updateAndGet(
s -> s.incSkippedBundles().addFailedPatient(patientId, step, e.getMessage()));
return Mono.empty();
}
private void logError(Step step, String patientIdentifier, Throwable e) {
var msg = "[Process {}] Failed to {} for patient {}. {}";
log.error(
msg, processId(), step, patientIdentifier, log.isDebugEnabled() ? e : e.getMessage());
}
public record PatientContext<T>(T data, ConsentedPatient consentedPatient) {}
private Flux<PatientContext<TransportBundle>> deidentify(
Flux<ConsentedPatientBundle> dataSelection) {
return dataSelection
.flatMap(this::deidentifyForPatient)
.doOnNext(b -> status.updateAndGet(TransferProcessStatus::incDeidentifiedBundles));
}
private Mono<PatientContext<TransportBundle>> deidentifyForPatient(
ConsentedPatientBundle bundle) {
var patientId = bundle.consentedPatient().identifier();
return process
.deidentificator()
.deidentify(bundle)
.map(t -> new PatientContext<>(t, bundle.consentedPatient()))
.onErrorResume(e -> handlePatientError(patientId, Step.DEIDENTIFY, e));
}
private Flux<Result> sendBundles(Flux<PatientContext<TransportBundle>> deidentification) {
return deidentification
.flatMap(this::sendBundleForPatient, config.maxSendConcurrency)
.doOnNext(b -> status.updateAndGet(TransferProcessStatus::incSentBundles));
}
private Mono<Result> sendBundleForPatient(PatientContext<TransportBundle> b) {
var patientId = b.consentedPatient().identifier();
return process
.bundleSender()
.send(b.data())
.onErrorResume(e -> handlePatientError(patientId, Step.SEND_BUNDLE, e));
}
private void onComplete() {
var status = this.status.updateAndGet(s -> s.phase() != Phase.FATAL ? checkCompletion(s) : s);
log.info("[Process {}] Finished with: {}", processId(), status.phase());
}
private TransferProcessStatus checkCompletion(TransferProcessStatus s) {
return s.skippedBundles() == 0
? s.setPhase(Phase.COMPLETED)
: s.setPhase(Phase.COMPLETED_WITH_ERROR);
}
public TransferProcessStatus status() {
return status.get();
}
private String processId() {
return status.get().processId();
}
public Boolean isRunning() {
return status().phase() == Phase.RUNNING;
}
}
}