• 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

30.22
src/main/java/com/knowledgepixels/nanodash/domain/AbstractResourceWithProfile.java
1
package com.knowledgepixels.nanodash.domain;
2

3
import com.google.common.collect.ArrayListMultimap;
4
import com.google.common.collect.Multimap;
5
import com.knowledgepixels.nanodash.ApiCache;
6
import com.knowledgepixels.nanodash.NanodashThreadPool;
7
import com.knowledgepixels.nanodash.QueryApiAccess;
8
import com.knowledgepixels.nanodash.View;
9
import com.knowledgepixels.nanodash.ViewDisplay;
10
import com.knowledgepixels.nanodash.repository.SpaceRepository;
11
import com.knowledgepixels.nanodash.vocabulary.KPXL_TERMS;
12
import org.apache.wicket.MetaDataKey;
13
import org.apache.wicket.request.cycle.RequestCycle;
14
import org.eclipse.rdf4j.model.IRI;
15
import org.eclipse.rdf4j.model.util.Values;
16
import org.nanopub.Nanopub;
17
import org.nanopub.extra.services.ApiResponse;
18
import org.nanopub.extra.services.ApiResponseEntry;
19
import org.nanopub.extra.services.QueryRef;
20
import org.slf4j.Logger;
21
import org.slf4j.LoggerFactory;
22

23
import java.io.Serializable;
24
import java.util.*;
25
import java.util.concurrent.CompletableFuture;
26
import java.util.concurrent.ConcurrentHashMap;
27
import java.util.concurrent.ExecutionException;
28
import java.util.concurrent.Future;
29
import java.util.concurrent.TimeUnit;
30
import java.util.concurrent.TimeoutException;
31

32
/**
33
 * Abstract class representing a resource with a profile in the Nanodash application.
34
 * This class provides common functionality for resources that have associated profiles, such as spaces and users.
35
 */
