electric-sql / electric

Sync little subsets of your Postgres data into local apps and services.
https://electric-sql.com
Apache License 2.0
6.44k stars 155 forks source link

Best pattern for handling 401/403 token expiry? #1982

Open thruflo opened 2 hours ago

thruflo commented 2 hours ago

I've written a little client for the new gatekeeper auth pattern as per https://github.com/electric-sql/electric/pull/1963

Basically I need to handle token expiry and when a token expires, get a new one and then reconnect. I'm doing this with the Shape and ShapeStream: https://github.com/electric-sql/electric/blob/thruflo/auth-guide/examples/gatekeeper-auth/client/index.ts

I have this working, but AFAICS it requires having access to the stream instance to process messages to manually keep track of the last offset. I wonder:

I'm thinking that anywhere we support providing auth headers, we should have an easy way of handling a FetchError and resetting them to reconnect with new auth (or whatever).

What do you think?

KyleAMathews commented 2 hours ago

Getting a fresh token had come up before and one idea is that for headers/params could take an async function vs. a straight value — then that function would ensure that the token is still valid on each request.

thruflo commented 57 minutes ago

Yup, that’s good.

There’s also the control flow issue that atm, the ShapeStream just stops on a 4xx status. So I believe a Shape or a useShape with a headers option just isn’t going to try to reconnect.

It might be nice to be able to explicitly configure a function that handles 4xx errors where the return value determines whether to retry with new request config or not?

Or is this what the fetchClient option is already able to support?

KyleAMathews commented 46 minutes ago

yeah there's no way to automatically restart a shapestream if it errors. We have a problem that in general there's no way to easily listen for errors (and optionally do something about them).