From 941f9a12c54cd0a86242432985ce974472a25dc6 Mon Sep 17 00:00:00 2001 From: Christiaan Landman Date: Mon, 16 Nov 2026 15:47:18 +0200 Subject: [PATCH] Move the connector snippets to the split connector API Each generic and Supabase connector snippet, except .NET, now connects with an Authenticator and a mutation uploader instead of a PowerSyncBackendConnector. Each Authenticator caches its token and clears it in invalidateCredentials(), because the SDK isn't guaranteed to cache tokens. The generic snippets put the instance URL placeholder in their connect() call. The reference write implementation and Supabase Edge Function pages now connect the reference connector with an Authenticator, matching powersync-reference-write-implementation#19. .NET stays on IPowerSyncBackendConnector until a stable .NET SDK release supports the split API. Co-Authored-By: Claude Opus 5.5 --- .../backend-connector-examples.mdx | 6 +- .../reference-write-implementation.mdx | 42 +++++--- .../write-path/supabase-edge-function.mdx | 50 +++++----- snippets/backend-connectors/generic/dart.mdx | 85 ++++++++++------ .../backend-connectors/generic/javascript.mdx | 97 +++++++++++-------- .../backend-connectors/generic/kotlin.mdx | 83 +++++++++------- .../generic/react-native.mdx | 93 +++++++++++------- snippets/backend-connectors/generic/rust.mdx | 4 +- snippets/backend-connectors/generic/swift.mdx | 89 ++++++++++------- .../backend-connectors/generic/typescript.mdx | 93 +++++++++++------- snippets/backend-connectors/supabase/dart.mdx | 74 +++++++++----- .../supabase/javascript.mdx | 32 ++++-- .../backend-connectors/supabase/kotlin.mdx | 54 ++++++++--- .../supabase/react-native.mdx | 38 ++++++-- .../backend-connectors/supabase/swift.mdx | 29 +++++- .../supabase/typescript.mdx | 46 +++++---- 16 files changed, 587 insertions(+), 328 deletions(-) diff --git a/configuration/app-backend/backend-connector-examples.mdx b/configuration/app-backend/backend-connector-examples.mdx index 3033e124..d43a8c78 100644 --- a/configuration/app-backend/backend-connector-examples.mdx +++ b/configuration/app-backend/backend-connector-examples.mdx @@ -5,6 +5,8 @@ keywords: - "backend connector" - "uploadData" - "fetchCredentials" + - "Authenticator" + - "MutationUploader" - "connector snippet" --- @@ -26,7 +28,7 @@ import SupabaseDotnet from '/snippets/backend-connectors/supabase/dotnet.mdx'; {/* These snippets are the source for the connector code shown in the PowerSync Dashboard. Keep the instance URL placeholder unchanged: the Dashboard replaces it with the instance URL. */} -Each example implements the two methods of a [backend connector](/configuration/app-backend/client-side-integration#backend-connector): `fetchCredentials()` and `uploadData()`. The Rust SDK splits these into an `Authenticator` and a `MutationUploader`. Copy the example for your SDK into your app, then replace the placeholders. +Each example implements authentication and uploads separately: an `Authenticator` supplies the token, and a mutation uploader uploads queued writes. Each `Authenticator` caches its token and clears the cache in `invalidateCredentials()`, because the SDK isn't guaranteed to cache tokens. The .NET examples implement the two methods of a [backend connector](/configuration/app-backend/client-side-integration#backend-connector) instead, `fetchCredentials()` and `uploadData()`, because no stable .NET SDK release supports the split API yet. Copy the example for your SDK into your app, then replace the placeholders. @@ -40,7 +42,7 @@ Each example implements the two methods of a [backend connector](/configuration/ ## Custom Backend -Use these examples if your app uploads writes to its own backend. By default, they call the [reference write API](/handling-writes/write-path/reference-write-implementation)'s `POST /api/data`. If your API's request or response format differs, either change the request and response handling in `uploadData()` to match your API, or use the [prompt for your coding agent](/handling-writes/write-path/existing-api#prompt-for-your-coding-agent) to generate an `uploadData()` for it. +Use these examples if your app uploads writes to its own backend. By default, they call the [reference write API](/handling-writes/write-path/reference-write-implementation)'s `POST /api/data`. If your API's request or response format differs, either change the example's request and response handling to match your API, or use the [prompt for your coding agent](/handling-writes/write-path/existing-api#prompt-for-your-coding-agent) to generate upload code for it. Each example sends the same JWT to your PowerSync instance and to the write API. Replace the token placeholder with a token from your auth provider. See [Authentication Setup](/configuration/auth/overview). diff --git a/handling-writes/write-path/reference-write-implementation.mdx b/handling-writes/write-path/reference-write-implementation.mdx index 9034bd00..93b5eb17 100644 --- a/handling-writes/write-path/reference-write-implementation.mdx +++ b/handling-writes/write-path/reference-write-implementation.mdx @@ -7,7 +7,7 @@ description: "Run PowerSync's open-source write API against your source database If you don't have a write API yet, you can run the reference write implementation instead of building one. It has two parts: - The **reference write API**: a Node.js (Express) server that receives uploaded transactions and applies them to your source database. It supports Postgres, MongoDB, MySQL, and SQL Server. -- The **reference connector**: a TypeScript backend connector with an `uploadData()` that calls the reference write API. You copy it into your app. For other SDKs, the [Backend Connector Examples](/configuration/app-backend/backend-connector-examples#custom-backend) port its upload behavior. +- The **reference connector**: a TypeScript mutation uploader that uploads queued transactions to the reference write API. You copy it into your app. For other SDKs, the [Backend Connector Examples](/configuration/app-backend/backend-connector-examples#custom-backend) port its upload behavior. An [OpenAPI spec](https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/backend/shared/powersync-reference-write-api.openapi.yaml) defines the API between the two parts. If your backend runs on another stack, see [Build Your Own Write API](/handling-writes/write-path/build-your-own-write-api). @@ -76,35 +76,49 @@ If your source database is Supabase and you rely on RLS policies to authorize wr - Copy the reference connector from the repository's [`example-client`](https://github.com/powersync-ja/powersync-reference-write-implementation/tree/main/example-client) folder into your app. If your app already has a `fetchCredentials()`, keep it, and copy only `uploadData()` and the code it uses. + Copy the reference connector from the repository's [`example-client`](https://github.com/powersync-ja/powersync-reference-write-implementation/tree/main/example-client) folder into your app. It requires `@powersync/web` 2.6.0 or `@powersync/react-native` 2.4.0 or later. If your app uses the Dart, Kotlin, Swift, .NET, or Rust SDK, copy the Custom Backend example for your SDK from [Backend Connector Examples](/configuration/app-backend/backend-connector-examples#custom-backend) instead, and skip the rest of this step. Each example sends one transaction per request and leaves retry timing to the SDK. There are two versions of the connector: - - [**Single file**](https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/example-client/src/PowersyncConnector.singlefile.ts): copy `src/PowersyncConnector.singlefile.ts`. It requires only your PowerSync SDK. Set the write API URL, the PowerSync instance URL, and the batch size in the constants at the top of the file. + - [**Single file**](https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/example-client/src/PowersyncConnector.singlefile.ts): copy `src/PowersyncConnector.singlefile.ts`. It requires only your PowerSync SDK. Set the write API URL and the batch size in the constants at the top of the file. - [**Modular**](https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/example-client/src/PowersyncConnector.ts): copy `src/PowersyncConnector.ts`, `src/library/powersync/`, and `src/generated/api.d.ts`, preserving their relative paths. Install `openapi-fetch` and `uuid` alongside your PowerSync SDK. This version reads the same settings from `VITE_` environment variables. Use a write API URL that the device can reach: `localhost` on a phone refers to the phone. - Replace the demo `fetchAuthToken()` with code that retrieves the current token from your auth provider. If the provider SDK manages session refresh, remove the `_authToken` field, its initialization in the constructor, and the `AuthenticationError` check in `onTransportError()` that resets it. Then replace `getAuthToken()` with: + The connector gets the token for write requests from an `Authenticator`. Pass it the same `Authenticator` that you pass to `connect()` for sync, so that sync and writes identify the same user. When the write API rejects the token, the connector calls `invalidateCredentials()` and keeps the transaction in the upload queue, so the next attempt uses a new token. - ```typescript - // Inside your copied PowersyncConnector class. - private async getAuthToken(): Promise { - return this.fetchAuthToken(); - } - ``` - - The demo cache is cleared only after an upload request fails authentication. Keeping it can make `fetchCredentials()` return an expired token even after the provider refreshes the session. See [client authentication](https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/example-client/README.md#authentication) for provider integration. + The SDK isn't guaranteed to cache tokens from an `Authenticator`, so cache the token in `resolveCredentials()` and clear the cache in `invalidateCredentials()`. Do this even if your auth provider's SDK refreshes sessions itself: after the cache is cleared, the next call gets the provider's current token. See [client authentication](https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/example-client/README.md#authentication) for provider examples. - Pass the connector to your PowerSync database, adjusting the import path to match your copied file: + Connect your PowerSync database with the `Authenticator` and the connector's `upload` callback, adjusting the import path to match your copied file: ```typescript + import type { Authenticator } from '@powersync/web'; import { PowersyncConnector } from './PowersyncConnector'; - await db.connect(new PowersyncConnector()); + let cachedToken: string | null = null; + + const authenticator: Authenticator = { + async resolveCredentials() { + // fetchAuthToken() is your code that gets a token from your auth provider. + cachedToken ??= await fetchAuthToken(); + return cachedToken; + }, + invalidateCredentials() { + cachedToken = null; + } + }; + + const connector = new PowersyncConnector({ authenticator }); + await db.connect({ + powerSyncEndpoint: 'https://.powersync.journeyapps.com', + authenticator, + upload: connector.upload + }); ``` + + If your app already connects with a `PowerSyncBackendConnector`, see [Migrating from a Backend Connector](https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/example-client/README.md#migrating-from-a-backend-connector). Add your checks to the `authorize()` function in `backend/standalone/src/auth/authorizer.ts`. It receives the transaction's operations and the verified token's `sub` and claims, and returns `false` to reject the transaction. By default, it allows every write and logs an error for each transaction until you replace it. See the repository's [authorization guide](https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/auth/authorization.md). diff --git a/handling-writes/write-path/supabase-edge-function.mdx b/handling-writes/write-path/supabase-edge-function.mdx index f4b8ceaa..f24633e4 100644 --- a/handling-writes/write-path/supabase-edge-function.mdx +++ b/handling-writes/write-path/supabase-edge-function.mdx @@ -78,37 +78,39 @@ The function runs each write as the signed-in user. Inside each transaction, it Copy the reference connector into your app, as described in the reference write implementation's [Connect Your App step](/handling-writes/write-path/reference-write-implementation#connect-your-app). Then make these changes: 1. Set the connector's write API URL to `https://.supabase.co/functions/v1/powersync-write`. Your PowerSync instance URL doesn't change. - 2. Pass your app's supabase-js client to the connector, and replace `fetchCredentials()` and `getAuthToken()` with the code below. This code reads the session on every call. - 3. Remove `fetchAuthToken()`, the `_authToken` field, its initialization in the constructor, and the `AuthenticationError` check in `onTransportError()` that resets it. supabase-js refreshes the session itself. The connector clears its cache only after a write request fails authentication, so while the cache is in place, sync keeps sending an expired token. + 2. Use an `Authenticator` that reads the access token from your app's supabase-js client, and pass it to both `connect()` and the connector. Cache the token and clear the cache in `invalidateCredentials()`, as in the code below. The SDK calls `invalidateCredentials()` 30 seconds before the token expires, and the connector calls it when the write API rejects the token. The next `getSession()` call then returns a valid session: in current supabase-js versions, it refreshes the session when it expires within 90 seconds. ```typescript - constructor(private readonly supabase: SupabaseClient) { - // existing setup - } + import type { SupabaseClient } from '@supabase/supabase-js'; + import type { Authenticator } from '@powersync/web'; + import { PowersyncConnector } from './PowersyncConnector'; - async fetchCredentials() { - const session = await this.getSession(); - return { - endpoint: this.config.powersyncUrl, - token: session.access_token, - expiresAt: session.expires_at ? new Date(session.expires_at * 1000) : undefined - }; - } + declare const supabase: SupabaseClient; // Your app's supabase-js client - private async getSession() { - const { data: { session }, error } = await this.supabase.auth.getSession(); - if (!session || error) throw new Error('Not signed in to Supabase'); - return session; - } + let cachedToken: string | null = null; - // Write requests call this to get their token. - private async getAuthToken(): Promise { - return (await this.getSession()).access_token; - } + const authenticator: Authenticator = { + async resolveCredentials() { + if (!cachedToken) { + const { data: { session }, error } = await supabase.auth.getSession(); + if (!session || error) throw new Error('Not signed in to Supabase'); + cachedToken = session.access_token; + } + return cachedToken; + }, + invalidateCredentials() { + cachedToken = null; + } + }; + + const connector = new PowersyncConnector({ authenticator }); + await db.connect({ + powerSyncEndpoint: 'https://.powersync.journeyapps.com', + authenticator, + upload: connector.upload + }); ``` - This code is for the modular connector. In the single-file connector, use `POWERSYNC_URL` instead of `this.config.powersyncUrl`. - The function accepts only a signed-in user's access token. It rejects API keys, anon tokens, and service-role tokens. diff --git a/snippets/backend-connectors/generic/dart.mdx b/snippets/backend-connectors/generic/dart.mdx index eaafd876..9a87b7d4 100644 --- a/snippets/backend-connectors/generic/dart.mdx +++ b/snippets/backend-connectors/generic/dart.mdx @@ -1,11 +1,13 @@ ```dart lib/powersync.dart // Uploads local writes to the PowerSync reference write API, one transaction per request. +// Requires powersync 2.6.0 or later. // Set up the write API: https://docs.powersync.com/handling-writes/write-path/reference-write-implementation // If your backend has a different API, change the request and response handling in _postTransaction() to match -// it, or have a coding agent write uploadData() for your API: +// it, or have a coding agent write the upload callback for your API: // https://docs.powersync.com/handling-writes/write-path/existing-api#prompt-for-your-coding-agent // For several transactions per request and client-side backoff, see the full reference connector: // https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/example-client/src/PowersyncConnector.singlefile.ts +import 'dart:async'; import 'dart:convert'; import 'package:http/http.dart' as http; // Add the http package: https://pub.dev/packages/http @@ -20,25 +22,60 @@ const requestTimeout = Duration(seconds: 30); /// Consecutive retryable errors for one transaction before it is passed to onFatalTransaction(). const retryMaxAttempts = 10; -class MyBackendConnector extends PowerSyncBackendConnector { - String? _authToken; - Object? _retryKey; - int _retryCount = 0; +/// Connects [db] for downloads and uploads. +Future connect(PowerSyncDatabase db) async { + final authenticator = MyAuthenticator(); + await db.connect( + connector: ConnectRequest( + endpoint: '[Your PowerSync instance URL or self-hosted endpoint]', + authenticator: authenticator, + uploader: MyBackendConnector(authenticator).upload, + ), + ); +} + +/// Provides the token for sync and for the write API, which accepts the same JWTs as your PowerSync instance. +/// The token is cached until it expires, or the PowerSync Service or the write API rejects it. +class MyAuthenticator implements Authenticator { + String? _token; @override - Future fetchCredentials() async { - return PowerSyncCredentials( - endpoint: '[Your PowerSync instance URL or self-hosted endpoint]', - token: await _getAuthToken(), - ); + Future resolveCredentials(Future abortSignal) async { + return _token ??= await _fetchAuthToken(); + } + + /// Called by the SDK when the token expires and when the PowerSync Service rejects it, and by the connector + /// when the write API rejects it. Keep this cache even if your auth provider's SDK refreshes sessions + /// itself: the SDK isn't guaranteed to cache tokens. + @override + void invalidateCredentials() { + _token = null; + } + + /// Replace this with your auth provider's token retrieval. See https://docs.powersync.com/configuration/auth/overview + /// Supabase and Firebase tokens can be used as they are: + /// - https://docs.powersync.com/configuration/auth/supabase-auth + /// - https://docs.powersync.com/configuration/auth/firebase-auth + /// To use a development token with the write API, see + /// https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/auth/development-tokens.md + Future _fetchAuthToken() async { + return 'An authentication token'; } +} + +class MyBackendConnector { + /// Supplies the token for write API requests. + MyBackendConnector(this._authenticator); + + final Authenticator _authenticator; + Object? _retryKey; + int _retryCount = 0; /// Uploads the oldest queued transaction. The SDK calls this after local writes, on (re)connect and on /// keepalives, and keeps calling it until the upload queue is empty. Throwing keeps the transaction queued, /// and the SDK retries after a delay. /// See https://docs.powersync.com/configuration/app-backend/client-side-integration#when-uploaddata-is-called - @override - Future uploadData(PowerSyncDatabase database) async { + late final MutationUploader upload = MutationUploader((database) async { final transaction = await database.getNextCrudTransaction(); if (transaction == null) { return; @@ -50,7 +87,7 @@ class MyBackendConnector extends PowerSyncBackendConnector { } on AuthenticationException { // Fetch a new token before the next attempt. Like other transport errors, this doesn't count toward // retryMaxAttempts. - _authToken = null; + _authenticator.invalidateCredentials(); rethrow; } @@ -73,7 +110,7 @@ class MyBackendConnector extends PowerSyncBackendConnector { throw Exception('Unexpected transaction result: ${result['status']}'); } await transaction.complete(); - } + }); /// Called for fatal errors that the write API leaves to the client, and when a transaction reaches /// retryMaxAttempts. [FatalDecision.retain] keeps the transaction queued, which blocks later uploads, and the @@ -85,23 +122,6 @@ class MyBackendConnector extends PowerSyncBackendConnector { return FatalDecision.retain; } - /// Returns the token for sync and for the write API, which accepts the same JWTs as your PowerSync instance. - /// The token is cached until the write API rejects it. If your auth provider's SDK refreshes sessions itself, - /// return `_fetchAuthToken()` directly instead. - Future _getAuthToken() async { - return _authToken ??= await _fetchAuthToken(); - } - - /// Replace this with your auth provider's token retrieval. See https://docs.powersync.com/configuration/auth/overview - /// Supabase and Firebase tokens can be used as they are: - /// - https://docs.powersync.com/configuration/auth/supabase-auth - /// - https://docs.powersync.com/configuration/auth/firebase-auth - /// To use a development token with the write API, see - /// https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/auth/development-tokens.md - Future _fetchAuthToken() async { - return 'An authentication token'; - } - /// Sends one transaction to POST /api/data and returns its result. The request and response shapes are defined /// by the write API's OpenAPI spec: /// https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/backend/shared/powersync-reference-write-api.openapi.yaml @@ -129,7 +149,8 @@ class MyBackendConnector extends PowerSyncBackendConnector { Uri.parse('$backendUrl/api/data'), headers: { 'Content-Type': 'application/json', - 'Authorization': 'Bearer ${await _getAuthToken()}', + // The abort signal is a future that never completes, so the request for a token is never aborted. + 'Authorization': 'Bearer ${await _authenticator.resolveCredentials(Completer().future)}', }, body: jsonEncode(body), ) diff --git a/snippets/backend-connectors/generic/javascript.mdx b/snippets/backend-connectors/generic/javascript.mdx index c2336269..4cb964cc 100644 --- a/snippets/backend-connectors/generic/javascript.mdx +++ b/snippets/backend-connectors/generic/javascript.mdx @@ -1,8 +1,9 @@ ```javascript PowerSyncConnector.js // Uploads local writes to the PowerSync reference write API, one transaction per request. +// Requires @powersync/web 2.6.0 or later. // Set up the write API: https://docs.powersync.com/handling-writes/write-path/reference-write-implementation // If your backend has a different API, change the request and response handling in postTransaction() to match it, -// or have a coding agent write uploadData() for your API: +// or have a coding agent write the upload callback for your API: // https://docs.powersync.com/handling-writes/write-path/existing-api#prompt-for-your-coding-agent // For several transactions per request and client-side backoff, see the full reference connector: // https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/example-client/src/PowersyncConnector.singlefile.ts @@ -16,18 +17,62 @@ const REQUEST_TIMEOUT_MS = 30000; // Consecutive retryable errors for one transaction before it is passed to onFatalTransaction(). const RETRY_MAX_ATTEMPTS = 10; -export class MyBackendConnector { +/** Connects `db` for downloads and uploads. */ +export async function connect(db) { + const authenticator = new MyAuthenticator(); + await db.connect({ + powerSyncEndpoint: '[Your PowerSync instance URL or self-hosted endpoint]', + authenticator, + upload: new MyBackendConnector({ authenticator }).upload + }); +} + +/** + * Provides the token for sync and for the write API, which accepts the same JWTs as your PowerSync instance. + * The token is cached until it is about to expire, or the PowerSync Service or the write API rejects it. + */ +export class MyAuthenticator { constructor() { - this.authToken = null; - this.retryKey = null; - this.retryCount = 0; + this.token = null; } - async fetchCredentials() { - return { - endpoint: '[Your PowerSync instance URL or self-hosted endpoint]', - token: await this.getAuthToken() - }; + async resolveCredentials() { + if (!this.token) { + this.token = await this.fetchAuthToken(); + } + return this.token; + } + + /** + * Called by the SDK before the token expires and when the PowerSync Service rejects it, and by the connector + * when the write API rejects it. Keep this cache even if your auth provider's SDK refreshes sessions + * itself: the SDK isn't guaranteed to cache tokens. + */ + invalidateCredentials() { + this.token = null; + } + + /** + * Replace this with your auth provider's token retrieval. See https://docs.powersync.com/configuration/auth/overview + * Supabase and Firebase tokens can be used as they are: + * - https://docs.powersync.com/configuration/auth/supabase-auth + * - https://docs.powersync.com/configuration/auth/firebase-auth + * To use a development token with the write API, see + * https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/auth/development-tokens.md + */ + async fetchAuthToken() { + return 'An authentication token'; + } +} + +export class MyBackendConnector { + /** @param authenticator Supplies the token for write API requests. */ + constructor({ authenticator }) { + this.authenticator = authenticator; + this.retryKey = null; + this.retryCount = 0; + // connect() calls upload() without the connector, so bind it. + this.upload = this.upload.bind(this); } /** @@ -36,7 +81,7 @@ export class MyBackendConnector { * and the SDK retries after a delay. * See https://docs.powersync.com/configuration/app-backend/client-side-integration#when-uploaddata-is-called */ - async uploadData(database) { + async upload({ database }) { const transaction = await database.getNextCrudTransaction(); if (!transaction) { return; @@ -47,8 +92,8 @@ export class MyBackendConnector { result = await this.postTransaction(transaction); } catch (error) { // Network errors, timeouts and non-2xx responses. These don't count toward RETRY_MAX_ATTEMPTS. - if (error instanceof AuthenticationError) { - this.authToken = null; // Fetch a new token before the next attempt. + if (error instanceof AuthenticationError && this.authenticator.invalidateCredentials) { + this.authenticator.invalidateCredentials(); // Fetch a new token before the next attempt. } throw error; } @@ -82,30 +127,6 @@ export class MyBackendConnector { return 'retain'; } - /** - * Returns the token for sync and for the write API, which accepts the same JWTs as your PowerSync instance. - * The token is cached until the write API rejects it. If your auth provider's SDK refreshes sessions itself, - * return `this.fetchAuthToken()` directly instead. - */ - async getAuthToken() { - if (!this.authToken) { - this.authToken = await this.fetchAuthToken(); - } - return this.authToken; - } - - /** - * Replace this with your auth provider's token retrieval. See https://docs.powersync.com/configuration/auth/overview - * Supabase and Firebase tokens can be used as they are: - * - https://docs.powersync.com/configuration/auth/supabase-auth - * - https://docs.powersync.com/configuration/auth/firebase-auth - * To use a development token with the write API, see - * https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/auth/development-tokens.md - */ - async fetchAuthToken() { - return 'An authentication token'; - } - /** * Sends one transaction to POST /api/data and returns its result. The request and response shapes are defined * by the write API's OpenAPI spec: @@ -131,7 +152,7 @@ export class MyBackendConnector { method: 'POST', headers: { 'Content-Type': 'application/json', - Authorization: 'Bearer ' + (await this.getAuthToken()) + Authorization: 'Bearer ' + (await this.authenticator.resolveCredentials({})) }, body: JSON.stringify(body), signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) diff --git a/snippets/backend-connectors/generic/kotlin.mdx b/snippets/backend-connectors/generic/kotlin.mdx index 05385f4e..c8948ed0 100644 --- a/snippets/backend-connectors/generic/kotlin.mdx +++ b/snippets/backend-connectors/generic/kotlin.mdx @@ -1,8 +1,9 @@ ```kotlin PowerSync.kt // Uploads local writes to the PowerSync reference write API, one transaction per request. +// Requires PowerSync Kotlin SDK 1.16.0 or later. // Set up the write API: https://docs.powersync.com/handling-writes/write-path/reference-write-implementation // If your backend has a different API, change the request and response handling in postTransaction() to match it, -// or have a coding agent write uploadData() for your API: +// or have a coding agent write the upload callback for your API: // https://docs.powersync.com/handling-writes/write-path/existing-api#prompt-for-your-coding-agent // For several transactions per request and client-side backoff, see the full reference connector: // https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/example-client/src/PowersyncConnector.singlefile.ts @@ -10,8 +11,8 @@ // Uses the Ktor client and kotlinx.serialization JSON, which the PowerSync SDK already builds on. Add // them to your module if they are not there yet: https://ktor.io/docs/client-engines.html import com.powersync.PowerSyncDatabase -import com.powersync.connectors.PowerSyncBackendConnector -import com.powersync.connectors.PowerSyncCredentials +import com.powersync.connectors.Authenticator +import com.powersync.connectors.MutationUploader import com.powersync.db.crud.CrudTransaction import io.ktor.client.HttpClient import io.ktor.client.request.bearerAuth @@ -44,35 +45,68 @@ private const val REQUEST_TIMEOUT_MS = 30_000L /** Consecutive retryable errors for one transaction before it is passed to onFatalTransaction(). */ private const val RETRY_MAX_ATTEMPTS = 10 +/** Connects `db` for downloads and uploads. */ +suspend fun connect(db: PowerSyncDatabase) { + val authenticator = MyAuthenticator() + db.connect( + endpoint = "[Your PowerSync instance URL or self-hosted endpoint]", + authenticator = authenticator, + uploader = MyBackendConnector(authenticator), + ) +} + +/** + * Provides the token for sync and for the write API, which accepts the same JWTs as your PowerSync instance. + * The token is cached until it is about to expire, or the PowerSync Service or the write API rejects it. + */ +open class MyAuthenticator : Authenticator { + private var token: String? = null + + override suspend fun resolveCredentials(): String = token ?: fetchAuthToken().also { token = it } + + /** + * Called by the SDK before the token expires and when the PowerSync Service rejects it, and by the connector + * when the write API rejects it. Keep this cache even if your auth provider's SDK refreshes sessions + * itself: the SDK isn't guaranteed to cache tokens. + */ + override fun invalidateCredentials() { + token = null + } + + /** + * Replace this with your auth provider's token retrieval. See https://docs.powersync.com/configuration/auth/overview + * Supabase and Firebase tokens can be used as they are: + * - https://docs.powersync.com/configuration/auth/supabase-auth + * - https://docs.powersync.com/configuration/auth/firebase-auth + * To use a development token with the write API, see + * https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/auth/development-tokens.md + */ + private suspend fun fetchAuthToken(): String = "An authentication token" +} + +/** @param authenticator Supplies the token for write API requests. */ open class MyBackendConnector( + private val authenticator: Authenticator, private val httpClient: HttpClient = HttpClient(), -) : PowerSyncBackendConnector() { - private var authToken: String? = null +) : MutationUploader { private var retryKey: Any? = null private var retryCount = 0 - override suspend fun fetchCredentials(): PowerSyncCredentials? { - return PowerSyncCredentials( - endpoint = "[Your PowerSync instance URL or self-hosted endpoint]", - token = getAuthToken(), - ) - } - /** * Uploads the oldest queued transaction. The SDK calls this after local writes, on (re)connect and on * keepalives, and keeps calling it until the upload queue is empty. Throwing keeps the transaction queued, * and the SDK retries after a delay. * See https://docs.powersync.com/configuration/app-backend/client-side-integration#when-uploaddata-is-called */ - override suspend fun uploadData(database: PowerSyncDatabase) { - val transaction = database.getNextCrudTransaction() ?: return + override suspend fun uploadMutations(onDatabase: PowerSyncDatabase) { + val transaction = onDatabase.getNextCrudTransaction() ?: return val result = try { postTransaction(transaction) } catch (e: AuthenticationException) { // Fetch a new token before the next attempt. Like other transport errors, this doesn't count toward // RETRY_MAX_ATTEMPTS. - authToken = null + authenticator.invalidateCredentials() throw e }.let { applyRetryLimit(transaction, it) } @@ -103,23 +137,6 @@ open class MyBackendConnector( return FatalDecision.RETAIN } - /** - * Returns the token for sync and for the write API, which accepts the same JWTs as your PowerSync instance. - * The token is cached until the write API rejects it. If your auth provider's SDK refreshes sessions itself, - * return fetchAuthToken() directly instead. - */ - private suspend fun getAuthToken(): String = authToken ?: fetchAuthToken().also { authToken = it } - - /** - * Replace this with your auth provider's token retrieval. See https://docs.powersync.com/configuration/auth/overview - * Supabase and Firebase tokens can be used as they are: - * - https://docs.powersync.com/configuration/auth/supabase-auth - * - https://docs.powersync.com/configuration/auth/firebase-auth - * To use a development token with the write API, see - * https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/auth/development-tokens.md - */ - private suspend fun fetchAuthToken(): String = "An authentication token" - /** * Sends one transaction to POST /api/data and returns its result. The request and response shapes are defined * by the write API's OpenAPI spec: @@ -154,7 +171,7 @@ open class MyBackendConnector( val response = withTimeoutOrNull(REQUEST_TIMEOUT_MS) { httpClient.post("$BACKEND_URL/api/data") { contentType(ContentType.Application.Json) - bearerAuth(getAuthToken()) + bearerAuth(authenticator.resolveCredentials()) setBody(body.toString()) } } ?: throw Exception("Write API request timed out") diff --git a/snippets/backend-connectors/generic/react-native.mdx b/snippets/backend-connectors/generic/react-native.mdx index c0e69e55..82be5d42 100644 --- a/snippets/backend-connectors/generic/react-native.mdx +++ b/snippets/backend-connectors/generic/react-native.mdx @@ -1,10 +1,11 @@ ```typescript PowerSyncConnector.ts -import type { AbstractPowerSyncDatabase, CrudTransaction, PowerSyncBackendConnector } from '@powersync/react-native'; +import type { Authenticator, CommonPowerSyncDatabase, CrudTransaction, MutationUploader } from '@powersync/react-native'; // Uploads local writes to the PowerSync reference write API, one transaction per request. +// Requires @powersync/react-native 2.4.0 or later. // Set up the write API: https://docs.powersync.com/handling-writes/write-path/reference-write-implementation // If your backend has a different API, change the request and response handling in postTransaction() to match it, -// or have a coding agent write uploadData() for your API: +// or have a coding agent write the upload callback for your API: // https://docs.powersync.com/handling-writes/write-path/existing-api#prompt-for-your-coding-agent // For several transactions per request and client-side backoff, see the full reference connector: // https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/example-client/src/PowersyncConnector.singlefile.ts @@ -18,16 +19,58 @@ const REQUEST_TIMEOUT_MS = 30_000; /** Consecutive retryable errors for one transaction before it is passed to onFatalTransaction(). */ const RETRY_MAX_ATTEMPTS = 10; -export class MyBackendConnector implements PowerSyncBackendConnector { - private authToken: string | null = null; +/** Connects `db` for downloads and uploads. */ +export async function connect(db: CommonPowerSyncDatabase) { + const authenticator = new MyAuthenticator(); + await db.connect({ + powerSyncEndpoint: '[Your PowerSync instance URL or self-hosted endpoint]', + authenticator, + upload: new MyBackendConnector({ authenticator }).upload + }); +} + +/** + * Provides the token for sync and for the write API, which accepts the same JWTs as your PowerSync instance. + * The token is cached until it is about to expire, or the PowerSync Service or the write API rejects it. + */ +export class MyAuthenticator implements Authenticator { + private token: string | null = null; + + async resolveCredentials(): Promise { + this.token ??= await this.fetchAuthToken(); + return this.token; + } + + /** + * Called by the SDK before the token expires and when the PowerSync Service rejects it, and by the connector + * when the write API rejects it. Keep this cache even if your auth provider's SDK refreshes sessions + * itself: the SDK isn't guaranteed to cache tokens. + */ + invalidateCredentials(): void { + this.token = null; + } + + /** + * Replace this with your auth provider's token retrieval. See https://docs.powersync.com/configuration/auth/overview + * Supabase and Firebase tokens can be used as they are: + * - https://docs.powersync.com/configuration/auth/supabase-auth + * - https://docs.powersync.com/configuration/auth/firebase-auth + * To use a development token with the write API, see + * https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/auth/development-tokens.md + */ + private async fetchAuthToken(): Promise { + return 'An authentication token'; + } +} + +export class MyBackendConnector { + private readonly authenticator: Authenticator; private retryKey: number | string | null = null; private retryCount = 0; - async fetchCredentials() { - return { - endpoint: '[Your PowerSync instance URL or self-hosted endpoint]', - token: await this.getAuthToken() - }; + /** @param authenticator Supplies the token for write API requests. */ + constructor({ authenticator }: { authenticator: Authenticator }) { + this.authenticator = authenticator; } /** @@ -36,7 +79,7 @@ export class MyBackendConnector implements PowerSyncBackendConnector { * and the SDK retries after a delay. * See https://docs.powersync.com/configuration/app-backend/client-side-integration#when-uploaddata-is-called */ - async uploadData(database: AbstractPowerSyncDatabase): Promise { + readonly upload: MutationUploader = async ({ database }) => { const transaction = await database.getNextCrudTransaction(); if (!transaction) { return; @@ -48,7 +91,7 @@ export class MyBackendConnector implements PowerSyncBackendConnector { } catch (error) { // Network errors, timeouts and non-2xx responses. These don't count toward RETRY_MAX_ATTEMPTS. if (error instanceof AuthenticationError) { - this.authToken = null; // Fetch a new token before the next attempt. + this.authenticator.invalidateCredentials?.(); // Fetch a new token before the next attempt. } throw error; } @@ -69,7 +112,7 @@ export class MyBackendConnector implements PowerSyncBackendConnector { // Success, a fatal error that the write API already handled (for example, with a dead-letter hook), // or a fatal error that onFatalTransaction() chose to discard. await transaction.complete(); - } + }; /** * Called for fatal errors that the write API leaves to the client, and when a transaction reaches @@ -85,30 +128,6 @@ export class MyBackendConnector implements PowerSyncBackendConnector { return 'retain'; } - /** - * Returns the token for sync and for the write API, which accepts the same JWTs as your PowerSync instance. - * The token is cached until the write API rejects it. If your auth provider's SDK refreshes sessions itself, - * return `this.fetchAuthToken()` directly instead. - */ - private async getAuthToken(): Promise { - if (!this.authToken) { - this.authToken = await this.fetchAuthToken(); - } - return this.authToken; - } - - /** - * Replace this with your auth provider's token retrieval. See https://docs.powersync.com/configuration/auth/overview - * Supabase and Firebase tokens can be used as they are: - * - https://docs.powersync.com/configuration/auth/supabase-auth - * - https://docs.powersync.com/configuration/auth/firebase-auth - * To use a development token with the write API, see - * https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/auth/development-tokens.md - */ - private async fetchAuthToken(): Promise { - return 'An authentication token'; - } - /** Sends one transaction to POST /api/data and returns its result. */ private async postTransaction(transaction: CrudTransaction): Promise { const body = { @@ -135,7 +154,7 @@ export class MyBackendConnector implements PowerSyncBackendConnector { method: 'POST', headers: { 'Content-Type': 'application/json', - Authorization: `Bearer ${await this.getAuthToken()}` + Authorization: `Bearer ${await this.authenticator.resolveCredentials({})}` }, body: JSON.stringify(body), signal: controller.signal diff --git a/snippets/backend-connectors/generic/rust.mdx b/snippets/backend-connectors/generic/rust.mdx index 053bf026..f21889e2 100644 --- a/snippets/backend-connectors/generic/rust.mdx +++ b/snippets/backend-connectors/generic/rust.mdx @@ -71,8 +71,8 @@ impl Authenticator for MyAuthenticator { } /// Called by the SDK when the PowerSync Service rejects the token, and by the uploader when the write API - /// rejects it. If your auth provider's SDK refreshes sessions itself, return its current token from - /// resolve_credentials() instead of caching it. + /// rejects it. Keep this cache even if your auth provider's SDK refreshes sessions + /// itself: the SDK isn't guaranteed to cache tokens. fn invalidate_credentials(&self) { *self.token.lock().unwrap() = None; } diff --git a/snippets/backend-connectors/generic/swift.mdx b/snippets/backend-connectors/generic/swift.mdx index 43e67e7c..e016e1ea 100644 --- a/snippets/backend-connectors/generic/swift.mdx +++ b/snippets/backend-connectors/generic/swift.mdx @@ -1,8 +1,9 @@ ```swift PowerSyncConnector.swift // Uploads local writes to the PowerSync reference write API, one transaction per request. +// Requires PowerSync Swift SDK 1.17.0 or later. // Set up the write API: https://docs.powersync.com/handling-writes/write-path/reference-write-implementation // If your backend has a different API, change the request and response handling in postTransaction() to match it, -// or have a coding agent write uploadData() for your API: +// or have a coding agent write the upload callback for your API: // https://docs.powersync.com/handling-writes/write-path/existing-api#prompt-for-your-coding-agent // For several transactions per request and client-side backoff, see the full reference connector: // https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/example-client/src/PowersyncConnector.singlefile.ts @@ -18,24 +19,66 @@ private let requestTimeout: TimeInterval = 30 /// Consecutive retryable errors for one transaction before it is passed to onFatalTransaction(). private let retryMaxAttempts = 10 -/// An actor, because the SDK requires a Sendable connector and this one caches a token and a retry count. -actor MyBackendConnector: PowerSyncBackendConnectorProtocol { - private var authToken: String? +/// Connects `db` for downloads and uploads. +func connect(db: PowerSyncDatabaseProtocol) async throws { + let authenticator = MyAuthenticator() + try await db.connect( + endpoint: "[Your PowerSync instance URL or self-hosted endpoint]", + authenticator: authenticator, + mutationUploader: MyBackendConnector(authenticator: authenticator).upload, + options: ConnectOptions() + ) +} + +/// Provides the token for sync and for the write API, which accepts the same JWTs as your PowerSync instance. +/// The token is cached until it is about to expire, or the PowerSync Service or the write API rejects it. +/// An actor, because the SDK requires a Sendable authenticator and this one caches a token. +actor MyAuthenticator: Authenticator { + private var token: String? + + func resolveCredentials() async throws -> String { + if let token { + return token + } + let token = try await fetchAuthToken() + self.token = token + return token + } + + /// Called by the SDK before the token expires and when the PowerSync Service rejects it, and by the connector + /// when the write API rejects it. Keep this cache even if your auth provider's SDK refreshes sessions + /// itself: the SDK isn't guaranteed to cache tokens. + func invalidateCredentials() async { + token = nil + } + + /// Replace this with your auth provider's token retrieval. See https://docs.powersync.com/configuration/auth/overview + /// Supabase and Firebase tokens can be used as they are: + /// - https://docs.powersync.com/configuration/auth/supabase-auth + /// - https://docs.powersync.com/configuration/auth/firebase-auth + /// To use a development token with the write API, see + /// https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/auth/development-tokens.md + private func fetchAuthToken() async throws -> String { + return "An authentication token" + } +} + +/// An actor, because the SDK requires a Sendable upload callback and this connector keeps a retry count. +actor MyBackendConnector { + private let authenticator: Authenticator private var retryKey: Int64? private var retryCount = 0 - func fetchCredentials() async throws -> PowerSyncCredentials? { - return PowerSyncCredentials( - endpoint: "[Your PowerSync instance URL or self-hosted endpoint]", - token: try await getAuthToken() - ) + /// - Parameter authenticator: Supplies the token for write API requests. + init(authenticator: Authenticator) { + self.authenticator = authenticator } /// Uploads the oldest queued transaction. The SDK calls this after local writes, on (re)connect and on /// keepalives, and keeps calling it until the upload queue is empty. Throwing keeps the transaction queued, /// and the SDK retries after a delay. /// See https://docs.powersync.com/configuration/app-backend/client-side-integration#when-uploaddata-is-called - func uploadData(database: PowerSyncDatabaseProtocol) async throws { + func upload(database: PowerSyncDatabaseProtocol) async throws { guard let transaction = try await database.getNextCrudTransaction() else { return } @@ -46,7 +89,7 @@ actor MyBackendConnector: PowerSyncBackendConnectorProtocol { } catch let error as AuthenticationError { // Fetch a new token before the next attempt. Like other transport errors, this doesn't count toward // retryMaxAttempts. - authToken = nil + await authenticator.invalidateCredentials() throw error } @@ -79,28 +122,6 @@ actor MyBackendConnector: PowerSyncBackendConnectorProtocol { return .retain } - /// Returns the token for sync and for the write API, which accepts the same JWTs as your PowerSync instance. - /// The token is cached until the write API rejects it. If your auth provider's SDK refreshes sessions itself, - /// return `fetchAuthToken()` directly instead. - private func getAuthToken() async throws -> String { - if let authToken { - return authToken - } - let token = try await fetchAuthToken() - authToken = token - return token - } - - /// Replace this with your auth provider's token retrieval. See https://docs.powersync.com/configuration/auth/overview - /// Supabase and Firebase tokens can be used as they are: - /// - https://docs.powersync.com/configuration/auth/supabase-auth - /// - https://docs.powersync.com/configuration/auth/firebase-auth - /// To use a development token with the write API, see - /// https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/auth/development-tokens.md - private func fetchAuthToken() async throws -> String { - return "An authentication token" - } - /// Sends one transaction to POST /api/data and returns its result. The request and response shapes are defined /// by the write API's OpenAPI spec: /// https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/backend/shared/powersync-reference-write-api.openapi.yaml @@ -124,7 +145,7 @@ actor MyBackendConnector: PowerSyncBackendConnectorProtocol { request.httpMethod = "POST" request.timeoutInterval = requestTimeout request.setValue("application/json", forHTTPHeaderField: "Content-Type") - request.setValue("Bearer \(try await getAuthToken())", forHTTPHeaderField: "Authorization") + request.setValue("Bearer \(try await authenticator.resolveCredentials())", forHTTPHeaderField: "Authorization") request.httpBody = try JSONEncoder().encode(body) let (data, response) = try await URLSession.shared.data(for: request) diff --git a/snippets/backend-connectors/generic/typescript.mdx b/snippets/backend-connectors/generic/typescript.mdx index b459eff7..c9e88b59 100644 --- a/snippets/backend-connectors/generic/typescript.mdx +++ b/snippets/backend-connectors/generic/typescript.mdx @@ -1,10 +1,11 @@ ```typescript PowerSyncConnector.ts -import type { AbstractPowerSyncDatabase, CrudTransaction, PowerSyncBackendConnector } from '@powersync/web'; +import type { Authenticator, CommonPowerSyncDatabase, CrudTransaction, MutationUploader } from '@powersync/web'; // Uploads local writes to the PowerSync reference write API, one transaction per request. +// Requires @powersync/web 2.6.0 or later. // Set up the write API: https://docs.powersync.com/handling-writes/write-path/reference-write-implementation // If your backend has a different API, change the request and response handling in postTransaction() to match it, -// or have a coding agent write uploadData() for your API: +// or have a coding agent write the upload callback for your API: // https://docs.powersync.com/handling-writes/write-path/existing-api#prompt-for-your-coding-agent // For several transactions per request and client-side backoff, see the full reference connector: // https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/example-client/src/PowersyncConnector.singlefile.ts @@ -18,16 +19,58 @@ const REQUEST_TIMEOUT_MS = 30_000; /** Consecutive retryable errors for one transaction before it is passed to onFatalTransaction(). */ const RETRY_MAX_ATTEMPTS = 10; -export class MyBackendConnector implements PowerSyncBackendConnector { - private authToken: string | null = null; +/** Connects `db` for downloads and uploads. */ +export async function connect(db: CommonPowerSyncDatabase) { + const authenticator = new MyAuthenticator(); + await db.connect({ + powerSyncEndpoint: '[Your PowerSync instance URL or self-hosted endpoint]', + authenticator, + upload: new MyBackendConnector({ authenticator }).upload + }); +} + +/** + * Provides the token for sync and for the write API, which accepts the same JWTs as your PowerSync instance. + * The token is cached until it is about to expire, or the PowerSync Service or the write API rejects it. + */ +export class MyAuthenticator implements Authenticator { + private token: string | null = null; + + async resolveCredentials(): Promise { + this.token ??= await this.fetchAuthToken(); + return this.token; + } + + /** + * Called by the SDK before the token expires and when the PowerSync Service rejects it, and by the connector + * when the write API rejects it. Keep this cache even if your auth provider's SDK refreshes sessions + * itself: the SDK isn't guaranteed to cache tokens. + */ + invalidateCredentials(): void { + this.token = null; + } + + /** + * Replace this with your auth provider's token retrieval. See https://docs.powersync.com/configuration/auth/overview + * Supabase and Firebase tokens can be used as they are: + * - https://docs.powersync.com/configuration/auth/supabase-auth + * - https://docs.powersync.com/configuration/auth/firebase-auth + * To use a development token with the write API, see + * https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/auth/development-tokens.md + */ + private async fetchAuthToken(): Promise { + return 'An authentication token'; + } +} + +export class MyBackendConnector { + private readonly authenticator: Authenticator; private retryKey: number | string | null = null; private retryCount = 0; - async fetchCredentials() { - return { - endpoint: '[Your PowerSync instance URL or self-hosted endpoint]', - token: await this.getAuthToken() - }; + /** @param authenticator Supplies the token for write API requests. */ + constructor({ authenticator }: { authenticator: Authenticator }) { + this.authenticator = authenticator; } /** @@ -36,7 +79,7 @@ export class MyBackendConnector implements PowerSyncBackendConnector { * and the SDK retries after a delay. * See https://docs.powersync.com/configuration/app-backend/client-side-integration#when-uploaddata-is-called */ - async uploadData(database: AbstractPowerSyncDatabase): Promise { + readonly upload: MutationUploader = async ({ database }) => { const transaction = await database.getNextCrudTransaction(); if (!transaction) { return; @@ -48,7 +91,7 @@ export class MyBackendConnector implements PowerSyncBackendConnector { } catch (error) { // Network errors, timeouts and non-2xx responses. These don't count toward RETRY_MAX_ATTEMPTS. if (error instanceof AuthenticationError) { - this.authToken = null; // Fetch a new token before the next attempt. + this.authenticator.invalidateCredentials?.(); // Fetch a new token before the next attempt. } throw error; } @@ -69,7 +112,7 @@ export class MyBackendConnector implements PowerSyncBackendConnector { // Success, a fatal error that the write API already handled (for example, with a dead-letter hook), // or a fatal error that onFatalTransaction() chose to discard. await transaction.complete(); - } + }; /** * Called for fatal errors that the write API leaves to the client, and when a transaction reaches @@ -85,30 +128,6 @@ export class MyBackendConnector implements PowerSyncBackendConnector { return 'retain'; } - /** - * Returns the token for sync and for the write API, which accepts the same JWTs as your PowerSync instance. - * The token is cached until the write API rejects it. If your auth provider's SDK refreshes sessions itself, - * return `this.fetchAuthToken()` directly instead. - */ - private async getAuthToken(): Promise { - if (!this.authToken) { - this.authToken = await this.fetchAuthToken(); - } - return this.authToken; - } - - /** - * Replace this with your auth provider's token retrieval. See https://docs.powersync.com/configuration/auth/overview - * Supabase and Firebase tokens can be used as they are: - * - https://docs.powersync.com/configuration/auth/supabase-auth - * - https://docs.powersync.com/configuration/auth/firebase-auth - * To use a development token with the write API, see - * https://github.com/powersync-ja/powersync-reference-write-implementation/blob/main/docs/auth/development-tokens.md - */ - private async fetchAuthToken(): Promise { - return 'An authentication token'; - } - /** Sends one transaction to POST /api/data and returns its result. */ private async postTransaction(transaction: CrudTransaction): Promise { const body = { @@ -130,7 +149,7 @@ export class MyBackendConnector implements PowerSyncBackendConnector { method: 'POST', headers: { 'Content-Type': 'application/json', - Authorization: `Bearer ${await this.getAuthToken()}` + Authorization: `Bearer ${await this.authenticator.resolveCredentials({})}` }, body: JSON.stringify(body), signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) diff --git a/snippets/backend-connectors/supabase/dart.mdx b/snippets/backend-connectors/supabase/dart.mdx index f2bfc753..8c241579 100644 --- a/snippets/backend-connectors/supabase/dart.mdx +++ b/snippets/backend-connectors/supabase/dart.mdx @@ -1,5 +1,6 @@ ```dart lib/powersync.dart // This file performs setup of the PowerSync database +// Requires powersync 2.6.0 or later. import 'package:flutter/foundation.dart'; import 'package:logging/logging.dart'; import 'package:path/path.dart'; @@ -27,43 +28,57 @@ final List fatalResponseCodes = [ ]; /// Use Supabase for authentication and data upload. -class SupabaseConnector extends PowerSyncBackendConnector { +// The connector is the Authenticator for sync and provides the upload callback. Connect with: +// db.connect(connector: ConnectRequest(endpoint: AppConfig.powersyncUrl, authenticator: connector, uploader: connector.upload)); +class SupabaseConnector implements Authenticator { PowerSyncDatabase db; Future? _refreshFuture; + String? _cachedToken; + SupabaseConnector(this.db); - /// Get a Supabase token to authenticate against the PowerSync instance. + /// Returns the Supabase access token for sync. Keep the cache: the SDK isn't + /// guaranteed to cache tokens. The SDK calls [invalidateCredentials] only + /// when the token has expired or the PowerSync Service rejects it, and this + /// method then waits for the session refresh that it starts. + /// `currentSession` doesn't refresh an expired session by itself, so an + /// expired session is refreshed here before its token is used. @override - Future fetchCredentials() async { + Future resolveCredentials(Future abortSignal) async { + if (_cachedToken case final token?) { + return token; + } + // Wait for pending session refresh if any await _refreshFuture; // Use Supabase token for PowerSync - final session = Supabase.instance.client.auth.currentSession; + final auth = Supabase.instance.client.auth; + var session = auth.currentSession; if (session == null) { // Not logged in - return null; + throw StateError('Not logged in'); + } + if (session.isExpired) { + // Throws if the refresh fails. The SDK then retries after a delay. + session = (await auth.refreshSession()).session ?? session; } // Use the access token to authenticate against PowerSync - final token = session.accessToken; - - // userId and expiresAt are for debugging purposes only - final userId = session.user.id; - final expiresAt = session.expiresAt == null - ? null - : DateTime.fromMillisecondsSinceEpoch(session.expiresAt! * 1000); - return PowerSyncCredentials( - endpoint: AppConfig.powersyncUrl, - token: token, - userId: userId, - expiresAt: expiresAt); + return _cachedToken = session.accessToken; + } + + /// Clears the cached token after a session change. + void clearCachedToken() { + _cachedToken = null; // A new session has a new token. } @override void invalidateCredentials() { + _cachedToken = null; + // Trigger a session refresh if auth fails on PowerSync. // Generally, sessions should be refreshed automatically by Supabase. // However, in some cases it can be a while before the session refresh is @@ -74,7 +89,8 @@ class SupabaseConnector extends PowerSyncBackendConnector { // expired, and nothing else attempt to use the session it in the meantime. // // Timeout the refresh call to avoid waiting for long retries, - // and ignore any errors. Errors will surface as expired tokens. + // and ignore any errors. resolveCredentials retries the refresh if the + // session is still expired. _refreshFuture = Supabase.instance.client.auth .refreshSession() .timeout(const Duration(seconds: 5)) @@ -82,8 +98,8 @@ class SupabaseConnector extends PowerSyncBackendConnector { } // Upload pending changes to Supabase. - @override - Future uploadData(PowerSyncDatabase database) async { + late final MutationUploader upload = + MutationUploader((PowerSyncDatabase database) async { // This function is called whenever there is data to upload, whether the // device is online or offline. // If this call throws an error, it is retried periodically. @@ -131,7 +147,7 @@ class SupabaseConnector extends PowerSyncBackendConnector { rethrow; } } - } + }); } /// Global reference to the database @@ -170,7 +186,11 @@ Future openDatabase() async { // If the user is already logged in, connect immediately. // Otherwise, connect once logged in. currentConnector = SupabaseConnector(db); - db.connect(connector: currentConnector); + db.connect( + connector: ConnectRequest( + endpoint: AppConfig.powersyncUrl, + authenticator: currentConnector, + uploader: currentConnector.upload)); } Supabase.instance.client.auth.onAuthStateChange.listen((data) async { @@ -178,14 +198,18 @@ Future openDatabase() async { if (event == AuthChangeEvent.signedIn) { // Connect to PowerSync when the user is signed in currentConnector = SupabaseConnector(db); - db.connect(connector: currentConnector!); + db.connect( + connector: ConnectRequest( + endpoint: AppConfig.powersyncUrl, + authenticator: currentConnector!, + uploader: currentConnector!.upload)); } else if (event == AuthChangeEvent.signedOut) { // Implicit sign out - disconnect, but don't delete data currentConnector = null; await db.disconnect(); } else if (event == AuthChangeEvent.tokenRefreshed) { - // Supabase token refreshed - trigger token refresh for PowerSync. - currentConnector?.prefetchCredentials(); + // Supabase token refreshed - PowerSync uses the new token on its next request. + currentConnector?.clearCachedToken(); } }); diff --git a/snippets/backend-connectors/supabase/javascript.mdx b/snippets/backend-connectors/supabase/javascript.mdx index d87ed3e5..0b26eb7d 100644 --- a/snippets/backend-connectors/supabase/javascript.mdx +++ b/snippets/backend-connectors/supabase/javascript.mdx @@ -1,4 +1,5 @@ ```javascript PowerSyncConnector.js +// Requires @powersync/web 2.6.0 or later. import { BaseObserver, UpdateType } from '@powersync/web'; import { createClient } from '@supabase/supabase-js'; @@ -15,9 +16,14 @@ const FATAL_RESPONSE_CODES = [ new RegExp('^42501$') ]; +// The connector is the Authenticator for sync and provides the upload callback. Connect with: +// await db.connect({ powerSyncEndpoint: connector.config.powersyncUrl, authenticator: connector, upload: connector.upload }); export class SupabaseConnector extends BaseObserver { constructor() { super(); + this.cachedToken = null; + // connect() calls upload() without the connector, so bind it. + this.upload = this.upload.bind(this); this.config = { supabaseUrl: import.meta.env.VITE_SUPABASE_URL, powersyncUrl: import.meta.env.VITE_POWERSYNC_URL, @@ -61,7 +67,16 @@ export class SupabaseConnector extends BaseObserver { this.updateSession(session); } - async fetchCredentials() { + /** + * Returns the Supabase access token for sync. Keep the cache: the SDK isn't guaranteed to cache tokens. + * After invalidateCredentials() clears it, getSession() returns a valid session, because supabase-js refreshes + * the session when it expires within 90 seconds. + */ + async resolveCredentials() { + if (this.cachedToken) { + return this.cachedToken; + } + const { data: { session }, error @@ -73,13 +88,17 @@ export class SupabaseConnector extends BaseObserver { console.debug('session expires at', session.expires_at); - return { - endpoint: this.config.powersyncUrl, - token: session.access_token ?? '' - }; + this.cachedToken = session.access_token; + return this.cachedToken; + } + + /** Called by the SDK before the token expires and when the PowerSync Service rejects it. */ + invalidateCredentials() { + this.cachedToken = null; } - async uploadData(database) { + /** Uploads the oldest queued transaction. Throwing keeps it queued, and the SDK retries after a delay. */ + async upload({ database }) { const transaction = await database.getNextCrudTransaction(); if (!transaction) { @@ -139,6 +158,7 @@ export class SupabaseConnector extends BaseObserver { updateSession(session) { this.currentSession = session; + this.cachedToken = null; // A new session has a new token. if (!session) { return; } diff --git a/snippets/backend-connectors/supabase/kotlin.mdx b/snippets/backend-connectors/supabase/kotlin.mdx index ec1236fd..5ce14e3b 100644 --- a/snippets/backend-connectors/supabase/kotlin.mdx +++ b/snippets/backend-connectors/supabase/kotlin.mdx @@ -1,10 +1,11 @@ ```kotlin PowerSync.kt +// Requires PowerSync Kotlin SDK 1.16.0 or later. package com.powersync.connector.supabase import co.touchlab.kermit.Logger import com.powersync.PowerSyncDatabase -import com.powersync.connectors.PowerSyncBackendConnector -import com.powersync.connectors.PowerSyncCredentials +import com.powersync.connectors.Authenticator +import com.powersync.connectors.MutationUploader import com.powersync.db.crud.CrudEntry import com.powersync.db.crud.CrudTransaction import com.powersync.db.crud.UpdateType @@ -29,8 +30,13 @@ import io.ktor.utils.io.InternalAPI import kotlinx.coroutines.flow.StateFlow import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonPrimitive +import kotlin.time.Clock +import kotlin.time.Duration.Companion.minutes import kotlin.toString +// The connector is the Authenticator for sync and the MutationUploader for uploads. Connect with: +// db.connect(connector.powerSyncEndpoint, authenticator = connector, uploader = connector) + /** * Get a Supabase token to authenticate against the PowerSync instance. */ @@ -39,9 +45,11 @@ public open class SupabaseConnector( public val supabaseClient: SupabaseClient, public val powerSyncEndpoint: String, private val storageBucket: String? = null, -) : PowerSyncBackendConnector() { +) : Authenticator, + MutationUploader { private val json = Json { coerceInputValues = true } private var errorCode: String? = null + private var cachedToken: String? = null public companion object PostgresFatalCodes { // Using Regex patterns for Postgres error codes @@ -124,6 +132,7 @@ public open class SupabaseConnector( this.email = email this.password = password } + cachedToken = null // A new session has a new token. } } @@ -136,12 +145,14 @@ public open class SupabaseConnector( this.email = email this.password = password } + cachedToken = null // A new session has a new token. } } public suspend fun signOut() { runWrapped { supabaseClient.auth.signOut() + cachedToken = null } } @@ -152,33 +163,50 @@ public open class SupabaseConnector( public suspend fun loginAnonymously() { runWrapped { supabaseClient.auth.signInAnonymously() + cachedToken = null // A new session has a new token. } } /** - * Get credentials for PowerSync. + * Returns the Supabase access token for sync. Keep the cache: the SDK isn't guaranteed to cache tokens. + * + * After [invalidateCredentials] clears the cache, this returns a valid token. The Supabase client refreshes + * the session in the background, but [io.github.jan.supabase.auth.Auth.currentSessionOrNull] only returns the + * stored session and never refreshes it. If that background refresh hasn't run, for example because the app was + * suspended or offline, the stored token can be expired, so it is refreshed here first. */ - override suspend fun fetchCredentials(): PowerSyncCredentials = + override suspend fun resolveCredentials(): String = runWrapped { + cachedToken?.let { return@runWrapped it } + check(supabaseClient.auth.sessionStatus.value is SessionStatus.Authenticated) { "Supabase client is not authenticated" } // Use Supabase token for PowerSync - val session = + var session = supabaseClient.auth.currentSessionOrNull() ?: error("Could not fetch Supabase credentials") + if (session.expiresAt <= Clock.System.now() + 1.minutes) { + supabaseClient.auth.refreshCurrentSession() + session = supabaseClient.auth.currentSessionOrNull() + ?: error("Could not fetch Supabase credentials") + } + check(session.user != null) { "No user data" } - PowerSyncCredentials( - endpoint = powerSyncEndpoint, - token = session.accessToken, // Use the access token to authenticate against PowerSync - ) + // Use the access token to authenticate against PowerSync + session.accessToken.also { cachedToken = it } } + /** Called by the SDK before the token expires and when the PowerSync Service rejects it. */ + override fun invalidateCredentials() { + cachedToken = null + } + /** * Uses the PostgREST APIs to upload a given [entry] to the backend database. * - * This method should report errors during the upload as an exception that would be caught by [uploadData]. + * This method should report errors during the upload as an exception that would be caught by [uploadMutations]. */ public open suspend fun uploadCrudEntry(entry: CrudEntry) { val table = supabaseClient.from(entry.table) @@ -253,9 +281,9 @@ public open class SupabaseConnector( * This function is called whenever there is data to upload, whether the device is online or offline. * If this call throws an error, it is retried periodically. */ - override suspend fun uploadData(database: PowerSyncDatabase) { + override suspend fun uploadMutations(onDatabase: PowerSyncDatabase) { return runWrapped { - val transaction = database.getNextCrudTransaction() ?: return@runWrapped + val transaction = onDatabase.getNextCrudTransaction() ?: return@runWrapped var lastEntry: CrudEntry? = null try { diff --git a/snippets/backend-connectors/supabase/react-native.mdx b/snippets/backend-connectors/supabase/react-native.mdx index c8e22c57..e1c028a1 100644 --- a/snippets/backend-connectors/supabase/react-native.mdx +++ b/snippets/backend-connectors/supabase/react-native.mdx @@ -1,5 +1,6 @@ ```typescript PowerSyncConnector.ts -import { UpdateType, type CommonPowerSyncDatabase, type CrudEntry, type PowerSyncBackendConnector, type PowerSyncCredentials } from '@powersync/react-native'; +// Requires @powersync/react-native 2.4.0 or later. +import { UpdateType, type Authenticator, type CrudEntry, type MutationUploader } from '@powersync/react-native'; import { SupabaseClient, createClient } from '@supabase/supabase-js'; import { AppConfig } from './AppConfig'; @@ -18,9 +19,12 @@ const FATAL_RESPONSE_CODES = [ new RegExp('^42501$') ]; -export class SupabaseConnector implements PowerSyncBackendConnector { +// The connector is the Authenticator for sync and provides the upload callback. Connect with: +// await db.connect({ powerSyncEndpoint: AppConfig.powersyncUrl, authenticator: connector, upload: connector.upload }); +export class SupabaseConnector implements Authenticator { client: SupabaseClient; storage: SupabaseStorageAdapter; + private cachedToken: string | null = null; constructor(protected system: System) { this.client = createClient(AppConfig.supabaseUrl, AppConfig.supabaseAnonKey, { @@ -41,6 +45,7 @@ export class SupabaseConnector implements PowerSyncBackendConnector { if (error) { throw error; } + this.cachedToken = null; // A new session has a new token. } async userId() { @@ -51,7 +56,16 @@ export class SupabaseConnector implements PowerSyncBackendConnector { return session?.user.id; } - async fetchCredentials() { + /** + * Returns the Supabase access token for sync. Keep the cache: the SDK isn't guaranteed to cache tokens. + * After invalidateCredentials() clears it, getSession() returns a valid session, because supabase-js refreshes + * the session when it expires within 90 seconds. + */ + async resolveCredentials(): Promise { + if (this.cachedToken) { + return this.cachedToken; + } + const { data: { session }, error @@ -63,13 +77,17 @@ export class SupabaseConnector implements PowerSyncBackendConnector { console.debug('session expires at', session.expires_at); - return { - endpoint: AppConfig.powersyncUrl, - token: session.access_token ?? '' - } satisfies PowerSyncCredentials; + this.cachedToken = session.access_token; + return this.cachedToken; } - async uploadData(database: CommonPowerSyncDatabase): Promise { + /** Called by the SDK before the token expires and when the PowerSync Service rejects it. */ + invalidateCredentials(): void { + this.cachedToken = null; + } + + /** Uploads the oldest queued transaction. Throwing keeps it queued, and the SDK retries after a delay. */ + readonly upload: MutationUploader = async ({ database }) => { const transaction = await database.getNextCrudTransaction(); if (!transaction) { @@ -91,7 +109,7 @@ export class SupabaseConnector implements PowerSyncBackendConnector { result = await table.upsert(record); break; case UpdateType.PATCH: - result = await table.update(op.opData).eq('id', op.id); + result = await table.update(op.opData ?? {}).eq('id', op.id); break; case UpdateType.DELETE: result = await table.delete().eq('id', op.id); @@ -125,6 +143,6 @@ export class SupabaseConnector implements PowerSyncBackendConnector { throw ex; } } - } + }; } ``` diff --git a/snippets/backend-connectors/supabase/swift.mdx b/snippets/backend-connectors/supabase/swift.mdx index 7de19fc2..bdfb6c0a 100644 --- a/snippets/backend-connectors/supabase/swift.mdx +++ b/snippets/backend-connectors/supabase/swift.mdx @@ -1,4 +1,5 @@ ```swift PowerSyncConnector.swift +// Requires PowerSync Swift SDK 1.17.0 or later. import AnyCodable import Auth import PowerSync @@ -38,9 +39,11 @@ private enum PostgresFatalCodes { } } +// The connector is the Authenticator for sync and provides the upload callback. Connect with: +// try await db.connect(endpoint: connector.powerSyncEndpoint, authenticator: connector, mutationUploader: connector.upload, options: ConnectOptions()) @Observable @MainActor // _session is mutable, limiting to the MainActor satisfies Sendable constraints -final class SupabaseConnector: PowerSyncBackendConnectorProtocol { +final class SupabaseConnector: PowerSync.Authenticator { let powerSyncEndpoint: String = Secrets.powerSyncEndpoint let client: SupabaseClient = .init( supabaseURL: Secrets.supabaseURL, @@ -49,6 +52,9 @@ final class SupabaseConnector: PowerSyncBackendConnectorProtocol { private(set) var session: Session? private var errorCode: String? + @ObservationIgnored + private var cachedToken: String? + @ObservationIgnored private var observeAuthStateChangesTask: Task? @@ -61,6 +67,7 @@ final class SupabaseConnector: PowerSyncBackendConnectorProtocol { guard [.initialSession, .signedIn, .signedOut].contains(event) else { throw AuthError.sessionMissing } self.session = session + self.cachedToken = nil // A new session has a new token. } } } @@ -81,7 +88,14 @@ final class SupabaseConnector: PowerSyncBackendConnectorProtocol { return client.storage.from(bucket) } - func fetchCredentials() async throws -> PowerSyncCredentials? { + /// Returns the Supabase access token for sync. Keep the cache: the SDK isn't guaranteed to cache tokens. + /// After invalidateCredentials() clears it, `client.auth.session` returns a valid session, because supabase-swift + /// refreshes the session when it expires within 30 seconds. + func resolveCredentials() async throws -> String { + if let cachedToken { + return cachedToken + } + session = try await client.auth.session if session == nil { @@ -90,10 +104,17 @@ final class SupabaseConnector: PowerSyncBackendConnectorProtocol { let token = session!.accessToken - return PowerSyncCredentials(endpoint: powerSyncEndpoint, token: token) + cachedToken = token + return token + } + + /// Called by the SDK before the token expires and when the PowerSync Service rejects it. + func invalidateCredentials() async { + cachedToken = nil } - func uploadData(database: PowerSyncDatabaseProtocol) async throws { + /// Uploads the oldest queued transaction. Throwing keeps it queued, and the SDK retries after a delay. + func upload(database: PowerSyncDatabaseProtocol) async throws { guard let transaction = try await database.getNextCrudTransaction() else { return } var lastEntry: CrudEntry? diff --git a/snippets/backend-connectors/supabase/typescript.mdx b/snippets/backend-connectors/supabase/typescript.mdx index 6a8d6f85..7257aa1e 100644 --- a/snippets/backend-connectors/supabase/typescript.mdx +++ b/snippets/backend-connectors/supabase/typescript.mdx @@ -1,12 +1,6 @@ ```typescript PowerSyncConnector.ts -import { - BaseObserver, - UpdateType, - type CommonPowerSyncDatabase, - type CrudEntry, - type PowerSyncBackendConnector, - type PowerSyncCredentials -} from '@powersync/web'; +// Requires @powersync/web 2.6.0 or later. +import { BaseObserver, UpdateType, type Authenticator, type CrudEntry, type MutationUploader } from '@powersync/web'; import { Session, SupabaseClient, createClient } from '@supabase/supabase-js'; @@ -33,7 +27,9 @@ export type SupabaseConnectorListener = { sessionStarted: (session: Session) => void; }; -export class SupabaseConnector extends BaseObserver implements PowerSyncBackendConnector { +// The connector is the Authenticator for sync and provides the upload callback. Connect with: +// await db.connect({ powerSyncEndpoint: connector.config.powersyncUrl, authenticator: connector, upload: connector.upload }); +export class SupabaseConnector extends BaseObserver implements Authenticator { readonly client: SupabaseClient; readonly config: SupabaseConfig; @@ -41,6 +37,8 @@ export class SupabaseConnector extends BaseObserver i currentSession: Session | null; + private cachedToken: string | null = null; + constructor() { super(); this.config = { @@ -86,7 +84,16 @@ export class SupabaseConnector extends BaseObserver i this.updateSession(session); } - async fetchCredentials() { + /** + * Returns the Supabase access token for sync. Keep the cache: the SDK isn't guaranteed to cache tokens. + * After invalidateCredentials() clears it, getSession() returns a valid session, because supabase-js refreshes + * the session when it expires within 90 seconds. + */ + async resolveCredentials(): Promise { + if (this.cachedToken) { + return this.cachedToken; + } + const { data: { session }, error @@ -98,13 +105,17 @@ export class SupabaseConnector extends BaseObserver i console.debug('session expires at', session.expires_at); - return { - endpoint: this.config.powersyncUrl, - token: session.access_token ?? '' - } satisfies PowerSyncCredentials; + this.cachedToken = session.access_token; + return this.cachedToken; } - async uploadData(database: CommonPowerSyncDatabase): Promise { + /** Called by the SDK before the token expires and when the PowerSync Service rejects it. */ + invalidateCredentials(): void { + this.cachedToken = null; + } + + /** Uploads the oldest queued transaction. Throwing keeps it queued, and the SDK retries after a delay. */ + readonly upload: MutationUploader = async ({ database }) => { const transaction = await database.getNextCrudTransaction(); if (!transaction) { @@ -125,7 +136,7 @@ export class SupabaseConnector extends BaseObserver i result = await table.upsert(record); break; case UpdateType.PATCH: - result = await table.update(op.opData).eq('id', op.id); + result = await table.update(op.opData ?? {}).eq('id', op.id); break; case UpdateType.DELETE: result = await table.delete().eq('id', op.id); @@ -159,10 +170,11 @@ export class SupabaseConnector extends BaseObserver i throw ex; } } - } + }; updateSession(session: Session | null) { this.currentSession = session; + this.cachedToken = null; // A new session has a new token. if (!session) { return; }