Skip to content

Pull upstream changes #36

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

Merged
merged 27 commits into from
May 2, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
e72d314
Update src/examples/README.md
rhashimoto Nov 24, 2024
4b9f235
Show demo query time in milliseconds.
shoestringresearch Nov 28, 2024
5669cfc
Merge pull request #227 from rhashimoto/demo-timing
rhashimoto Nov 28, 2024
428c815
Bump nanoid from 3.3.7 to 3.3.8
dependabot[bot] Dec 18, 2024
690dde7
Merge pull request #229 from rhashimoto/dependabot/npm_and_yarn/nanoi…
rhashimoto Dec 18, 2024
d66768e
Bump package version.
shoestringresearch Dec 18, 2024
7e4c4d0
Bump cross-spawn from 7.0.3 to 7.0.6
dependabot[bot] Dec 18, 2024
3c20261
Merge pull request #230 from rhashimoto/dependabot/npm_and_yarn/cross…
rhashimoto Dec 18, 2024
d1f6248
Make disabling WASM_BIGINT explicit. (#241)
rhashimoto Jan 22, 2025
32d9fc0
Fix xUnlock() call without prior call to xLock() (#245)
rhashimoto Jan 28, 2025
91cff2b
Ensure transaction state exists in jTruncate(). (#247)
rhashimoto Feb 2, 2025
e472300
Bump koa from 2.13.4 to 2.15.4 (#254)
dependabot[bot] Feb 14, 2025
33c1b68
Upgrade @web/test-runner. (#257)
rhashimoto Apr 1, 2025
7a14d78
Bump package version.
shoestringresearch Apr 1, 2025
8377bfb
Fix IDBBatchAtomicVFS use of completed transaction.
shoestringresearch Apr 11, 2025
52f5c4c
Merge pull request #261 from rhashimoto/attempted-ci-fix
rhashimoto Apr 11, 2025
c087b71
IDBMirrorVFS: Fix database corruption caused by unfilled blocks (#259)
Spxg Apr 11, 2025
2f74ba3
Fix #260. Avoid IDBBatchAtomicVFS null dereference. (#263)
rhashimoto Apr 11, 2025
13f059b
Bump koa from 2.15.4 to 2.16.1
dependabot[bot] Apr 11, 2025
c7804f9
Merge pull request #264 from rhashimoto/dependabot/npm_and_yarn/koa-2…
rhashimoto Apr 11, 2025
c861c61
Fix resetting isHandleRequested
simolus3 Apr 30, 2025
94ccf52
Merge remote-tracking branch 'origin/opfs-sync-coop-typo' into upstre…
simolus3 Apr 30, 2025
54ad303
build and add changeset
stevensJourney Apr 30, 2025
289c2c5
Merge pull request #269 from powersync-ja/opfs-sync-coop-typo
rhashimoto Apr 30, 2025
97db43a
Bump package version.
rhashimoto Apr 30, 2025
1caeb13
Merge pull request #270 from rhashimoto/bump-version
rhashimoto Apr 30, 2025
8eba6ae
Merge remote-tracking branch 'upstream/master' into upstream-changes
simolus3 May 2, 2025
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
5 changes: 5 additions & 0 deletions .changeset/proud-moose-report.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@journeyapps/wa-sqlite': patch
---

Fix issue where OPFS VFS could freeze in infinite loop
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ EMFLAGS_COMMON = \
-s INVOKE_RUN \
-s ENVIRONMENT="web,worker" \
-s STACK_SIZE=512KB \
-s WASM_BIGINT=0 \
$(EMFLAGS_EXTRA)

EMFLAGS_DEBUG = \
Expand Down
2 changes: 1 addition & 1 deletion demo/demo.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ window.addEventListener('DOMContentLoaded', async function() {
let time = performance.now();
worker.postMessage(queries);
worker.addEventListener('message', async function(event) {
timestamp.textContent += ` ${(performance.now() - time).toFixed(1)} milliseconds`;
if (event.data.results) {
// Format the results as tables.
event.data.results
Expand All @@ -85,7 +86,6 @@ window.addEventListener('DOMContentLoaded', async function() {
} else {
output.innerHTML = `<pre>${event.data.error.message}</pre>`;
}
timestamp.textContent += ` ${Math.trunc(performance.now() - time) / 1000} seconds`;
button.disabled = false;
}, { once: true });
});
Expand Down
9 changes: 5 additions & 4 deletions demo/file/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as VFS from "../../src/VFS.js";
import { IDBBatchAtomicVFS } from "../../src/examples/IDBBatchAtomicVFS.js";
import { IDBBatchAtomicVFS as MyVFS } from "../../src/examples/IDBBatchAtomicVFS.js";
// import { IDBMirrorVFS as MyVFS } from "../../src/examples/IDBMirrorVFS.js";

const SEARCH_PARAMS = new URLSearchParams(location.search);
const IDB_NAME = SEARCH_PARAMS.get('idb') ?? 'sqlite-vfs';
Expand Down Expand Up @@ -43,7 +44,7 @@ document.getElementById('file-fetch').addEventListener('click', async () => {
let vfs;
try {
log(`Importing to IndexedDB ${IDB_NAME}, path ${DB_NAME}`);
vfs = await IDBBatchAtomicVFS.create(IDB_NAME, null);
vfs = await MyVFS.create(IDB_NAME, null);

// @ts-ignore
const importURL = document.getElementById('file-url').value;
Expand All @@ -69,7 +70,7 @@ document.getElementById('file-import').addEventListener('change', async event =>
let vfs;
try {
log(`Importing to IndexedDB ${IDB_NAME}, path ${DB_NAME}`);
vfs = await IDBBatchAtomicVFS.create(IDB_NAME, null);
vfs = await MyVFS.create(IDB_NAME, null);
// @ts-ignore
await importDatabase(vfs, DB_NAME, event.target.files[0].stream());
log('Import complete');
Expand All @@ -87,7 +88,7 @@ document.getElementById('file-import').addEventListener('change', async event =>
});

/**
* @param {IDBBatchAtomicVFS} vfs
* @param {MyVFS} vfs
* @param {string} path
* @param {ReadableStream} stream
*/
Expand Down
5 changes: 3 additions & 2 deletions demo/file/service-worker.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as VFS from "../../src/VFS.js";
import { IDBBatchAtomicVFS } from "../../src/examples/IDBBatchAtomicVFS.js";
import { IDBBatchAtomicVFS as MyVFS } from "../../src/examples/IDBBatchAtomicVFS.js";
// import { IDBMirrorVFS as MyVFS } from "../../src/examples/IDBMirrorVFS.js";

// Install the service worker as soon as possible.
globalThis.addEventListener('install', (/** @type {ExtendableEvent} */ event) => {
Expand All @@ -26,7 +27,7 @@ globalThis.addEventListener('fetch', async (/** @type {FetchEvent} */ event) =>

return event.respondWith((async () => {
// Create the VFS and streaming source using the request parameters.
const vfs = await IDBBatchAtomicVFS.create(url.searchParams.get('idb'), null);
const vfs = await MyVFS.create(url.searchParams.get('idb'), null);
const path = url.searchParams.get('db');
const source = new DatabaseSource(vfs, path);

Expand Down
5 changes: 3 additions & 2 deletions demo/file/verifier.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import SQLiteESMFactory from '../../dist/wa-sqlite-async.mjs';
import * as SQLite from '../../src/sqlite-api.js';
import { IDBBatchAtomicVFS } from '../../src/examples/IDBBatchAtomicVFS.js';
import { IDBBatchAtomicVFS as MyVFS } from "../../src/examples/IDBBatchAtomicVFS.js";
// import { IDBMirrorVFS as MyVFS } from "../../src/examples/IDBMirrorVFS.js";

const SEARCH_PARAMS = new URLSearchParams(location.search);
const IDB_NAME = SEARCH_PARAMS.get('idb') ?? 'sqlite-vfs';
Expand All @@ -10,7 +11,7 @@ const DB_NAME = SEARCH_PARAMS.get('db') ?? 'sqlite.db';
const module = await SQLiteESMFactory();
const sqlite3 = SQLite.Factory(module);

const vfs = await IDBBatchAtomicVFS.create(IDB_NAME, module);
const vfs = await MyVFS.create(IDB_NAME, module);
// @ts-ignore
sqlite3.vfs_register(vfs, true);

Expand Down
5 changes: 2 additions & 3 deletions dist/mc-wa-sqlite-async.mjs

Large diffs are not rendered by default.

Binary file modified dist/mc-wa-sqlite-async.wasm
Binary file not shown.
5 changes: 2 additions & 3 deletions dist/mc-wa-sqlite-jspi.mjs

Large diffs are not rendered by default.

Binary file modified dist/mc-wa-sqlite-jspi.wasm
Binary file not shown.
5 changes: 2 additions & 3 deletions dist/mc-wa-sqlite.mjs

Large diffs are not rendered by default.

Binary file modified dist/mc-wa-sqlite.wasm
Binary file not shown.
5 changes: 2 additions & 3 deletions dist/wa-sqlite-async-dynamic-main.mjs

Large diffs are not rendered by default.

Binary file modified dist/wa-sqlite-async-dynamic-main.wasm
Binary file not shown.
5 changes: 2 additions & 3 deletions dist/wa-sqlite-async.mjs

Large diffs are not rendered by default.

Binary file modified dist/wa-sqlite-async.wasm
Binary file not shown.
5 changes: 2 additions & 3 deletions dist/wa-sqlite-dynamic-main.mjs

Large diffs are not rendered by default.

Binary file modified dist/wa-sqlite-dynamic-main.wasm
Binary file not shown.
5 changes: 2 additions & 3 deletions dist/wa-sqlite-jspi.mjs

Large diffs are not rendered by default.

Binary file modified dist/wa-sqlite-jspi.wasm
Binary file not shown.
5 changes: 2 additions & 3 deletions dist/wa-sqlite.mjs

Large diffs are not rendered by default.

Binary file modified dist/wa-sqlite.wasm
Binary file not shown.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@
"@changesets/cli": "^2.26.2",
"@types/jasmine": "^5.1.4",
"@web/dev-server": "^0.4.6",
"@web/test-runner": "^0.18.2",
"@web/test-runner-core": "^0.13.3",
"@web/test-runner": "^0.20.0",
"@web/test-runner-core": "^0.13.4",
"comlink": "^4.4.1",
"jasmine-core": "^4.5.0",
"monaco-editor": "^0.34.1",
Expand Down
14 changes: 8 additions & 6 deletions src/WebLocksMixin.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,10 @@ export const WebLocksMixin = superclass => class extends superclass {
*/
async jUnlock(fileId, lockType) {
try {
// SQLite can call xUnlock() without ever calling xLock() so
// the state may not exist.
const lockState = this.#mapIdToState.get(fileId);
if (lockType >= lockState.type) return VFS.SQLITE_OK;
if (!(lockType < lockState?.type)) return VFS.SQLITE_OK;

switch (this.#options.lockPolicy) {
case 'exclusive':
Expand Down Expand Up @@ -122,17 +124,17 @@ export const WebLocksMixin = superclass => class extends superclass {
}

/**
* @param {number} pFile
* @param {number} fileId
* @param {number} op
* @param {DataView} pArg
* @returns {number|Promise<number>}
*/
jFileControl(pFile, op, pArg) {
const lockState = this.#mapIdToState.get(pFile) ??
jFileControl(fileId, op, pArg) {
const lockState = this.#mapIdToState.get(fileId) ??
(() => {
// Call jLock() to create the lock state.
this.jLock(pFile, VFS.SQLITE_LOCK_NONE);
return this.#mapIdToState.get(pFile);
this.jLock(fileId, VFS.SQLITE_LOCK_NONE);
return this.#mapIdToState.get(fileId);
})();
if (op === WebLocksMixin.WRITE_HINT_OP_CODE &&
this.#options.lockPolicy === 'shared+hint'){
Expand Down
59 changes: 33 additions & 26 deletions src/examples/IDBBatchAtomicVFS.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@ import { FacadeVFS } from '../FacadeVFS.js';
import * as VFS from '../VFS.js';
import { WebLocksMixin } from '../WebLocksMixin.js';

const RETRYABLE_ERRORS = new Set([
'TransactionInactiveError',
'InvalidStateError'
]);

/**
* @typedef Metadata
* @property {string} name
Expand Down Expand Up @@ -482,25 +487,27 @@ export class IDBBatchAtomicVFS extends WebLocksMixin(FacadeVFS) {
break;
case VFS.SQLITE_FCNTL_SYNC:
this.log?.('xFileControl', file.path, 'SYNC');
const commitMetadata = Object.assign({}, file.metadata);
const prevFileSize = file.rollback.fileSize
this.#idb.q(({ metadata, blocks }) => {
metadata.put(commitMetadata);

// Remove old page versions.
for (const offset of file.changedPages) {
if (offset < prevFileSize) {
const range = IDBKeyRange.bound(
[file.path, -offset, commitMetadata.version],
[file.path, -offset, Infinity],
true);
blocks.delete(range);
if (file.rollback) {
const commitMetadata = Object.assign({}, file.metadata);
const prevFileSize = file.rollback.fileSize
this.#idb.q(({ metadata, blocks }) => {
metadata.put(commitMetadata);

// Remove old page versions.
for (const offset of file.changedPages) {
if (offset < prevFileSize) {
const range = IDBKeyRange.bound(
[file.path, -offset, commitMetadata.version],
[file.path, -offset, Infinity],
true);
blocks.delete(range);
}
}
}
file.changedPages.clear();
}, 'rw', file.txOptions);
file.needsMetadataSync = false;
file.rollback = null;
file.changedPages.clear();
}, 'rw', file.txOptions);
file.needsMetadataSync = false;
file.rollback = null;
}
break;
case VFS.SQLITE_FCNTL_BEGIN_ATOMIC_WRITE:
// Every write transaction is atomic, so this is a no-op.
Expand Down Expand Up @@ -717,21 +724,21 @@ export class IDBContext {
});
}

// @ts-ignore
// Create object store proxies.
const objectStores = [...tx.objectStoreNames].map(name => {
return [name, this.proxyStoreOrIndex(tx.objectStore(name))];
});

try {
// @ts-ignore
// Create object store proxies.
const objectStores = [...tx.objectStoreNames].map(name => {
return [name, this.proxyStoreOrIndex(tx.objectStore(name))];
});

// Execute the function.
return await f(Object.fromEntries(objectStores));
} catch (e) {
// Use a new transaction if this one was inactive. This will
// happen if the last request in the transaction completed
// in a previous task but the transaction has not yet committed.
if (!i && e.name === 'TransactionInactiveError') {
this.log?.('TransactionInactiveError, retrying');
if (!i && RETRYABLE_ERRORS.has(e.name)) {
this.log?.(`${e.name}, retrying`);
tx = null;
continue;
}
Expand Down
28 changes: 21 additions & 7 deletions src/examples/IDBMirrorVFS.js
Original file line number Diff line number Diff line change
Expand Up @@ -332,13 +332,12 @@ export class IDBMirrorVFS extends FacadeVFS {
const file = this.#mapIdToFile.get(fileId);

if (file.flags & VFS.SQLITE_OPEN_MAIN_DB) {
if (!file.txActive) {
file.txActive = {
path: file.path,
txId: file.viewTx.txId + 1,
blocks: new Map(),
fileSize: file.blockSize * file.blocks.size,
};
this.#requireTxActive(file);
// SQLite is not necessarily written sequentially, so fill in the
// unwritten blocks here.
for (let fillOffset = file.txActive.fileSize;
fillOffset < iOffset; fillOffset += pData.byteLength) {
file.txActive.blocks.set(fillOffset, new Uint8Array(pData.byteLength));
}
file.txActive.blocks.set(iOffset, pData.slice());
file.txActive.fileSize = Math.max(file.txActive.fileSize, iOffset + pData.byteLength);
Expand Down Expand Up @@ -375,6 +374,7 @@ export class IDBMirrorVFS extends FacadeVFS {
const file = this.#mapIdToFile.get(fileId);

if (file.flags & VFS.SQLITE_OPEN_MAIN_DB) {
this.#requireTxActive(file);
file.txActive.fileSize = iSize;
} else {
// All files that are not main databases are stored in a single
Expand Down Expand Up @@ -717,6 +717,20 @@ export class IDBMirrorVFS extends FacadeVFS {
file.txWriteHint = false;
}

/**
* @param {File} file
*/
#requireTxActive(file) {
if (!file.txActive) {
file.txActive = {
path: file.path,
txId: file.viewTx.txId + 1,
blocks: new Map(),
fileSize: file.blockSize * file.blocks.size,
};
}
}

/**
* @param {string} path
* @returns {Promise}
Expand Down
2 changes: 1 addition & 1 deletion src/examples/OPFSAdaptiveVFS.js
Original file line number Diff line number Diff line change
Expand Up @@ -413,7 +413,7 @@ export class OPFSAdaptiveVFS extends WebLocksMixin(FacadeVFS) {
this.lastError = e;
return VFS.SQLITE_IOERR;
}
return VFS.SQLITE_NOTFOUND;
return super.jFileControl(fileId, op, pArg);
}

jGetLastError(zBuf) {
Expand Down
2 changes: 1 addition & 1 deletion src/examples/OPFSCoopSyncVFS.js
Original file line number Diff line number Diff line change
Expand Up @@ -437,7 +437,7 @@ export class OPFSCoopSyncVFS extends FacadeVFS {
if (file.persistentFile.isHandleRequested) {
// Another connection wants the access handle.
this.#releaseAccessHandle(file);
this.isHandleRequested = false;
file.persistentFile.isHandleRequested = false;
}
file.persistentFile.isFileLocked = false;
}
Expand Down
3 changes: 3 additions & 0 deletions src/examples/OPFSPermutedVFS.js
Original file line number Diff line number Diff line change
Expand Up @@ -463,6 +463,9 @@ export class OPFSPermutedVFS extends FacadeVFS {
const file = this.#mapIdToFile.get(fileId);
if ((file.flags & VFS.SQLITE_OPEN_MAIN_DB) && !file.txIsOverwrite) {
file.abortController.signal.throwIfAborted();
if (!file.txActive) {
this.#beginTx(file);
}
file.txActive.fileSize = iSize;

// Remove now obsolete pages from file.txActive.pages
Expand Down
2 changes: 1 addition & 1 deletion src/examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ Changing the page size after the database is created is not supported (this is a
### IDBMirrorVFS
This VFS keeps all files in memory, persisting database files to IndexedDB. It works on all contexts.

IDBBatchAtomicVFS can trade durability for performance by setting `PRAGMA synchronous=normal`.
IDBMirrorVFS can trade durability for performance by setting `PRAGMA synchronous=normal`.

Changing the page size after the database is created is not supported.

Expand Down
3 changes: 3 additions & 0 deletions web-test-runner.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,12 @@ export default /** @type {import("@web/test-runner").TestRunnerConfig} */ ({
defaultTimeoutInterval: 5 * 60 * 1000
},
},
browserLogs: true,
browserStartTimeout: 60_000,
nodeResolve: true,
files: ['./test/*.test.js'],
concurrency: 1,
concurrentBrowsers: 1,
browsers: [
chromeLauncher({
launchOptions: {
Expand Down
Loading