36
public abstract class AbstractResourceWithProfile implements Serializable, ResourceWithProfile {
37

38
    private static final Logger logger = LoggerFactory.getLogger(AbstractResourceWithProfile.class);
9 ✔
39

40
    private static final Map<Class<?>, Map<String, AbstractResourceWithProfile>> instances = new ConcurrentHashMap<>();
12 ✔
41

42
    // Backoff after a failed data update, so a persistently failing resource
43
    // doesn't respawn an update task on every page poll (~1/s per open page).
44
    private static final long FAILED_UPDATE_BACKOFF_MS = 10 * 1000;
45

46
    // How long after an update starts a page still waits for its seed from the cache (see
47
    // awaitSeed): ample for a seed from a warm cache, short enough not to tie up request
48
    // threads when the seed has to fetch.
49
    static final long SEED_WAIT_MS = 2000;
50

51
    private final String id;
52
    private Space space;
53
    // Volatile: replaced wholesale by the update task on a pool thread and read by the
54
    // request threads rendering (and polling for) the structure it holds.
55
    private volatile ResourceWithProfile data = new ResourceWithProfile();
15 ✔
56
    private volatile boolean dataInitialized = false;
9 ✔
57
    private volatile boolean dataNeedsUpdate = true;
9 ✔
58
    private volatile Long runUpdateAfter = null;
9 ✔
59
    // A refresh of this resource's own data (its view displays, i.e. the page structure)
60
    // requested after a publication, with the previously loaded structure kept on screen
61
    // meanwhile. Cleared once the refreshed data has landed. See forceRefresh.
62
    private volatile boolean structureRefreshPending = false;
9 ✔
63
    // The page-level "refresh now" asks not only for a refreshed structure but for the
64
    // views of that structure to be brought up to date with it. Kept apart from
65
    // forceRefresh, which a publication triggers too — there only the view that was acted
66
    // on is refreshed (issue #622). Taken away by the first view list built once the
67
    // refreshed structure has landed. See isViewRefreshDue.
68
    private volatile boolean viewRefreshRequested = false;
9 ✔
69
    // The same page-level "refresh now" also asks for the view definitions the refreshed
70
    // structure references to be re-checked, not only their results (issue #654): a
71
    // memoized resolution is otherwise only re-checked once a minute in the background, so
72
    // a view published a moment ago would keep rendering as its previous version. Read and
73
    // taken by the structure update itself, where going back to the API costs nobody's
74
    // request thread. See buildViewDisplays.
75
    private volatile boolean viewDefinitionRefreshRequested = false;
9 ✔
76

77
    // The seed step of the update last started, completed once that update has seeded the
78
    // data from the cache or found nothing to seed from, and the time until which pages
79
    // wait for it. See awaitSeed.
80
    private transient volatile CompletableFuture<Void> seedStep = null;
9 ✔
81
    private volatile long seedWaitUntil = 0;
9 ✔
82

83
    // Whether the view lists built during the current request are to refresh their views,
84
    // answered once per resource and remembered for the rest of the render so that several
85
    // view lists on one page all refresh together rather than the first one taking the
86
    // request away from the others.
87
    private static final MetaDataKey<HashMap<String, Boolean>> VIEW_REFRESH_DUE = new MetaDataKey<>() {
24 ✔
88
    };
89

90
    /**
91
     * Inner class to hold the data associated with a resource, including its view displays.
92
     */
93
    protected static class ResourceWithProfile implements Serializable {
6 ✔
94
        List<ViewDisplay> viewDisplays = new ArrayList<>();
18 ✔
95
        // The admin-declared profile picture (issue #632), fetched together with the view
96
        // displays so that rendering never waits on it and a publication's forced refresh
97
        // picks up a new picture along with the rest of the structure.
98
        ProfilePicture profilePicture;
99
    }
100

101
    /**
102
     * Checks if a resource with the given unique identifier exists in the system.
103
     *
104
     * @param id the unique identifier of the resource
105
     * @return true if a resource with the given id exists, false otherwise
106
     */
107
    public static boolean isResourceWithProfile(String id) {
108
        return get(id) != null;
×
109
    }
110

111
    /**
112
     * Retrieves an instance of AbstractResourceWithProfile by its unique identifier.
113
     *
114
     * @param id the unique identifier of the resource
115
     * @return the AbstractResourceWithProfile instance associated with the given id, or null if no such instance exists
116
     */
117
    public static AbstractResourceWithProfile get(String id) {
118
        for (Map<String, AbstractResourceWithProfile> map : instances.values()) {
33 ✔
119
            if (map.containsKey(id)) {
12 ✔
120
                return map.get(id);
15 ✔
121
            }
122
        }
3 ✔
123
        return null;
6 ✔
124
    }
125

126
    /**
127
     * Constructor for AbstractResourceWithProfile.
128
     *
129
     * @param id the unique identifier for this resource
130
     */
131
    protected AbstractResourceWithProfile(String id) {
6 ✔
132
        this.id = id;
9 ✔
133
        instances.computeIfAbsent(getClass(), k -> new ConcurrentHashMap<>()).put(id, this);
42 ✔
134
    }
3 ✔
135

136
    /**
137
     * Removes an instance of AbstractResourceWithProfile from the instances map based on its type and unique identifier.
138
     *
139
     * @param type the class type of the resource to remove
140
     * @param id   the unique identifier of the resource to remove
141
     */
142
    protected static void removeInstance(Class<?> type, String id) {
143
        Map<String, AbstractResourceWithProfile> map = instances.get(type);
15 ✔
144
        if (map != null) {
6 !
145
            map.remove(id);
12 ✔
146
        }
147
    }
3 ✔
148

149
    /**
150
     * Retrieves all instances of AbstractResourceWithProfile of a specific type.
151
     *
152
     * @param type the class type of the resources to retrieve
153
     * @return a map of resource IDs to AbstractResourceWithProfile instances of the specified type, or an empty map if no instances exist for that type
154
     */
155
    protected static Map<String, AbstractResourceWithProfile> getInstances(Class<?> type) {
156
        return instances.getOrDefault(type, Collections.emptyMap());
18 ✔
157
    }
158

159
    /**
160
     * Initializes the space for this resource.
161
     *
162
     * @param space the space to associate with this resource
163
     */
164
    protected void initSpace(Space space) {
165
        this.space = space;
9 ✔
166
        logger.info("Initialized space {} for resource {}", space.getId(), id);
21 ✔
167
    }
3 ✔
168

169
    @Override
170
    public String getId() {
171
        return id;
9 ✔
172
    }
173

174
    @Override
175
    public Future<?> triggerDataUpdate() {
176
        final boolean refreshViewDefinitions;
177
        final CompletableFuture<Void> seeded = new CompletableFuture<>();
12 ✔
178
        synchronized (this) {
12 ✔
179
            if (!dataNeedsUpdate) return null;
21 !
180
            // Not due yet (delayed forceRefresh or backoff after a failure): don't
181
            // occupy a pool thread with sleeping; a later access re-triggers.
182
            Long after = runUpdateAfter;
×
183
            if (after != null && System.currentTimeMillis() < after) {
×
184
                return null;
×
185
            }
186
            runUpdateAfter = null;
×
187
            logger.info("Data needs update for resource {}, starting update thread", id);
×
188
            dataNeedsUpdate = false;
×
189
            // Taken here rather than in the task, so that a request arriving while the
190
            // fetch runs is left standing for the next round instead of being answered by
191
            // a build that started before it.
192
            refreshViewDefinitions = viewDefinitionRefreshRequested;
×
193
            viewDefinitionRefreshRequested = false;
×
194
            seedStep = seeded;
×
195
            seedWaitUntil = System.currentTimeMillis() + SEED_WAIT_MS;
×
196
        }
×
197
        // Submitted outside the lock: a saturated pool runs the task on this very thread,
198
        // and the update must not hold the resource's monitor while it goes to the network,
199
        // or every request touching this resource waits for it (issue #892).
200
        return NanodashThreadPool.submit(() -> {
×
201
            try {
202
                ResourceWithProfile newData = new ResourceWithProfile();
×
203

204
                try {
205
                    seedFromCacheIfPossible();
×
206
                } finally {
207
                    seeded.complete(null);
×
208
                }
209
                // The query returns both standalone view displays (bound ?display) and
210
                // preset-supplied views (issue #302: unbound ?display, the assignment's
211
                // preset expanded into its views server-side), already ordered by date
212
                // (latest first) so the per-view-kind latest-wins / deactivation
213
                // aggregation in getViewDisplays() resolves overrides between presets and
214
                // standalone displays correctly, in either direction.
215
                newData.viewDisplays.addAll(buildViewDisplays(viewDisplaysQueryRef(), refreshViewDefinitions));
×
216
                newData.profilePicture = fetchProfilePicture();
×
217
                synchronized (this) {
×
218
                    data = newData;
×
219
                    dataInitialized = true;
×
220
                }
×
221
                // A forceRefresh that came in while this fetch was already running has
222
                // re-armed dataNeedsUpdate, so what just landed is not the refreshed
223
                // structure yet and the refresh stays pending for the next round.
224
                if (!dataNeedsUpdate) structureRefreshPending = false;
×
225
            } catch (Exception ex) {
×
226
                logger.error("Error while trying to update data for resource {}", id, ex);
×
227
                runUpdateAfter = System.currentTimeMillis() + FAILED_UPDATE_BACKOFF_MS;
×
228
                dataNeedsUpdate = true;
×
229
                // Nothing was rebuilt, so the request the retry is to honour is put back.
230
                if (refreshViewDefinitions) viewDefinitionRefreshRequested = true;
×
231
            }
×
232
        });
×
233
    }
234

235
    /**
236
     * The query for this resource's view displays. For a space, scoped to its
237
     * representative ref (root nanopub) so a multi-ref identifier doesn't merge displays
238
     * across rival definitions; other resource kinds (and spaces with no known ref root)
239
     * stay IRI-keyed.
240
     */
241
    private QueryRef viewDisplaysQueryRef() {
242
        String vdRefRoot = getViewDisplayRefRoot();
9 ✔
243
        return (vdRefRoot != null && !vdRefRoot.isEmpty())
9 !
244
                ? viewDisplaysRefQueryRef(vdRefRoot)
×
245
                : new QueryRef(QueryApiAccess.GET_VIEW_DISPLAYS, "resource", id);
21 ✔
246
    }
247

248
    /**
249
     * Initializes the resource data from whatever view-displays response the cache still
250
     * holds — typically the persisted snapshot right after a restart (issue #570) — so
251
     * pages gated on {@link #isDataInitialized()} render their content on the first
252
     * request instead of a loading spinner. The first step of the update task, which
253
     * {@link #isDataInitialized()} waits for briefly. The response comes from the cache,
254
     * but building the view displays out of it needs the display and view nanopubs, which
255
     * are fetched if the cache doesn't hold them, so this runs on the update task and never
256
     * under the resource's monitor: run by a request thread holding the monitor, it once
257
     * kept every other request for the home page waiting for its fetches (issue #892). Does
258
     * nothing on a genuinely cold cache, where the update's fetch remains the only path.
259
     * The seeded data doubles as the outage fallback should that fetch fail.
260
     */
261
    private void seedFromCacheIfPossible() {
262
        if (dataInitialized) return;
×
263
        // A pending delayed refresh (forceRefresh, e.g. just after publishing) must not be
264
        // masked by re-seeding the old state as initialized: there the page is meant to
265
        // wait for the fresh data. Seeding is for the never-initialized case, where
266
        // runUpdateAfter has not been set.
267
        if (runUpdateAfter != null) return;
×
268
        QueryRef vdQuery = viewDisplaysQueryRef();
×
269
        ApiResponse cachedResponse = ApiCache.retrieveStaleResponse(vdQuery);
×
270
        if (cachedResponse == null) return;
×
271
        ResourceWithProfile seeded = new ResourceWithProfile();
×
272
        seeded.viewDisplays.addAll(buildViewDisplays(cachedResponse, vdQuery));
×
273
        seeded.profilePicture = firstPicture(ApiCache.retrieveStaleResponse(profilePictureQueryRef()));
×
274
        synchronized (this) {
×
275
            // An update that finished meanwhile has brought fresher data than this.
276
            if (dataInitialized) return;
×
277
            data = seeded;
×
278
            dataInitialized = true;
×
279
        }
×
280
    }
×
281

282
    /**
283
     * Waits for the running update to have seeded this resource from the cache, but no
284
     * longer than {@link #SEED_WAIT_MS} after the update started. A seed from a warm cache
285
     * is quick, and waiting for it lets the first render after a restart show the content;
286
     * a seed that has to fetch takes longer, and a page then shows its loading state and
287
     * polls rather than holding a request thread. The time limit is counted from the start
288
     * of the update rather than per call, so polls don't each wait again.
289
     */
290
    private void awaitSeed() {
291
        CompletableFuture<Void> step = seedStep;
9 ✔
292
        if (step == null || step.isDone()) return;
15 !
293
        long wait = seedWaitUntil - System.currentTimeMillis();
15 ✔
294
        if (wait <= 0) return;
15 ✔
295
        try {
296
            step.get(wait, TimeUnit.MILLISECONDS);
15 ✔
297
        } catch (InterruptedException ex) {
×
298
            Thread.currentThread().interrupt();
×
299
        } catch (ExecutionException | TimeoutException ex) {
3 ✔
300
            // Not seeded in time: the page shows its loading state.
301
        }
3 ✔
302
    }
3 ✔
303

304
    /**
305
     * Forces a refresh of the resource data after a specified delay.
306
     * <p>
307
     * A structure that is already loaded is <b>kept</b>: the pages go on rendering it and
308
     * swap in the rebuilt one once the refreshed data lands (see
309
     * {@link com.knowledgepixels.nanodash.component.RefreshingStructurePanel}), rather
310
     * than blanking out into a loading spinner for the whole ingest delay. Blanking out
311
     * would also throw away the in-place refresh of the individual view the user just
312
     * published from (issue #622), since the view panels would be rebuilt cold. Only an
313
     * empty structure is invalidated outright, as there is nothing on screen to keep and
314
     * the pages' lazy path is what makes a first view display appear.
315
     *
316
     * @param waitMillis the delay in milliseconds before the data refresh is triggered
317
     */
318
    public void forceRefresh(long waitMillis) {
319
        logger.info("Forcing refresh of resource {} after {} ms", id, waitMillis);
21 ✔
320
        dataNeedsUpdate = true;
9 ✔
321
        // Mark the view-display query itself as outdated, the way every other refresh does
322
        // (see ApiCache.clearCache). Without it, a forced fetch that finds a refresh of the
323
        // same query already in flight settles for whatever that one leaves behind — a
324
        // response fetched before this refresh was asked for, so the structure would come
325
        // back unchanged even though it was re-fetched.
326
        ApiCache.clearCache(viewDisplaysQueryRef(), waitMillis);
12 ✔
327
        if (dataInitialized && !data.viewDisplays.isEmpty()) {
24 !
328
            structureRefreshPending = true;
12 ✔
329
        } else {
330
            dataInitialized = false;
9 ✔
331
        }
332
        runUpdateAfter = System.currentTimeMillis() + waitMillis;
18 ✔
333
    }
3 ✔
334

335
    /**
336
     * Whether a {@link #forceRefresh} of this resource's structure is still in flight while
337
     * the previously loaded structure stays on screen. Triggers the pending update, so that
338
     * polling this also drives it (once its delay has passed).
339
     *
340
     * @return true while the refreshed structure has not landed yet
341
     */
342
    public boolean isStructureRefreshPending() {
343
        if (!structureRefreshPending) return false;
15 ✔
344
        triggerDataUpdate();
9 ✔
345
        return structureRefreshPending;
9 ✔
346
    }
347

348
    /**
349
     * Asks for the views of this resource's structure to be brought up to date along with
350
     * the structure itself — the page-level "refresh now", which refreshes the list of view
351
     * displays first and then the views that list turns out to contain. The request is
352
     * honoured by the first view list built once the refreshed structure has landed (see
353
     * {@link #isViewRefreshDue(boolean)}), so it is the refreshed list that gets refreshed, not
354
     * the one that happened to be on screen when the user clicked.
355
     * <p>
356
     * "Up to date" covers each view's definition as well as its results: the structure
357
     * update re-resolves the referenced views instead of trusting the memoized resolution,
358
     * so a view definition superseded a moment ago is picked up by this refresh rather than
359
     * by whichever one happens to follow it (issue #654).
360
     */
361
    public void requestViewRefresh() {
362
        viewRefreshRequested = true;
9 ✔
363
        requestViewDefinitionRefresh();
6 ✔
364
    }
3 ✔
365

366
    /**
367
     * Asks for the view definitions this resource's structure references to be re-resolved
368
     * when it is next rebuilt, without asking for the views' results to be refreshed along
369
     * with them. What a publication needs: the nanopub just published may be a new version
370
     * of a view shown here, and the resolution that would otherwise be reused is memoized
371
     * (issue #654). Refreshing every view's results on top of that is what issue #622 took
372
     * away, so it stays away — only the view that was acted on is refreshed there.
373
     */
374
    public void requestViewDefinitionRefresh() {
375
        viewDefinitionRefreshRequested = true;
9 ✔
376
    }
3 ✔
377

378
    /**
379
     * Whether a {@link #requestViewRefresh()} is still waiting to be honoured. Read by
380
     * {@link com.knowledgepixels.nanodash.component.RefreshingStructurePanel}, which has to
381
     * rebuild its content for the request to reach the views even when the refreshed
382
     * structure turned out to be the same one.
383
     *
384
     * @return true while the views have not been refreshed yet
385
     */
386
    public boolean isViewRefreshRequested() {
387
        return viewRefreshRequested;
9 ✔
388
    }
389

390
    /**
391
     * Whether the view lists built for this resource in the current request are to refresh
392
     * their views, i.e. a {@link #requestViewRefresh()} is pending and the list being built
393
     * is the refreshed one. Takes the request away, but answers the same for every view
394
     * list of the same render, so that several lists on one page refresh together.
395
     *
396
     * @param waitsForStructure whether the list being built takes its view displays from
397
     *                          this resource's asynchronously refreshed structure, as
398
     *                          opposed to carrying its own (a {@code ?root=}-pinned space
399
     *                          page fetches them itself, and so has nothing to wait for)
400
     * @return true if this render's views are to be brought up to date
401
     */
402
    public boolean isViewRefreshDue(boolean waitsForStructure) {
403
        // Off a request thread there is nothing to remember the answer in; the request is
404
        // then simply taken by the caller.
405
        HashMap<String, Boolean> answered = null;
6 ✔
406
        RequestCycle requestCycle = RequestCycle.get();
6 ✔
407
        if (requestCycle != null) {
6 !
408
            answered = requestCycle.getMetaData(VIEW_REFRESH_DUE);
×
409
            if (answered == null) {
×
410
                answered = new HashMap<>();
×
411
                requestCycle.setMetaData(VIEW_REFRESH_DUE, answered);
×
412
            }
413
            Boolean known = answered.get(id);
×
414
            if (known != null) return known;
×
415
        }
416
        // Still waiting for the refreshed structure: the views to refresh are the ones that
417
        // list will contain, so the request is left standing for the render that follows it.
418
        boolean due = viewRefreshRequested && !(waitsForStructure && structureRefreshPending);
36 ✔
419
        if (due) viewRefreshRequested = false;
15 ✔
420
        if (answered != null) answered.put(id, due);
6 !
421
        return due;
6 ✔
422
    }
423

424
    /**
425
     * A fingerprint of the resource's view-display structure, to tell a refresh that
426
     * changed the page structure from one that left it as it was.
427
     *
428
     * @return the fingerprint of the current structure
429
     */
430
    public String getStructureSignature() {
431
        StringBuilder sb = new StringBuilder();
12 ✔
432
        for (ViewDisplay vd : data.viewDisplays) {
36 ✔
433
            // Both the referenced view and the version it resolved to: a new version of a
434
            // view the displays already reference leaves the reference as it was, and the
435
            // page would go on showing the previous definition if that were all we compared.
436
            sb.append(vd.getNanopubId()).append('\t')
21 ✔
437
                    .append(vd.getViewIri()).append('\t')
12 ✔
438
                    .append(vd.getView() == null ? "" : vd.getView().getId()).append('\t')
27 !
439
                    .append(vd.getStructuralPosition()).append('\n');
15 ✔
440
        }
3 ✔
441
        return sb.toString();
9 ✔
442
    }
443

444
    /**
445
     * Static method to force a refresh of the resource data for all instances of AbstractResourceWithProfile.
446
     */
447
    public static void refresh() {
448
        instances.values().forEach(map -> map.values().forEach(AbstractResourceWithProfile::setDataNeedsUpdate));
×
449
    }
×
450

451
    @Override
452
    public Long getRunUpdateAfter() {
453
        return runUpdateAfter;
9 ✔
454
    }
455

456
    @Override
457
    public Space getSpace() {
458
        return space;
×
459
    }
460

461
    @Override
462
    public abstract String getNanopubId();
463

464
    @Override
465
    public abstract Nanopub getNanopub();
466

467
    public abstract String getNamespace();
468

469
    @Override
470
    public void setDataNeedsUpdate() {
471
        dataNeedsUpdate = true;
9 ✔
472
    }
3 ✔
473

474
    @Override
475
    public boolean isDataInitialized() {
476
        triggerDataUpdate();
9 ✔
477
        // Waiting briefly for the update's seed is what lets the FIRST render of a page
478
        // reach this resource's content: the update runs asynchronously, so without it that
479
        // render would fall back to a loading spinner even though everything it needs is in
480
        // the (restored) cache.
481
        if (!dataInitialized) awaitSeed();
15 !
482
        return dataInitialized;
9 ✔
483
    }
484

485
    @Override
486
    public List<ViewDisplay> getViewDisplays() {
487
        logger.info("Getting view displays for resource {}", id);
×
488
        return data.viewDisplays;
×
489
    }
490

491
    @Override
492
    public List<ViewDisplay> getTopLevelViewDisplays() {
493
        // Pass the resource's own type(s) so that views targeting that type (e.g. a
494
        // messages view for gen:MaintainedResource) are shown at the top level, while
495
        // views targeting part types (e.g. gen:hasViewTargetClass owl:Class) are not.
496
        return getViewDisplays(true, getId(), getOwnClasses());
×
497
    }
498

499
    /**
500
     * The resource's own type IRI(s), used to match top-level views by
501
     * {@code gen:appliesToInstancesOf}. Empty by default; overridden per resource type.
502
     *
503
     * @return the resource's own classes (never null)
504
     */
505
    protected Set<IRI> getOwnClasses() {
506
        return Collections.emptySet();
×
507
    }
508

509
    @Override
510
    public List<ViewDisplay> getPartLevelViewDisplays(String resourceId, Set<IRI> classes) {
511
        return getViewDisplays(false, resourceId, classes);
×
512
    }
513

514
    private List<ViewDisplay> getViewDisplays(boolean toplevel, String resourceId, Set<IRI> classes) {
515
        triggerDataUpdate();
×
516
        return filterViewDisplays(getViewDisplays(), toplevel, resourceId, classes);
×
517
    }
518

519
    /**
520
     * Top-level view displays scoped to a specific space ref (root nanopub), fetched on demand
521
     * rather than from the IRI-keyed singleton data — used to render the Content tab of a
522
     * {@code ?root=}-pinned space page so it shows only that ref's displays. Falls back to the
523
     * default (singleton) displays when {@code refRoot} is null/empty. See docs/space-ref-identity.md.
524
     *
525
     * @param refRoot the ref's root nanopub, or null/empty for the default
526
     * @return the ref-scoped top-level view displays
527
     */
528
    public List<ViewDisplay> getTopLevelViewDisplays(String refRoot) {
529
        if (refRoot == null || refRoot.isEmpty()) return getTopLevelViewDisplays();
×
530
        return filterViewDisplays(buildViewDisplays(viewDisplaysRefQueryRef(refRoot)), true, getId(), getOwnClasses());
×
531
    }
532

533
    private List<ViewDisplay> filterViewDisplays(List<ViewDisplay> source, boolean toplevel, String resourceId, Set<IRI> classes) {
534
        List<ViewDisplay> viewDisplays = new ArrayList<>();
×
535
        Set<IRI> viewKinds = new HashSet<>();
×
536

537
        // Results are sorted by date (most recent first); only the most recent per view-kind is considered
538
        for (ViewDisplay vd : source) {
×
539
            IRI kind = vd.getViewKindIri();
×
540
            if (kind != null) {
×
541
                if (viewKinds.contains(kind)) {
×
542
                    continue;
×
543
                }
544
                viewKinds.add(kind);
×
545
            }
546

547
            if (vd.hasType(KPXL_TERMS.DEACTIVATED_VIEW_DISPLAY)) {
×
548
                continue;
×
549
            }
550

551
            if (!toplevel && vd.hasType(KPXL_TERMS.TOP_LEVEL_VIEW_DISPLAY)) {
×
552
                // Deprecated
553
                // do nothing
554
            } else if (vd.appliesTo(resourceId, classes)) {
×
555
                viewDisplays.add(vd);
×
556
            } else if (toplevel && vd.hasType(KPXL_TERMS.TOP_LEVEL_VIEW_DISPLAY)) {
×
557
                // Deprecated
558
                viewDisplays.add(vd);
×
559
            }
560
        }
×
561

562
        Collections.sort(viewDisplays);
×
563
        return viewDisplays;
×
564
    }
565

566
    /**
567
     * Fetches the applicable view displays synchronously from the API, bypassing the async
568
     * singleton data. Used by the download pages, which need the displays within the current
569
     * request; the resolution mirrors the page rendering (ref-scoped query for spaces,
570
     * preset-supplied views, per-view-kind latest-wins).
571
     *
572
     * @param partId      the part IRI, or null for the resource's top-level displays
573
     * @param partClasses the part's classes (ignored for top-level, where the resource's
574
     *                    own classes are used)
575
     * @return the applicable view displays, sorted by structural position
576
     */
577
    public List<ViewDisplay> fetchViewDisplaysSync(String partId, Set<IRI> partClasses) {
578
        String vdRefRoot = getViewDisplayRefRoot();
×
579
        QueryRef vdQuery = (vdRefRoot != null && !vdRefRoot.isEmpty())
×
580
                ? viewDisplaysRefQueryRef(vdRefRoot)
×
581
                : new QueryRef(QueryApiAccess.GET_VIEW_DISPLAYS, "resource", id);
×
582
        boolean toplevel = (partId == null);
×
583
        return filterViewDisplays(buildViewDisplays(vdQuery), toplevel,
×
584
                toplevel ? getId() : partId, toplevel ? getOwnClasses() : partClasses);
×
585
    }
586

587
    /**
588
     * Builds {@link ViewDisplay} objects from a get-view-displays(-ref) query result (standalone
589
     * displays with a bound {@code ?display}, and preset-supplied views with an unbound one).
590
     */
591
    private List<ViewDisplay> buildViewDisplays(QueryRef ref) {
592
        return buildViewDisplays(ref, false);
×
593
    }
594

595
    /**
596
     * @param refreshViewDefinitions whether to go back to the API for each referenced view's
597
     *                               latest version instead of trusting what is memoized —
598
     *                               what a page-level "refresh now" asks for (issue #654).
599
     *                               Only ever true on the update thread, as the lookups block.
600
     */
601
    private List<ViewDisplay> buildViewDisplays(QueryRef ref, boolean refreshViewDefinitions) {
602
        // Null on a cold cache or a failed (flaky federated) fetch — yields nothing for now;
603
        // the cache refreshes asynchronously and the page's auto-refresh repopulates it.
604
        return buildViewDisplays(ApiCache.retrieveResponseSync(ref, true), ref, refreshViewDefinitions);
×
605
    }
606

607
    private List<ViewDisplay> buildViewDisplays(ApiResponse response, QueryRef ref) {
608
        return buildViewDisplays(response, ref, false);
×
609
    }
610

611
    private List<ViewDisplay> buildViewDisplays(ApiResponse response, QueryRef ref, boolean refreshViewDefinitions) {
612
        if (refreshViewDefinitions) {
×
613
            // Every view this build resolves goes back to the API rather than to the memo.
614
            // Done around the whole build rather than per row: which id a display's view is
615
            // resolved by is up to the display nanopub (the referenced version) and the
616
            // query variant (the server-resolved one), and the scope catches either.
617
            return View.withFreshResolution(() -> buildViewDisplays(response, ref, false));
×
618
        }
619
        List<ViewDisplay> list = new ArrayList<>();
×
620
        if (response == null) return list;
×
621
        // The unresolved query variant returns ?view as the referenced version, leaving
622
        // latest-version resolution to us (View.get with resolveLatest=true, memoized;
623
        // it also covers space-governed pins); the older resolved heads return ?view
624
        // already latest-resolved server-side, so it is passed through as-is.
625
        boolean viewsPreResolved = !QueryApiAccess.GET_VIEW_DISPLAYS_UNRESOLVED.equals(ref.getQueryId());
×
626
        // A preset assignment is identified by the preset's stable kind and the resource
627
        // (issue #607), just as a view display is by view kind and resource. The rows come
628
        // newest first, so the first assignment nanopub seen for a preset kind is the one
629
        // that counts; rows from any older assignment of the same kind are dropped, and a
630
        // view that a newer preset version no longer carries goes away with them. Queries
631
        // that don't return the column (an older head) leave every row in place.
632
        Map<String, String> winningPresetNp = new HashMap<>();
×
633
        for (ApiResponseEntry r : response.getData()) {
×
634
            try {
635
                String view = r.get("view");
×
636
                String display = r.get("display");
×
637
                if (display != null && !display.isEmpty()) {
×
638
                    list.add(ViewDisplay.get(display, viewsPreResolved ? view : null));
×
639
                } else {
640
                    if (view == null || view.isEmpty()) continue;
×
641
                    String presetKind = r.get("presetKind");
×
642
                    if (presetKind != null && !presetKind.isEmpty()) {
×
643
                        String np = r.get("np");
×
644
                        String winner = winningPresetNp.computeIfAbsent(presetKind, k -> np);
×
645
                        if (winner != null && !winner.equals(np)) continue;
×
646
                    }
647
                    boolean topLevel = KPXL_TERMS.TOP_LEVEL_VIEW_DISPLAY.stringValue().equals(r.get("displayType"));
×
648
                    boolean deactivated = KPXL_TERMS.DEACTIVATED_PRESET_ASSIGNMENT.stringValue().equals(r.get("displayMode"));
×
649
                    ViewDisplay vd = ViewDisplay.forPresetView(id, view, topLevel, deactivated, !viewsPreResolved);
×
650
                    if (vd != null) list.add(vd);
×
651
                }
652
            } catch (IllegalArgumentException ex) {
×
653
                logger.error("Couldn't generate view display object", ex);
×
654
            }
×
655
        }
×
656
        return list;
×
657
    }
658

659
    private QueryRef viewDisplaysRefQueryRef(String refRoot) {
660
        Multimap<String, String> params = ArrayListMultimap.create();
×
661
        params.put("resource", id);
×
662
        params.put("root_np", refRoot);
×
663
        return new QueryRef(QueryApiAccess.GET_VIEW_DISPLAYS_UNRESOLVED, params);
×
664
    }
665

666
    /**
667
     * The root nanopub of the space ref the resource's view displays should be scoped to, or null
668
     * to use the IRI-keyed query (merged across refs). Null by default; {@link Space} overrides it
669
     * to its representative ref so a multi-ref identifier doesn't merge Content-tab displays.
670
     *
671
     * @return the ref's root nanopub, or null
672
     */
673
    protected String getViewDisplayRefRoot() {
674
        return null;
6 ✔
675
    }
676

677
    /**
678
     * The profile picture of this resource, declared as {@code schema:image} with the
679
     * resource IRI as subject (issue #632). Only declarations signed by a current admin of
680
     * the governing space count — a space's picture is not something an unrelated agent can
681
     * set, unlike a user's self-declared one (see
682
     * {@link QueryApiAccess#GET_RESOURCE_PROFILE_PICTURE}). Read from the asynchronously
683
     * updated data, so this never blocks the render; a resource without a declared picture
684
     * simply shows none (there is no fallback icon).
685
     *
686
     * @return the picture, or null if none is declared
687
     */
688
    public ProfilePicture getProfilePicture() {
689
        triggerDataUpdate();
×
690
        return data.profilePicture;
×
691
    }
692

693
    private QueryRef profilePictureQueryRef() {
694
        return new QueryRef(QueryApiAccess.GET_RESOURCE_PROFILE_PICTURE, "resource", id);
×
695
    }
696

697
    private ProfilePicture fetchProfilePicture() {
698
        return firstPicture(ApiCache.retrieveResponseSync(profilePictureQueryRef(), true));
×
699
    }
700

701
    /**
702
     * The newest usable picture of a get-resource-profile-picture response (the query orders
703
     * newest first), skipping values that are neither an image link nor usable SVG markup —
704
     * the declaring triple is unconstrained, so anything can turn up there.
705
     */
706
    private ProfilePicture firstPicture(ApiResponse response) {
707
        if (response == null) return null;
×
708
        for (ApiResponseEntry r : response.getData()) {
×
709
            ProfilePicture picture = ProfilePicture.of(r.get("imageUrl"));
×
710
            if (picture != null) return picture;
×
711
            String value = r.get("imageUrl");
×
712
            if (value != null && !value.isEmpty()) {
×
713
                logger.warn("Ignoring unusable profile picture value for resource {}", id);
×
714
            }
715
        }
×
716
        return null;
×
717
    }
718

719
    @Override
720
    public abstract String getLabel();
721

722
    @Override
723
    public String toString() {
724
        return id;
×
725
    }
726

727
    /**
728
     * Gets the chain of superspaces from the current space up to the root space.
729
     *
730
     * @return the list of superspaces from the given space to the root space
731
     */
732
    @Override
733
    public List<AbstractResourceWithProfile> getAllSuperSpacesUntilRoot() {
734
        List<AbstractResourceWithProfile> chain = new ArrayList<>();
×
735
        Set<String> visited = new HashSet<>();
×
736
        collectAncestors(space, chain, visited);
×
737
        Collections.reverse(chain);
×
738
        return chain;
×
739
    }
740

741
    private void collectAncestors(Space current, List<AbstractResourceWithProfile> chain, Set<String> visited) {
742
        if (current == null) {
×
743
            return;
×
744
        }
745
        List<Space> parents = SpaceRepository.get().findSuperspaces(current);
×
746
        if (parents == null || parents.isEmpty()) {
×
747
            return;
×
748
        }
749
        Space parent = parents.getFirst();
×
750
        if (parent == null) {
×
751
            return;
×
752
        }
753
        String pid = parent.getId();
×
754
        if (pid == null || !visited.add(pid)) {
×
755
            return;
×
756
        }
757
        chain.add(parent);
×
758
        collectAncestors(parent, chain, visited);
×
759
    }
×
760

761
    /**
762
     * Checks if any view display of this resource applies to the given element ID and set of classes by triggering a data update and checking each view display for applicability.
763
     *
764
     * @param elementId the ID of the element to check for applicability
765
     * @param classes   the set of classes to check for applicability
766
     * @return true if any view display of this resource applies to the given element ID and set of classes, false otherwise
767
     */
768
    /**
769
     * Whether any view display of this resource is about the given element <em>specifically</em>:
770
     * one the element's part page would render that does not equally apply to this resource
771
     * itself.
772
     * <p>
773
     * The distinction is what tells a space that keeps pages about its people from one that
774
     * merely owns a view they also match. A conference declares a view
775
     * {@code gen:appliesToInstancesOf gen:IndividualAgent} -- a person's role, the talks they
776
     * are giving -- and that view is about people and nothing else. A pinned-resources list
777
     * declares {@code gen:IndividualAgent, gen:MaintainedResource, gen:Space} and is shown on
778
     * the space's own page: it fits a person, but it is not a reason to give every person in
779
     * that space a page of their own (issue #822).
780
     * <p>
781
     * Asked of the displays the part page would actually render, so a deactivated display, or
782
     * one superseded by a newer of the same kind, does not keep a page alive.
783
     *
784
     * @param partId  the id of the element the page would be about
785
     * @param classes the classes it is known to have
786
     * @return true if some display is about it rather than merely fitting it
787
     */
788
    public boolean hasPartSpecificDisplay(String partId, Set<IRI> classes) {
789
        for (ViewDisplay v : getPartLevelViewDisplays(partId, classes)) {
39 ✔
790
            if (!v.appliesTo(getId(), getOwnClasses())) return true;
27 ✔
791
        }
3 ✔
792
        return false;
6 ✔
793
    }
794

795
    public boolean appliesTo(String elementId, Set<IRI> classes) {
796
        triggerDataUpdate();
×
797
        for (ViewDisplay v : getViewDisplays()) {
×
798
            if (v.appliesTo(elementId, classes)) {
×
799
                return true;
×
800
            }
801
        }
×
802
        return false;
×
803
    }
804

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