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

knowledgepixels / nanopub-query / 24672438593

20 Apr 2026 02:34PM UTC coverage: 61.033% (+0.8%) from 60.242%
24672438593

Pull #71

github

web-flow
Merge f38dcb3ad into d9b6b6359
Pull Request #71: feat: extract admin grants and profile fields into the spaces repo (#62)

326 of 594 branches covered (54.88%)

Branch coverage included in aggregate %.

927 of 1459 relevant lines covered (63.54%)

9.32 hits per line

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

73.24
src/main/java/com/knowledgepixels/query/NanopubLoader.java
1
package com.knowledgepixels.query;
2

3
import net.trustyuri.TrustyUriUtils;
4
import org.apache.http.client.HttpClient;
5
import org.apache.http.impl.client.HttpClientBuilder;
6
import org.eclipse.rdf4j.common.exception.RDF4JException;
7
import org.eclipse.rdf4j.common.transaction.IsolationLevels;
8
import org.eclipse.rdf4j.model.*;
9
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
10
import org.eclipse.rdf4j.model.vocabulary.DCTERMS;
11
import org.eclipse.rdf4j.model.vocabulary.RDFS;
12
import org.eclipse.rdf4j.query.BindingSet;
13
import org.eclipse.rdf4j.query.QueryLanguage;
14
import org.eclipse.rdf4j.query.TupleQuery;
15
import org.eclipse.rdf4j.query.TupleQueryResult;
16
import org.eclipse.rdf4j.repository.RepositoryConnection;
17
import org.nanopub.Nanopub;
18
import org.nanopub.NanopubUtils;
19
import org.nanopub.SimpleCreatorPattern;
20
import org.nanopub.SimpleTimestampPattern;
21
import org.nanopub.extra.security.KeyDeclaration;
22
import org.nanopub.extra.security.MalformedCryptoElementException;
23
import org.nanopub.extra.security.NanopubSignatureElement;
24
import org.nanopub.extra.security.SignatureUtils;
25
import org.nanopub.extra.server.GetNanopub;
26
import org.nanopub.extra.setting.IntroNanopub;
27
import org.nanopub.vocabulary.NP;
28
import org.nanopub.vocabulary.NPA;
29
import org.nanopub.vocabulary.NPX;
30
import org.nanopub.vocabulary.PAV;
31
import org.slf4j.Logger;
32
import org.slf4j.LoggerFactory;
33

34
import com.knowledgepixels.query.vocabulary.GEN;
35

36
import java.security.GeneralSecurityException;
37
import java.util.*;
38
import java.util.concurrent.ExecutionException;
39
import java.util.concurrent.Executors;
40
import java.util.concurrent.Future;
41
import java.util.concurrent.ThreadLocalRandom;
42
import java.util.concurrent.ThreadPoolExecutor;
43
import java.util.function.Consumer;
44

45
/**
46
 * Utility class for loading nanopublications into the database.
47
 */
