Skip to content

Commit

Permalink
MongoDB Bucket Storage Module (#136)
Browse files Browse the repository at this point in the history
  • Loading branch information
stevensJourney authored Jan 8, 2025
1 parent e25263c commit fea550f
Show file tree
Hide file tree
Showing 165 changed files with 3,360 additions and 2,060 deletions.
7 changes: 7 additions & 0 deletions .changeset/big-guests-hunt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@powersync/service-core': patch
'@powersync/lib-services-framework': patch
'@powersync/service-sync-rules': patch
---

Updated ts-codec to 1.3.0 for better decode error responses
5 changes: 5 additions & 0 deletions .changeset/hungry-brooms-sniff.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@powersync/service-module-postgres': minor
---

Added minor typing utilities
5 changes: 5 additions & 0 deletions .changeset/ninety-cycles-accept.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@powersync/service-core-tests': minor
---

Initial release of shared tests for different sync bucket storage providers
9 changes: 9 additions & 0 deletions .changeset/poor-pandas-obey.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
'@powersync/service-module-mongodb': minor
'@powersync/service-core': minor
'@powersync/service-types': minor
'@powersync/service-module-mongodb-storage': minor
'@powersync/lib-service-mongodb': minor
---

Moved MongoDB sync bucket storage implementation to the MongoDB module.
5 changes: 5 additions & 0 deletions .changeset/wicked-papayas-hide.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@powersync/lib-services-framework': minor
---

Made migrations more pluggable
1 change: 0 additions & 1 deletion .github/workflows/packages_release.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ jobs:
# This expects you to have a script called release which does a build for your packages and calls changeset publish
publish: pnpm release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}

- name: Check if @powersync/service-image Released
Expand Down
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,28 @@ The service can be started using the public Docker image. See the image [notes](

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

- [libs/lib-mongodb](./libs/lib-mongodb/README.md)

- A light-weight set of common logic and types for the MongoDB replication and storage modules.

## Modules

- [modules/module-mongodb](./modules/module-mongodb/README.md)

- MongoDB replication module.

- [modules/module-mongodb-storage](./modules/module-mongodb-storage/README.md)

- MongoDB bucket storage module.

- [modules/module-mysql](./modules/module-mysql/README.md)

- MySQL replication module.

- [modules/module-postgres](./modules/module-postgres/README.md)

- Postgres replication module.

## Service

- [service](./service/README.md)
Expand Down
1 change: 1 addition & 0 deletions libs/lib-mongodb/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# @powersync/lib-service-mongodb
67 changes: 67 additions & 0 deletions libs/lib-mongodb/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# Functional Source License, Version 1.1, Apache 2.0 Future License

## Abbreviation

FSL-1.1-Apache-2.0

## Notice

Copyright 2023-2024 Journey Mobile, Inc.

## Terms and Conditions

### Licensor ("We")

The party offering the Software under these Terms and Conditions.

### The Software

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.

### License Grant

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.

### Permitted Purpose

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:

1. substitutes for the Software;
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
3. offers the same or substantially similar functionality as the Software.

Permitted Purposes specifically include using the Software:

1. for your internal use and access;
2. for non-commercial education;
3. for non-commercial research; and
4. in connection with professional services that you provide to a licensee using the Software in accordance with these Terms and Conditions.

### Patents

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.

### Redistribution

The Terms and Conditions apply to all copies, modifications and derivatives of the Software.
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.

### Disclaimer

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.
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.

### Trademarks

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.

## Grant of Future License

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:

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

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.
3 changes: 3 additions & 0 deletions libs/lib-mongodb/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# PowerSync Service MongoDB

Library for common MongoDB logic used in the PowerSync service.
38 changes: 38 additions & 0 deletions libs/lib-mongodb/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"name": "@powersync/lib-service-mongodb",
"repository": "https://github.com/powersync-ja/powersync-service",
"types": "dist/index.d.ts",
"version": "0.1.8",
"main": "dist/index.js",
"license": "FSL-1.1-Apache-2.0",
"type": "module",
"publishConfig": {
"access": "public"
},
"scripts": {
"build": "tsc -b",
"build:tests": "tsc -b test/tsconfig.json",
"clean": "rm -rf ./dist && tsc -b --clean",
"test": "vitest"
},
"exports": {
".": {
"import": "./dist/index.js",
"require": "./dist/index.js",
"default": "./dist/index.js"
},
"./types": {
"import": "./dist/types/types.js",
"require": "./dist/types/types.js",
"default": "./dist/types/types.js"
}
},
"dependencies": {
"@powersync/lib-services-framework": "workspace:*",
"bson": "^6.8.0",
"mongodb": "^6.11.0",
"ts-codec": "^1.3.0",
"uri-js": "^4.4.1"
},
"devDependencies": {}
}
1 change: 1 addition & 0 deletions libs/lib-mongodb/src/db/db-index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './mongo.js';
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import * as mongo from 'mongodb';
import * as timers from 'timers/promises';

import { configFile } from '@powersync/service-types';
import { normalizeMongoConfig } from '../storage/storage-index.js';
import { BaseMongoConfigDecoded, normalizeMongoConfig } from '../types/types.js';

/**
* Time for new connection to timeout.
Expand Down Expand Up @@ -30,7 +28,7 @@ export const MONGO_OPERATION_TIMEOUT_MS = 30_000;
*/
export const MONGO_CLEAR_OPERATION_TIMEOUT_MS = 5_000;

export function createMongoClient(config: configFile.PowerSyncConfig['storage']) {
export function createMongoClient(config: BaseMongoConfigDecoded) {
const normalized = normalizeMongoConfig(config);
return new mongo.MongoClient(normalized.uri, {
auth: {
Expand Down
8 changes: 8 additions & 0 deletions libs/lib-mongodb/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export * from './db/db-index.js';
export * as db from './db/db-index.js';

export * from './locks/locks-index.js';
export * as locks from './locks/locks-index.js';

export * from './types/types.js';
export * as types from './types/types.js';
123 changes: 123 additions & 0 deletions libs/lib-mongodb/src/locks/MongoLockManager.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import * as framework from '@powersync/lib-services-framework';
import * as bson from 'bson';
import * as mongo from 'mongodb';

/**
* Lock Document Schema
*/
export type Lock = {
name: string;
active_lock?: {
lock_id: bson.ObjectId;
ts: Date;
};
};

export type Collection = mongo.Collection<Lock>;

export type MongoLockManagerParams = framework.locks.LockManagerParams & {
collection: Collection;
};

const DEFAULT_LOCK_TIMEOUT = 60 * 1000; // 1 minute

export class MongoLockManager extends framework.locks.AbstractLockManager {
collection: Collection;
constructor(params: MongoLockManagerParams) {
super(params);
this.collection = params.collection;
}

protected async acquireHandle(options?: framework.LockAcquireOptions): Promise<framework.LockHandle | null> {
const lock_id = await this.getHandle();
if (!lock_id) {
return null;
}
return {
refresh: () => this.refreshHandle(lock_id),
release: () => this.releaseHandle(lock_id)
};
}

protected async refreshHandle(lock_id: bson.ObjectId) {
const res = await this.collection.updateOne(
{
'active_lock.lock_id': lock_id
},
{
$set: {
'active_lock.ts': new Date()
}
}
);

if (res.modifiedCount === 0) {
throw new Error('Lock not found, could not refresh');
}
}

protected async getHandle() {
const now = new Date();
const lock_timeout = this.params.timeout ?? DEFAULT_LOCK_TIMEOUT;
const lock_id = new bson.ObjectId();

const { name } = this.params;
await this.collection.updateOne(
{
name
},
{
$setOnInsert: {
name
}
},
{
upsert: true
}
);

const expired_ts = now.getTime() - lock_timeout;

const res = await this.collection.updateOne(
{
$and: [
{ name: name },
{
$or: [{ active_lock: { $exists: false } }, { 'active_lock.ts': { $lte: new Date(expired_ts) } }]
}
]
},
{
$set: {
active_lock: {
lock_id: lock_id,
ts: now
}
}
}
);

if (res.modifiedCount === 0) {
return null;
}

return lock_id;
}

protected async releaseHandle(lock_id: bson.ObjectId) {
const res = await this.collection.updateOne(
{
'active_lock.lock_id': lock_id
},
{
$unset: {
active_lock: true
}
}
);

if (res.modifiedCount === 0) {
throw new Error('Lock not found, could not release');
}
}
}
1 change: 1 addition & 0 deletions libs/lib-mongodb/src/locks/locks-index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './MongoLockManager.js';
56 changes: 56 additions & 0 deletions libs/lib-mongodb/src/types/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import * as t from 'ts-codec';
import * as urijs from 'uri-js';

export const MONGO_CONNECTION_TYPE = 'mongodb' as const;

export const BaseMongoConfig = t.object({
type: t.literal(MONGO_CONNECTION_TYPE),
uri: t.string,
database: t.string.optional(),
username: t.string.optional(),
password: t.string.optional()
});

export type BaseMongoConfig = t.Encoded<typeof BaseMongoConfig>;
export type BaseMongoConfigDecoded = t.Decoded<typeof BaseMongoConfig>;

/**
* Construct a mongodb URI, without username, password or ssl options.
*
* Only contains hostname, port, database.
*/
export function baseUri(options: BaseMongoConfig) {
return options.uri;
}

/**
* Validate and normalize connection options.
*
* Returns destructured options.
*
* For use by both storage and mongo module.
*/
export function normalizeMongoConfig(options: BaseMongoConfigDecoded) {
let uri = urijs.parse(options.uri);

const database = options.database ?? uri.path?.substring(1) ?? '';

const userInfo = uri.userinfo?.split(':');

const username = options.username ?? userInfo?.[0];
const password = options.password ?? userInfo?.[1];

if (database == '') {
throw new Error(`database required`);
}

delete uri.userinfo;

return {
uri: urijs.serialize(uri),
database,

username,
password
};
}
Loading

0 comments on commit fea550f

Please sign in to comment.