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

Write Checkpoints #10

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
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: 5 additions & 1 deletion src/api/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,16 @@ router.get('/token', async (req, res) => {
await ensureKeys();
const powerSyncKey = keys.privateKey;

const { user_id = 'UserID ' } = req.query;

console.log('UserID for token is', user_id);

const token = await new SignJWT({})
.setProtectedHeader({
alg: powerSyncKey.alg,
kid: powerSyncKey.kid
})
.setSubject('UserID')
.setSubject(user_id)
.setIssuedAt()
.setIssuer(config.powersync.jwtIssuer)
.setAudience(config.powersync.url)
Expand Down
18 changes: 17 additions & 1 deletion src/api/data.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const router = express.Router();

const persistenceFactory = factories[config.database.type];

const { updateBatch } = await persistenceFactory(config.database.uri);
const { updateBatch, createCheckpoint } = await persistenceFactory(config.database.uri);

/**
* Handle a batch of events.
Expand Down Expand Up @@ -58,6 +58,22 @@ router.put('/', async (req, res) => {
}
});

router.put('/checkpoint', async (req, res) => {
if (!req.body) {
res.status(400).send({
message: 'Invalid body provided'
});
return;
}
const { user_id = 'UserID', client_id = '1' } = req.body;

const checkpoint = await createCheckpoint(user_id, client_id);

res.status(200).send({
checkpoint
});
});

/**
* Handle all PATCH events sent to the server by the client PowerSync application
*/
Expand Down
25 changes: 21 additions & 4 deletions src/persistance/mongo/mongo-persistance.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,25 @@ export const createMongoPersister = async (uri) => {
const db = client.db();
await client.connect();

return {
/**
* @type {import('../persister-factories.js').BatchPersister}
*/
/**
* @type {import('../persister-factories.js').Persister}
*/
const persister = {
createCheckpoint: async (user_id, client_id) => {
const doc = await db.collection('checkpoints').findOneAndUpdate(
{
user_id,
client_id
},
{
$inc: {
checkpoint: 1n
}
},
{ upsert: true, returnDocument: 'after' }
);
return doc.checkpoint;
},
updateBatch: async (batch) => {
// TODO: Use batches & transactions.
// TODO: Do type conversion. This currently persists data from the client as is,
Expand Down Expand Up @@ -53,4 +68,6 @@ export const createMongoPersister = async (uri) => {
}
}
};

return persister;
};
38 changes: 37 additions & 1 deletion src/persistance/mysql/mysql-persistance.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,43 @@ export const createMySQLPersister = (uri) => {
console.debug('Using MySQL Persister');

const pool = mysql.createPool(uri);
/**
* @type {import('../persister-factories.js').Persister}
*/
const persister = {
async createCheckpoint(user_id, client_id) {
const connection = await pool.getConnection();
try {
await connection.beginTransaction();
await connection.query(
`
INSERT INTO checkpoints
(user_id, client_id, checkpoint)
VALUES (?, ?, 1)
ON DUPLICATE KEY UPDATE
checkpoint = checkpoint + 1;
`,
[user_id, client_id]
);
const [rows] = await connection.query(
`
SELECT checkpoint FROM checkpoints WHERE user_id = ? AND client_id = ?;
`,
[user_id, client_id]
);

return {
await connection.commit();
/**
* @type {bigint}
*/
const checkpoint = rows[0].checkpoint;
return checkpoint;
} catch (ex) {
await connection.rollback();
} finally {
connection.release();
}
},
/**
* @type {import('../persister-factories.js').BatchPersister}
*/
Expand Down Expand Up @@ -82,4 +117,5 @@ export const createMySQLPersister = (uri) => {
}
}
};
return persister;
};
6 changes: 6 additions & 0 deletions src/persistance/persister-factories.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,14 @@ import { createPostgresPersister } from './postgres/postgres-persistance.js';
* @param {(DeleteOp | PutOp | PatchOp)[]} batch
* @returns {Promise<void>}
*
* @callback CreateCheckpoint
* @param {string} user_id
* @param {string} client_id
* @returns {Promise<bigint>} checkpoint
*
* @typedef {Object} Persister
* @prop {BatchPersister} updateBatch
* @prop {CreateCheckpoint} createCheckpoint

* @callback PersisterFactory
* @param {string} URI -
Expand Down
29 changes: 25 additions & 4 deletions src/persistance/postgres/postgres-persistance.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,10 @@ export const createPostgresPersister = (uri) => {
console.error('Pool connection failure to postgres:', err, client);
});

return {
/**
* @type {import('../persister-factories.js').BatchPersister}
*/
/**
* @type {import('../persister-factories.js').Persister}
*/
const persister = {
updateBatch: async (batch) => {
const client = await pool.connect();
try {
Expand Down Expand Up @@ -109,6 +109,27 @@ export const createPostgresPersister = (uri) => {
} finally {
client.release();
}
},
async createCheckpoint(user_id, client_id) {
const response = await pool.query(
`
INSERT INTO checkpoints(user_id, client_id, checkpoint)
VALUES
($1, $2, '1')
ON
CONFLICT (user_id, client_id)
DO
UPDATE SET checkpoint = checkpoints.checkpoint + 1
RETURNING checkpoint;
`,
[user_id, client_id]
);
/**
* @type {bigint}
*/
const checkpoint = response.rows[0].checkpoint;
return checkpoint;
}
};
return persister;
};