48
public class NanopubLoader {
49

50
    private static HttpClient httpClient;
51
    private static final ThreadPoolExecutor loadingPool = (ThreadPoolExecutor) Executors.newFixedThreadPool(4);
12✔
52

53
    /**
54
     * Retry budget for the five (with #71 merged: six) structurally identical
55
     * retry loops in this file. Previously the shape was flat {@code 10 s × 30} —
56
     * five minutes of constant hammering at RDF4J that did not help a slow server.
57
     * The new shape is bounded exponential backoff with ±50 % jitter:
58
     * {@code base = 1, 2, 4, 8, 16, 32, 60, 60 s} for attempts 1…8, each perturbed
59
     * by up to half its base value. Jitter prevents the 4-thread loadingPool from
60
     * retrying in lock-step after a shared RDF4J failure (GC pause / overload spike).
61
     * Worst-case wall time per failing task drops from ~35 min (post-change-1
62
     * timeouts × 30 flat retries) to ~11 min (8 retries × 60 s timeout + backoff
63
     * sleeps). This is the figure that sets the circuit-breaker trip time in
64
     * {@link JellyNanopubLoader}.
65
     */
66
    private static final int MAX_RETRIES = 8;
67
    private static final long[] BACKOFF_BASE_MS =
105✔
68
            {1_000L, 2_000L, 4_000L, 8_000L, 16_000L, 32_000L, 60_000L, 60_000L};
69

70
    /**
71
     * Returns the sleep delay in ms for the given 1-indexed retry attempt. Delay
72
     * is {@link #BACKOFF_BASE_MS}{@code [attempt-1]} perturbed by ±50 % uniform
73
     * jitter, clamped to be non-negative.
74
     *
75
     * @param attempt 1-indexed retry attempt number
76
     * @return the computed sleep delay in ms
77
     */
78
    static long computeBackoffMillis(int attempt) {
79
        long base = BACKOFF_BASE_MS[Math.min(attempt - 1, BACKOFF_BASE_MS.length - 1)];
×
80
        long jitter = ThreadLocalRandom.current().nextLong(base + 1) - base / 2;
×
81
        return Math.max(0L, base + jitter);
×
82
    }
83
    private Nanopub np;
84
    private NanopubSignatureElement el = null;
9✔
85
    private List<Statement> metaStatements = new ArrayList<>();
15✔
86
    private List<Statement> nanopubStatements = new ArrayList<>();
15✔
87
    private List<Statement> literalStatements = new ArrayList<>();
15✔
88
    private List<Statement> invalidateStatements = new ArrayList<>();
15✔
89
    private List<Statement> textStatements, allStatements;
90
    private Calendar timestamp = null;
9✔
91
    private Statement pubkeyStatement, pubkeyStatementX;
92
    private List<String> notes = new ArrayList<>();
15✔
93
    private boolean aborted = false;
9✔
94
    private static final Logger log = LoggerFactory.getLogger(NanopubLoader.class);
9✔
95

96

97
    NanopubLoader(Nanopub np, long counter) {
6✔
98
        this.np = np;
9✔
99
        if (counter >= 0) {
12✔
100
            log.info("Loading {}: {}", counter, np.getUri());
24✔
101
        } else {
102
            log.info("Loading: {}", np.getUri());
15✔
103
        }
104

105
        // TODO Ensure proper synchronization and DB rollbacks
106

107
        // TODO Check for null characters ("\0"), which can cause problems in Virtuoso.
108

109
        String ac = TrustyUriUtils.getArtifactCode(np.getUri().toString());
15✔
110
        if (!np.getHeadUri().toString().contains(ac) || !np.getAssertionUri().toString().contains(ac) || !np.getProvenanceUri().toString().contains(ac) || !np.getPubinfoUri().toString().contains(ac)) {
72!
111
            notes.add("could not load nanopub as not all graphs contained the artifact code");
×
112
            aborted = true;
×
113
            return;
×
114
        }
115

116
        try {
117
            el = SignatureUtils.getSignatureElement(np);
12✔
118
        } catch (MalformedCryptoElementException ex) {
×
119
            notes.add("Signature error");
×
120
        }
3✔
121
        if (!hasValidSignature(el)) {
12✔
122
            aborted = true;
9✔
123
            return;
3✔
124
        }
125

126
        pubkeyStatement = vf.createStatement(np.getUri(), NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY, vf.createLiteral(el.getPublicKeyString()), NPA.GRAPH);
39✔
127
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasValidSignatureForPublicKey, FULL_PUBKEY, npa:graph, meta, full pubkey if signature is valid
128
        metaStatements.add(pubkeyStatement);
18✔
129
        pubkeyStatementX = vf.createStatement(np.getUri(), NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY_HASH, vf.createLiteral(Utils.createHash(el.getPublicKeyString())), NPA.GRAPH);
42✔
130
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasValidSignatureForPublicKeyHash, PUBKEY_HASH, npa:graph, meta, hex-encoded SHA256 hash if signature is valid
131
        metaStatements.add(pubkeyStatementX);
18✔
132

133
        if (el.getSigners().size() == 1) {  // > 1 is deprecated
18!
134
            metaStatements.add(vf.createStatement(np.getUri(), NPX.SIGNED_BY, el.getSigners().iterator().next(), NPA.GRAPH));
48✔
135
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, npx:signedBy, SIGNER, npa:graph, meta, ID of signer
136
        }
137

138
        Set<IRI> subIris = new HashSet<>();
12✔
139
        Set<IRI> otherNps = new HashSet<>();
12✔
140
        Set<IRI> invalidated = new HashSet<>();
12✔
141
        Set<IRI> retracted = new HashSet<>();
12✔
142
        Set<IRI> superseded = new HashSet<>();
12✔
143
        String combinedLiterals = "";
6✔
144
        for (Statement st : NanopubUtils.getStatements(np)) {
33✔
145
            nanopubStatements.add(st);
15✔
146

147
            if (st.getPredicate().toString().contains(ac)) {
18!
148
                subIris.add(st.getPredicate());
×
149
            } else {
150
                IRI b = getBaseTrustyUri(st.getPredicate());
12✔
151
                if (b != null) otherNps.add(b);
6!
152
            }
153
            if (st.getPredicate().equals(NPX.RETRACTS) && st.getObject() instanceof IRI) {
15!
154
                retracted.add((IRI) st.getObject());
×
155
            }
156
            if (st.getPredicate().equals(NPX.INVALIDATES) && st.getObject() instanceof IRI) {
15!
157
                invalidated.add((IRI) st.getObject());
×
158
            }
159
            if (st.getSubject().equals(np.getUri()) && st.getObject() instanceof IRI) {
30✔
160
                if (st.getPredicate().equals(NPX.SUPERSEDES)) {
15✔
161
                    superseded.add((IRI) st.getObject());
18✔
162
                }
163
                if (st.getObject().toString().matches(".*[^A-Za-z0-9\\-_]RA[A-Za-z0-9\\-_]{43}")) {
18✔
164
                    metaStatements.add(vf.createStatement(np.getUri(), st.getPredicate(), st.getObject(), NPA.NETWORK_GRAPH));
39✔
165
                    // @ADMIN-TRIPLE-TABLE@ NANOPUB1, RELATION, NANOPUB2, npa:networkGraph, meta, any inter-nanopub relation found in NANOPUB1
166
                }
167
                if (st.getContext().equals(np.getPubinfoUri())) {
18✔
168
                    if (st.getPredicate().equals(NPX.INTRODUCES) || st.getPredicate().equals(NPX.DESCRIBES) || st.getPredicate().equals(NPX.EMBEDS)) {
45!
169
                        metaStatements.add(vf.createStatement(np.getUri(), st.getPredicate(), st.getObject(), NPA.GRAPH));
39✔
170
                        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npx:introduces, THING, npa:graph, meta, when such a triple is present in pubinfo of NANOPUB
171
                        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npx:describes, THING, npa:graph, meta, when such a triple is present in pubinfo of NANOPUB
172
                        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npx:embeds, THING, npa:graph, meta, when such a triple is present in pubinfo of NANOPUB
173
                    }
174
                }
175
            }
176
            if (st.getSubject().toString().contains(ac)) {
18✔
177
                subIris.add((IRI) st.getSubject());
21✔
178
            } else {
179
                IRI b = getBaseTrustyUri(st.getSubject());
12✔
180
                if (b != null) otherNps.add(b);
6!
181
            }
182
            if (st.getObject() instanceof IRI) {
12✔
183
                if (st.getObject().toString().contains(ac)) {
18✔
184
                    subIris.add((IRI) st.getObject());
21✔
185
                } else {
186
                    IRI b = getBaseTrustyUri(st.getObject());
12✔
187
                    if (b != null) otherNps.add(b);
18✔
188
                }
3✔
189
            } else {
190
                combinedLiterals += st.getObject().stringValue().replaceAll("\\s+", " ") + "\n";
27✔
191
//                                if (st.getSubject().equals(np.getUri()) && !st.getSubject().equals(HAS_FILTER_LITERAL)) {
192
//                                        literalStatements.add(vf.createStatement(np.getUri(), st.getPredicate(), st.getObject(), LITERAL_GRAPH));
193
//                                } else {
194
//                                        literalStatements.add(vf.createStatement(np.getUri(), HAS_LITERAL, st.getObject(), LITERAL_GRAPH));
195
//                                }
196
            }
197
        }
3✔
198
        subIris.remove(np.getUri());
15✔
199
        subIris.remove(np.getAssertionUri());
15✔
200
        subIris.remove(np.getProvenanceUri());
15✔
201
        subIris.remove(np.getPubinfoUri());
15✔
202
        for (IRI i : subIris) {
30✔
203
            metaStatements.add(vf.createStatement(np.getUri(), NPA.HAS_SUB_IRI, i, NPA.GRAPH));
33✔
204
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasSubIri, SUB_IRI, npa:graph, meta, for any IRI minted in the namespace of the NANOPUB
205
        }
3✔
206
        for (IRI i : otherNps) {
30✔
207
            metaStatements.add(vf.createStatement(np.getUri(), NPA.REFERS_TO_NANOPUB, i, NPA.NETWORK_GRAPH));
33✔
208
            // @ADMIN-TRIPLE-TABLE@ NANOPUB1, npa:refersToNanopub, NANOPUB2, npa:networkGraph, meta, generic inter-nanopub relation
209
        }
3✔
210
        for (IRI i : invalidated) {
18!
211
            invalidateStatements.add(vf.createStatement(np.getUri(), NPX.INVALIDATES, i, NPA.GRAPH));
×
212
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, npx:invalidates, INVALIDATED_NANOPUB, npa:graph, meta, if the NANOPUB retracts or supersedes another nanopub
213
        }
×
214
        for (IRI i : retracted) {
18!
215
            invalidateStatements.add(vf.createStatement(np.getUri(), NPX.INVALIDATES, i, NPA.GRAPH));
×
216
            metaStatements.add(vf.createStatement(np.getUri(), NPX.RETRACTS, i, NPA.GRAPH));
×
217
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, npx:retracts, RETRACTED_NANOPUB, npa:graph, meta, if the NANOPUB retracts another nanopub
218
        }
×
219
        for (IRI i : superseded) {
30✔
220
            invalidateStatements.add(vf.createStatement(np.getUri(), NPX.INVALIDATES, i, NPA.GRAPH));
33✔
221
            metaStatements.add(vf.createStatement(np.getUri(), NPX.SUPERSEDES, i, NPA.GRAPH));
33✔
222
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, npx:supersedes, SUPERSEDED_NANOPUB, npa:graph, meta, if the NANOPUB supersedes another nanopub
223
        }
3✔
224

225
        metaStatements.add(vf.createStatement(np.getUri(), NPA.HAS_HEAD_GRAPH, np.getHeadUri(), NPA.GRAPH));
36✔
226
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasHeadGraph, HEAD_GRAPH, npa:graph, meta, direct link to the head graph of the NANOPUB
227
        metaStatements.add(vf.createStatement(np.getUri(), NPA.HAS_GRAPH, np.getHeadUri(), NPA.GRAPH));
36✔
228
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasGraph, GRAPH, npa:graph, meta, generic link to all four graphs of the given NANOPUB
229
        metaStatements.add(vf.createStatement(np.getUri(), NP.HAS_ASSERTION, np.getAssertionUri(), NPA.GRAPH));
36✔
230
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, np:hasAssertion, ASSERTION_GRAPH, npa:graph, meta, direct link to the assertion graph of the NANOPUB
231
        metaStatements.add(vf.createStatement(np.getUri(), NPA.HAS_GRAPH, np.getAssertionUri(), NPA.GRAPH));
36✔
232
        metaStatements.add(vf.createStatement(np.getUri(), NP.HAS_PROVENANCE, np.getProvenanceUri(), NPA.GRAPH));
36✔
233
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, np:hasProvenance, PROVENANCE_GRAPH, npa:graph, meta, direct link to the provenance graph of the NANOPUB
234
        metaStatements.add(vf.createStatement(np.getUri(), NPA.HAS_GRAPH, np.getProvenanceUri(), NPA.GRAPH));
36✔
235
        metaStatements.add(vf.createStatement(np.getUri(), NP.HAS_PUBINFO, np.getPubinfoUri(), NPA.GRAPH));
36✔
236
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, np:hasPublicationInfo, PUBINFO_GRAPH, npa:graph, meta, direct link to the pubinfo graph of the NANOPUB
237
        metaStatements.add(vf.createStatement(np.getUri(), NPA.HAS_GRAPH, np.getPubinfoUri(), NPA.GRAPH));
36✔
238

239
        String artifactCode = TrustyUriUtils.getArtifactCode(np.getUri().stringValue());
15✔
240
        metaStatements.add(vf.createStatement(np.getUri(), NPA.ARTIFACT_CODE, vf.createLiteral(artifactCode), NPA.GRAPH));
39✔
241
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:artifactCode, ARTIFACT_CODE, npa:graph, meta, artifact code starting with 'RA...'
242

243
        if (isIntroNanopub(np)) {
9✔
244
            IntroNanopub introNp = new IntroNanopub(np);
15✔
245
            metaStatements.add(vf.createStatement(np.getUri(), NPA.IS_INTRODUCTION_OF, introNp.getUser(), NPA.GRAPH));
36✔
246
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:isIntroductionOf, AGENT, npa:graph, meta, linking intro nanopub to the agent it is introducing
247
            for (KeyDeclaration kc : introNp.getKeyDeclarations()) {
33✔
248
                metaStatements.add(vf.createStatement(np.getUri(), NPA.DECLARES_PUBKEY, vf.createLiteral(kc.getPublicKeyString()), NPA.GRAPH));
42✔
249
                // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:declaresPubkey, FULL_PUBKEY, npa:graph, meta, full pubkey declared by the given intro NANOPUB
250
            }
3✔
251
        }
252

253
        try {
254
            timestamp = SimpleTimestampPattern.getCreationTime(np);
12✔
255
        } catch (IllegalArgumentException ex) {
×
256
            notes.add("Illegal date/time");
×
257
        }
3✔
258
        if (timestamp != null) {
9!
259
            metaStatements.add(vf.createStatement(np.getUri(), DCTERMS.CREATED, vf.createLiteral(timestamp.getTime()), NPA.GRAPH));
45✔
260
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, dct:created, CREATION_DATE, npa:graph, meta, normalized creation timestamp
261
        }
262

263
        String literalFilter = "_pubkey_" + Utils.createHash(el.getPublicKeyString());
18✔
264
        for (IRI typeIri : NanopubUtils.getTypes(np)) {
33✔
265
            metaStatements.add(vf.createStatement(np.getUri(), NPX.HAS_NANOPUB_TYPE, typeIri, NPA.GRAPH));
33✔
266
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, npx:hasNanopubType, NANOPUB_TYPE, npa:graph, meta, type of NANOPUB
267
            literalFilter += " _type_" + Utils.createHash(typeIri);
15✔
268
        }
3✔
269
        // Side-effecting call: populates SpaceRegistry as gen:Space-typed nanopubs flow through.
270
        // Consumers of the registry (extraction, materialization) land in later steps of #62.
271
        detectAndRegisterSpaces(np);
9✔
272
        String label = NanopubUtils.getLabel(np);
9✔
273
        if (label != null) {
6!
274
            metaStatements.add(vf.createStatement(np.getUri(), RDFS.LABEL, vf.createLiteral(label), NPA.GRAPH));
39✔
275
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, rdfs:label, LABEL, npa:graph, meta, label of NANOPUB
276
        }
277
        String description = NanopubUtils.getDescription(np);
9✔
278
        if (description != null) {
6✔
279
            metaStatements.add(vf.createStatement(np.getUri(), DCTERMS.DESCRIPTION, vf.createLiteral(description), NPA.GRAPH));
39✔
280
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, dct:description, LABEL, npa:graph, meta, description of NANOPUB
281
        }
282
        for (IRI creatorIri : SimpleCreatorPattern.getCreators(np)) {
33✔
283
            metaStatements.add(vf.createStatement(np.getUri(), DCTERMS.CREATOR, creatorIri, NPA.GRAPH));
33✔
284
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, dct:creator, CREATOR, npa:graph, meta, creator of NANOPUB (can be several)
285
        }
3✔
286
        for (IRI authorIri : SimpleCreatorPattern.getAuthors(np)) {
21!
287
            metaStatements.add(vf.createStatement(np.getUri(), PAV.AUTHORED_BY, authorIri, NPA.GRAPH));
×
288
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, pav:authoredBy, AUTHOR, npa:graph, meta, author of NANOPUB (can be several)
289
        }
×
290

291
        if (!combinedLiterals.isEmpty()) {
9!
292
            literalStatements.add(vf.createStatement(np.getUri(), NPA.HAS_FILTER_LITERAL, vf.createLiteral(literalFilter + "\n" + combinedLiterals), NPA.GRAPH));
45✔
293
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasFilterLiteral, FILTER_LITERAL, npa:graph, literal, auxiliary literal for filtering by type and pubkey in text repo
294
        }
295

296
        // Any statements that express that the currently processed nanopub is already invalidated:
297
        List<Statement> invalidatingStatements = getInvalidatingStatements(np.getUri());
12✔
298

299
        metaStatements.addAll(invalidateStatements);
18✔
300

301
        allStatements = new ArrayList<>(nanopubStatements);
21✔
302
        allStatements.addAll(metaStatements);
18✔
303
        allStatements.addAll(invalidatingStatements);
15✔
304

305
        textStatements = new ArrayList<>(literalStatements);
21✔
306
        textStatements.addAll(metaStatements);
18✔
307
        textStatements.addAll(invalidatingStatements);
15✔
308
    }
3✔
309

310
    /**
311
     * Get the HTTP client used for fetching nanopublications.
312
     *
313
     * @return the HTTP client
314
     */
315
    static HttpClient getHttpClient() {
316
        if (httpClient == null) {
6✔
317
            httpClient = HttpClientBuilder.create().setDefaultRequestConfig(Utils.getHttpRequestConfig()).build();
15✔
318
        }
319
        return httpClient;
6✔
320
    }
321

322
    /**
323
     * Load the given nanopublication into the database.
324
     *
325
     * @param nanopubUri Nanopublication identifier (URI)
326
     */
327
    public static void load(String nanopubUri) {
328
        if (isNanopubLoaded(nanopubUri)) {
9!
329
            log.info("Already loaded: {}", nanopubUri);
×
330
        } else {
331
            Nanopub np = GetNanopub.get(nanopubUri, getHttpClient());
12✔
332
            load(np, -1);
9✔
333
        }
334
    }
3✔
335

336
    /**
337
     * Load a nanopub into the database.
338
     *
339
     * @param np      the nanopub to load
340
     * @param counter the load counter, only used for logging (or -1 if not known)
341
     * @throws RDF4JException if the loading fails
342
     */
343
    public static void load(Nanopub np, long counter) throws RDF4JException {
344
        NanopubLoader loader = new NanopubLoader(np, counter);
18✔
345
        loader.executeLoading();
6✔
346
    }
3✔
347

348
    @GeneratedFlagForDependentElements
349
    private void executeLoading() {
350
        var runningTasks = new ArrayList<Future<?>>();
351
        Consumer<Runnable> runTask = t -> runningTasks.add(loadingPool.submit(t));
×
352

353
        for (String note : notes) {
354
            loadNoteToRepo(np.getUri(), note);
355
        }
356

357
        if (!aborted) {
358
            // Submit all tasks except the "meta" task
359
            if (timestamp != null) {
360
                if (new Date().getTime() - timestamp.getTimeInMillis() < THIRTY_DAYS) {
361
                    if (FeatureFlags.last30dRepoEnabled()) {
362
                        runTask.accept(() -> loadNanopubToLatest(allStatements));
×
363
                    }
364
                }
365
            }
366

367
            if (FeatureFlags.textRepoEnabled()) {
368
                runTask.accept(() -> loadNanopubToRepo(np.getUri(), textStatements, "text"));
×
369
            }
370
            if (FeatureFlags.fullRepoEnabled()) {
371
                runTask.accept(() -> loadNanopubToRepo(np.getUri(), allStatements, "full"));
×
372
            }
373
            // Note: "meta" task is deferred until all other tasks complete successfully
374

375
            runTask.accept(() -> loadNanopubToRepo(np.getUri(), allStatements, "pubkey_" + Utils.createHash(el.getPublicKeyString())));
×
376
            //                loadNanopubToRepo(np.getUri(), textStatements, "text-pubkey_" + Utils.createHash(el.getPublicKeyString()));
377
            for (IRI typeIri : NanopubUtils.getTypes(np)) {
378
                // Exclude locally minted IRIs:
379
                if (typeIri.stringValue().startsWith(np.getUri().stringValue())) continue;
380
                if (!typeIri.stringValue().matches("https?://.*")) continue;
381
                runTask.accept(() -> loadNanopubToRepo(np.getUri(), allStatements, "type_" + Utils.createHash(typeIri)));
×
382
                //                        loadNanopubToRepo(np.getUri(), textStatements, "text-type_" + Utils.createHash(typeIri));
383
            }
384
            // Project authority and profile contributions into the shared `spaces` repo.
385
            // Computation is cheap (a walk over the assertion) so we do it inline; the
386
            // write itself is parallelized with the other repo writes.
387
            SpacesExtractor.ExtractionResult spaceExtracts =
388
                    SpacesExtractor.extract(np, SpaceRegistry.get());
389
            if (!spaceExtracts.statements().isEmpty()) {
390
                runTask.accept(() -> loadSpaceExtracts(np.getUri(), spaceExtracts));
×
391
            }
392
            //                for (IRI creatorIri : SimpleCreatorPattern.getCreators(np)) {
393
            //                        // Exclude locally minted IRIs:
394
            //                        if (creatorIri.stringValue().startsWith(np.getUri().stringValue())) continue;
395
            //                        if (!creatorIri.stringValue().matches("https?://.*")) continue;
396
            //                        loadNanopubToRepo(np.getUri(), allStatements, "user_" + Utils.createHash(creatorIri));
397
            //                        loadNanopubToRepo(np.getUri(), textStatements, "text-user_" + Utils.createHash(creatorIri));
398
            //                }
399
            //                for (IRI authorIri : SimpleCreatorPattern.getAuthors(np)) {
400
            //                        // Exclude locally minted IRIs:
401
            //                        if (authorIri.stringValue().startsWith(np.getUri().stringValue())) continue;
402
            //                        if (!authorIri.stringValue().matches("https?://.*")) continue;
403
            //                        loadNanopubToRepo(np.getUri(), allStatements, "user_" + Utils.createHash(authorIri));
404
            //                        loadNanopubToRepo(np.getUri(), textStatements, "text-user_" + Utils.createHash(authorIri));
405
            //                }
406

407
            for (Statement st : invalidateStatements) {
408
                runTask.accept(() -> loadInvalidateStatements(np, el.getPublicKeyString(), st, pubkeyStatement, pubkeyStatementX));
×
409
            }
410

411
            // Wait for all non-meta tasks to complete successfully before submitting the meta task
412
            for (var task : runningTasks) {
413
                try {
414
                    task.get();
415
                } catch (ExecutionException | InterruptedException ex) {
416
                    throw new RuntimeException("Error in nanopub loading thread", ex.getCause());
417
                }
418
            }
419

420
            // Now submit and wait for the "meta" task after all other tasks have completed successfully
421
            Future<?> metaTask = loadingPool.submit(() -> loadNanopubToRepo(np.getUri(), metaStatements, "meta"));
×
422
            try {
423
                metaTask.get();
424
            } catch (ExecutionException | InterruptedException ex) {
425
                throw new RuntimeException("Error in nanopub loading thread (meta task)", ex.getCause());
426
            }
427
        }
428
    }
429

430
    private static Long lastUpdateOfLatestRepo = null;
6✔
431
    private static long THIRTY_DAYS = 1000L * 60 * 60 * 24 * 30;
6✔
432
    private static long ONE_HOUR = 1000L * 60 * 60;
6✔
433

434
    @GeneratedFlagForDependentElements
435
    private static void loadNanopubToLatest(List<Statement> statements) {
436
        boolean success = false;
437
        int retries = 0;
438
        while (!success) {
439
            RepositoryConnection conn = TripleStore.get().getRepoConnection("last30d");
440
            try (conn) {
441
                // Read committed, because deleting old nanopubs is idempotent. Inserts do not collide
442
                // with deletes, because we are not inserting old nanopubs.
443
                conn.begin(IsolationLevels.READ_COMMITTED);
444
                conn.add(statements);
445
                if (lastUpdateOfLatestRepo == null || new Date().getTime() - lastUpdateOfLatestRepo > ONE_HOUR) {
446
                    log.trace("Remove old nanopubs...");
447
                    Literal thirtyDaysAgo = vf.createLiteral(new Date(new Date().getTime() - THIRTY_DAYS));
448
                    TupleQuery q = conn.prepareTupleQuery(QueryLanguage.SPARQL, "SELECT * { graph <" + NPA.GRAPH + "> { " + "?np <" + DCTERMS.CREATED + "> ?date . " + "filter ( ?date < ?thirtydaysago ) " + "} }");
449
                    q.setBinding("thirtydaysago", thirtyDaysAgo);
450
                    try (TupleQueryResult r = q.evaluate()) {
451
                        while (r.hasNext()) {
452
                            BindingSet b = r.next();
453
                            IRI oldNpId = (IRI) b.getBinding("np").getValue();
454
                            log.trace("Remove old nanopub: {}", oldNpId);
455
                            for (Value v : Utils.getObjectsForPattern(conn, NPA.GRAPH, oldNpId, NPA.HAS_GRAPH)) {
456
                                // Remove all four nanopub graphs:
457
                                conn.remove((Resource) null, (IRI) null, (Value) null, (IRI) v);
458
                            }
459
                            // Remove nanopubs in admin graphs:
460
                            conn.remove(oldNpId, null, null, NPA.GRAPH);
461
                            conn.remove(oldNpId, null, null, NPA.NETWORK_GRAPH);
462
                        }
463
                    }
464
                    lastUpdateOfLatestRepo = new Date().getTime();
465
                }
466
                conn.commit();
467
                success = true;
468
            } catch (Exception ex) {
469
                log.warn("Could not load nanopub to last30d repo.", ex);
470
                if (conn.isActive()) conn.rollback();
471
            }
472
            if (!success) {
473
                retries++;
474
                if (retries >= MAX_RETRIES) {
475
                    throw new RuntimeException("Failed to load nanopub to last30d repo after " + MAX_RETRIES + " retries");
476
                }
477
                long delay = computeBackoffMillis(retries);
478
                log.info("Retrying in {} ms (attempt {}/{})...", delay, retries, MAX_RETRIES);
479
                try {
480
                    Thread.sleep(delay);
481
                } catch (InterruptedException x) {
482
                    Thread.currentThread().interrupt();
483
                }
484
            }
485
        }
486
    }
487

488
    @GeneratedFlagForDependentElements
489
    private static void loadNanopubToRepo(IRI npId, List<Statement> statements, String repoName) {
490
        boolean success = false;
491
        int retries = 0;
492
        while (!success) {
493
            RepositoryConnection conn = TripleStore.get().getRepoConnection(repoName);
494
            try (conn) {
495
                // Serializable, because write skew would cause the chain of hashes to be broken.
496
                // The inserts must be done serially.
497
                conn.begin(IsolationLevels.SERIALIZABLE);
498
                var repoStatus = fetchRepoStatus(conn, npId);
499
                if (repoStatus.isLoaded) {
500
                    log.info("Already loaded: {}", npId);
501
                } else {
502
                    String newChecksum = NanopubUtils.updateXorChecksum(npId, repoStatus.checksum);
503
                    conn.remove(NPA.THIS_REPO, NPA.HAS_NANOPUB_COUNT, null, NPA.GRAPH);
504
                    conn.remove(NPA.THIS_REPO, NPA.HAS_NANOPUB_CHECKSUM, null, NPA.GRAPH);
505
                    conn.add(NPA.THIS_REPO, NPA.HAS_NANOPUB_COUNT, vf.createLiteral(repoStatus.count + 1), NPA.GRAPH);
506
                    // @ADMIN-TRIPLE-TABLE@ REPO, npa:hasNanopubCount, NANOPUB_COUNT, npa:graph, admin, number of nanopubs loaded
507
                    conn.add(NPA.THIS_REPO, NPA.HAS_NANOPUB_CHECKSUM, vf.createLiteral(newChecksum), NPA.GRAPH);
508
                    // @ADMIN-TRIPLE-TABLE@ REPO, npa:hasNanopubChecksum, NANOPUB_CHECKSUM, npa:graph, admin, checksum of all loaded nanopubs (order-independent XOR checksum on trusty URIs in Base64 notation)
509
                    conn.add(npId, NPA.HAS_LOAD_NUMBER, vf.createLiteral(repoStatus.count), NPA.GRAPH);
510
                    // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasLoadNumber, LOAD_NUMBER, npa:graph, admin, the sequential number at which this NANOPUB was loaded
511
                    conn.add(npId, NPA.HAS_LOAD_CHECKSUM, vf.createLiteral(newChecksum), NPA.GRAPH);
512
                    // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasLoadChecksum, LOAD_CHECKSUM, npa:graph, admin, the checksum of all loaded nanopubs after loading the given NANOPUB
513
                    conn.add(npId, NPA.HAS_LOAD_TIMESTAMP, vf.createLiteral(new Date()), NPA.GRAPH);
514
                    // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasLoadTimestamp, LOAD_TIMESTAMP, npa:graph, admin, the time point at which this NANOPUB was loaded
515
                    conn.add(statements);
516
                }
517
                conn.commit();
518
                success = true;
519
            } catch (Exception ex) {
520
                log.warn("Could not load nanopub to repo.", ex);
521
                if (conn.isActive()) conn.rollback();
522
            }
523
            if (!success) {
524
                retries++;
525
                if (retries >= MAX_RETRIES) {
526
                    throw new RuntimeException("Failed to load nanopub " + npId + " to repo " + repoName + " after " + MAX_RETRIES + " retries");
527
                }
528
                long delay = computeBackoffMillis(retries);
529
                log.info("Retrying in {} ms (attempt {}/{})...", delay, retries, MAX_RETRIES);
530
                try {
531
                    Thread.sleep(delay);
532
                } catch (InterruptedException x) {
533
                    Thread.currentThread().interrupt();
534
                }
535
            }
536
        }
537
    }
538

539
    private record RepoStatus(boolean isLoaded, long count, String checksum) {
×
540
    }
541

542
    /**
543
     * To execute before loading a nanopub: check if the nanopub is already loaded and what is the
544
     * current load counter and checksum. This effectively batches three queries into one.
545
     * This method must be called from within a transaction.
546
     *
547
     * @param conn repo connection
548
     * @param npId nanopub ID
549
     * @return the current status
550
     */
551
    @GeneratedFlagForDependentElements
552
    private static RepoStatus fetchRepoStatus(RepositoryConnection conn, IRI npId) {
553
        var result = conn.prepareTupleQuery(QueryLanguage.SPARQL, REPO_STATUS_QUERY_TEMPLATE.formatted(npId)).evaluate();
554
        try (result) {
555
            if (!result.hasNext()) {
556
                // This may happen if the repo was created, but is completely empty.
557
                return new RepoStatus(false, 0, NanopubUtils.INIT_CHECKSUM);
558
            }
559
            var row = result.next();
560
            return new RepoStatus(row.hasBinding("loadNumber"), Long.parseLong(row.getBinding("count").getValue().stringValue()), row.getBinding("checksum").getValue().stringValue());
561
        }
562
    }
563

564
    @GeneratedFlagForDependentElements
565
    private static void loadInvalidateStatements(Nanopub thisNp, String thisPubkey, Statement invalidateStatement, Statement pubkeyStatement, Statement pubkeyStatementX) {
566
        boolean success = false;
567
        int retries = 0;
568
        while (!success) {
569
            List<RepositoryConnection> connections = new ArrayList<>();
570
            RepositoryConnection metaConn = TripleStore.get().getRepoConnection("meta");
571
            try {
572
                IRI invalidatedNpId = (IRI) invalidateStatement.getObject();
573
                // Basic isolation because here we only read append-only data.
574
                metaConn.begin(IsolationLevels.READ_COMMITTED);
575

576
                Value pubkeyValue = Utils.getObjectForPattern(metaConn, NPA.GRAPH, invalidatedNpId, NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY);
577
                if (pubkeyValue != null) {
578
                    String pubkey = pubkeyValue.stringValue();
579

580
                    if (!pubkey.equals(thisPubkey)) {
581
                        //log.info("Adding invalidation expressed in " + thisNp.getUri() + " also to repo for pubkey " + pubkey);
582
                        connections.add(loadStatements("pubkey_" + Utils.createHash(pubkey), invalidateStatement, pubkeyStatement, pubkeyStatementX));
583
//                                                connections.add(loadStatements("text-pubkey_" + Utils.createHash(pubkey), invalidateStatement, pubkeyStatement));
584
                    }
585

586
                    for (Value v : Utils.getObjectsForPattern(metaConn, NPA.GRAPH, invalidatedNpId, NPX.HAS_NANOPUB_TYPE)) {
587
                        IRI typeIri = (IRI) v;
588
                        // TODO Avoid calling getTypes and getCreators multiple times:
589
                        if (!NanopubUtils.getTypes(thisNp).contains(typeIri)) {
590
                            //log.info("Adding invalidation expressed in " + thisNp.getUri() + " also to repo for type " + typeIri);
591
                            connections.add(loadStatements("type_" + Utils.createHash(typeIri), invalidateStatement, pubkeyStatement, pubkeyStatementX));
592
//                                                        connections.add(loadStatements("text-type_" + Utils.createHash(typeIri), invalidateStatement, pubkeyStatement));
593
                        }
594
                    }
595

596
//                                        for (Value v : Utils.getObjectsForPattern(metaConn, NPA.GRAPH, invalidatedNpId, DCTERMS.CREATOR)) {
597
//                                                IRI creatorIri = (IRI) v;
598
//                                                if (!SimpleCreatorPattern.getCreators(thisNp).contains(creatorIri)) {
599
//                                                        //log.info("Adding invalidation expressed in " + thisNp.getUri() + " also to repo for user " + creatorIri);
600
//                                                        connections.add(loadStatements("user_" + Utils.createHash(creatorIri), invalidateStatement, pubkeyStatement));
601
//                                                        connections.add(loadStatements("text-user_" + Utils.createHash(creatorIri), invalidateStatement, pubkeyStatement));
602
//                                                }
603
//                                        }
604
                }
605

606
                metaConn.commit();
607
                // TODO handle case that some commits succeed and some fail
608
                for (RepositoryConnection c : connections) c.commit();
609
                success = true;
610
            } catch (Exception ex) {
611
                log.warn("Could not load invalidate statements.", ex);
612
                if (metaConn.isActive()) metaConn.rollback();
613
                for (RepositoryConnection c : connections) {
614
                    if (c.isActive()) c.rollback();
615
                }
616
            } finally {
617
                metaConn.close();
618
                for (RepositoryConnection c : connections) c.close();
619
            }
620
            if (!success) {
621
                retries++;
622
                if (retries >= MAX_RETRIES) {
623
                    throw new RuntimeException("Failed to load invalidate statements for " + thisNp.getUri() + " after " + MAX_RETRIES + " retries");
624
                }
625
                long delay = computeBackoffMillis(retries);
626
                log.info("Retrying in {} ms (attempt {}/{})...", delay, retries, MAX_RETRIES);
627
                try {
628
                    Thread.sleep(delay);
629
                } catch (InterruptedException x) {
630
                    Thread.currentThread().interrupt();
631
                }
632
            }
633
        }
634
    }
635

636
    @GeneratedFlagForDependentElements
637
    private static RepositoryConnection loadStatements(String repoName, Statement... statements) {
638
        RepositoryConnection conn = TripleStore.get().getRepoConnection(repoName);
639
        // Basic isolation: we only append new statements
640
        conn.begin(IsolationLevels.READ_COMMITTED);
641
        for (Statement st : statements) {
642
            conn.add(st);
643
        }
644
        return conn;
645
    }
646

647
    @GeneratedFlagForDependentElements
648
    static List<Statement> getInvalidatingStatements(IRI npId) {
649
        List<Statement> invalidatingStatements = new ArrayList<>();
650
        boolean success = false;
651
        int retries = 0;
652
        while (!success) {
653
            RepositoryConnection conn = TripleStore.get().getRepoConnection("meta");
654
            try (conn) {
655
                // Basic isolation because here we only read append-only data.
656
                conn.begin(IsolationLevels.READ_COMMITTED);
657

658
                TupleQueryResult r = conn.prepareTupleQuery(QueryLanguage.SPARQL, "SELECT * { graph <" + NPA.GRAPH + "> { " + "?np <" + NPX.INVALIDATES + "> <" + npId + "> ; <" + NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY + "> ?pubkey . " + "} }").evaluate();
659
                try (r) {
660
                    while (r.hasNext()) {
661
                        BindingSet b = r.next();
662
                        invalidatingStatements.add(vf.createStatement((IRI) b.getBinding("np").getValue(), NPX.INVALIDATES, npId, NPA.GRAPH));
663
                        invalidatingStatements.add(vf.createStatement((IRI) b.getBinding("np").getValue(), NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY, b.getBinding("pubkey").getValue(), NPA.GRAPH));
664
                    }
665
                }
666
                conn.commit();
667
                success = true;
668
            } catch (Exception ex) {
669
                log.warn("Could not load invalidating statements.", ex);
670
                if (conn.isActive()) conn.rollback();
671
            }
672
            if (!success) {
673
                retries++;
674
                if (retries >= MAX_RETRIES) {
675
                    throw new RuntimeException("Failed to get invalidating statements for " + npId + " after " + MAX_RETRIES + " retries");
676
                }
677
                long delay = computeBackoffMillis(retries);
678
                log.info("Retrying in {} ms (attempt {}/{})...", delay, retries, MAX_RETRIES);
679
                try {
680
                    Thread.sleep(delay);
681
                } catch (InterruptedException x) {
682
                    Thread.currentThread().interrupt();
683
                }
684
            }
685
        }
686
        return invalidatingStatements;
687
    }
688

689
    private static void loadSpaceExtracts(IRI npUri, SpacesExtractor.ExtractionResult result) {
690
        boolean success = false;
×
691
        int retries = 0;
×
692
        while (!success) {
×
693
            RepositoryConnection conn = TripleStore.get().getRepoConnection("spaces");
×
694
            try (conn) {
×
695
                conn.begin(IsolationLevels.SERIALIZABLE);
×
696
                conn.add(result.statements());
×
697
                conn.commit();
×
698
                success = true;
×
699
            } catch (Exception ex) {
×
700
                log.warn("Could not load space extracts.", ex);
×
701
                if (conn.isActive()) conn.rollback();
×
702
            }
×
703
            if (!success) {
×
704
                retries++;
×
705
                if (retries >= MAX_RETRIES) {
×
706
                    throw new RuntimeException("Failed to load space extracts after " + MAX_RETRIES + " retries");
×
707
                }
708
                long delay = computeBackoffMillis(retries);
×
709
                log.info("Retrying in {} ms (attempt {}/{})...", delay, retries, MAX_RETRIES);
×
710
                try {
711
                    Thread.sleep(delay);
×
712
                } catch (InterruptedException x) {
×
713
                    Thread.currentThread().interrupt();
×
714
                }
×
715
            }
716
        }
×
717
        // Reverse index: only after the write commits.
718
        for (String spaceRef : result.spaceRefs()) {
×
719
            SpaceRegistry.get().recordSourceNanopub(npUri, spaceRef);
×
720
        }
×
721
    }
×
722

723
    @GeneratedFlagForDependentElements
724
    private static void loadNoteToRepo(Resource subj, String note) {
725
        boolean success = false;
726
        int retries = 0;
727
        while (!success) {
728
            RepositoryConnection conn = TripleStore.get().getAdminRepoConnection();
729
            try (conn) {
730
                List<Statement> statements = new ArrayList<>();
731
                statements.add(vf.createStatement(subj, NPA.NOTE, vf.createLiteral(note), NPA.GRAPH));
732
                conn.add(statements);
733
                success = true;
734
            } catch (Exception ex) {
735
                log.warn("Could not load note to repo.", ex);
736
            }
737
            if (!success) {
738
                retries++;
739
                if (retries >= MAX_RETRIES) {
740
                    throw new RuntimeException("Failed to load note to repo for " + subj + " after " + MAX_RETRIES + " retries");
741
                }
742
                long delay = computeBackoffMillis(retries);
743
                log.info("Retrying in {} ms (attempt {}/{})...", delay, retries, MAX_RETRIES);
744
                try {
745
                    Thread.sleep(delay);
746
                } catch (InterruptedException x) {
747
                    Thread.currentThread().interrupt();
748
                }
749
            }
750
        }
751
    }
752

753
    static boolean hasValidSignature(NanopubSignatureElement el) {
754
        try {
755
            if (el != null && SignatureUtils.hasValidSignature(el) && el.getPublicKeyString() != null) {
24!
756
                return true;
6✔
757
            }
758
        } catch (GeneralSecurityException ex) {
3✔
759
            log.warn("Signature validation failed for signature element {}", el.getUri(), ex);
18✔
760
        }
3✔
761
        return false;
6✔
762
    }
763

764
    private static IRI getBaseTrustyUri(Value v) {
765
        if (!(v instanceof IRI)) return null;
9!
766
        String s = v.stringValue();
9✔
767
        if (!s.matches(".*[^A-Za-z0-9\\-_]RA[A-Za-z0-9\\-_]{43}([^A-Za-z0-9\\\\-_].{0,43})?")) {
12✔
768
            return null;
6✔
769
        }
770
        return vf.createIRI(s.replaceFirst("^(.*[^A-Za-z0-9\\-_]RA[A-Za-z0-9\\-_]{43})([^A-Za-z0-9\\\\-_].{0,43})?$", "$1"));
21✔
771
    }
772

773
    // TODO: Move this to nanopub library:
774
    private static boolean isIntroNanopub(Nanopub np) {
775
        for (Statement st : np.getAssertion()) {
33✔
776
            if (st.getPredicate().equals(NPX.DECLARED_BY)) return true;
21✔
777
        }
3✔
778
        return false;
6✔
779
    }
780

781
    /**
782
     * Detects whether the given nanopub is a Space-defining nanopub (typed
783
     * {@code gen:Space}) and, if so, registers each space it declares (one per
784
     * {@code <spaceIri> gen:hasRootDefinition <rootUri>} triple) in
785
     * {@link SpaceRegistry}. Nanopubs missing the {@code gen:hasRootDefinition}
786
     * triple are not recognized as space-defining — there is no transition fallback.
787
     *
788
     * @param np the nanopub to inspect
789
     * @return the set of space refs registered from this nanopub (possibly empty);
790
     *         currently used by tests to assert detection behavior. Production
791
     *         callers invoke this for its side effect on {@link SpaceRegistry};
792
     *         downstream consumers (extraction, materialization) follow in later
793
     *         steps of #62.
794
     */
795
    static Set<String> detectAndRegisterSpaces(Nanopub np) {
796
        if (!FeatureFlags.spacesEnabled()) return Collections.emptySet();
6!
797
        boolean isSpaceTyped = false;
6✔
798
        for (IRI typeIri : NanopubUtils.getTypes(np)) {
33✔
799
            if (typeIri.equals(GEN.SPACE)) {
12✔
800
                isSpaceTyped = true;
6✔
801
                break;
3✔
802
            }
803
        }
3✔
804
        if (!isSpaceTyped) return Collections.emptySet();
12✔
805
        Set<String> spaceRefs = new LinkedHashSet<>();
12✔
806
        for (Statement st : np.getAssertion()) {
33✔
807
            if (!st.getPredicate().equals(GEN.HAS_ROOT_DEFINITION)) continue;
18✔
808
            if (!(st.getSubject() instanceof IRI spaceIri)) continue;
27!
809
            if (!(st.getObject() instanceof IRI rootUri)) continue;
27!
810
            String rootNanopubId = TrustyUriUtils.getArtifactCode(rootUri.stringValue());
12✔
811
            if (rootNanopubId == null || rootNanopubId.isEmpty()) {
15!
812
                log.warn("Ignoring space {}: gen:hasRootDefinition target is not a trusty URI: {}", spaceIri, rootUri);
15✔
813
                continue;
3✔
814
            }
815
            SpaceRegistry.Registration registration = SpaceRegistry.get().registerSpace(rootNanopubId, spaceIri);
15✔
816
            spaceRefs.add(registration.spaceRef());
15✔
817
            if (registration.wasNew()) {
9!
818
                SpacesStateStore.persistSpace(rootNanopubId, spaceIri, rootUri);
12✔
819
            }
820
        }
3✔
821
        return spaceRefs;
6✔
822
    }
823

824
    /**
825
     * Check if a nanopub is already loaded in the admin graph.
826
     *
827
     * @param npId the nanopub ID
828
     * @return true if the nanopub is loaded, false otherwise
829
     */
830
    @GeneratedFlagForDependentElements
831
    static boolean isNanopubLoaded(String npId) {
832
        boolean loaded = false;
833
        RepositoryConnection conn = TripleStore.get().getRepoConnection("meta");
834
        try (conn) {
835
            if (Utils.getObjectForPattern(conn, NPA.GRAPH, vf.createIRI(npId), NPA.HAS_LOAD_NUMBER) != null) {
836
                loaded = true;
837
            }
838
        } catch (Exception ex) {
839
            log.warn("Could not check whether nanopub is loaded.", ex);
840
        }
841
        return loaded;
842
    }
843

844
    private static ValueFactory vf = SimpleValueFactory.getInstance();
6✔
845

846
    // TODO remove the constants and use the ones from the nanopub library instead
847

848
    /**
849
     * Template for the query that fetches the status of a repository.
850
     */
851
    // Template for .fetchRepoStatus
852
    private static final String REPO_STATUS_QUERY_TEMPLATE = """
84✔
853
            SELECT * { graph <%s> {
854
              OPTIONAL { <%s> <%s> ?loadNumber . }
855
              <%s> <%s> ?count ;
856
                   <%s> ?checksum .
857
            } }
858
            """.formatted(NPA.GRAPH, "%s", NPA.HAS_LOAD_NUMBER, NPA.THIS_REPO, NPA.HAS_NANOPUB_COUNT, NPA.HAS_NANOPUB_CHECKSUM);
6✔
859
}
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