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

Fix 51888 cors errors are displayed for attachments #53407

Open
wants to merge 33 commits into
base: main
Choose a base branch
from

Conversation

Kalydosos
Copy link
Contributor

@Kalydosos Kalydosos commented Dec 2, 2024

Explanation of Change

Fixed Issues

$ 51888
PROPOSAL: #51888 (comment)

Tests

Test 1 steps

  1. open a chat
  2. send a text + image as comment if you dont have it already
  3. click to edit the comment
  4. copy the comment
  5. send the copy as new comment
  6. observe the preview image displayed correctly

Test 2 steps

  1. open a chat
  2. send an image
  3. open the devtools console
  4. run the following code in the console to simulate expiring the session tokens :

Onyx.merge('session', {authToken: 'pizza', encryptedAuthToken: 'pizza', creationDate: new Date().getTime() - 236001000});

  1. observe the attachment preview does not display a gray box
  2. observe the attachment preview reloads while displaying a loading spinner

Note : on native platforms, the troubleshooting test tool "Authentication Status/Invalidate with delay" can be used to simulate expiring the session in the next 15 seconds when clicked.

Test 3 steps

  1. open a chat
  2. send an image
  3. click on the image to display it in the carousel
  4. open the devtools console
  5. run the following code in the console to simulate expiring the session tokens :

Onyx.merge('session', {authToken: 'pizza', encryptedAuthToken: 'pizza', creationDate: new Date().getTime() - 236001000});

  1. Observe the attachment image does not display a gray box
  2. Observe the attachment image reloads while displaying a loading spinner

Note : on native platforms, the troubleshooting test tool "Authentication Status/Invalidate with delay can be used to simulate expiring the session in the next 15 seconds when clicked.

  • Verify that no errors appear in the JS console

Offline tests

QA Steps

Same as tests

  • Verify that no errors appear in the JS console

