Skip to content

Commit 062c624

Browse files
authored
Merge pull request #54 from powersync-ja/test-client
Add test client
2 parents a308e45 + c61d073 commit 062c624

File tree

11 files changed

+415
-0
lines changed

11 files changed

+415
-0
lines changed

pnpm-lock.yaml

Lines changed: 29 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

pnpm-workspace.yaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,5 +2,6 @@ packages:
22
- 'packages/*'
33
- 'libs/*'
44
- 'service'
5+
- 'test-client'
56
# exclude packages that are inside test directories
67
- '!**/test/**'

test-client/README.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Test Client
2+
3+
This is a minimal client demonstrating direct usage of the HTTP stream sync api.
4+
5+
For a full implementation, see our client SDKs.
6+
7+
## Usage
8+
9+
```sh
10+
# In project root
11+
pnpm install
12+
pnpm build:packages
13+
# In this folder
14+
pnpm build
15+
node dist/bin.js fetch-operations --token <token> --endpoint http://localhost:8080
16+
17+
# More examples:
18+
19+
# If the endpoint is present in token aud field, it can be omitted from args:
20+
node dist/bin.js fetch-operations --token <token>
21+
22+
# If a local powersync.yaml is present with a configured HS256 key, this can be used:
23+
node dist/bin.js fetch-operations --config path/to/powersync.yaml --endpoint http://localhost:8080
24+
25+
# Without endpoint, it defaults to http://127.0.0.1:<port> from the config:
26+
node dist/bin.js fetch-operations --config path/to/powersync.yaml
27+
28+
# Use --sub to specify a user id in the generated token:
29+
node dist/bin.js fetch-operations --config path/to/powersync.yaml --sub test-user
30+
```
31+
32+
The `fetch-operations` command downloads data for a single checkpoint, and outputs a normalized form: one CLEAR operation, followed by the latest PUT operation for each row. This normalized form is still split per bucket. The output is not affected by compacting, but can be affected by replication order.
33+
34+
To avoid normalizing the data, use the `--raw` option. This may include additional CLEAR, MOVE, REMOVE and duplicate PUT operations.
35+
36+
To generate a token without downloading data, use the `generate-token` command:
37+
38+
```sh
39+
node dist/bin.js generate-token --config path/to/powersync.yaml --sub test-user
40+
```

test-client/package.json

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
{
2+
"name": "test-client",
3+
"repository": "https://github.com/powersync-ja/powersync-service",
4+
"private": true,
5+
"version": "0.1.0",
6+
"main": "dist/index.js",
7+
"bin": "dist/bin.js",
8+
"license": "Apache-2.0",
9+
"type": "module",
10+
"scripts": {
11+
"fetch-operations": "tsc -b && node dist/bin.js fetch-operations",
12+
"generate-token": "tsc -b && node dist/bin.js generate-token",
13+
"build": "tsc -b",
14+
"clean": "rm -rf ./dist && tsc -b --clean"
15+
},
16+
"dependencies": {
17+
"@powersync/service-core": "workspace:*",
18+
"commander": "^12.0.0",
19+
"jose": "^4.15.1",
20+
"yaml": "^2.5.0"
21+
},
22+
"devDependencies": {
23+
"@types/node": "18.11.11",
24+
"typescript": "^5.2.2"
25+
}
26+
}

test-client/src/auth.ts

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import * as jose from 'jose';
2+
import * as fs from 'node:fs/promises';
3+
import * as yaml from 'yaml';
4+
5+
export interface CredentialsOptions {
6+
token?: string;
7+
endpoint?: string;
8+
config?: string;
9+
sub?: string;
10+
}
11+
12+
export async function getCredentials(options: CredentialsOptions): Promise<{ endpoint: string; token: string }> {
13+
if (options.token != null) {
14+
if (options.endpoint != null) {
15+
return { token: options.token, endpoint: options.endpoint };
16+
} else {
17+
const parsed = jose.decodeJwt(options.token);
18+
const aud = Array.isArray(parsed.aud) ? parsed.aud[0] : parsed.aud;
19+
if (!(aud ?? '').startsWith('http')) {
20+
throw new Error(`Specify endpoint, or aud in the token`);
21+
}
22+
return {
23+
token: options.token,
24+
endpoint: aud!
25+
};
26+
}
27+
} else if (options.config != null) {
28+
const file = await fs.readFile(options.config, 'utf-8');
29+
const parsed = await yaml.parse(file);
30+
const keys = (parsed.client_auth?.jwks?.keys ?? []).filter((key: any) => key.alg == 'HS256');
31+
if (keys.length == 0) {
32+
throw new Error('No HS256 key found in the config');
33+
}
34+
35+
let endpoint = options.endpoint;
36+
if (endpoint == null) {
37+
endpoint = `http://127.0.0.1:${parsed.port ?? 8080}`;
38+
}
39+
40+
const aud = parsed.client_auth?.audience?.[0] ?? endpoint;
41+
42+
const rawKey = keys[0];
43+
const key = await jose.importJWK(rawKey);
44+
45+
const sub = options.sub ?? 'test_user';
46+
47+
const token = await new jose.SignJWT({})
48+
.setProtectedHeader({ alg: rawKey.alg, kid: rawKey.kid })
49+
.setSubject(sub)
50+
.setIssuedAt()
51+
.setIssuer('test-client')
52+
.setAudience(aud)
53+
.setExpirationTime('1h')
54+
.sign(key);
55+
56+
return { token, endpoint };
57+
} else {
58+
throw new Error(`Specify token or config path`);
59+
}
60+
}

test-client/src/bin.ts

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import { program } from 'commander';
2+
import { getCheckpointData } from './client.js';
3+
import { getCredentials } from './auth.js';
4+
import * as jose from 'jose';
5+
6+
program
7+
.command('fetch-operations')
8+
.option('-t, --token [token]', 'JWT to use for authentication')
9+
.option('-e, --endpoint [endpoint]', 'endpoint URI')
10+
.option('-c, --config [config]', 'path to powersync.yaml, to auto-generate a token from a HS256 key')
11+
.option('-u, --sub [sub]', 'sub field for auto-generated token')
12+
.option('--raw', 'output operations as received, without normalizing')
13+
.action(async (options) => {
14+
const credentials = await getCredentials(options);
15+
const data = await getCheckpointData({ ...credentials, raw: options.raw });
16+
console.log(JSON.stringify(data, null, 2));
17+
});
18+
19+
program
20+
.command('generate-token')
21+
.description('Generate a JWT from for a given powersync.yaml config file')
22+
.option('-c, --config [config]', 'path to powersync.yaml')
23+
.option('-u, --sub [sub]', 'sub field for auto-generated token')
24+
.action(async (options) => {
25+
const credentials = await getCredentials(options);
26+
const decoded = await jose.decodeJwt(credentials.token);
27+
28+
console.error(`Payload:\n${JSON.stringify(decoded, null, 2)}\nToken:`);
29+
console.log(credentials.token);
30+
});
31+
32+
await program.parseAsync();

test-client/src/client.ts

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import { ndjsonStream } from './ndjson.js';
2+
import type * as types from '@powersync/service-core';
3+
import { isCheckpoint, isCheckpointComplete, isStreamingSyncData, normalizeData } from './util.js';
4+
5+
export interface GetCheckpointOptions {
6+
endpoint: string;
7+
token: string;
8+
raw?: boolean;
9+
}
10+
11+
export async function getCheckpointData(options: GetCheckpointOptions) {
12+
const response = await fetch(`${options.endpoint}/sync/stream`, {
13+
method: 'POST',
14+
headers: {
15+
'Content-Type': 'application/json',
16+
Authorization: `Token ${options.token}`
17+
},
18+
body: JSON.stringify({
19+
raw_data: true,
20+
include_checksum: true,
21+
// Client parameters can be specified here
22+
parameters: {}
23+
} satisfies types.StreamingSyncRequest)
24+
});
25+
if (!response.ok) {
26+
throw new Error(response.statusText + '\n' + (await response.text()));
27+
}
28+
29+
let data: types.StreamingSyncData[] = [];
30+
let checkpoint: types.StreamingSyncCheckpoint;
31+
32+
for await (let chunk of ndjsonStream<types.StreamingSyncLine>(response.body!)) {
33+
if (isStreamingSyncData(chunk)) {
34+
// Collect data
35+
data.push(chunk);
36+
} else if (isCheckpoint(chunk)) {
37+
checkpoint = chunk;
38+
} else if (isCheckpointComplete(chunk)) {
39+
// Stop on the first checkpoint_complete message.
40+
break;
41+
}
42+
}
43+
44+
return normalizeData(checkpoint!, data, { raw: options.raw ?? false });
45+
}

test-client/src/index.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
export * from './client.js';
2+
export * from './ndjson.js';
3+
export * from './util.js';

test-client/src/ndjson.ts

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
export function ndjsonStream<T>(response: ReadableStream<Uint8Array>): ReadableStream<T> & AsyncIterable<T> {
2+
var is_reader: any,
3+
cancellationRequest = false;
4+
return new ReadableStream<T>({
5+
start: function (controller) {
6+
var reader = response.getReader();
7+
is_reader = reader;
8+
var decoder = new TextDecoder();
9+
var data_buf = '';
10+
11+
reader.read().then(function processResult(result): void | Promise<any> {
12+
if (result.done) {
13+
if (cancellationRequest) {
14+
// Immediately exit
15+
return;
16+
}
17+
18+
data_buf = data_buf.trim();
19+
if (data_buf.length !== 0) {
20+
try {
21+
var data_l = JSON.parse(data_buf);
22+
controller.enqueue(data_l);
23+
} catch (e) {
24+
controller.error(e);
25+
return;
26+
}
27+
}
28+
controller.close();
29+
return;
30+
}
31+
32+
var data = decoder.decode(result.value, { stream: true });
33+
data_buf += data;
34+
var lines = data_buf.split('\n');
35+
for (var i = 0; i < lines.length - 1; ++i) {
36+
var l = lines[i].trim();
37+
if (l.length > 0) {
38+
try {
39+
var data_line = JSON.parse(l);
40+
controller.enqueue(data_line);
41+
} catch (e) {
42+
controller.error(e);
43+
cancellationRequest = true;
44+
reader.cancel();
45+
return;
46+
}
47+
}
48+
}
49+
data_buf = lines[lines.length - 1];
50+
51+
return reader.read().then(processResult);
52+
});
53+
},
54+
cancel: function (reason) {
55+
cancellationRequest = true;
56+
is_reader.cancel();
57+
}
58+
}) as any;
59+
}

0 commit comments

Comments
 (0)