Skip to content

Commit fea550f

Browse files
MongoDB Bucket Storage Module (#136)
1 parent e25263c commit fea550f

File tree

165 files changed

+3360
-2060
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

165 files changed

+3360
-2060
lines changed

.changeset/big-guests-hunt.md

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
'@powersync/service-core': patch
3+
'@powersync/lib-services-framework': patch
4+
'@powersync/service-sync-rules': patch
5+
---
6+
7+
Updated ts-codec to 1.3.0 for better decode error responses

.changeset/hungry-brooms-sniff.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@powersync/service-module-postgres': minor
3+
---
4+
5+
Added minor typing utilities

.changeset/ninety-cycles-accept.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@powersync/service-core-tests': minor
3+
---
4+
5+
Initial release of shared tests for different sync bucket storage providers

.changeset/poor-pandas-obey.md

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
---
2+
'@powersync/service-module-mongodb': minor
3+
'@powersync/service-core': minor
4+
'@powersync/service-types': minor
5+
'@powersync/service-module-mongodb-storage': minor
6+
'@powersync/lib-service-mongodb': minor
7+
---
8+
9+
Moved MongoDB sync bucket storage implementation to the MongoDB module.

.changeset/wicked-papayas-hide.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@powersync/lib-services-framework': minor
3+
---
4+
5+
Made migrations more pluggable

.github/workflows/packages_release.yaml

-1
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,6 @@ jobs:
5555
# This expects you to have a script called release which does a build for your packages and calls changeset publish
5656
publish: pnpm release
5757
env:
58-
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
5958
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
6059

6160
- name: Check if @powersync/service-image Released

README.md

+22
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,28 @@ The service can be started using the public Docker image. See the image [notes](
4343

4444
- A light-weight set of definitions and utilities for micro services
4545

46+
- [libs/lib-mongodb](./libs/lib-mongodb/README.md)
47+
48+
- A light-weight set of common logic and types for the MongoDB replication and storage modules.
49+
50+
## Modules
51+
52+
- [modules/module-mongodb](./modules/module-mongodb/README.md)
53+
54+
- MongoDB replication module.
55+
56+
- [modules/module-mongodb-storage](./modules/module-mongodb-storage/README.md)
57+
58+
- MongoDB bucket storage module.
59+
60+
- [modules/module-mysql](./modules/module-mysql/README.md)
61+
62+
- MySQL replication module.
63+
64+
- [modules/module-postgres](./modules/module-postgres/README.md)
65+
66+
- Postgres replication module.
67+
4668
## Service
4769

4870
- [service](./service/README.md)

libs/lib-mongodb/CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# @powersync/lib-service-mongodb

libs/lib-mongodb/LICENSE

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
# Functional Source License, Version 1.1, Apache 2.0 Future License
2+
3+
## Abbreviation
4+
5+
FSL-1.1-Apache-2.0
6+
7+
## Notice
8+
9+
Copyright 2023-2024 Journey Mobile, Inc.
10+
11+
## Terms and Conditions
12+
13+
### Licensor ("We")
14+
15+
The party offering the Software under these Terms and Conditions.
16+
17+
### The Software
18+
19+
The "Software" is each version of the software that we make available under these Terms and Conditions, as indicated by our inclusion of these Terms and Conditions with the Software.
20+
21+
### License Grant
22+
23+
Subject to your compliance with this License Grant and the Patents, Redistribution and Trademark clauses below, we hereby grant you the right to use, copy, modify, create derivative works, publicly perform, publicly display and redistribute the Software for any Permitted Purpose identified below.
24+
25+
### Permitted Purpose
26+
27+
A Permitted Purpose is any purpose other than a Competing Use. A Competing Use means making the Software available to others in a commercial product or service that:
28+
29+
1. substitutes for the Software;
30+
2. substitutes for any other product or service we offer using the Software that exists as of the date we make the Software available; or
31+
3. offers the same or substantially similar functionality as the Software.
32+
33+
Permitted Purposes specifically include using the Software:
34+
35+
1. for your internal use and access;
36+
2. for non-commercial education;
37+
3. for non-commercial research; and
38+
4. in connection with professional services that you provide to a licensee using the Software in accordance with these Terms and Conditions.
39+
40+
### Patents
41+
42+
To the extent your use for a Permitted Purpose would necessarily infringe our patents, the license grant above includes a license under our patents. If you make a claim against any party that the Software infringes or contributes to the infringement of any patent, then your patent license to the Software ends immediately.
43+
44+
### Redistribution
45+
46+
The Terms and Conditions apply to all copies, modifications and derivatives of the Software.
47+
If you redistribute any copies, modifications or derivatives of the Software, you must include a copy of or a link to these Terms and Conditions and not remove any copyright notices provided in or with the Software.
48+
49+
### Disclaimer
50+
51+
THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
52+
IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES, EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
53+
54+
### Trademarks
55+
56+
Except for displaying the License Details and identifying us as the origin of the Software, you have no right under these Terms and Conditions to use our trademarks, trade names, service marks or product names.
57+
58+
## Grant of Future License
59+
60+
We hereby irrevocably grant you an additional license to use the Software under the Apache License, Version 2.0 that is effective on the second anniversary of the date we make the Software available. On or after that date, you may use the Software under the Apache License, Version 2.0, in which case the following will apply:
61+
62+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
63+
You may obtain a copy of the License at
64+
65+
http://www.apache.org/licenses/LICENSE-2.0
66+
67+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

libs/lib-mongodb/README.md

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# PowerSync Service MongoDB
2+
3+
Library for common MongoDB logic used in the PowerSync service.

libs/lib-mongodb/package.json

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
{
2+
"name": "@powersync/lib-service-mongodb",
3+
"repository": "https://github.com/powersync-ja/powersync-service",
4+
"types": "dist/index.d.ts",
5+
"version": "0.1.8",
6+
"main": "dist/index.js",
7+
"license": "FSL-1.1-Apache-2.0",
8+
"type": "module",
9+
"publishConfig": {
10+
"access": "public"
11+
},
12+
"scripts": {
13+
"build": "tsc -b",
14+
"build:tests": "tsc -b test/tsconfig.json",
15+
"clean": "rm -rf ./dist && tsc -b --clean",
16+
"test": "vitest"
17+
},
18+
"exports": {
19+
".": {
20+
"import": "./dist/index.js",
21+
"require": "./dist/index.js",
22+
"default": "./dist/index.js"
23+
},
24+
"./types": {
25+
"import": "./dist/types/types.js",
26+
"require": "./dist/types/types.js",
27+
"default": "./dist/types/types.js"
28+
}
29+
},
30+
"dependencies": {
31+
"@powersync/lib-services-framework": "workspace:*",
32+
"bson": "^6.8.0",
33+
"mongodb": "^6.11.0",
34+
"ts-codec": "^1.3.0",
35+
"uri-js": "^4.4.1"
36+
},
37+
"devDependencies": {}
38+
}

libs/lib-mongodb/src/db/db-index.ts

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export * from './mongo.js';

packages/service-core/src/db/mongo.ts renamed to libs/lib-mongodb/src/db/mongo.ts

+2-4
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
import * as mongo from 'mongodb';
22
import * as timers from 'timers/promises';
3-
4-
import { configFile } from '@powersync/service-types';
5-
import { normalizeMongoConfig } from '../storage/storage-index.js';
3+
import { BaseMongoConfigDecoded, normalizeMongoConfig } from '../types/types.js';
64

75
/**
86
* Time for new connection to timeout.
@@ -30,7 +28,7 @@ export const MONGO_OPERATION_TIMEOUT_MS = 30_000;
3028
*/
3129
export const MONGO_CLEAR_OPERATION_TIMEOUT_MS = 5_000;
3230

33-
export function createMongoClient(config: configFile.PowerSyncConfig['storage']) {
31+
export function createMongoClient(config: BaseMongoConfigDecoded) {
3432
const normalized = normalizeMongoConfig(config);
3533
return new mongo.MongoClient(normalized.uri, {
3634
auth: {

libs/lib-mongodb/src/index.ts

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
export * from './db/db-index.js';
2+
export * as db from './db/db-index.js';
3+
4+
export * from './locks/locks-index.js';
5+
export * as locks from './locks/locks-index.js';
6+
7+
export * from './types/types.js';
8+
export * as types from './types/types.js';
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
import * as framework from '@powersync/lib-services-framework';
2+
import * as bson from 'bson';
3+
import * as mongo from 'mongodb';
4+
5+
/**
6+
* Lock Document Schema
7+
*/
8+
export type Lock = {
9+
name: string;
10+
active_lock?: {
11+
lock_id: bson.ObjectId;
12+
ts: Date;
13+
};
14+
};
15+
16+
export type Collection = mongo.Collection<Lock>;
17+
18+
export type MongoLockManagerParams = framework.locks.LockManagerParams & {
19+
collection: Collection;
20+
};
21+
22+
const DEFAULT_LOCK_TIMEOUT = 60 * 1000; // 1 minute
23+
24+
export class MongoLockManager extends framework.locks.AbstractLockManager {
25+
collection: Collection;
26+
constructor(params: MongoLockManagerParams) {
27+
super(params);
28+
this.collection = params.collection;
29+
}
30+
31+
protected async acquireHandle(options?: framework.LockAcquireOptions): Promise<framework.LockHandle | null> {
32+
const lock_id = await this.getHandle();
33+
if (!lock_id) {
34+
return null;
35+
}
36+
return {
37+
refresh: () => this.refreshHandle(lock_id),
38+
release: () => this.releaseHandle(lock_id)
39+
};
40+
}
41+
42+
protected async refreshHandle(lock_id: bson.ObjectId) {
43+
const res = await this.collection.updateOne(
44+
{
45+
'active_lock.lock_id': lock_id
46+
},
47+
{
48+
$set: {
49+
'active_lock.ts': new Date()
50+
}
51+
}
52+
);
53+
54+
if (res.modifiedCount === 0) {
55+
throw new Error('Lock not found, could not refresh');
56+
}
57+
}
58+
59+
protected async getHandle() {
60+
const now = new Date();
61+
const lock_timeout = this.params.timeout ?? DEFAULT_LOCK_TIMEOUT;
62+
const lock_id = new bson.ObjectId();
63+
64+
const { name } = this.params;
65+
await this.collection.updateOne(
66+
{
67+
name
68+
},
69+
{
70+
$setOnInsert: {
71+
name
72+
}
73+
},
74+
{
75+
upsert: true
76+
}
77+
);
78+
79+
const expired_ts = now.getTime() - lock_timeout;
80+
81+
const res = await this.collection.updateOne(
82+
{
83+
$and: [
84+
{ name: name },
85+
{
86+
$or: [{ active_lock: { $exists: false } }, { 'active_lock.ts': { $lte: new Date(expired_ts) } }]
87+
}
88+
]
89+
},
90+
{
91+
$set: {
92+
active_lock: {
93+
lock_id: lock_id,
94+
ts: now
95+
}
96+
}
97+
}
98+
);
99+
100+
if (res.modifiedCount === 0) {
101+
return null;
102+
}
103+
104+
return lock_id;
105+
}
106+
107+
protected async releaseHandle(lock_id: bson.ObjectId) {
108+
const res = await this.collection.updateOne(
109+
{
110+
'active_lock.lock_id': lock_id
111+
},
112+
{
113+
$unset: {
114+
active_lock: true
115+
}
116+
}
117+
);
118+
119+
if (res.modifiedCount === 0) {
120+
throw new Error('Lock not found, could not release');
121+
}
122+
}
123+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export * from './MongoLockManager.js';

libs/lib-mongodb/src/types/types.ts

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import * as t from 'ts-codec';
2+
import * as urijs from 'uri-js';
3+
4+
export const MONGO_CONNECTION_TYPE = 'mongodb' as const;
5+
6+
export const BaseMongoConfig = t.object({
7+
type: t.literal(MONGO_CONNECTION_TYPE),
8+
uri: t.string,
9+
database: t.string.optional(),
10+
username: t.string.optional(),
11+
password: t.string.optional()
12+
});
13+
14+
export type BaseMongoConfig = t.Encoded<typeof BaseMongoConfig>;
15+
export type BaseMongoConfigDecoded = t.Decoded<typeof BaseMongoConfig>;
16+
17+
/**
18+
* Construct a mongodb URI, without username, password or ssl options.
19+
*
20+
* Only contains hostname, port, database.
21+
*/
22+
export function baseUri(options: BaseMongoConfig) {
23+
return options.uri;
24+
}
25+
26+
/**
27+
* Validate and normalize connection options.
28+
*
29+
* Returns destructured options.
30+
*
31+
* For use by both storage and mongo module.
32+
*/
33+
export function normalizeMongoConfig(options: BaseMongoConfigDecoded) {
34+
let uri = urijs.parse(options.uri);
35+
36+
const database = options.database ?? uri.path?.substring(1) ?? '';
37+
38+
const userInfo = uri.userinfo?.split(':');
39+
40+
const username = options.username ?? userInfo?.[0];
41+
const password = options.password ?? userInfo?.[1];
42+
43+
if (database == '') {
44+
throw new Error(`database required`);
45+
}
46+
47+
delete uri.userinfo;
48+
49+
return {
50+
uri: urijs.serialize(uri),
51+
database,
52+
53+
username,
54+
password
55+
};
56+
}

0 commit comments

Comments
 (0)