PR Author Checklist

  • I linked the correct issue in the ### Fixed Issues section above
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I added steps for the expected offline behavior in the Offline steps section
    • I added steps for Staging and/or Production testing in the QA steps section
    • I added steps to cover failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
    • MacOS: Desktop
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I followed proper code patterns (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick)
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text shown in the product is localized by adding it to src/languages/* files and using the translation method
      • If any non-english text was added/modified, I used JaimeGPT to get English > Spanish translation. I then posted it in #expensify-open-source and it was approved by an internal Expensify engineer. Link to Slack message:
    • I verified all numbers, amounts, dates and phone numbers shown in the product are using the localization methods
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
    • I verified proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I followed the guidelines as stated in the Review Guidelines
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.ts or at the top of the file that uses the constant) are defined as such
  • I verified that if a function's arguments changed that all usages have also been updated correctly
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG))
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • If a new page is added, I verified it's using the ScrollView component to make it scrollable when more elements are added to the page.
  • I added unit tests for any new feature or bug fix in this PR to help automatically prevent regressions in this user flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.

Screenshots/Videos

Android: Native
android_native.mp4
Android: mWeb Chrome
android_mweb.mp4
iOS: Native
ios_native.mp4
iOS: mWeb Safari
ios_mweb_safari.mp4
MacOS: Chrome / Safari
ios_web_safari.mp4
MacOS: Desktop
macos_desktop.mp4

@Kalydosos
Copy link
Contributor Author

Kalydosos commented Dec 3, 2024

@hungvu193 should we ask for Design team's help for a better spinner now ?

@hungvu193
Copy link
Contributor

Not yet, please address the linting. After the codes look good then I will request a review from Design team.

@hungvu193
Copy link
Contributor

Here's the flow:

  1. Address the lint, added the screenshots/videos
  2. I reviewed the code.
  3. I request the review from Design team.

@Kalydosos
Copy link
Contributor Author

Kalydosos commented Dec 3, 2024

@hungvu193 we need Design to make the choice of the type of image (SVG, GIF, ...) and certainly provide us the image to use based on this video https://github.com/user-attachments/assets/ccd73db5-d00a-49cd-83b2-0b3fb7388577 and the GIF file. Their help will change the code (call to updateAspectRatio, sizing, style...). After all the changes made based on their advice, they review. Thats the work experience i have with them. But as you said we can also go this way #53407 (comment)

@Kalydosos
Copy link
Contributor Author

@hungvu193 run lint was hanging on my pc. Now we are done with the lint errors, the remaining error is related to the legacy use of withOnyx not our changes. I guess that step should be skipped when deploying on staging.

@hungvu193
Copy link
Contributor

the remaining error is related to the legacy use of withOnyx not our changes. I guess that step should be skipped when deploying on staging.

Ah no. Once you changed a file that includes withOnyx, you will need to migrate it to useOnyx, otherwise we can't pass the test.
Please replace withOnyx with useOnyx

@Kalydosos
Copy link
Contributor Author

@hungvu193 sorry but that's a whole different issue with its testing and debugging. been there done, done that. We can not take that extra load as we are not even close to be done here. I had the same experience from a previous ticket and the ticket created to make such replacement was a whole issue in itself as it was necessary to avoid regressions. Let's not go that road, i will advise.

@hungvu193
Copy link
Contributor

We don't create a separate ticket if the changes to the Onyx migration are small. For example, in my previous PR, I also migrated useOnyx within the same PR

@Kalydosos
Copy link
Contributor Author

@hungvu193 i propose we reconsider that possibility once we are done with the main issue

@hungvu193
Copy link
Contributor

What's the main issue? The useOnyx migration is pretty simple for Image component btw. Please update it. I'll review PR in the meantime.

@Kalydosos
Copy link
Contributor Author

@hungvu193 dont forget that Image is a central component highly used in every screen of the code, so this "simple" change will require a lot of testing for possible regressions. Why not deal with issues one after the other ?

@Kalydosos
Copy link
Contributor Author

Kalydosos commented Dec 4, 2024

@hungvu193 Many have made changes and PRs on this file before us and faced that Lint error/warning. This "simple" component could be at high risks of regressions. I will advise in this case to not do anything instead of breaking something

src/CONST.ts Outdated
@@ -1445,6 +1445,8 @@ const CONST = {
UNKNOWN: 'unknown',
},
},
// the number of hours for an idle session to expire
SESSIONS_MAXIDLE_NB_HOURS: 2,
Copy link
Contributor

Choose a reason for hiding this comment

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

Can we use milliseconds instead?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

yes good idea

}
return previousSessionAge.current;
}
if (Math.abs(new Date().getTime() - session.creationDate) >= CONST.SESSIONS_MAXIDLE_NB_HOURS * 3600000) {
Copy link
Contributor

Choose a reason for hiding this comment

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

If we used milliseconds for CONST.SESSIONS_MAXIDLE_NB_HOURS we can do this instead:

Suggested change
if (Math.abs(new Date().getTime() - session.creationDate) >= CONST.SESSIONS_MAXIDLE_NB_HOURS * 3600000) {
if (Math.abs(new Date().getTime() - session.creationDate) >= CONST.SESSIONS_MAXIDLE_NB_HOURS) {

/**
* trying to figure out if the current session is expired or fresh from a necessary reauthentication
*/
const previousSessionAge = useRef<number | undefined>();
Copy link
Contributor

Choose a reason for hiding this comment

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

We have a hook called usePrevious, let use it.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

ok i'll check that

Copy link
Contributor

Choose a reason for hiding this comment

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

Did we give up on using usePrevious?

Comment on lines 60 to 83
useEffect(() => {
previousSessionAge.current = validSessionAge;
});
Copy link
Contributor

Choose a reason for hiding this comment

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

After using usePrevious we can remove this block:

Suggested change
useEffect(() => {
previousSessionAge.current = validSessionAge;
});

[CONST.CHAT_ATTACHMENT_TOKEN_KEY]: authToken,
},
};
if (!!session?.creationDate && new Date().getTime() - session.creationDate < CONST.SESSIONS_MAXIDLE_NB_HOURS * 3600000) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Can we create a function called isValidSessionCreationDate to reuse this logic?
ie:

function isValidSessionCreationDate() {
 return !!session?.creationDate && (new Date().getTime() - session.creationDate) > CONST.SESSIONS_MAXIDLE_NB_HOURS
}

Copy link
Contributor Author

Choose a reason for hiding this comment

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

i'll see how can isolate that logic in a function with a relevant name, good idea

Comment on lines 48 to 68
if (Math.abs(previousSessionAge.current - session.creationDate) < 60000) {
return session.creationDate;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Can you explain why we have this condition?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

we expect a reauthenticate to happen in less than 60s if the current session was expired. I have made the tests. so the new valid session will be newer than 60s after

src/components/Image/index.tsx Show resolved Hide resolved
@@ -72,6 +102,7 @@ function Image({source: propsSource, isAuthTokenRequired = false, session, onLoa
{...forwardedProps}
onLoad={handleLoad}
style={[style, shouldSetAspectRatioInStyle && aspectRatio ? {aspectRatio, height: 'auto'} : {}, shouldOpacityBeZero && {opacity: 0}]}
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
Copy link
Contributor

Choose a reason for hiding this comment

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

Please add a comment to explain why we disable eslint here

@hungvu193
Copy link
Contributor

@hungvu193 Many have made changes and PRs on this file before us and faced that Lint error/warning. This "simple" component could be at high risks of regressions. I will advise in this case to not do anything instead of breaking something

We still need to do it anyway. PR can't be merged if all the tests aren't passed. That's mandatory.

@Kalydosos
Copy link
Contributor Author

We still need to do it anyway. PR can't be merged if all the tests aren't passed. That's mandatory.

How did previous PRs end up in main then ? I really think we should avoid this as we can never do enough testing for regressions imho

@hungvu193
Copy link
Contributor

We still need to do it anyway. PR can't be merged if all the tests aren't passed. That's mandatory.

How did previous PRs end up in main then ? I really think we should avoid this as we can never do enough testing for regressions imho

Changes from previous PRs were added when we didn't deprecate withOnyx HOC.

@Kalydosos
Copy link
Contributor Author

@hungvu193 lets change it after we are done with the main issue, if you insist on it. I can't put my focus on that right now as i must start testing for regressions right away once we change it.

@Kalydosos
Copy link
Contributor Author

Kalydosos commented Dec 4, 2024

@hungvu193 i will upload the web test video as you can see the sizing of the image cause the attachments not to render properly (we cant just use any gif from the web). So the code will be adjusted once we have the definitive image from Design. I think we can have Design team's help based on the web test and the other envs are not necessary as they will be reviewed anyway once we have the definitive image

demo_with_2H_expired_token.mp4

@hungvu193
Copy link
Contributor

The fact that we display image based on its size. I'm thinking about the way we should keep image loading until it has valid session. Wdyt?

@hungvu193
Copy link
Contributor

So There's no image/gif placeholder needed. Instead we improve the loading conditions of image

@Kalydosos
Copy link
Contributor Author

So There's no image/gif placeholder needed. Instead we improve the loading conditions of image

the problem is the final source of the image is not known yet at that step, it will be recalculated once we have a valid session, so we cannot anticipate the loading unless you're thinking of some other way for it

@Kalydosos
Copy link
Contributor Author

@hungvu193 i did some updates based on your review but it didnt use the useprevious hook yet (i will test it some more).

@hungvu193
Copy link
Contributor

hungvu193 commented Dec 5, 2024

I think for now that's fine to keep image resize like that. Let's complete the author checklist and mark this PR as ready for review.

I took a few tests, everything seems working fine. Let's finish the PR phrase so I'll request a review from Design team 😄

@hungvu193
Copy link
Contributor

So I abandoned my tab for hours and when I'm back I got this issue.

Screen.Recording.2024-12-05.at.15.40.06.mov

@hungvu193
Copy link
Contributor

As I checked the log, ReAuthenticate seems to never get called during that time, so session was invalid and the loading was showed forever

@Kalydosos
Copy link
Contributor Author

As I checked the log, ReAuthenticate seems to never get called during that time, so session was invalid and the loading was showed forever

yes we need to fix it in the caroussel also. I'll work on it.

@Kalydosos
Copy link
Contributor Author

@hungvu193 we will be using a reauthenticator which will be a singleton object called when the spinner is returned as source for the image. The current session will be send as parameter. It will listen to network and session onyx keys so it wont do anything if offline and will deactivate once it receive a session from Onyx. Once activated (only once) it will expect a session from Onyx in the next 10s (preferred) or 15s and if it doesnt receive a new session it will ask for reauthentication (only once with no retry). Wdyt ? i'll implement it

@Kalydosos
Copy link
Contributor Author

Kalydosos commented Dec 5, 2024

@hungvu193 but normally the notification pusher triggers reauthentifications (if necessary every 5 seconds) and we shouldnt need a reauthenticator

https://github.com/Kalydosos/App/blob/6fc2b615a449caac1acd3ba8ca956674e4d344bf/src/libs/actions/Session/index.ts#L848-L860

triggers

https://github.com/Kalydosos/App/blob/6fc2b615a449caac1acd3ba8ca956674e4d344bf/src/libs/Authentication.ts#L93

edit*
but reauthentication is triggered only when the pusher cannot send push due to invalid tokens, so it cannot be rely on finally

@Kalydosos
Copy link
Contributor Author

I will do some testings about the caroussel display

@Kalydosos
Copy link
Contributor Author

Kalydosos commented Dec 6, 2024

@hungvu193 i have implemented the reauthenticator (still i dont know what you think of the idea) https://github.com/Kalydosos/App/blob/fix-51888-cors-errors-are-displayed-for-attachments/src/libs/actions/Session/Reauthenticator.ts . I let the comments in the code to help you test it out. I set the session expiration time to 5mn for testing. You can then see how it works for the image in the chat

reauthenticate_for_thread_images.mp4

and then for the carousel

reauthenticator_demo.mp4

the point is now to make sure it is used when it is really necessary and maybe we could shorten the wait time to 7s or 8s

@Kalydosos
Copy link
Contributor Author

Kalydosos commented Dec 26, 2024

@hungvu193 it's all good now except the translations #53407 (comment) . I redo all the videos (for the nth time 😃 ), hope it's all setted !

@hungvu193
Copy link
Contributor

Let's wait for confirmation from Internal Engineer in our ongoing discussion

@Kalydosos
Copy link
Contributor Author

Let's wait for confirmation from Internal Engineer in our ongoing discussion

@hungvu193 this is internal tool, it has no impact on the fix.

I was stating that calling it "Invalidate session delayed" could be misleading as any tester could think that it's a delayed version of the "Invalidate session" testtool, which it's not. @rlinoz gave us a go for the tool and suggested a name. He never meant we have to call it as such by all costs imho, please let me know if i'm wrong. I explained the choice of the name here #53407 (comment) yesterday

showContextMenuForReport(
event,
anchor,
report?.reportID ?? '-1',
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
report?.reportID ?? '-1',
report?.reportID ?? CONST.DEFAULT_NUMBER_ID,

Copy link
Contributor Author

@Kalydosos Kalydosos Dec 31, 2024

Choose a reason for hiding this comment

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

check the new commit on that point

Copy link
Contributor

Choose a reason for hiding this comment

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

One suggestion for you that you need to have meaningful commit message instead repeating fix cors errors on attachments.

Copy link
Contributor

Choose a reason for hiding this comment

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

That's really confusing

@Kalydosos
Copy link
Contributor Author

@hungvu193 i updated as we discuss, videos also are updated

@hungvu193
Copy link
Contributor

Thanks. The only pending here is the translation confirmation.

@Kalydosos
Copy link
Contributor Author

Thanks. The only pending here is the translation confirmation.

still an internal tool so i think we shouldn't wait too long if there is no translation provided

Copy link
Contributor

@hungvu193 hungvu193 left a comment

Choose a reason for hiding this comment

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

Thanks @Kalydosos. LGTM

@melvin-bot melvin-bot bot requested a review from rlinoz December 31, 2024 15:46
@hungvu193
Copy link
Contributor

Hey @rlinoz This is ready for your final review!

@hungvu193
Copy link
Contributor

@Kalydosos Can you resolve the conflicts in the meantime? Ty

Copy link
Contributor

@rlinoz rlinoz left a comment

Choose a reason for hiding this comment

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

Thanks for the hard work here, I have a few of suggestions and some questions

src/CONST.ts Outdated Show resolved Hide resolved
@@ -37,58 +40,115 @@ function Image({source: propsSource, isAuthTokenRequired = false, session, onLoa
},
[onLoad, updateAspectRatio],
);

// an accepted session is either received less than 60s after the previous
Copy link
Contributor

Choose a reason for hiding this comment

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

Please explain why and what is an acceptedSession in the comment

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@rlinoz accepted sessions are sessions of a certain criteria that we think can necessitate a reload of the images because images sources barely changes unless specific events occur like network issues (offline/online) per example. Here we target new session received less than 60s after the previous session (that could be from fresh reauthentication, the previous session was not necessarily expired) or new session after the previous session was expired (based on timestamp gap between the 2 creationDate and the freshness of the new session).

/**
* trying to figure out if the current session is expired or fresh from a necessary reauthentication
*/
const previousSessionAge = useRef<number | undefined>();
Copy link
Contributor

Choose a reason for hiding this comment

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

Did we give up on using usePrevious?

src/components/Image/index.tsx Outdated Show resolved Hide resolved
const previousSessionAge = useRef<number | undefined>();
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const validSessionAge: number | undefined = useMemo(() => {
// for performance gain, the processing is reserved to attachments images only
Copy link
Contributor

Choose a reason for hiding this comment

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

I don't get this comment, can you explain it to me please?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@rlinoz yes we want the session age aspects and related processing to be applied only to images that require authentication (attachments images and receipts) because some other images use the same Image component but are not connected to the cors errors bceause they dont require authentication

Copy link
Contributor

Choose a reason for hiding this comment

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

Thanks, left a suggestion

@@ -111,6 +111,12 @@ function ImageWithSizeCalculation({url, altText, style, onMeasure, onLoadFailure
}}
onError={onError}
onLoad={imageLoadedSuccessfully}
waitForSession={() => {
// at the moment this function is called the image is not in cache anymore
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
// at the moment this function is called the image is not in cache anymore
// At the moment this function is called the image is not in cache anymore

Copy link
Contributor Author

Choose a reason for hiding this comment

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

done 👍

@@ -234,6 +234,14 @@ function Lightbox({isAuthTokenRequired = false, uri, onScaleChanged: onScaleChan
updateContentSize(e);
setLightboxImageLoaded(true);
}}
waitForSession={() => {
// only active lightbox should call this function
Copy link
Contributor

Choose a reason for hiding this comment

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

Can we explain why in the comment please?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

ok

@@ -36,6 +36,9 @@ type Session = {

/** User signed in with short lived token */
signedInWithShortLivedAuthToken?: boolean;

/** timestamp of the session creation date */
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
/** timestamp of the session creation date */
/** Timestamp of the session creation date */

}

/**
* Send an expired session to FE and invalidate the session in the BE. Action is delayed for 15s
Copy link
Contributor

Choose a reason for hiding this comment

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

I think this is not calling the BE at all, is it?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

no it doesnt call the BE but the next request to the BE will send the "pizza" token, i will rephrase to "Send an expired session to FE and invalidate the session in the BE perspective"

* @param session the current session
* @returns
*/
function activate(session: Session) {
Copy link
Contributor

Choose a reason for hiding this comment

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

We already have reauthentication mechanisms throughout the app, can you help me understand why we can't use those?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

yes we are using the core (re)Authentication feature but we need more control over the context of the use of that feature, meaning only one Image component can ask for reauthentication (in a singleton mode) and we only use that feature when there hasnt been any reauthentication for 3.5s since we detected that the current session is expired (particulary useful in the carousel)

Copy link
Contributor

Choose a reason for hiding this comment

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

From what I can tell Reuathenticate.reauthenticate also ensures that we make a single auth request, I also would like to avoid all these setTimeout calls honestly

const previousSessionAge = useRef<number | undefined>();
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const validSessionAge: number | undefined = useMemo(() => {
// for performance gain, the processing is reserved to attachments images only
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
// for performance gain, the processing is reserved to attachments images only
// Authentication is required only for certain types of images (attachments and receipts), so let's only calculate the session age for those

const previousSessionAge = useRef<number | undefined>();
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const validSessionAge: number | undefined = useMemo(() => {
// for performance gain, the processing is reserved to attachments images only
Copy link
Contributor

Choose a reason for hiding this comment

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

Thanks, left a suggestion

/**
* Check if the image source is a URL - if so the `encryptedAuthToken` is appended
* to the source.
*/
// source could be a result of require or a number or an object but all are expected so no unsafe-assignment
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
// source could be a result of require or a number or an object but all are expected so no unsafe-assignment

return (
<BaseImage
// eslint-disable-next-line react/jsx-props-no-spreading
{...forwardedProps}
onLoad={handleLoad}
style={[style, shouldSetAspectRatioInStyle && aspectRatio ? {aspectRatio, height: 'auto'} : {}, shouldOpacityBeZero && {opacity: 0}]}
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
Copy link
Contributor

Choose a reason for hiding this comment

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

I think we don't need this anymore, right?

Suggested change
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@rlinoz i am not sure, but i will remove to see

Comment on lines 50 to 51
/** Called when the image should wait for a valid session to reload
* At the moment this function is called, the image is not in cache anymore
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
/** Called when the image should wait for a valid session to reload
* At the moment this function is called, the image is not in cache anymore
/**
* Called when the image should wait for a valid session to reload
* At the moment this function is called, the image is not in cache anymore

* @param session the current session
* @returns
*/
function activate(session: Session) {
Copy link
Contributor

Choose a reason for hiding this comment

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

From what I can tell Reuathenticate.reauthenticate also ensures that we make a single auth request, I also would like to avoid all these setTimeout calls honestly

@Kalydosos
Copy link
Contributor Author

Kalydosos commented Jan 3, 2025

@rlinoz i tried not using a timeout for the reauthentication and we had the reauthentication calls overlapping and previous images reload requests where canceled and then retrieved with the 2nd session from the 2nd reauthentication (we are dealing with milliseconds calls indeed)

request1

request2

@Kalydosos
Copy link
Contributor Author

Kalydosos commented Jan 3, 2025

@rlinoz the Reauthenticator.ts was only needed in fact for when the user clicks on the image and display the carousel but the session was expired (the "Action Performed" of the ticket and also this test case #53407 (comment)). At that moment, no "natural" reauthentication was triggered so we have to call it ourselves. But we needed to be sure we were in the carousel but using attachmentCarouselPagerContext?.pagerRef was not reliable where the carousel is accessed from deep linking so we implemented Reauthenticator. But to avoid the overlap of reauthentication calls (in my previous comment) we set up a timeout which is only useful when in a chat thread per example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants