yakovkhalinsky/backblaze-b2

Automatically call authorize_account on 401

odensc opened this issue · 4 comments

Perhaps we should have backblaze-b2 automatically call authorize_account when it encounters a 401 error, or have it as an option at least.

I encountered an issue in a long-running application where after 24 hours all calls stopped working.

https://www.backblaze.com/b2/docs/application_keys.html

Authorization tokens are only good for 24 hours. You can use the application key to make new authorization tokens as they expire.

It would be nice if the module automatically did this rather than the user having to: 1. Call authorize before every method (incurs a Class C transaction cost), 2. Add an error handler to every call to check for 401s, or 3. Add a setInterval every 24 hours to authorize (a bit hacky).

Thoughts?

cbess commented

Seems like a good idea, but that may be a bit tricky to embed it, because it can happen for any call. So we would essentially have do #2 for every API call

You just need to check a timestamp before every call. Every time you call authorize() you save a timestamp 24hours ahead which will be checked.
Edit: I'm using this method for my helper functions, but handling it automatically on 401s would, of course, be better.

+1.

Note that we should handle the case where multiple requests are made in the same tick. We don't want each one generating a new authorize() call. In our code, we solve this using memoizee:

const reauth = memoize(
    () => client.authorize(),
    { promise: true, maxAge: 1000 * 60 * 10 /* 10 minutes */ }
);