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

knowledgepixels / nanodash / 42271484420

06 Nov 2026 06:31PM UTC coverage: 55.026% (+0.2%) from 54.813%
42271484420

push

github

web-flow
Merge pull request #896 from knowledgepixels/fix/startup-space-and-seed-locks

fix: fetch space roots in parallel and seed resources off the monitor

6637 of 12894 branches covered (51.47%)

Branch coverage included in aggregate %.

11456 of 19987 relevant lines covered (57.32%)

9.49 hits per line

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

79.89
src/main/java/com/knowledgepixels/nanodash/repository/SpaceRepository.java
1
package com.knowledgepixels.nanodash.repository;
2

3
import com.github.jsonldjava.shaded.com.google.common.collect.Ordering;
4
import com.knowledgepixels.nanodash.ApiCache;
5
import com.knowledgepixels.nanodash.QueryApiAccess;
6
import com.knowledgepixels.nanodash.Utils;
7
import com.knowledgepixels.nanodash.domain.Space;
8
import com.knowledgepixels.nanodash.domain.SpaceFactory;
9
import org.nanopub.Nanopub;
10
import org.nanopub.extra.services.ApiResponse;
11
import org.nanopub.extra.services.ApiResponseEntry;
12
import org.nanopub.extra.services.QueryRef;
13
import org.slf4j.Logger;
14
import org.slf4j.LoggerFactory;
15

16
import java.util.ArrayList;
17
import java.util.Collections;
18
import java.util.HashMap;
19
import java.util.HashSet;
20
import java.util.LinkedHashMap;
21
import java.util.LinkedHashSet;
22
import java.util.List;
23
import java.util.Map;
24
import java.util.Set;
25

26
/**
27
 * Repository class for managing Space instances, providing methods to refresh, retrieve, and query spaces based on API responses.
28
 */
29
public class SpaceRepository {
30

31
    private static final Logger logger = LoggerFactory.getLogger(SpaceRepository.class);
9 ✔
32

33
    private static final SpaceRepository INSTANCE = new SpaceRepository();
15 ✔
34

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

44
    private SpaceRepository() {
6 ✔
45
    }
3 ✔
46

47
    private static final class Snapshot {
48
        final Map<String, Space> spacesById;
49
        final Map<String, Space> spacesByAltId;
50
        final Map<Space, Set<Space>> subspaceMap;
51
        final Map<Space, Set<Space>> superspaceMap;
52

53
        Snapshot(Map<String, Space> byId,
54
                 Map<String, Space> byAltId,
55
                 Map<Space, Set<Space>> subspaces,
56
                 Map<Space, Set<Space>> superspaces) {
6 ✔
57
            this.spacesById = byId;
9 ✔
58
            this.spacesByAltId = byAltId;
9 ✔
59
            this.subspaceMap = subspaces;
9 ✔
60
            this.superspaceMap = superspaces;
9 ✔
61
        }
3 ✔
62

63
        static final Snapshot EMPTY = new Snapshot(
9 ✔
64
                Collections.emptyMap(), Collections.emptyMap(),
6 ✔
65
                Collections.emptyMap(), Collections.emptyMap());
12 ✔
66
    }
67

68
    // Source of truth is ApiCache (60s TTL on its own); we memoise the derived
69
    // maps keyed by the ApiResponse instance identity for get-spaces, and
70
    // re-resolve the sub-space link response on each rebuild.
71
    private volatile ApiResponse cachedFor;
72
    private volatile Snapshot snapshot = Snapshot.EMPTY;
9 ✔
73

74
    private Snapshot current() {
75
        ApiResponse resp = ApiCache.retrieveResponseIfAvailable(new QueryRef(QueryApiAccess.GET_SPACES_REF));
18 ✔
76
        if (resp == null) {
6 !
77
            return snapshot;
×
78
        }
79
        if (resp == cachedFor) {
12 ✔
80
            return snapshot;
9 ✔
81
        }
82
        synchronized (this) {
12 ✔
83
            if (resp == cachedFor) {
12 !
84
                return snapshot;
×
85
            }
86
            Snapshot built = build(resp);
12 ✔
87
            snapshot = built;
9 ✔
88
            cachedFor = resp;
9 ✔
89
            return built;
12 ✔
90
        }
91
    }
92

93
    /**
94
     * Reduce the {@code get-spaces} rows to one representative entry per space IRI and
95
     * collect the distinct ref roots seen for each IRI. Rows are expected in
96
     * {@code DESC(?date)} order.
97
     * <p>
98
     * The ref-aware query (v3) returns {@code ?ref} (the space ref = space IRI + root
99
     * definition) and {@code ?root} (the ref's root nanopub) per (ref, definition) row.
100
     * We dedup by ref (latest definition within a ref wins), then keep one representative
101
     * per IRI — the globally latest definition, preserving the pre-ref-aware behaviour —
102
     * and return the full set of ref roots per IRI for the (deferred) multi-ref
103
     * disambiguation UI. See docs/space-ref-identity.md.
104
     * <p>
105
     * When rows carry no {@code ?ref} (the pre-v3, IRI-keyed {@code get-spaces} query, e.g. a
106
     * server that has not ingested v3) this degrades to dedup-by-IRI exactly as before, with
107
     * empty ref-root sets.
108
     */
109
    static RefReduction reduceByRef(List<ApiResponseEntry> rows) {
110
        Set<String> seenRef = new HashSet<>();
12 ✔
111
        Map<String, Set<String>> refRootsByIri = new LinkedHashMap<>();
12 ✔
112
        Map<String, ApiResponseEntry> representativeByIri = new LinkedHashMap<>();
12 ✔
113
        for (ApiResponseEntry r : rows) {
30 ✔
114
            String spaceIri = r.get("space_iri");
12 ✔
115
            if (spaceIri == null || spaceIri.isEmpty()) continue;
18 !
116
            String ref = r.get("ref");
12 ✔
117
            // Dedup by ref when available, else by IRI (pre-v3 query).
118
            String refKey = (ref != null && !ref.isEmpty()) ? ref : spaceIri;
27 !
119
            if (!seenRef.add(refKey)) continue;
15 ✔
120
            String root = r.get("root");
12 ✔
121
            if (root != null && !root.isEmpty()) {
15 !
122
                refRootsByIri.computeIfAbsent(spaceIri, k -> new LinkedHashSet<>()).add(root);
36 ✔
123
            }
124
            // First surviving row per IRI = latest definition overall (rows are DESC(date)).
125
            representativeByIri.putIfAbsent(spaceIri, r);
15 ✔
126
        }
3 ✔
127
        return new RefReduction(new ArrayList<>(representativeByIri.values()), refRootsByIri);
30 ✔
128
    }
129

130
    /** Result of {@link #reduceByRef}: one representative row per IRI plus the ref roots per IRI. */
131
    static final class RefReduction {
132
        final List<ApiResponseEntry> representatives;
133
        final Map<String, Set<String>> refRootsByIri;
134

135
        RefReduction(List<ApiResponseEntry> representatives, Map<String, Set<String>> refRootsByIri) {
6 ✔
136
            this.representatives = representatives;
9 ✔
137
            this.refRootsByIri = refRootsByIri;
9 ✔
138
        }
3 ✔
139
    }
140

141
    /**
142
     * Build the space lookup maps from the spaces-repo response. Pulls the
143
     * latest non-invalidated SpaceDefinition per space ref from
144
     * {@code npa:spacesGraph} and joins to the declaring nanopub for label and
145
     * type, then keeps one representative space per IRI (see {@link #reduceByRef}).
146
     * Each space additionally carries the set of ref roots claiming its IRI for the
147
     * (deferred) multi-ref disambiguation UI.
148
     */
149
    private Snapshot build(ApiResponse resp) {
150
        Map<String, Space> byId = new HashMap<>();
12 ✔
151
        Map<String, Space> byAltId = new HashMap<>();
12 ✔
152
        Map<Space, Set<Space>> subspaceMap = new HashMap<>();
12 ✔
153
        Map<Space, Set<Space>> superspaceMap = new HashMap<>();
12 ✔
154
        List<Space> spaceList = new ArrayList<>();
12 ✔
155
        RefReduction reduction = reduceByRef(resp.getData());
12 ✔
156
        Map<String, Nanopub> rootNanopubs = fetchRootNanopubs(reduction.representatives);
12 ✔
157
        for (ApiResponseEntry r : reduction.representatives) {
33 ✔
158
            String spaceIri = r.get("space_iri");
12 ✔
159
            ApiResponseEntry entry = new ApiResponseEntry();
12 ✔
160
            entry.add("space", spaceIri);
12 ✔
161
            entry.add("np", r.get("np"));
18 ✔
162
            entry.add("label", r.get("space_iri_label"));
18 ✔
163
            entry.add("type", r.get("type"));
18 ✔
164
            String refRoot = r.get("root");
12 ✔
165
            if (refRoot != null && !refRoot.isEmpty()) entry.add("ref_root", refRoot);
27 !
166
            Space space = SpaceFactory.getOrCreate(entry, rootNanopubs.get(r.get("np")));
27 ✔
167
            space.setRefRoots(reduction.refRootsByIri.getOrDefault(spaceIri, Collections.emptySet()));
24 ✔
168
            spaceList.add(space);
12 ✔
169
            byId.put(space.getId(), space);
18 ✔
170
            for (String altId : space.getAltIDs()) {
33 ✔
171
                byAltId.put(altId, space);
15 ✔
172
            }
3 ✔
173
        }
3 ✔
174
        logger.info("Refreshed spaces from spaces repo: {} distinct spaces", spaceList.size());
18 ✔
175
        SpaceFactory.removeStale(byId.keySet());
9 ✔
176
        populateSubspaceRelations(byId, subspaceMap, superspaceMap);
12 ✔
177
        // Mark each space's per-space detail data stale; the upstream spaces
178
        // listing has refreshed, so members/admins/roles should be re-fetched
179
        // on next access.
180
        for (Space space : spaceList) {
30 ✔
181
            space.setDataNeedsUpdate();
6 ✔
182
        }
3 ✔
183
        return new Snapshot(byId, byAltId, subspaceMap, superspaceMap);
24 ✔
184
    }
185

186
    /**
187
     * Fetches the root nanopubs a build needs, several at a time. After a restart that is
188
     * one per space, a few hundred, and the build runs under the lock every lookup waits
189
     * for: fetched one by one, as each space used to fetch its own, they kept every page
190
     * waiting for minutes (issue #892). Later builds only need the nanopubs of new or
191
     * changed spaces.
192
     */
193
    private static Map<String, Nanopub> fetchRootNanopubs(List<ApiResponseEntry> rows) {
194
        List<String> needed = new ArrayList<>();
12 ✔
195
        for (ApiResponseEntry r : rows) {
30 ✔
196
            String np = r.get("np");
12 ✔
197
            if (np != null && SpaceFactory.needsRootNanopub(r.get("space_iri"), np)) needed.add(np);
36 !
198
        }
3 ✔
199
        if (needed.isEmpty()) return Collections.emptyMap();
15 ✔
200
        long start = System.currentTimeMillis();
6 ✔
201
        Map<String, Nanopub> fetched = Utils.getNanopubs(needed);
9 ✔
202
        logger.info("Fetched {} of {} space root nanopubs in {} ms",
24 ✔
203
                fetched.size(), needed.size(), System.currentTimeMillis() - start);
48 ✔
204
        return fetched;
6 ✔
205
    }
206

207
    /**
208
     * Invalidate the underlying ApiCache entries, optionally delaying the next refresh.
209
     *
210
     * @param waitMillis Delay in milliseconds before the next access may trigger a refresh; 0 for immediate.
211
     */
212
    public void forceRootRefresh(long waitMillis) {
213
        ApiCache.clearCache(new QueryRef(QueryApiAccess.GET_SPACES_REF), waitMillis);
×
214
        ApiCache.clearCache(new QueryRef(QueryApiAccess.GET_SUB_SPACE_LINKS), waitMillis);
×
215
    }
×
216

217
    /**
218
     * Get a space by its id.
219
     *
220
     * @param id The id of the space.
221
     * @return The corresponding Space object, or null if not found.
222
     */
223
    public Space findById(String id) {
224
        return current().spacesById.get(id);
21 ✔
225
    }
226

227
    /**
228
     * Get all known spaces, one representative per space IRI (see {@link #reduceByRef}).
229
     *
230
     * @return The list of spaces, in no particular order.
231
     */
232
    public List<Space> findAll() {
233
        return new ArrayList<>(current().spacesById.values());
24 ✔
234
    }
235

236
    /**
237
     * Get a space by one of its alternative IDs.
238
     *
239
     * @param altId The alternative ID of the space.
240
     * @return The corresponding Space object, or null if not found.
241
     */
242
    public Space findByAltId(String altId) {
243
        return current().spacesByAltId.get(altId);
21 ✔
244
    }
245

246
    /**
247
     * Get a space by its id, falling back to its alternative IDs. An IRI that a space declares
248
     * as an {@code owl:sameAs} alias of itself names that space here, which is what keeps a
249
     * reference to a space's former IRI working after it was renamed.
250
     *
251
     * @param id The id of the space, or one of its alternative IDs.
252
     * @return The corresponding Space object, or null if neither matches.
253
     */
254
    public Space findByIdOrAltId(String id) {
255
        Space space = findById(id);
12 ✔
256
        return space != null ? space : findByAltId(id);
24 ✔
257
    }
258

259
    /**
260
     * Get subspaces of a given space.
261
     *
262
     * @param space The space for which to find subspaces.
263
     * @return List of subspaces.
264
     */
265
    public List<Space> findSubspaces(Space space) {
266
        Set<Space> subspaces = current().subspaceMap.get(space);
×
267
        if (subspaces == null) return new ArrayList<>();
×
268
        List<Space> sorted = new ArrayList<>(subspaces);
×
269
        sorted.sort(Ordering.usingToString());
×
270
        return sorted;
×
271
    }
272

273
    /**
274
     * Get subspaces of a given space that match a specific type.
275
     *
276
     * @param space The space for which to find subspaces.
277
     * @param type  The type of subspaces to filter by.
278
     * @return List of subspaces matching the specified type.
279
     */
280
    public List<Space> findSubspaces(Space space, String type) {
281
        List<Space> l = new ArrayList<>();
×
282
        for (Space s : findSubspaces(space)) {
×
283
            if (s.getType().equals(type)) l.add(s);
×
284
        }
×
285
        return l;
×
286
    }
287

288
    /**
289
     * Get superspaces of this space.
290
     *
291
     * @return List of superspaces.
292
     */
293
    public List<Space> findSuperspaces(Space space) {
294
        Set<Space> superspaces = current().superspaceMap.get(space);
×
295
        if (superspaces == null) return new ArrayList<>();
×
296
        List<Space> sorted = new ArrayList<>(superspaces);
×
297
        sorted.sort(Ordering.usingToString());
×
298
        return sorted;
×
299
    }
300

301
    private static void populateSubspaceRelations(
302
            Map<String, Space> spacesById,
303
            Map<Space, Set<Space>> subspaceMap,
304
            Map<Space, Set<Space>> superspaceMap) {
305
        ApiResponse resp = ApiCache.retrieveResponseIfAvailable(new QueryRef(QueryApiAccess.GET_SUB_SPACE_LINKS));
18 ✔
306
        if (resp == null) return;
9 ✔
307
        for (ApiResponseEntry r : resp.getData()) {
33 ✔
308
            Space child = spacesById.get(r.get("child"));
21 ✔
309
            Space parent = spacesById.get(r.get("parent"));
21 ✔
310
            if (child == null || parent == null) continue;
12 !
311
            subspaceMap.computeIfAbsent(parent, k -> new HashSet<>()).add(child);
36 ✔
312
            superspaceMap.computeIfAbsent(child, k -> new HashSet<>()).add(parent);
36 ✔
313
        }
3 ✔
314
    }
3 ✔
315

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