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

knowledgepixels / nanodash / 42266133876

06 Nov 2026 05:56PM UTC coverage: 54.813% (-0.02%) from 54.828%
42266133876

push

github

web-flow
Merge pull request #895 from knowledgepixels/fix/892-lazy-maintained-resource-nanopub

fix: load maintained-resource nanopubs off the repository lock

6585 of 12842 branches covered (51.28%)

Branch coverage included in aggregate %.

11369 of 19913 relevant lines covered (57.09%)

9.46 hits per line

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

66.07
src/main/java/com/knowledgepixels/nanodash/repository/MaintainedResourceRepository.java
1
package com.knowledgepixels.nanodash.repository;
2

3
import com.knowledgepixels.nanodash.ApiCache;
4
import com.knowledgepixels.nanodash.NanodashPreferences;
5
import com.knowledgepixels.nanodash.NanodashThreadPool;
6
import com.knowledgepixels.nanodash.QueryApiAccess;
7
import com.knowledgepixels.nanodash.domain.MaintainedResource;
8
import com.knowledgepixels.nanodash.domain.MaintainedResourceFactory;
9
import com.knowledgepixels.nanodash.domain.Space;
10
import org.apache.wicket.request.cycle.RequestCycle;
11
import org.nanopub.extra.services.ApiResponse;
12
import org.nanopub.extra.services.ApiResponseEntry;
13
import org.nanopub.extra.services.QueryRef;
14
import org.slf4j.Logger;
15
import org.slf4j.LoggerFactory;
16

17
import java.util.ArrayList;
18
import java.util.Collections;
19
import java.util.HashMap;
20
import java.util.HashSet;
21
import java.util.List;
22
import java.util.Map;
23
import java.util.Set;
24
import java.util.concurrent.ConcurrentHashMap;
25
import java.util.concurrent.atomic.AtomicBoolean;
26

