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

knowledgepixels / nanopub-query / 28397979857

29 Jun 2026 07:41PM UTC coverage: 62.401% (+0.5%) from 61.856%
28397979857

Pull #135

github

web-flow
Merge b842064b8 into d59621ae9
Pull Request #135: fix(triplestore): defer repo-cache eviction shutdown and pin hot repos

581 of 1040 branches covered (55.87%)

Branch coverage included in aggregate %.

1711 of 2633 relevant lines covered (64.98%)

10.06 hits per line

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

70.39
src/main/java/com/knowledgepixels/query/TripleStore.java
1
package com.knowledgepixels.query;
2

3
import org.apache.http.client.config.RequestConfig;
4
import org.apache.http.client.methods.CloseableHttpResponse;
5
import org.apache.http.client.methods.HttpUriRequest;
6
import org.apache.http.client.methods.RequestBuilder;
7
import org.apache.http.entity.StringEntity;
8
import org.apache.http.impl.client.BasicResponseHandler;
9
import org.apache.http.impl.client.CloseableHttpClient;
10
import org.apache.http.impl.client.HttpClients;
11
import com.google.common.hash.Hashing;
12
import org.eclipse.rdf4j.common.transaction.IsolationLevels;
13
import org.eclipse.rdf4j.model.ValueFactory;
14
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
15
import org.eclipse.rdf4j.repository.Repository;
16
import org.eclipse.rdf4j.repository.RepositoryConnection;
17
import org.eclipse.rdf4j.repository.base.RepositoryConnectionWrapper;
18
import org.eclipse.rdf4j.repository.http.HTTPRepository;
19
import org.nanopub.NanopubUtils;
20
import org.nanopub.vocabulary.NPA;
21
import org.slf4j.Logger;
22
import org.slf4j.LoggerFactory;
23

24
import java.io.BufferedReader;
25
import java.io.IOException;
26
import java.io.InputStreamReader;
27
import java.nio.charset.StandardCharsets;
28
import java.util.*;
29
import java.util.Map.Entry;
30
import java.util.concurrent.ConcurrentHashMap;
31
import java.util.concurrent.TimeUnit;
32
import java.util.concurrent.atomic.AtomicBoolean;
33
import java.util.concurrent.atomic.AtomicInteger;
34
import java.util.concurrent.locks.ReadWriteLock;
35
import java.util.concurrent.locks.ReentrantReadWriteLock;
36

37
/**
38
 * Class to access the database in the form of triple stores.
39
 */
40
public class TripleStore {
41

42
    /**
43
     * Name of the admin graph.
44
     */
45
    public static final String ADMIN_REPO = "admin";
46

47
    private static ValueFactory vf = SimpleValueFactory.getInstance();
6✔
48

49
    private static final Logger logger = LoggerFactory.getLogger(TripleStore.class);
9✔
50

51
    private final Map<String, Repository> repositories = new LinkedHashMap<>();
15✔
52

53
    /**
54
     * Per-repo open-connection counter, read by the eviction loop to skip repos that
55
     * still have live connections. Incremented in {@link #getRepoConnection(String)}
56
     * just before the connection is handed out and decremented via a
57
     * {@link RepositoryConnectionWrapper} that intercepts {@code close()} exactly once.
58
     */
59
    private final ConcurrentHashMap<String, AtomicInteger> openConnections = new ConcurrentHashMap<>();
15✔
60

61
    /**
62
     * Handles evicted from {@link #repositories} but not yet shut down. Eviction is
63
     * deferred and idle-only: calling {@link HTTPRepository#shutDown()} closes the
64
     * session manager and kills any live (possibly streaming) server-side transaction
65
     * with the {@code MMapIndexInput - Already closed} error, which can wedge the
66
     * underlying LMDB store on the server for <em>every</em> client. Instead of shutting
67
     * a handle down the instant its app-side connection count hits zero — a count that
68
     * can momentarily read zero between operations, or undercount a result set still
69
     * being streamed — we park it here and only shut it down from
70
     * {@link #reapPendingShutdowns()} once it has stayed idle for {@link #SHUTDOWN_GRACE_MS}.
71
     * Guarded by the {@code this} monitor, like {@link #repositories}.
72
     */
73
    private final Map<String, Repository> pendingShutdown = new LinkedHashMap<>();
15✔
74
    private final Map<String, Long> pendingShutdownSince = new HashMap<>();
15✔
75

76
    /** Idle grace period before a parked handle is actually shut down. */
77
    private static final long SHUTDOWN_GRACE_MS = 60_000;
78

79
    /**
80
     * Repos that are never evicted. The core named repos plus the view-critical type
81
     * repos: ResourceView and ViewDisplay are queried and federated into constantly by
82
     * the spaces/view UI, so they churn through the {@code cap 100} LRU fastest and were
83
     * the handles most exposed to the shutdown-during-use race. Pinning a handful of
84
     * them is cheap (a few always-warm LMDB envs) and removes the thrash on exactly the
85
     * repos that wedge.
86
     */
87
    private static final Set<String> PINNED_REPO_NAMES = buildPinnedRepoNames();
9✔
88

89
    private static Set<String> buildPinnedRepoNames() {
90
        Set<String> names = new HashSet<>(Arrays.asList("admin", "empty", "meta", "full", "spaces", "last30d"));
93✔
91
        for (String typeIri : new String[] {
75✔
92
                "https://w3id.org/kpxl/gen/terms/ResourceView",
93
                "https://w3id.org/kpxl/gen/terms/ViewDisplay" }) {
94
            names.add("type_" + Hashing.sha256().hashString(typeIri, StandardCharsets.UTF_8).toString());
27✔
95
        }
96
        return Collections.unmodifiableSet(names);
9✔
97
    }
98

99
    private String endpointBase = null;
9✔
100
    private String endpointType = null;
9✔
101

102
    private static TripleStore tripleStoreInstance;
103

104
    /**
105
     * Returns singleton triple store instance.
106
     *
107
     * @return Triple store instance
108
     */
109
    public static TripleStore get() {
110
        if (tripleStoreInstance == null) {
6!
111
            try {
112
                tripleStoreInstance = new TripleStore();
×
113
            } catch (IOException ex) {
×
114
                logger.info("Could not init TripleStore. ", ex);
×
115
            }
×
116
        }
117
        return tripleStoreInstance;
×
118
    }
119

120
    private TripleStore() throws IOException {
6✔
121
        // Read directly from the JVM's in-memory environment block rather than via
122
        // Apache Commons Exec's EnvironmentUtils.getProcEnvironment(), which forks a
123
        // subprocess and can throw under memory pressure / a restart storm — leaving
124
        // the singleton uninitialised. Same fragile mechanism that caused issue #117
125
        // on the per-nanopub hot path (see Utils.getEnvString); retired here too.
126
        endpointBase = System.getenv("ENDPOINT_BASE");
12✔
127
        logger.info("Endpoint base: {}", endpointBase);
15✔
128
        endpointType = System.getenv("ENDPOINT_TYPE");
12✔
129

130
        getRepository("empty");  // Make sure empty repo exists
×
131
    }
×
132

133
    /**
134
     * Shared HTTP client for all RDF4J traffic. Apache HttpClient treats all requests
135
     * to a given host + port + protocol as one "route", so every `HTTPRepository` in
136
     * this process funnels through this single client's connection pool — plus the
137
     * two ad-hoc users in {@link #createRepo} and {@link #getRepositoryNames}, which
138
     * have been consolidated onto this client too.
139
     *
140
     * <p>The Apache defaults (maxPerRoute=2 / maxTotal=20) throttle four concurrent
141
     * loader-pool threads down to two-way parallelism at the HTTP layer — invisible
142
     * client-side serialisation the code is actively fighting. Raised to 10 / 40
143
     * here: comfortable headroom for the 4-thread loader pool plus admin-repo
144
     * transactions and the metrics tick, small enough to be a conservative first
145
     * step with room to grow later.
146
     *
147
     * <p>Timeouts set via {@code setDefaultRequestConfig}:
148
     * <ul>
149
     *   <li><b>socket-read = 60 s</b> — an individual HTTP response body must arrive
150
     *       within this window. Healthy per-nanopub commits complete in milliseconds,
151
     *       so 60 s is pure safety margin; its job is to turn the silent "threads
152
     *       parked forever inside a commit" wedge (observed in the April test) into
153
     *       a recoverable error that feeds the existing retry path.</li>
154
     *   <li><b>connection-request = 30 s</b> — a caller waiting for a pooled connection
155
     *       gives up after this long. Prevents the invisible self-deadlock in
156
     *       {@code loadInvalidateStatements} (one thread holding N connections while
157
     *       waiting for an (N+1)th) from hanging forever.</li>
158
     *   <li><b>connect = 10 s</b> — kills TCP handshakes that stall. Generous but
159
     *       bounded.</li>
160
     * </ul>
161
     * Without these defaults, HttpClient uses {@code -1} everywhere, which means
162
     * "wait forever".
163
     */
164
    private final CloseableHttpClient httpclient = HttpClients.custom()
9✔
165
            .setMaxConnPerRoute(10)
6✔
166
            .setMaxConnTotal(40)
3✔
167
            .setDefaultRequestConfig(RequestConfig.custom()
9✔
168
                    .setSocketTimeout(60_000)
6✔
169
                    .setConnectionRequestTimeout(30_000)
6✔
170
                    .setConnectTimeout(10_000)
3✔
171
                    .build())
3✔
172
            // Hygiene: kill pooled connections that RDF4J has quietly closed server-side
173
            // before we try to reuse them. Without this, a half-broken connection is
174
            // only noticed when the next request fails, spending the full socket-read
175
            // timeout discovering it.
176
            .evictExpiredConnections()
9✔
177
            .evictIdleConnections(30, TimeUnit.SECONDS)
3✔
178
            .build();
6✔
179

180
    @GeneratedFlagForDependentElements
181
    Repository getRepository(String name) {
182
        synchronized (this) {
183
            // Reap parked handles that have now been idle long enough, even when we're
184
            // not over cap, so a burst that parked some repos doesn't leave them warm
185
            // forever if load then drops. Cheap: early-returns when nothing is parked.
186
            reapPendingShutdowns();
187
            if (repositories.size() > 100) {
188
                evictIdleRepos();
189
            }
190
            if (repositories.containsKey(name)) {
191
                // Move to the end of the list:
192
                Repository repo = repositories.remove(name);
193
                repositories.put(name, repo);
194
            } else if (pendingShutdown.containsKey(name)) {
195
                // Needed again before its grace period elapsed: resurrect the parked
196
                // handle instead of shutting it down and re-creating, avoiding both the
197
                // re-init round-trip and any shutdown/use race.
198
                Repository repo = pendingShutdown.remove(name);
199
                pendingShutdownSince.remove(name);
200
                repositories.put(name, repo);
201
            } else {
202
                Repository repository = null;
203
                if (endpointType == null || endpointType.equals("rdf4j")) {
204
                    HTTPRepository hr = new HTTPRepository(endpointBase + "repositories/" + name);
205
                    hr.setHttpClient(httpclient);
206
                    repository = hr;
207
//                        } else if (endpointType.equals("virtuoso")) {
208
//                                repository = new VirtuosoRepository(endpointBase + name, username, password);
209
                } else {
210
                    throw new RuntimeException("Unknown repository type: " + endpointType);
211
                }
212
                repositories.put(name, repository);
213
                createRepo(name);
214
                getRepoConnection(name).close();
215
            }
216
            return repositories.get(name);
217
        }
218
    }
219

220
    /**
221
     * Return the repository connection for the given repository name.
222
     *
223
     * @param name repository name
224
     * @return repository connection
225
     */
226
    @GeneratedFlagForDependentElements
227
    public RepositoryConnection getRepoConnection(String name) {
228
        // The increment has to happen under the same monitor that guards eviction,
229
        // otherwise another thread could evict this repo in the window between
230
        // getRepository() returning and the counter going above zero. getConnection()
231
        // on HTTPRepository is local (it doesn't do HTTP), so holding the lock here
232
        // is cheap.
233
        synchronized (this) {
234
            Repository repo = getRepository(name);
235
            if (repo == null) {
236
                return null;
237
            }
238
            AtomicInteger counter = openConnections.computeIfAbsent(name, k -> new AtomicInteger());
×
239
            counter.incrementAndGet();
240
            try {
241
                return new CountingRepositoryConnection(repo, repo.getConnection(), counter);
242
            } catch (Throwable t) {
243
                // If getConnection() or the wrapper constructor throws after we bumped
244
                // the counter, decrement so the repo isn't pinned against eviction by
245
                // a phantom "active" connection it doesn't actually have.
246
                counter.decrementAndGet();
247
                throw t;
248
            }
249
        }
250
    }
251

252
    /**
253
     * Evicts the eldest cache entries until either the size is back within the
254
     * 100-entry cap or every remaining entry is pinned or has an open connection.
255
     * The cap is load-bearing — each cached entry keeps an LMDB environment alive
256
     * on the RDF4J server (in-memory cache, mmap pages, native memory), so
257
     * exceeding it by much risks server-side OOM.
258
     *
259
     * <p>Eviction is <em>non-destructive</em>: it only unlinks the handle from the
260
     * live cache into {@link #pendingShutdown}; it does <strong>not</strong> call
261
     * {@link org.eclipse.rdf4j.repository.http.HTTPRepository#shutDown()} here.
262
     * Shutting a handle down closes the session manager and kills any live transaction
263
     * on that repo with a connection-close error (the {@code MMapIndexInput – Already
264
     * closed} failure mode observed on query-3 in the April test), which can wedge the
265
     * server-side LMDB store for every client. The actual shutdown happens later in
266
     * {@link #reapPendingShutdowns()}, only after a repo has stayed provably idle for
267
     * {@link #SHUTDOWN_GRACE_MS}. Pinned and actively-used repos are skipped entirely.
268
     * The cap is still enforced immediately, because unlinked handles leave
269
     * {@link #repositories} right away.
270
     */
271
    /**
272
     * Current time in millis. A seam so tests can drive the eviction grace period
273
     * deterministically instead of sleeping.
274
     */
275
    long nowMillis() {
276
        return System.currentTimeMillis();
×
277
    }
278

279
    @GeneratedFlagForDependentElements
280
    void evictIdleRepos() {
281
        reapPendingShutdowns();
282
        List<String> skipped = new ArrayList<>();
283
        long now = nowMillis();
284
        Iterator<Entry<String, Repository>> iter = repositories.entrySet().iterator();
285
        while (iter.hasNext() && repositories.size() > 100) {
286
            Entry<String, Repository> e = iter.next();
287
            String name = e.getKey();
288
            if (PINNED_REPO_NAMES.contains(name)) {
289
                skipped.add(name);
290
                continue;
291
            }
292
            AtomicInteger active = openConnections.get(name);
293
            if (active != null && active.get() > 0) {
294
                skipped.add(name);
295
                continue;
296
            }
297
            iter.remove();
298
            // Park for deferred shutdown rather than shutting down in this hot path.
299
            pendingShutdown.put(name, e.getValue());
300
            pendingShutdownSince.put(name, now);
301
        }
302
        if (!skipped.isEmpty()) {
303
            logger.warn("Skipped eviction for {} active/pinned repo(s); cache size is now {} (cap 100). Active names: {}",
304
                    skipped.size(), repositories.size(), skipped);
305
        }
306
    }
307

308
    /**
309
     * Shuts down handles parked in {@link #pendingShutdown} that have stayed idle
310
     * ({@code openConnections == 0}) for at least {@link #SHUTDOWN_GRACE_MS}. The grace
311
     * period keeps eviction from killing a server-side transaction whose app-side
312
     * connection count merely dipped to zero between operations, or that is still
313
     * streaming a result set. A handle re-requested before it is reaped is resurrected
314
     * in {@link #getRepository(String)} and never shut down. Must be called under the
315
     * {@code this} monitor.
316
     */
317
    void reapPendingShutdowns() {
318
        if (pendingShutdown.isEmpty()) {
12✔
319
            return;
3✔
320
        }
321
        long now = nowMillis();
9✔
322
        Iterator<Entry<String, Repository>> iter = pendingShutdown.entrySet().iterator();
15✔
323
        while (iter.hasNext()) {
9✔
324
            Entry<String, Repository> e = iter.next();
12✔
325
            String name = e.getKey();
12✔
326
            AtomicInteger active = openConnections.get(name);
18✔
327
            Long since = pendingShutdownSince.get(name);
18✔
328
            if ((active == null || active.get() == 0) && since != null && now - since >= SHUTDOWN_GRACE_MS) {
42!
329
                iter.remove();
6✔
330
                pendingShutdownSince.remove(name);
15✔
331
                logger.info("Shutting down idle repo (deferred): {}", name);
12✔
332
                try {
333
                    e.getValue().shutDown();
12✔
334
                } catch (Exception ex) {
×
335
                    logger.warn("Deferred shutdown failed for repo '{}': {}", name, ex.getMessage());
×
336
                }
3✔
337
                logger.info("Shutdown complete");
9✔
338
            }
339
        }
3✔
340
    }
3✔
341

342
    /**
343
     * Minimal wrapper around a delegate {@link RepositoryConnection} whose only job
344
     * is to decrement the per-repo open-connection counter exactly once when the
345
     * caller closes it. Uses {@link AtomicBoolean} so that repeated/idempotent
346
     * {@code close()} calls (common with try-with-resources plus explicit close)
347
     * don't decrement more than once.
348
     */
349
    private static final class CountingRepositoryConnection extends RepositoryConnectionWrapper {
350

351
        private final AtomicInteger counter;
352
        private final AtomicBoolean closed = new AtomicBoolean();
×
353

354
        CountingRepositoryConnection(Repository repo, RepositoryConnection delegate, AtomicInteger counter) {
355
            super(repo, delegate);
×
356
            this.counter = counter;
×
357
        }
×
358

359
        @Override
360
        public void close() {
361
            try {
362
                super.close();
×
363
            } finally {
364
                if (closed.compareAndSet(false, true)) {
×
365
                    counter.decrementAndGet();
×
366
                }
367
            }
368
        }
×
369

370
    }
371

372
    @GeneratedFlagForDependentElements
373
    private void createRepo(String repoName) {
374
        if (!repoName.equals(ADMIN_REPO)) {
375
            getRepository(ADMIN_REPO);  // make sure admin repo is loaded first
376
        }
377
        // Uses the shared this.httpclient rather than a per-call client so it inherits
378
        // the configured pool sizes (and, once change 1 of the fix plan lands, the
379
        // socket/connection-request timeouts).
380
        try {
381
            //logger.info("Trying to creating repo " + name);
382

383
            // TODO new syntax somehow doesn't work for the Lucene case:
384

385
//                        String createRegularRepoQueryString = "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>.\n"
386
//                                        + "@prefix config: <tag:rdf4j.org,2023:config/>.\n"
387
//                                        + "[] a config:Repository ;\n"
388
//                                        + "    config:rep.id \"" + name + "\" ;\n"
389
//                                        + "    rdfs:label \"" + name + " native store\" ;\n"
390
//                                        + "    config:rep.impl [\n"
391
//                                        + "        config:rep.type \"openrdf:SailRepository\" ;\n"
392
//                                        + "        config:sail.impl [\n"
393
//                                        + "            config:sail.type \"openrdf:NativeStore\" ;\n"
394
//                                        + "            config:sail.iterationCacheSyncThreshold \"10000\";\n"
395
//                                        + "            config:native.tripleIndexes \"spoc,posc,ospc,opsc,psoc,sopc,spoc,cpos,cosp,cops,cpso,csop\" ;\n"
396
//                                        + "            config:sail.defaultQueryEvaluationMode \"STANDARD\"\n"
397
//                                        + "        ]\n"
398
//                                        + "    ].";
399
//                        String createTextRepoQueryString = "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>.\n"
400
//                                        + "@prefix config: <tag:rdf4j.org,2023:config/>.\n"
401
//                                        + "[] a config:Repository ;\n"
402
//                                        + "    config:rep.id \"" + name + "\" ;\n"
403
//                                        + "    rdfs:label \"" + name + " native store\" ;\n"
404
//                                        + "    config:rep.impl [\n"
405
//                                        + "        config:rep.type \"openrdf:SailRepository\" ;\n"
406
//                                        + "        config:sail.impl [\n"
407
//                                        + "            config:sail.type \"openrdf:LuceneSail\" ;\n"
408
//                                        + "            config:sail.lucene.indexDir \"index/\" ;\n"
409
//                                        + "            config:delegate [\n"
410
//                                        + "                config:rep.type \"openrdf:SailRepository\" ;\n"
411
//                                        + "                config:sail.impl [\n"
412
//                                        + "                    config:sail.type \"openrdf:NativeStore\" ;\n"
413
//                                        + "                    config:sail.iterationCacheSyncThreshold \"10000\";\n"
414
//                                        + "                    config:native.tripleIndexes \"spoc,posc,ospc,opsc,psoc,sopc,spoc,cpos,cosp,cops,cpso,csop\" ;\n"
415
//                                        + "                    config:sail.defaultQueryEvaluationMode \"STANDARD\"\n"
416
//                                        + "                ]\n"
417
//                                        + "            ]\n"
418
//                                        + "        ]\n"
419
//                                        + "    ].";
420

421
            String indexTypes = "spoc,posc,ospc,cspo,cpos,cosp";
422
            if (repoName.startsWith("meta") || repoName.startsWith("text")) {
423
                indexTypes = "spoc,posc,ospc";
424
            }
425

426
            String createRegularRepoQueryString =
427
                    "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>.\n" +
428
                    "@prefix rep: <http://www.openrdf.org/config/repository#>.\n" +
429
                    "@prefix sr: <http://www.openrdf.org/config/repository/sail#>.\n" +
430
                    "@prefix sail: <http://www.openrdf.org/config/sail#>.\n" +
431
                    "@prefix sail-luc: <http://www.openrdf.org/config/sail/lucene#>.\n" +
432
                    "@prefix lmdb: <http://rdf4j.org/config/sail/lmdb#>.\n" +
433
                    "@prefix sb: <http://www.openrdf.org/config/sail/base#>.\n" +
434
                    "\n" +
435
                    "[] a rep:Repository ;\n" +
436
                    "    rep:repositoryID \"" + repoName + "\" ;\n" +
437
                    "    rdfs:label \"" + repoName + " LMDB store\" ;\n" +
438
                    "    rep:repositoryImpl [\n" +
439
                    "        rep:repositoryType \"openrdf:SailRepository\" ;\n" +
440
                    "        sr:sailImpl [\n" +
441
                    "            sail:sailType \"rdf4j:LmdbStore\" ;\n" +
442
                    "            sail:iterationCacheSyncThreshold \"10000\";\n" +
443
                    "            lmdb:tripleIndexes \"" + indexTypes + "\" ;\n" +
444
                    "            sb:defaultQueryEvaluationMode \"STANDARD\"\n" +
445
                    "        ]\n"
446
                    + "    ].\n";
447

448
            // TODO Index npa:hasFilterLiteral predicate too (see https://groups.google.com/g/rdf4j-users/c/epF4Af1jXGU):
449
            String createTextRepoQueryString =
450
                    "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>.\n" +
451
                    "@prefix rep: <http://www.openrdf.org/config/repository#>.\n" +
452
                    "@prefix sr: <http://www.openrdf.org/config/repository/sail#>.\n" +
453
                    "@prefix sail: <http://www.openrdf.org/config/sail#>.\n" +
454
                    "@prefix sail-luc: <http://www.openrdf.org/config/sail/lucene#>.\n" +
455
                    "@prefix lmdb: <http://rdf4j.org/config/sail/lmdb#>.\n" +
456
                    "@prefix sb: <http://www.openrdf.org/config/sail/base#>.\n" +
457
                    "\n"
458
                    + "[] a rep:Repository ;\n" +
459
                    "    rep:repositoryID \"" + repoName + "\" ;\n" +
460
                    "    rdfs:label \"" + repoName + " store\" ;\n" +
461
                    "    rep:repositoryImpl [\n" +
462
                    "        rep:repositoryType \"openrdf:SailRepository\" ;\n" +
463
                    "        sr:sailImpl [\n" +
464
                    "            sail:sailType \"openrdf:LuceneSail\" ;\n" +
465
                    "            sail-luc:indexDir \"index/\" ;\n" +
466
                    "            sail-luc:transactional false ;\n" +
467
                    "            sail:delegate [\n" +
468
                    "              sail:sailType \"rdf4j:LmdbStore\" ;\n" +
469
                    "              sail:iterationCacheSyncThreshold \"10000\";\n" +
470
                    "              lmdb:tripleIndexes \"" + indexTypes + "\" ;\n" +
471
                    "              sb:defaultQueryEvaluationMode \"STANDARD\"\n" +
472
                    "            ]\n" +
473
                    "        ]\n" +
474
                    "    ].";
475

476
            String createRepoQueryString = createRegularRepoQueryString;
477
            if (repoName.startsWith("text")) {
478
                createRepoQueryString = createTextRepoQueryString;
479
            }
480

481
            HttpUriRequest createRepoRequest = RequestBuilder.put().setUri(endpointBase + "repositories/" + repoName).addHeader("Content-Type", "text/turtle").setEntity(new StringEntity(createRepoQueryString)).build();
482

483
            // Response is try-with-resources'd so the connection is released back to
484
            // the shared pool rather than leaked.
485
            try (CloseableHttpResponse response = httpclient.execute(createRepoRequest)) {
486
                int statusCode = response.getStatusLine().getStatusCode();
487
                if (statusCode == 409) {
488
                    //logger.info("Already exists.");
489
                    getRepository(repoName).init();
490
                } else if (statusCode >= 200 && statusCode < 300) {
491
                    //logger.info("Successfully created.");
492
                    initNewRepo(repoName);
493
                } else {
494
                    logger.info("Status code: {}", response.getStatusLine().getStatusCode());
495
                    logger.info(response.getStatusLine().getReasonPhrase());
496
                    String handledResponse = new BasicResponseHandler().handleResponse(response);
497
                    logger.info("Response: {}", handledResponse);
498
                }
499
            }
500
        } catch (IOException ex) {
501
            logger.info("Could not create repo.", ex);
502
        }
503
    }
504

505
    /**
506
     * Sends shutdown signal to all repositories.
507
     */
508
    @GeneratedFlagForDependentElements
509
    public void shutdownRepositories() {
510
        for (Repository repo : repositories.values()) {
511
            if (repo != null && repo.isInitialized()) {
512
                repo.shutDown();
513
            }
514
        }
515
    }
516

517
    /**
518
     * Returns admin repo connection.
519
     *
520
     * @return repository connection to admin repository
521
     */
522
    @GeneratedFlagForDependentElements
523
    public RepositoryConnection getAdminRepoConnection() {
524
        return get().getRepoConnection(ADMIN_REPO);
525
    }
526

527
    private Set<String> cachedRepositoryNames = Set.of();
9✔
528
    private boolean repoNamesCacheValid = false;
9✔
529
    private final ReadWriteLock repoNamesCacheLock = new ReentrantReadWriteLock();
15✔
530

531
    /**
532
     * Returns set of all repository names.
533
     *
534
     * @return Repository name set
535
     */
536
    public Set<String> getRepositoryNames() {
537
        // See if the repository names are cached:
538
        final var readLock = repoNamesCacheLock.readLock();
12✔
539
        try {
540
            readLock.lock();
6✔
541
            if (repoNamesCacheValid) {
9✔
542
                return cachedRepositoryNames;
15✔
543
            }
544
        } finally {
545
            readLock.unlock();
6✔
546
        }
547

548
        // Not cached, get from server:
549
        final var writeLock = repoNamesCacheLock.writeLock();
12✔
550
        try {
551
            writeLock.lock();
6✔
552
            // Check again if another thread has already updated the cache:
553
            if (repoNamesCacheValid) {
9!
554
                return cachedRepositoryNames;
×
555
            }
556
            Map<String, Boolean> repositoryNames = null;
6✔
557
            // Uses the shared this.httpclient; response try-with-resources releases
558
            // the pooled connection when done.
559
            try (CloseableHttpResponse resp = httpclient.execute(RequestBuilder.get()
24✔
560
                    .setUri(endpointBase + "/repositories")
9✔
561
                    .addHeader("Content-Type", "text/csv")
3✔
562
                    .build())) {
3✔
563
                BufferedReader reader = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
30✔
564
                int code = resp.getStatusLine().getStatusCode();
12✔
565
                if (code < 200 || code >= 300) return null;
30!
566
                repositoryNames = new HashMap<>();
12✔
567
                int lineCount = 0;
6✔
568
                while (true) {
569
                    String line = reader.readLine();
9✔
570
                    if (line == null) break;
9✔
571
                    if (lineCount > 0) {
6✔
572
                        String repoName = line.split(",")[1];
18✔
573
                        repositoryNames.put(repoName, true);
18✔
574
                    }
575
                    lineCount = lineCount + 1;
12✔
576
                }
3✔
577
            } catch (IOException ex) {
15!
578
                logger.info("Could not get repository names.", ex);
12✔
579
                return null;
12✔
580
            }
3✔
581
            cachedRepositoryNames = repositoryNames.keySet();
12✔
582
            repoNamesCacheValid = true;
9✔
583
            return cachedRepositoryNames;
15✔
584
        } finally {
585
            writeLock.unlock();
6✔
586
        }
587
    }
588

589
    /**
590
     * Invalidates the repository names cache. Call this method when a repository is created or deleted.
591
     */
592
    private void invalidateRepositoryNamesCache() {
593
        final var writeLock = repoNamesCacheLock.writeLock();
×
594
        try {
595
            writeLock.lock();
×
596
            repoNamesCacheValid = false;
×
597
        } finally {
598
            writeLock.unlock();
×
599
        }
600
    }
×
601

602
    @GeneratedFlagForDependentElements
603
    private void initNewRepo(String repoName) {
604
        String repoInitId = new Random().nextLong() + "";
605
        getRepository(repoName).init();
606
        if (!repoName.equals("empty")) {
607
            RepositoryConnection conn = getRepoConnection(repoName);
608
            try (conn) {
609
                // Full isolation, just in case.
610
                conn.begin(IsolationLevels.SERIALIZABLE);
611
                conn.add(NPA.THIS_REPO, NPA.HAS_REPO_INIT_ID, vf.createLiteral(repoInitId), NPA.GRAPH);
612
                if (tracksNanopubCountAndChecksum(repoName)) {
613
                    conn.add(NPA.THIS_REPO, NPA.HAS_NANOPUB_COUNT, vf.createLiteral(0L), NPA.GRAPH);
614
                    conn.add(NPA.THIS_REPO, NPA.HAS_NANOPUB_CHECKSUM, vf.createLiteral(NanopubUtils.INIT_CHECKSUM), NPA.GRAPH);
615
                }
616
                if (repoName.startsWith("pubkey_") || repoName.startsWith("type_")) {
617
                    String h = repoName.replaceFirst("^[^_]+_", "");
618
                    conn.add(NPA.THIS_REPO, NPA.HAS_COVERAGE_ITEM, Utils.getObjectForHash(h), NPA.GRAPH);
619
                    conn.add(NPA.THIS_REPO, NPA.HAS_COVERAGE_HASH, vf.createLiteral(h), NPA.GRAPH);
620
                    conn.add(NPA.THIS_REPO, NPA.HAS_COVERAGE_FILTER, vf.createLiteral("_" + repoName), NPA.GRAPH);
621
                }
622
                conn.commit();
623
            }
624
            // Refresh repository names cache
625
            invalidateRepositoryNamesCache();
626
        }
627
    }
628

629
    /**
630
     * Whether the given repo participates in the cumulative nanopub-count / XOR-checksum
631
     * tracking. Repos that don't produce their own content-addressed population
632
     * skip the {@code npa:hasNanopubCount} and {@code npa:hasNanopubChecksum}
633
     * initial triples — leaving them at {@code 0} and the empty-XOR placeholder
634
     * forever would just be misleading. Currently excluded:
635
     * <ul>
636
     *   <li>{@code admin} — holds metadata only.</li>
637
     *   <li>{@code last30d} — content expires on a periodic cleanup.</li>
638
     *   <li>{@code trust} — holds derived trust state, mirrored from the registry.</li>
639
     *   <li>{@code spaces} — holds space-relevant raw nanopubs (a filtered projection
640
     *       of {@code full}) plus extraction triples; its XOR checksum over loaded
641
     *       trusty URIs would diverge from {@code full}'s without adding value.</li>
642
     * </ul>
643
     */
644
    private static boolean tracksNanopubCountAndChecksum(String repoName) {
645
        return !repoName.equals(ADMIN_REPO)
×
646
                && !repoName.equals("last30d")
×
647
                && !repoName.equals("trust")
×
648
                && !repoName.equals("spaces");
×
649
    }
650

651
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc