• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

openmrs / openmrs-core / 43502855768

13 Nov 2026 08:33PM UTC coverage: 67.328% (+0.4%) from 66.969%
43502855768

push

github

ibacher
TRUNK-6616: Count obs version history statements without the privilege check

getObsVersionHistory_shouldLoadTheWholeChainInTwoQueries counted the
statements of the service call, which include its privilege check. When
test setup has cleared the role privilege cache in the same transaction,
that check reads roles from the database, so the count depended on test
order. Measure the DAO call instead.

26896 of 39948 relevant lines covered (67.33%)

0.67 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

94.31
/api/src/main/java/org/openmrs/api/cache/RolePrivilegeCache.java
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
3
 * v. 2.0. If a copy of the MPL was not distributed with this file, You can
4
 * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under
5
 * the terms of the Healthcare Disclaimer located at http://openmrs.org/license.
6
 *
7
 * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS
8
 * graphic logo is a trademark of OpenMRS Inc.
9
 */
10
package org.openmrs.api.cache;
11

12
import java.util.ArrayDeque;
13
import java.util.Deque;
14
import java.util.HashSet;
15
import java.util.Objects;
16
import java.util.Set;
17
import java.util.concurrent.CompletableFuture;
18
import java.util.concurrent.ConcurrentHashMap;
19
import java.util.concurrent.ConcurrentMap;
20
import java.util.concurrent.ExecutionException;
21
import java.util.concurrent.Future;
22
import java.util.function.Function;
23

24
import org.infinispan.Cache;
25
import org.infinispan.spring.embedded.provider.SpringEmbeddedCacheManager;
26
import org.openmrs.Role;
27
import org.openmrs.api.APIException;
28
import org.openmrs.api.context.Daemon;
29
import org.openmrs.api.db.ContextDAO;
30
import org.openmrs.api.db.StoredRole;
31
import org.openmrs.api.db.UserDAO;
32
import org.openmrs.util.RoleConstants;
33
import org.slf4j.Logger;
34
import org.slf4j.LoggerFactory;
35
import org.springframework.beans.factory.DisposableBean;
36
import org.springframework.beans.factory.annotation.Autowired;
37
import org.springframework.beans.factory.annotation.Qualifier;
38
import org.springframework.context.ApplicationListener;
39
import org.springframework.context.event.ContextRefreshedEvent;
40
import org.springframework.stereotype.Component;
41

42
/**
43
 * Per-role cache of flattened privilege resolutions, so privilege, role and superuser checks need
44
 * not re-expand a user's role graph on every call. The cached value for a role is an immutable
45
 * {@link RolePrivileges} covering that role and its entire inherited closure. Roles are looked up
46
 * by name, exactly as given: only the name of a caller-supplied {@link Role} is used.
47
 * <p>
48
 * On a miss the closure is read from the database as stored, never from a loaded {@link Role},
49
 * which may hold unsaved changes or be stale. The read runs in a daemon thread, so it neither
50
 * depends on the caller's privileges nor sees the caller's uncommitted changes. The caller waits
51
 * for the load, and concurrent misses for the same role share one. A role absent from the database
52
 * grants nothing.
53
 * <p>
54
 * If the load fails, the caller is interrupted while waiting for it, or the cache was evicted while
55
 * the caller waited, so that the load may have read the role from before a change, the role is
56
 * instead read once through the caller's own session, without caching it. That read sees committed
57
 * data and the caller's flushed changes, but not unflushed ones. If that read fails too, the role
58
 * grants nothing, so a privilege check denies rather than throws.
59
 * <p>
60
 * The daemon only sees committed data. Evictions go through {@link CacheInvalidation}, so a load
61
 * only keeps its entry if nothing was evicted, on any node, while it ran, and a miss never waits on
62
 * a load that started before the latest eviction.
63
 * <p>
64
 * Within a transaction, the eviction is applied once, when the transaction completes. Until then
65
 * the transaction resolves roles through its own session, without the cache, so it sees its own
66
 * flushed changes while other transactions keep reading the committed ones. Once a transaction that
67
 * changed a role or privilege has completed, privileges are therefore never served from before that
68
 * change, except on a node that missed the eviction while cut off from the cluster.
69
 * <p>
70
 * {@link org.openmrs.api.UserService} clears the cache when it saves or purges a role or privilege,
71
 * and {@link org.openmrs.api.db.hibernate.RolePrivilegeCacheInterceptor} clears it whenever
72
 * Hibernate flushes a change to one; such a change is first vetted by
73
 * {@link org.openmrs.api.db.hibernate.RoleWriteGuardListener}. Changes to the tables made outside
74
 * Hibernate, for example with SQL, are not detected, but the {@code role-privileges} cache
75
 * template's lifespan limits how long they can be served stale.
76
 *
77
 * @since 2.8.9
78
 */