27
public class MaintainedResourceRepository {
28

29
    private static final Logger logger = LoggerFactory.getLogger(MaintainedResourceRepository.class);
9 ✔
30

31
    private static final MaintainedResourceRepository INSTANCE = new MaintainedResourceRepository();
15 ✔
32

33
    /**
34
     * Get the singleton instance of MaintainedResourceRepository.
35
     *
36
     * @return The singleton instance of MaintainedResourceRepository.
37
     */
38
    public static MaintainedResourceRepository get() {
39
        return INSTANCE;
6 ✔
40
    }
41

42
    private MaintainedResourceRepository() {
6 ✔
43
    }
3 ✔
44

45
    private static final class Snapshot {
46
        final Map<String, MaintainedResource> resourcesById;
47
        final Map<String, MaintainedResource> resourcesByNamespace;
48
        final Map<Space, List<MaintainedResource>> resourcesBySpace;
49

50
        Snapshot(Map<String, MaintainedResource> byId,
51
                 Map<String, MaintainedResource> byNs,
52
                 Map<Space, List<MaintainedResource>> bySpace) {
6 ✔
53
            this.resourcesById = byId;
9 ✔
54
            this.resourcesByNamespace = byNs;
9 ✔
55
            this.resourcesBySpace = bySpace;
9 ✔
56
        }
3 ✔
57

58
        static final Snapshot EMPTY = new Snapshot(
9 ✔
59
                Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap());
15 ✔
60
    }
61

62
    // Source of truth is ApiCache (60s TTL on its own); we memoise the derived
63
    // maps keyed by the ApiResponse instance identity so they get rebuilt
64
    // exactly when ApiCache returns a fresh response and not on every call.
65
    private volatile ApiResponse cachedFor;
66
    private volatile Snapshot snapshot = Snapshot.EMPTY;
9 ✔
67

68
    // Every resource a snapshot ever held, by id. The query API is a set of instances
69
    // with independently built indexes, so an answer that is short of a resource -- or
70
    // of all of them -- is a normal kind of failure rather than news that the resource
71
    // is gone. Letting such an answer make a resource disappear is what had the home
72
    // page reporting its own configuration as broken (issue #623), so callers that must
73
    // not fail over a momentarily missing resource ask findLastKnownById() instead.
74
    private final Map<String, MaintainedResource> lastKnownById = new ConcurrentHashMap<>();
15 ✔
75

76
    // Whether a background pass loading the resources' nanopubs is under way.
77
    private final AtomicBoolean loadingNanopubs = new AtomicBoolean(false);
18 ✔
78

79
    private Snapshot current() {
80
        ApiResponse resp = ApiCache.retrieveResponseIfAvailable(new QueryRef(QueryApiAccess.GET_MAINTAINED_RESOURCES));
18 ✔
81
        if (resp == null) {
6 ✔
82
            return snapshot;
9 ✔
83
        }
84
        if (resp == cachedFor) {
12 ✔
85
            return snapshot;
9 ✔
86
        }
87
        Snapshot built;
88
        synchronized (this) {
12 ✔
89
            if (resp == cachedFor) {
12 !
90
                return snapshot;
×
91
            }
92
            built = build(resp);
12 ✔
93
            if (built == null) {
6 ✔
94
                // Spaces weren't loaded yet, so every resource would have been
95
                // dropped (each row's space resolved to null). Don't latch this
96
                // empty result against the current response identity — return what
97
                // we have and rebuild on the next access, once spaces are warm.
98
                return snapshot;
15 ✔
99
            }
100
            snapshot = built;
9 ✔
101
            cachedFor = resp;
9 ✔
102
            lastKnownById.putAll(built.resourcesById);
15 ✔
103
        }
9 ✔
104
        loadNanopubsInBackground();
6 ✔
105
        return built;
6 ✔
106
    }
107

108
    /**
109
     * Fetches the declaring nanopub of each resource in the current snapshot that doesn't
110
     * have it yet, on a pool thread. Building a snapshot fetches nothing (issue #892), so
111
     * this is what spares a resource's page the fetch on its first view. One pass at a
112
     * time: a snapshot latched while a pass runs is covered by the pass of a later rebuild,
113
     * and rebuilds come with every refresh of the underlying query.
114
     */
115
    private void loadNanopubsInBackground() {
116
        // Where the background loading is switched off (issue #809), the nanopubs are
117
        // fetched when a page first asks for them.
118
        if (!NanodashPreferences.get().isDataRefreshEnabled()) return;
12 !
119
        if (!loadingNanopubs.compareAndSet(false, true)) return;
×
120
        try {
121
            NanodashThreadPool.submit(() -> {
×
122
                try {
123
                    // A saturated pool runs the task in the thread that submitted it. A
124
                    // request must not be the one fetching ~200 nanopubs one by one; a
125
                    // later rebuild tries again.
126
                    if (RequestCycle.get() != null) return;
×
127
                    long start = System.currentTimeMillis();
×
128
                    int loaded = 0, failed = 0;
×
129
                    for (MaintainedResource resource : snapshot.resourcesById.values()) {
×
130
                        if (resource.isNanopubLoaded()) continue;
×
131
                        if (resource.getNanopub() != null) loaded++;
×
132
                        else failed++;
×
133
                    }
×
134
                    if (loaded + failed > 0) {
×
135
                        logger.info("Loaded the nanopubs of {} maintained resources in {} ms ({} could not be fetched)",
×
136
                                loaded, System.currentTimeMillis() - start, failed);
×
137
                    }
138
                } catch (Exception ex) {
×
139
                    logger.warn("Loading maintained-resource nanopubs failed", ex);
×
140
                } finally {
141
                    loadingNanopubs.set(false);
×
142
                }
143
            });
×
144
        } catch (RuntimeException ex) {
×
145
            loadingNanopubs.set(false);
×
146
            logger.warn("Could not start loading maintained-resource nanopubs", ex);
×
147
        }
×
148
    }
×
149

150
    /**
151
     * Build the resource lookup maps from the spaces-repo response. Pulls
152
     * server-validated {@code npa:isMaintainedBy} links from the current
153
     * space-state graph; only the most recent declaration per resource is kept
154
     * (the {@code get-maintained-resources} query orders by {@code DESC(?date)},
155
     * so the first row per resource wins).
156
     */
157
    private Snapshot build(ApiResponse resp) {
158
        Map<String, MaintainedResource> byId = new HashMap<>();
12 ✔
159
        Map<String, MaintainedResource> byNamespace = new HashMap<>();
12 ✔
160
        Map<Space, List<MaintainedResource>> bySpace = new HashMap<>();
12 ✔
161
        Set<String> seenResources = new HashSet<>();
12 ✔
162
        boolean droppedForMissingSpace = false;
6 ✔
163
        for (ApiResponseEntry r : resp.getData()) {
33 ✔
164
            String resourceId = r.get("resource");
12 ✔
165
            if (resourceId == null || resourceId.isEmpty()) continue;
15 !
166
            if (!seenResources.add(resourceId)) continue; // first row (newest date) wins
12 !
167
            String spaceId = r.get("space");
12 ✔
168
            Space space = SpaceRepository.get().findById(spaceId);
12 ✔
169
            if (space == null) {
6 !
170
                // Space not (yet) loaded — likely a cold/racing SpaceRepository
171
                // rather than a genuinely unknown space. Track it so current()
172
                // can avoid latching an under-built snapshot.
173
                if (spaceId != null && !spaceId.isEmpty()) droppedForMissingSpace = true;
×
174
                continue;
175
            }
176
            ApiResponseEntry entry = new ApiResponseEntry();
12 ✔
177
            entry.add("resource", resourceId);
12 ✔
178
            entry.add("np", r.get("np"));
18 ✔
179
            String label = r.get("label");
12 ✔
180
            if (label != null && !label.isEmpty()) entry.add("label", label);
27 !
181
            String namespace = r.get("namespace");
12 ✔
182
            if (namespace != null && !namespace.isEmpty()) entry.add("namespace", namespace);
27 ✔
183
            MaintainedResource resource = MaintainedResourceFactory.getOrCreate(entry, space);
12 ✔
184
            byId.put(resourceId, resource);
15 ✔
185
            bySpace.computeIfAbsent(space, k -> new ArrayList<>()).add(resource);
36 ✔
186
            if (resource.getNamespace() != null) {
9 ✔
187
                // TODO Handle conflicts when two resources claim the same namespace:
188
                byNamespace.put(resource.getNamespace(), resource);
18 ✔
189
            }
190
        }
3 ✔
191
        if (byId.isEmpty() && droppedForMissingSpace) {
15 !
192
            // Every resource was dropped because its space wasn't resolvable, yet
193
            // the response did contain rows — SpaceRepository is cold. Signal "not
194
            // ready" so current() doesn't memoise this empty result.
195
            return null;
×
196
        }
197
        if (byId.isEmpty() && !snapshot.resourcesById.isEmpty()) {
24 ✔
198
            // An instance that has been shown maintained resources does not suddenly
199
            // have none: an answer carrying nothing at all is the query API failing to
200
            // answer, not the resources being gone. Keep what we have — latching this
201
            // would also let removeStale() below wipe every resource instance.
202
            return null;
6 ✔
203
        }
204
        MaintainedResourceFactory.removeStale(byId.keySet());
9 ✔
205
        return new Snapshot(byId, byNamespace, bySpace);
21 ✔
206
    }
207

208
    /**
209
     * Find a maintained resource by its namespace.
210
     *
211
     * @param namespace The namespace to search for.
212
     * @return The MaintainedResource with the given namespace, or null if not found.
213
     */
214
    public MaintainedResource findByNamespace(String namespace) {
215
        return current().resourcesByNamespace.get(namespace);
21 ✔
216
    }
217

218
    /**
219
     * Get all known maintained resources.
220
     *
221
     * @return The list of maintained resources, in no particular order.
222
     */
223
    public List<MaintainedResource> findAll() {
224
        return new ArrayList<>(current().resourcesById.values());
24 ✔
225
    }
226

227
    /**
228
     * Find the maintained resources belonging to a given space.
229
     *
230
     * @param space The space to look up.
231
     * @return The list of maintained resources for the space, possibly empty.
232
     */
233
    public List<MaintainedResource> findResourcesBySpace(Space space) {
234
        List<MaintainedResource> l = current().resourcesBySpace.get(space);
×
235
        return l != null ? l : new ArrayList<>();
×
236
    }
237

238
    /**
239
     * Get a maintained resource by its id.
240
     *
241
     * @param id The id of the resource.
242
     * @return The corresponding MaintainedResource object, or null if not found.
243
     */
244
    public MaintainedResource findById(String id) {
245
        return current().resourcesById.get(id);
21 ✔
246
    }
247

248
    /**
249
     * Like {@link #findById(String)}, but falls back to the resource as it was last
250
     * known when the current snapshot has no entry for the id. For the callers that must
251
     * keep working across an answer that came back short (issue #623) — above all the
252
     * home page, which would otherwise declare its configured resource missing — rather
253
     * than for the many callers that ask merely whether an IRI <em>is</em> a maintained
254
     * resource; those want {@link #findById(String)} and its strict answer.
255
     *
256
     * @param id The id of the resource.
257
     * @return The resource, from the current snapshot or from before it, or null if no
258
     *         answer ever carried this id.
259
     */
260
    public MaintainedResource findLastKnownById(String id) {
261
        MaintainedResource resource = findById(id);
12 ✔
262
        if (resource != null) return resource;
6 !
263
        return lastKnownById.get(id);
18 ✔
264
    }
265

266
    /**
267
     * Whether the given id can be taken to be genuinely unknown, i.e. a null from
268
     * {@link #findLastKnownById(String)} is final rather than a matter of waiting. Three
269
     * things have to hold: a snapshot has been latched at all (the response was fetched
270
     * and {@link #build} kept it), that snapshot holds resources, and neither it nor any
271
     * earlier answer carried this id. Short of that, an unresolved id means the data is
272
     * missing — a cold cache, a racing {@link SpaceRepository}, or an answer short of
273
     * every resource — and not that the id is wrong. What lets the home page tell a
274
     * misconfigured home resource from an instance that has not been told about its
275
     * resources yet (issue #623).
276
     *
277
     * @param id The id to ask about.
278
     * @return true if the id is known not to be a maintained resource
279
     */
280
    public boolean isAbsent(String id) {
281
        Snapshot current = current();
9 ✔
282
        return cachedFor != null
18 ✔
283
                && !current.resourcesById.isEmpty()
15 ✔
284
                && !current.resourcesById.containsKey(id)
15 ✔
285
                && !lastKnownById.containsKey(id);
15 ✔
286
    }
287

288
    /**
289
     * Invalidate the underlying ApiCache entry, optionally delaying the next refresh.
290
     *
291
     * @param waitMillis Delay in milliseconds before the next access may trigger a refresh; 0 for immediate.
292
     */
293
    public void forceRootRefresh(long waitMillis) {
294
        ApiCache.clearCache(new QueryRef(QueryApiAccess.GET_MAINTAINED_RESOURCES), waitMillis);
×
295
    }
×
296

297
}
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