Repository navigation
Batch anonymous authorization checks per object - #6257
Conversation
An anonymous item render fires ~15 per-feature authorization checks, about ten of which ask about admin/edit/login-only capabilities an unauthenticated visitor can never hold. AuthorizationDataService.isAuthorized now answers false locally, without a REST call, for those features when no one is logged in, and waits for isAuthenticationLoaded() before deciding so authenticated users are never transiently treated as anonymous. Measured on a local DSpace 11 stack with OpenTelemetry tracing: an anonymous item render drops from 42 to 31 backend calls (15 to 5 authorization checks) and single-core SSR render throughput rises ~45%. Refs DSpace#6256, DSpace#3161 Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
|
Hi @bram-atmire, thanks for the PR! Would you be able to add the complete PR checklist to the description? Also you may have already seen, but this is currently running into a few errors in the CI (looks like just linting). |
|
This is a big step towards a good idea. Cutting waste on anonymous traffic-the largest load contributor-feels like exactly the right place to optimize After checking the code, I have a tiiiny comment regarding the open design question you asked:
Personally, I lean toward the backend-first approach rather than frontend changes. Genuine question, did you already consider defining the whitelist directly in the backend instead of the frontend? This is my "open design question for open design question", but how would you feel about this alternative:
Does that make sense? My reasoning for the backend-first approach is that:
Happy to see this moving. Overall, great work (on all your PRs lately)! |
|
@MMilosz, thank you for the review & feedback!! I agree that the backend should own the permission decisions. I removed the hardcoded frontend list. Your distinction between authentication, policy and configuration was important: QA/COAR can be enabled anonymously, and some edit/manage features can be granted through Anonymous resource policies. The companion backend PR, DSpace/DSpace#13134, adds a default-false For the HTTP request reduction, I switched Angular to the existing all-features object search. A conservative authentication-only list plus a catalogue fetch gave no net request saving on the tested item page. The revised batching shares one lookup per object and selects each feature from the grants returned by the backend. It follows pagination, uses the existing request cache/invalidation, and falls back to individual checks if a batch fails. Logged-in and explicit-EPerson checks retain their original path. No new public metadata endpoint/property is needed. The updated production SSR measurements are 14 → 2 authorization requests and 39 → 27 total API calls, consistent across 22 renders per variant. All 14 decisions matched the individual requests, and both HTML and HTTP COAR inbox links were preserved. Browser navigation required one authorization GET for a new item and none when returning to the cached item. I replaced the earlier performance claims; the timing sample does not establish a reliable throughput gain. @lgeggleston, the complete PR checklist and updated validation/reviewer instructions are now in the description. The original import-order lint issue is fixed. Local selected tests and production builds passed; the standard lint/circular checks still report generated-registry issues as documented in the description, and CI for this revision is pending. |
|
I did a performance test on this PR and it showed a response time increase of about 100 - 150ms per item page load. This was tested on an item with 50 bitstreams per page, 100 iterations per test, multiple test runs. The performance degradation was unexpected. I'd say it is not a blocker per se for merging this, but nevertheless worth looking into where the performance degradation stems from. I did not use the Backend PR in the testing. Is this now necessary? The instructions for reviewers were not so clear on that. |
Thank you for the testing!! Any clue where the extra 100-150ms per page load is coming from. E.g which requests are slower?
Personally I would consider performance degradation a blocker. No point in merging something intended to make performance better if in fact, it makes it worse.
Not necessary, but with the back end companion PR in place it should be faster. |
|
@bram-atmire thanks for appreciating the tests! I ran some more to verify my findings from yesterday. Unfortunately I was able to reproduce them in a slightly different test setting again. Yesterday I only tested the SSR performance, today I tested the whole CSR and used largest contentful paint (LCP) as the measurement value. The results are as follows:
From looking at the code, I don't believe single REST calls are suddenly slower. It is more likely that the new logic that was introduced takes longer to compute. Yesterday I debugged it a bit and tried to fix it with the help of an LLM (since I am not fluent in Typescript and Angular) and I would say one problem could be testing if It is also possible that my test setup does not profit from the code optimizations, since each test run is isolated from each other. I understood the reviewer instructions above that only the second request to any item benefits from the performance optimization. Btw, what does "enable I am still not entirely sure what the code in this PR here does. I thought we might be able to perform just one authorization check per item page, find out that the user is not logged in (= anonymous user), and then not trigger any more authorization checks on features that require a log in. If we trigger less requests in that case, my tests should be able to verify the performance optimization, like with the changes and tests I did earlier this year. But I guess it is not so easy unfortunately. |
|
@tinsch I've been able to replicate similar findings in load tests. I'm looking for the root cause & remediation now. |
|
@tinsch I think I got it & that it's resolved now. Would highly appreciate if you could test the latest code on the branch to see if you can confirm the same. Benchmark follow-up: avoid repeated anonymous feature scansCode inspection confirmed that the batch endpoint request was reused by the request cache, but each anonymous A focused matched SSR run on This supports the repeated Angular-side processing hypothesis and shows a substantial improvement for this SSR fixture. It is a targeted SSR result; browser/CSR and concurrency runs have not yet been repeated for the optimized build. The earlier broader run showed public SSR, browser LCP, and CSR slower on the original PR than main despite fewer API calls, which motivated this follow-up. |
|
Thanks @bram-atmire for looking into it! I can confirm that the changes fixed the performance outcome. My CSR-tests show a drop from 2147.44ms on main to 1825.64ms with the PR applied. Well done 👏 Just one small thing: Could you fix the linting errors? |
The spec relied on the real AuthorizationDataService being created for FileDownloadLinkComponent. Now that the service depends on AuthService, that construction fails with a missing AuthRequestService provider, which the test runner also reports as a circular dependency. Provide the existing stub, as other component specs do. Assisted-by: Claude Code [claude-opus-5-5]
|
Thanks for testing and measuring this, @tinsch! The lint errors were fixed on 10-05, which then exposed a unit test failure: This comment was drafted with the help of Claude Code (AI); I reviewed it before posting. |
|
@tdonohue I cannot do a code review on this one, all I could do is run the performance tests again (which I think is not necessary, given the recent changes where only test adjustments and linting fixes). I am just not fluent enough in Typescript and Angular to do a full code review. |
|
@tinsch : My apologies, I wasn't attempting to request a code review from you. I just saw that you'd given feedback and that feedback was addressed. So, I was pinging you to see if you wanted to re-test to potentially give it a +1. Unfortunately, GitHub doesn't have a way to separate out testers from code reviewers (they are all together in the "Reviewers" list). So, when I clicked to have you re-review, I was just asking for a re-test or simply verifying your feedback has been addressed. :) In general, if I request a re-review, you are welcome to consider that just a request to either re-test or re-review code (the choice is yours, based on what you have time for or feel comfortable with). |
artlowel
left a comment
There was a problem hiding this comment.
Thanks @bram-atmire, I think it's a good idea!
I just have a few inline comments
Remove the per-object feature ID memo. The request cache already deduplicates the identical unfiltered searches, and the memo's own expiry did not follow request-cache invalidation. Move pagination into findAllAuthorizationsForObject and handle every failure with a single fallback to the individual feature check. Resolving the feature links no longer waits for a successful response: a failed feature link now errors, triggering that fallback instead of leaving the check pending. Assisted-by: Claude Code [claude-opus-5-5]
|
@tdonohue would you be able/willing to merge based on the current state (Atmire contributed, Atmire reviewed) or do you prefer to seek another reviewer? |
|
Hi @bram-atmire , many thanks for your work on this, I also gave a look and tested your implementation and it looks great! I am also a +1 on this one |
|
Thanks @bram-atmire ! Because this is a performance-related fix, I'm going to flag this for auto-backport to 10.x and 9.x. I'm not entirely sure whether that auto-backport will succeed, but it makes sense to try to backport anything performance-related. (Note: I've skipped backport to 8.x as I'm pretty certain the backport will fail there. The code on that branch is less similar to |
|
Backport failed for Please cherry-pick the changes locally and resolve any conflicts. git fetch origin dspace-9_x
git worktree add -d .worktree/backport-6257-to-dspace-9_x origin/dspace-9_x
cd .worktree/backport-6257-to-dspace-9_x
git switch --create backport-6257-to-dspace-9_x
git cherry-pick -x ec77307c389773010832fb9e71425277eace9057 0a36bb02e847d8510d7af30f9a3c8363679ec1af 3a45c31e9f1d7429224b06b8547005d6b82fc6a4 0766e67b0d2ef272633c75b01e9c5994e4cdb30b 833726f05e564a8d5b5d08a8bb4ce6dfe1b6d7dd 6f522621291da128ed407fb078b1651df6314f1d |
|
Backport failed for Please cherry-pick the changes locally and resolve any conflicts. git fetch origin dspace-10_x
git worktree add -d .worktree/backport-6257-to-dspace-10_x origin/dspace-10_x
cd .worktree/backport-6257-to-dspace-10_x
git switch --create backport-6257-to-dspace-10_x
git cherry-pick -x ec77307c389773010832fb9e71425277eace9057 0a36bb02e847d8510d7af30f9a3c8363679ec1af 3a45c31e9f1d7429224b06b8547005d6b82fc6a4 0766e67b0d2ef272633c75b01e9c5994e4cdb30b 833726f05e564a8d5b5d08a8bb4ce6dfe1b6d7dd 6f522621291da128ed407fb078b1651df6314f1d |
|
@bram-atmire : And, unfortunately none of the backports worked. So any backports would need to be done manually. |
|
Unfortunately it seems these last changes were merged a bit prematurely. I ran the performance tests again and the results come back way worse than before:
The whole point of this PR was to enhance the performance, therefore this degradation is a problem. I would encourage developers to run performance tests, or maybe we could include some kind of these tests in the pipeline. I personally use k6 by Grafana Labs to measure the performance: https://grafana.com/docs/k6/latest/ |
|
If you want to run the tests yourself, this is my setup:
# Caching settings
cache:
msToLive:
default: 900000 # 15 minutes
control: max-age=604800 # revalidate browser
autoSync:
defaultTime: 0
maxBufferSize: 100
timePerMethod:
PATCH: 3 # time in seconds
serverSide:
debug: false
botCache:
max: 0
timeToLive: 86400000 # 1 day
allowStale: true
anonymousCache:
max: 0
timeToLive: 10000 # 10 seconds
allowStale: true
# Item Config
item:
edit:
undoTimeout: 10000 # 10 seconds
showAccessStatuses: false
bitstream:
pageSize: 50
showAccessStatuses: true
layout:
showDownloadLinkAsAttachment: false
import { browser } from 'k6/browser';
import { sleep, check, fail } from 'k6';
export const options = {
summaryTimeUnit: 'ms',
scenarios: {
ui: {
executor: 'shared-iterations',
vus: 1,
iterations: 100,
options: {
browser: {
type: 'chromium',
timeout: '3m'
},
},
maxDuration: '2h',
},
},
};
export default async function () {
let checkData;
const page = await browser.newPage();
try {
await page.goto('http://localhost:4000/items/<your-items-uuid>');
await page.waitForLoadState('load');
const title = await page.title();
check(title, {
'page title is correct': (t) => t.includes('<your items title>'),
});
} catch (error) {
fail(`Browser iteration failed: ${error.message}`);
} finally {
await page.close();
}
sleep(1);
} |
|
I broke it with that last commit cfr Art's review. Working on a fix. |
|
Once #6544 is merged, i'll do the backports |
|
Thanks @bram-atmire for responding so quickly! I am not sure about the way to go, maybe we could also revert the merge and work on the new PR isolated from this merged PR? |
References
Fixes #6256. Related to the request-batching discussion in #3161.
Companion backend guard: DSpace/DSpace#13134. This request reduction uses the existing REST API and does not require that companion change or a REST contract change.
Description
Batch anonymous authorization checks per object using
/authz/authorizations/search/objectwithout a feature filter. The backend evaluates permissions once per object request; Angular selects each requested feature from the returned grants. This replaces the hardcoded list of features assumed to be denied anonymously.On the measured anonymous item page, 14 authorization requests become 2 (site and item), and total API requests fall from 39 to 27. All 14 individual decisions match the batched results, including public COAR discovery. There is no metadata catalogue request.
Authenticated visitors and explicit-EPerson queries retain individual checks. Anonymous batching uses the existing request cache for pending-request deduplication, expiry, invalidation and SSR transfer; it adds no separate permission cache. It follows all pagination links before deciding that a feature is absent. If any page fails, it falls back to the individual feature request, preserving behavior on installations with a broken custom feature.
Authentication readiness follows the same blocking flag used by application initialization. The previous
loadedcheck never completed for successful anonymous initialization.Measurements
Production builds, one public item, same local backend/data, HTML page caches disabled. Four process runs in baseline/revised/revised/baseline order; each includes one initial render and ten warm renders. The baseline is the pre-PR authorization service at
2f1bf85ce2ea.Counts were identical across all 22 renders per variant. Median warm full-response time was 270→262 ms; timings varied by run order, so this is not a demonstrated latency or throughput improvement. The measured benefit is 12 fewer HTTP requests (86% fewer authorization requests; 31% fewer total API requests). The original PR performance claims are superseded.
Browser verification: authorization GETs were 2 during hydration, 1 when navigating to a new item, and 0 on returning to the first item. CORS adds matching OPTIONS preflights. Item content and COAR inbox links were preserved with no JavaScript exceptions.
Instructions for Reviewers
ldn.enabledand visit a public item anonymously with server page caching disabled. Expect two unfiltered authorization searches (site and item), withembed=featureandsize=100, instead of one search per feature.Validation: 137 selected Angular tests passed (including a rerun of the affected tests); production browser and SSR builds passed. Full source lint passed with generated decorator registries excluded, and no source circular dependencies were found with those generated files excluded. The standard checks still encounter pre-existing generated-registry lint errors/cycles; full CI and Docker-based end-to-end tests remain pending. No new dependencies, UI text or configuration options.
Checklist
This checklist provides a reminder of what we are going to look for when reviewing your PR. You do not need to complete this checklist prior creating your PR (draft PRs are always welcome).
However, reviewers may request that you complete any actions in this list if you have not done so. If you are unsure about an item in the checklist, don't hesitate to ask. We're here to help!
mainbranch of code (unless it is a backport or is fixing an issue specific to an older branch).npm run lintnpm run check-circ-deps)package.json), I've made sure their licenses align with the DSpace BSD License based on the Licensing of Contributions documentation.Implementation and validation assisted by OpenAI Codex.