79
@Component("rolePrivilegeCache")
80
public class RolePrivilegeCache implements ApplicationListener<ContextRefreshedEvent>, DisposableBean {
81

82
        private static final Logger log = LoggerFactory.getLogger(RolePrivilegeCache.class);
1 ✔
83

84
        public static final String CACHE_NAME = "rolePrivileges";
85

86
        /**
87
         * Capability token issued by {@link Daemon}, letting this component launch a daemon thread to load
88
         * roles with full trust.
89
         */
90
        private static volatile Daemon.CallerKey daemonCallerKey;
91

92
        private final SpringEmbeddedCacheManager cacheManager;
93

94
        private final UserDAO dao;
95

96
        /**
97
         * Runs a load on another thread, returning a future for the thread's task, or null if there is
98
         * none. The task may fail without running the load, for example if a daemon cannot open a session.
99
         */
100
        private final Function<Runnable, Future<?>> backgroundRunner;
101

102
        /** Reads a role by name on the background thread, seeing only committed data. */
103
        private final Function<String, StoredRole> committedRoleLoader;
104

105
        /** Loads in progress, by role name, so concurrent misses share a single load. */
106
        private final ConcurrentMap<String, Load> loads = new ConcurrentHashMap<>();
1 ✔
107

108
        private final CacheInvalidation invalidation;
109

110
        @Autowired
111
        public RolePrivilegeCache(@Qualifier("apiCacheManager") SpringEmbeddedCacheManager cacheManager, UserDAO dao,
112
            ContextDAO contextDAO) {
113
                // the daemon thread has no transaction of its own, so it reads through the transactional ContextDAO
114
                this(cacheManager, dao, task -> Daemon.runNewDaemonTask(task, daemonCallerKey()), contextDAO::getStoredRole);
1 ✔
115
        }
1 ✔
116

117
        RolePrivilegeCache(SpringEmbeddedCacheManager cacheManager, UserDAO dao, Function<Runnable, Future<?>> backgroundRunner,
118
            Function<String, StoredRole> committedRoleLoader) {
1 ✔
119
                this.cacheManager = cacheManager;
1 ✔
120
                this.dao = dao;
1 ✔
121
                this.backgroundRunner = backgroundRunner;
1 ✔
122
                this.committedRoleLoader = committedRoleLoader;
1 ✔
123

124
                this.invalidation = new CacheInvalidation("the role privilege cache", this::getCache,
1 ✔
125
                        cacheManager.getNativeCacheManager());
1 ✔
126
        }
1 ✔
127

128
        /**
129
         * Receives the {@link Daemon} caller key. Called only by {@link Daemon} during its initialization.
130
         *
131
         * @param callerKey the caller key issued by {@link Daemon}
132
         */
133
        public static void setDaemonCallerKey(Daemon.CallerKey callerKey) {
134
                if (callerKey != null && daemonCallerKey == null) {
1 ✔
135
                        daemonCallerKey = callerKey;
1 ✔
136
                }
137
        }
1 ✔
138

139
        private static Daemon.CallerKey daemonCallerKey() {
140
                if (daemonCallerKey == null) {
1 ✔
141
                        // Guarantee Daemon has initialized and therefore handed us the key, regardless of the order in
142
                        // which the two classes were first loaded.
143
                        Daemon.ensureInitialized();
×
144
                }
145
                return daemonCallerKey;
1 ✔
146
        }
147

148
        /**
149
         * Returns the flattened privileges for the given role, loading and caching them on a miss. Never
150
         * returns {@code null} and never throws; a role that cannot be loaded grants nothing.
151
         *
152
         * @param role the directly assigned role to resolve
153
         * @return the flattened privilege closure for the role
154
         */
155
        public RolePrivileges getRolePrivileges(Role role) {
156
                return getRolePrivileges(role == null ? null : role.getRole());
1 ✔
157
        }
158

159
        /**
160
         * Returns the flattened privileges for the named role, loading and caching them on a miss. Never
161
         * returns {@code null} and never throws; a role that cannot be loaded grants nothing.
162
         *
163
         * @param roleName the name of the directly assigned role to resolve
164
         * @return the flattened privilege closure for the role
165
         * @since 2.8.11
166
         */
167
        public RolePrivileges getRolePrivileges(String roleName) {
168
                if (roleName == null) {
1 ✔
169
                        return new RolePrivileges(new HashSet<>(), false);
×
170
                }
171

172
                if (invalidation.isWrittenInCurrentTransaction(null)) {
1 ✔
173
                        return resolveInCurrentSession(roleName, null);
1 ✔
174
                }
175

176
                Cache<Object, Object> cache = getCache();
1 ✔
177
                // not normalized: on a case-sensitive database, names differing only in case are different roles
178
                String key = roleName;
1 ✔
179
                if (cache != null) {
1 ✔
180
                        Object cached = cache.get(key);
1 ✔
181
                        if (cached instanceof RolePrivileges) {
1 ✔
182
                                return (RolePrivileges) cached;
1 ✔
183
                        }
184
                }
185

186
                Load load = startOrJoinLoad(key, roleName, cache);
1 ✔
187
                RolePrivileges loaded;
188
                try {
189
                        loaded = await(key, load);
1 ✔
190
                } catch (APIException e) {
1 ✔
191
                        // the daemon may have failed for want of a connection the caller already holds, or the caller
192
                        // may have been interrupted
193
                        log.warn("Could not load the privileges of role {}; reading it through the caller's session", key, e);
1 ✔
194
                        return resolveInCurrentSession(roleName, e);
1 ✔
195
                }
1 ✔
196

197
                if (cache != null && !CacheInvalidation.isCurrent(cache, load.generation)) {
1 ✔
198
                        return resolveInCurrentSession(roleName, null);
1 ✔
199
                }
200
                return loaded;
1 ✔
201
        }
202

203
        /**
204
         * Evicts every role. Must be called whenever a role or privilege is saved or purged; closures span
205
         * inherited roles, so a change to one role can affect any entry.
206
         * <p>
207
         * Within a transaction the cache is cleared once, when the transaction completes, whether it
208
         * commits or rolls back, and until then the transaction resolves roles without the cache. Outside
209
         * one it is cleared immediately.
210
         */
211
        public void clear() {
212
                invalidation.invalidate(CacheInvalidation.ALL);
1 ✔
213
        }
1 ✔
214

215
        @Override
216
        public void destroy() {
217
                invalidation.close();
1 ✔
218
        }
1 ✔
219

220
        /**
221
         * Clears the cache whenever the application context is refreshed, ensuring role graph changes
222
         * applied outside the API before or during startup are not served stale.
223
         */
224
        @Override
225
        public void onApplicationEvent(ContextRefreshedEvent event) {
226
                clear();
1 ✔
227
        }
1 ✔
228

229
        /**
230
         * Flattens a role and its inherited roles as read through {@code reader}, tolerating inheritance
231
         * cycles. Superuser status is judged from the names as stored, so a name the database matches
232
         * loosely, for example with different case or trailing spaces, can't hide a superuser role. A role
233
         * absent from the database grants nothing.
234
         *
235
         * @param roleName the name of the role to flatten
236
         * @param reader reads a role as stored, returning null if there is no such role
237
         * @return the flattened privilege closure
238
         * @since 2.8.11
239
         */
240
        public static RolePrivileges resolve(String roleName, Function<String, StoredRole> reader) {
241
                Set<String> privileges = new HashSet<>();
1 ✔
242
                // names as stored, which also marks a role as visited however it was named when reached
243
                Set<String> roleNames = new HashSet<>();
1 ✔
244
                Set<String> requested = new HashSet<>();
1 ✔
245
                Deque<String> pending = new ArrayDeque<>();
1 ✔
246
                pending.push(roleName);
1 ✔
247
                boolean grantsSuperuser = false;
1 ✔
248
                while (!pending.isEmpty()) {
1 ✔
249
                        String name = pending.pop();
1 ✔
250
                        if (!requested.add(name)) {
1 ✔
251
                                continue;
1 ✔
252
                        }
253
                        StoredRole stored = reader.apply(name);
1 ✔
254
                        if (stored != null && roleNames.add(stored.getName())) {
1 ✔
255
                                grantsSuperuser |= RoleConstants.SUPERUSER.equalsIgnoreCase(stored.getName());
1 ✔
256
                                privileges.addAll(stored.getPrivileges());
1 ✔
257
                                stored.getParentRoles().forEach(pending::push);
1 ✔
258
                        }
259
                }
1 ✔
260
                return new RolePrivileges(privileges, grantsSuperuser, roleNames);
1 ✔
261
        }
262

263
        /**
264
         * Waits for the loads in progress to finish. A load writes or discards its cache entry before
265
         * handing over its result, so this is only needed to wait for loads the caller is not itself
266
         * waiting on, for example in tests.
267
         */
268
        void awaitLoads() {
269
                loads.forEach((key, load) -> {
1 ✔
270
                        try {
271
                                await(key, load);
×
272
                        } catch (APIException e) {
×
273
                                // the load's failure is its caller's to handle
274
                        }
×
275
                });
×
276
        }
1 ✔
277

278
        /**
279
         * Evicts every role immediately, even within a transaction, which still resolves roles without the
280
         * cache until it completes. Only for tests that load data behind the API.
281
         */
282
        void clearNow() {
283
                invalidation.clearNow();
1 ✔
284
        }
1 ✔
285

286
        /**
287
         * Lets the current transaction read through the cache again and not evict it when it completes.
288
         * Only for tests that load data behind the API but still need to observe cache hits.
289
         */
290
        void forgetWritesInCurrentTransaction() {
291
                invalidation.forgetWritesInCurrentTransaction();
1 ✔
292
        }
1 ✔
293

294
        /**
295
         * Returns the load in progress for the role if it started after the latest eviction, and otherwise
296
         * starts a new one. A load that started before the latest eviction may have read the role before
297
         * the change that caused it, so it is replaced rather than joined.
298
         */
299
        private Load startOrJoinLoad(String key, String roleName, Cache<Object, Object> cache) {
300
                Load fresh = new Load(cache == null ? null : CacheInvalidation.currentGeneration(cache));
1 ✔
301
                Load current = loads.compute(key,
1 ✔
302
                    (k, existing) -> existing != null && Objects.equals(existing.generation, fresh.generation) ? existing : fresh);
1 ✔
303
                if (current != fresh) {
1 ✔
304
                        return current;
1 ✔
305
                }
306

307
                Future<?> task = null;
1 ✔
308
                try {
309
                        task = backgroundRunner.apply(() -> {
1 ✔
310
                                try {
311
                                        fresh.result.complete(load(key, roleName, cache, fresh.generation));
1 ✔
312
                                } catch (Throwable e) {
1 ✔
313
                                        fresh.result.completeExceptionally(e);
1 ✔
314
                                } finally {
315
                                        loads.remove(key, fresh);
1 ✔
316
                                }
317
                        });
1 ✔
318
                } catch (RuntimeException e) {
1 ✔
319
                        fresh.result.completeExceptionally(e);
1 ✔
320
                        loads.remove(key, fresh);
1 ✔
321
                } finally {
322
                        fresh.task.complete(task);
1 ✔
323
                }
324
                return fresh;
1 ✔
325
        }
326

327
        /**
328
         * Runs on the background thread: reads the role as stored, flattens it, and caches it unless the
329
         * generation token has changed since <code>generation</code> was read. A role absent from the
330
         * database grants nothing.
331
         */
332
        private RolePrivileges load(String key, String roleName, Cache<Object, Object> cache, Object generation) {
333
                RolePrivileges loaded = resolve(roleName, committedRoleLoader);
1 ✔
334
                if (cache != null) {
1 ✔
335
                        CacheInvalidation.putIfCurrent(cache, key, loaded, generation);
1 ✔
336
                }
337
                return loaded;
1 ✔
338
        }
339

340
        /**
341
         * Flattens the role as stored, read through the caller's own session, without caching the result.
342
         * If the read fails, the role grants nothing.
343
         *
344
         * @param loadFailure why the load failed, if it did, which is recorded on any failure of this read
345
         */
346
        private RolePrivileges resolveInCurrentSession(String roleName, Exception loadFailure) {
347
                try {
348
                        return resolve(roleName, dao::getStoredRole);
1 ✔
349
                } catch (RuntimeException e) {
1 ✔
350
                        if (loadFailure != null) {
1 ✔
351
                                e.addSuppressed(loadFailure);
1 ✔
352
                        }
353
                        log.error("Could not load the privileges of role {}; it grants nothing", roleName, e);
1 ✔
354
                        return new RolePrivileges(new HashSet<>(), false);
1 ✔
355
                }
356
        }
357

358
        /**
359
         * Waits for the load. The thread's task is waited for first, since it can end without running the
360
         * load, which would then never complete.
361
         */
362
        private RolePrivileges await(String key, Load load) {
363
                try {
364
                        Future<?> task = load.task.join();
1 ✔
365
                        if (task != null) {
1 ✔
366
                                try {
367
                                        task.get();
1 ✔
368
                                } catch (ExecutionException e) {
1 ✔
369
                                        load.result.completeExceptionally(e.getCause());
1 ✔
370
                                        loads.remove(key, load);
1 ✔
371
                                }
1 ✔
372
                        }
373
                        return load.result.get();
1 ✔
374
                } catch (InterruptedException e) {
1 ✔
375
                        Thread.currentThread().interrupt();
1 ✔
376
                        throw new APIException("Interrupted while loading the privileges of role " + key, e);
1 ✔
377
                } catch (ExecutionException e) {
1 ✔
378
                        Throwable cause = e.getCause();
1 ✔
379
                        if (cause instanceof APIException) {
1 ✔
380
                                throw (APIException) cause;
1 ✔
381
                        }
382
                        if (cause instanceof Error) {
1 ✔
383
                                throw (Error) cause;
×
384
                        }
385
                        throw new APIException("Could not load the privileges of role " + key, cause);
1 ✔
386
                }
387
        }
388

389
        @SuppressWarnings("unchecked")
390
        private Cache<Object, Object> getCache() {
391
                org.springframework.cache.Cache cache = cacheManager.getCache(CACHE_NAME);
1 ✔
392
                return cache == null ? null : (Cache<Object, Object>) cache.getNativeCache();
1 ✔
393
        }
394

395
        /** A load in progress, with the generation token read before it started. */
396
        private static final class Load {
397

398
                private final Object generation;
399

400
                private final CompletableFuture<RolePrivileges> result = new CompletableFuture<>();
1 ✔
401

402
                /** The thread's task running the load, completed as soon as it has been started. */
403
                private final CompletableFuture<Future<?>> task = new CompletableFuture<>();
1 ✔
404

405
                private Load(Object generation) {
1 ✔
406
                        this.generation = generation;
1 ✔
407
                }
1 ✔
408
        }
409
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc