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

Support client_id and User-Agent #64

Merged
merged 4 commits into from
Aug 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/rude-timers-matter.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@powersync/service-core': minor
'@powersync/service-image': minor
---

Support client_id parameter and User-Agent headers.
3 changes: 2 additions & 1 deletion packages/service-core/src/routes/configure-rsocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export function configureRSocket(router: ReactiveSocketRouter<Context>, options:

router.applyWebSocketEndpoints(server, {
contextProvider: async (data: Buffer) => {
const { token } = RSocketContextMeta.decode(deserialize(data) as any);
const { token, user_agent } = RSocketContextMeta.decode(deserialize(data) as any);

if (!token) {
throw new errors.AuthorizationError('No token provided');
Expand All @@ -38,6 +38,7 @@ export function configureRSocket(router: ReactiveSocketRouter<Context>, options:
}
return {
token,
user_agent,
...context,
token_errors: token_errors,
system
Expand Down
8 changes: 6 additions & 2 deletions packages/service-core/src/routes/endpoints/checkpointing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import * as util from '../../util/util-index.js';
import { authUser } from '../auth.js';
import { routeDefinition } from '../router.js';

const WriteCheckpointRequest = t.object({});
const WriteCheckpointRequest = t.object({
client_id: t.string.optional()
});

export const writeCheckpoint = routeDefinition({
path: '/write-checkpoint.json',
Expand All @@ -30,8 +32,10 @@ export const writeCheckpoint2 = routeDefinition({
validator: schema.createTsCodecValidator(WriteCheckpointRequest, { allowAdditional: true }),
handler: async (payload) => {
const { user_id, system } = payload.context;
const client_id = payload.params.client_id;
const full_user_id = util.checkpointUserId(user_id, client_id);
const storage = system.storage;
const write_checkpoint = await util.createWriteCheckpoint(system.requirePgPool(), storage, user_id!);
const write_checkpoint = await util.createWriteCheckpoint(system.requirePgPool(), storage, full_user_id);
return {
write_checkpoint: String(write_checkpoint)
};
Expand Down
1 change: 1 addition & 0 deletions packages/service-core/src/routes/endpoints/socket-route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ export const syncStreamReactive: SocketRouteGenerator = (router) =>
disposer();
logger.info(`Sync stream complete`, {
user_id: syncParams.user_id,
user_agent: context.user_agent,
operations_synced: tracker.operationsSynced,
data_synced_bytes: tracker.dataSyncedBytes
});
Expand Down
5 changes: 5 additions & 0 deletions packages/service-core/src/routes/endpoints/sync-stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ export const syncStreamed = routeDefinition({
validator: schema.createTsCodecValidator(util.StreamingSyncRequest, { allowAdditional: true }),
handler: async (payload) => {
const system = payload.context.system;
const headers = payload.request.headers;
const userAgent = headers['x-user-agent'] ?? headers['user-agent'];
rkistner marked this conversation as resolved.
Show resolved Hide resolved
const clientId = payload.params.client_id;

if (system.closed) {
throw new errors.JourneyError({
Expand Down Expand Up @@ -92,6 +95,8 @@ export const syncStreamed = routeDefinition({
Metrics.getInstance().concurrent_connections.add(-1);
logger.info(`Sync stream complete`, {
user_id: syncParams.user_id,
client_id: clientId,
user_agent: userAgent,
operations_synced: tracker.operationsSynced,
data_synced_bytes: tracker.dataSyncedBytes
});
Expand Down
3 changes: 2 additions & 1 deletion packages/service-core/src/routes/router-socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,6 @@ import { Context } from './router.js';
export type SocketRouteGenerator = (router: ReactiveSocketRouter<Context>) => IReactiveStream;

export const RSocketContextMeta = t.object({
token: t.string
token: t.string,
user_agent: t.string.optional()
});
4 changes: 4 additions & 0 deletions packages/service-core/src/routes/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ export type Context = {

token_payload?: auth.JwtPayload;
token_errors?: string[];
/**
* Only on websocket endpoints.
*/
user_agent?: string;
};

export type BasicRouterRequest = {
Expand Down
3 changes: 2 additions & 1 deletion packages/service-core/src/sync/sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,8 @@ async function* streamResponseInner(
}
}

const stream = storage.watchWriteCheckpoint(syncParams.token_parameters.user_id as string, signal);
const checkpointUserId = util.checkpointUserId(syncParams.token_parameters.user_id as string, params.client_id);
const stream = storage.watchWriteCheckpoint(checkpointUserId, signal);
for await (const next of stream) {
const { base, writeCheckpoint } = next;
const checkpoint = base.checkpoint;
Expand Down
7 changes: 6 additions & 1 deletion packages/service-core/src/util/protocol-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,12 @@ export const StreamingSyncRequest = t.object({
/**
* Client parameters to be passed to the sync rules.
*/
parameters: t.record(t.any).optional()
parameters: t.record(t.any).optional(),

/**
* Unique client id.
*/
client_id: t.string.optional()
});

export type StreamingSyncRequest = t.Decoded<typeof StreamingSyncRequest>;
Expand Down
10 changes: 10 additions & 0 deletions packages/service-core/src/util/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,3 +120,13 @@ export async function createWriteCheckpoint(
logger.info(`Write checkpoint 2: ${JSON.stringify({ lsn, id: String(id) })}`);
return id;
}

export function checkpointUserId(user_id: string | undefined, client_id: string | undefined) {
if (user_id == null) {
throw new Error('user_id is required');
}
if (client_id == null) {
return user_id;
}
return `${user_id}/${client_id}`;
}
2 changes: 1 addition & 1 deletion service/src/runners/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export async function startServer(runnerConfig: core.utils.RunnerConfig) {

server.register(cors, {
origin: '*',
allowedHeaders: ['Content-Type', 'Authorization'],
allowedHeaders: ['Content-Type', 'Authorization', 'User-Agent', 'X-User-Agent'],
exposedHeaders: ['Content-Type'],
// Cache time for preflight response
maxAge: 3600
Expand Down
Loading