Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Automatically use user token when sharing token is not sufficient for a request #8139

Merged
merged 16 commits into from
Oct 28, 2024
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.unreleased.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ For upgrade instructions, please check the [migration guide](MIGRATIONS.released

### Fixed
- Fixed a bug during dataset upload in case the configured `datastore.baseFolder` is an absolute path. [#8098](https://github.com/scalableminds/webknossos/pull/8098) [#8103](https://github.com/scalableminds/webknossos/pull/8103)
- When trying to save an annotation opened via a link including a sharing token, the token is automatically discarded in case it is insufficient for update actions but the users token is. [#8139](https://github.com/scalableminds/webknossos/pull/8139)
- Fixed that the skeleton search did not automatically expand groups that contained the selected tree [#8129](https://github.com/scalableminds/webknossos/pull/8129)
- Fixed a bug that zarr streaming version 3 returned the shape of mag (1, 1, 1) / the finest mag for all mags. [#8116](https://github.com/scalableminds/webknossos/pull/8116)
- Fixed sorting of mags in outbound zarr streaming. [#8125](https://github.com/scalableminds/webknossos/pull/8125)
Expand Down
27 changes: 20 additions & 7 deletions frontend/javascripts/admin/api/token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import * as Utils from "libs/utils";
let tokenPromise: Promise<string>;

let tokenRequestPromise: Promise<string> | null;
let shouldUseURLToken: boolean = true;
MichaelBuessemeyer marked this conversation as resolved.
Show resolved Hide resolved

function requestUserToken(): Promise<string> {
if (tokenRequestPromise) {
Expand Down Expand Up @@ -33,22 +34,34 @@ export function getSharingTokenFromUrlParameters(): string | null | undefined {
return null;
}

export function doWithToken<T>(fn: (token: string) => Promise<T>, tries: number = 1): Promise<any> {
const sharingToken = getSharingTokenFromUrlParameters();
export async function doWithToken<T>(
fn: (token: string) => Promise<T>,
tries: number = 1,
useURLTokenIfAvailable: boolean = true,
): Promise<any> {
MichaelBuessemeyer marked this conversation as resolved.
Show resolved Hide resolved
let token =
useURLTokenIfAvailable && shouldUseURLToken ? getSharingTokenFromUrlParameters() : null;

if (sharingToken != null) {
return fn(sharingToken);
if (token == null) {
tokenPromise = tokenPromise == null ? requestUserToken() : tokenPromise;
} else {
tokenPromise = Promise.resolve(token);
}

if (!tokenPromise) tokenPromise = requestUserToken();
return tokenPromise.then(fn).catch((error) => {
return tokenPromise.then(fn).catch(async (error) => {
if (error.status === 403) {
console.warn("Token expired. Requesting new token...");
tokenPromise = requestUserToken();

// If three new tokens did not fix the 403, abort, otherwise we'll get into an endless loop here
if (tries < 3) {
return doWithToken(fn, tries + 1);
// If using the url sharing token failed, we try the user specific token instead.
const result = await doWithToken(fn, tries + 1, false);
// Upon successful retry with own token, discard the url token.
if (useURLTokenIfAvailable) {
shouldUseURLToken = false;
}
return result;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Enhance error handling and retry mechanism.

The retry logic could be improved in several ways:

  1. The magic number '3' should be a named constant
  2. Consider implementing exponential backoff for retries
  3. Error logging could be more informative about the retry attempt number
+const MAX_TOKEN_RETRY_ATTEMPTS = 3;
+const RETRY_BACKOFF_MS = 1000;
+
 return tokenPromise.then(fn).catch(async (error) => {
   if (error.status === 403) {
-    console.warn("Token expired. Requesting new token...");
+    console.warn(`Token expired (attempt ${tries}/${MAX_TOKEN_RETRY_ATTEMPTS}). Requesting new token...`);
     tokenPromise = requestUserToken();

-    // If three new tokens did not fix the 403, abort, otherwise we'll get into an endless loop here
-    if (tries < 3) {
+    // Retry with exponential backoff until max attempts reached
+    if (tries < MAX_TOKEN_RETRY_ATTEMPTS) {
+      await new Promise(resolve => setTimeout(resolve, RETRY_BACKOFF_MS * Math.pow(2, tries - 1)));
       // If using the url sharing token failed, we try the user specific token instead.
       const result = await doWithToken(fn, tries + 1, false);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return tokenPromise.then(fn).catch(async (error) => {
if (error.status === 403) {
console.warn("Token expired. Requesting new token...");
tokenPromise = requestUserToken();
// If three new tokens did not fix the 403, abort, otherwise we'll get into an endless loop here
if (tries < 3) {
return doWithToken(fn, tries + 1);
// If using the url sharing token failed, we try the user specific token instead.
const result = await doWithToken(fn, tries + 1, false);
// Upon successful retry with own token, discard the url token.
if (useURLTokenIfAvailable) {
shouldUseURLToken = false;
}
return result;
const MAX_TOKEN_RETRY_ATTEMPTS = 3;
const RETRY_BACKOFF_MS = 1000;
return tokenPromise.then(fn).catch(async (error) => {
if (error.status === 403) {
console.warn(`Token expired (attempt ${tries}/${MAX_TOKEN_RETRY_ATTEMPTS}). Requesting new token...`);
tokenPromise = requestUserToken();
// Retry with exponential backoff until max attempts reached
if (tries < MAX_TOKEN_RETRY_ATTEMPTS) {
await new Promise(resolve => setTimeout(resolve, RETRY_BACKOFF_MS * Math.pow(2, tries - 1)));
// If using the url sharing token failed, we try the user specific token instead.
const result = await doWithToken(fn, tries + 1, false);
// Upon successful retry with own token, discard the url token.
if (useURLTokenIfAvailable) {
shouldUseURLToken = false;
}
return result;

}
}

Expand Down
12 changes: 10 additions & 2 deletions frontend/javascripts/libs/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -311,15 +311,23 @@ class Request {
...message,
key: json.status.toString(),
}));
if (showErrorToast) Toast.messages(messages);
if (showErrorToast) {
Toast.messages(messages); // Toast.error already logs the error
} else {
console.error(messages);
}
MichaelBuessemeyer marked this conversation as resolved.
Show resolved Hide resolved
// Check whether the error chain mentions an url which belongs
// to a datastore. Then, ping the datastore
pingMentionedDataStores(text);

/* eslint-disable-next-line prefer-promise-reject-errors */
return Promise.reject({ ...json, url: requestedUrl });
} catch (_jsonError) {
if (showErrorToast) Toast.error(text);
if (showErrorToast) {
Toast.error(text); // Toast.error already logs the error
} else {
console.error(text);
}
MichaelBuessemeyer marked this conversation as resolved.
Show resolved Hide resolved

/* eslint-disable-next-line prefer-promise-reject-errors */
return Promise.reject({
Expand Down
3 changes: 3 additions & 0 deletions frontend/javascripts/oxalis/model/sagas/save_saga.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,9 @@ export function* sendRequestToServer(
method: "POST",
data: compactedSaveQueue,
compress: process.env.NODE_ENV === "production",
// Suppressing error toast, as the doWithToken retry with personal token functionality should not show an error.
// Instead the error is logged and toggleErrorHighlighting should take care of showing an error to the user.
showErrorToast: false,
},
);
const endTime = Date.now();
Expand Down
3 changes: 3 additions & 0 deletions frontend/javascripts/test/sagas/save_saga.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ test("SaveSaga should send request to server", (t) => {
method: "POST",
data: saveQueueWithVersions,
compress: false,
showErrorToast: false,
}),
);
});
Expand All @@ -147,6 +148,7 @@ test("SaveSaga should retry update actions", (t) => {
method: "POST",
data: saveQueueWithVersions,
compress: false,
showErrorToast: false,
},
);
const saga = sendRequestToServer(TRACING_TYPE, tracingId);
Expand Down Expand Up @@ -187,6 +189,7 @@ test("SaveSaga should escalate on permanent client error update actions", (t) =>
method: "POST",
data: saveQueueWithVersions,
compress: false,
showErrorToast: false,
}),
);
saga.throw({
Expand Down