Skip to content

Commit

Permalink
Merge pull request #423 from a-type/persistence-refactor
Browse files Browse the repository at this point in the history
Persistence layer refactoring overhaul
  • Loading branch information
a-type authored Oct 20, 2024
2 parents 6604111 + a6a87a4 commit 1c955f0
Show file tree
Hide file tree
Showing 109 changed files with 16,196 additions and 14,094 deletions.
5 changes: 0 additions & 5 deletions .changeset/dirty-planes-lick.md

This file was deleted.

8 changes: 8 additions & 0 deletions .changeset/light-cups-poke.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'@verdant-web/store': major
'@verdant-web/common': minor
'@verdant-web/server': patch
'@verdant-web/cli': patch
---

Major internal refactoring of persistence layer. Verdant still only supports IndexedDB for now, but this is a huge step toward configurable storage. Prereleasing this version to test in real-world environments.
15 changes: 15 additions & 0 deletions .changeset/pre.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"mode": "pre",
"tag": "next",
"initialVersions": {
"@verdant-web/cli": "4.6.1",
"@verdant-web/common": "2.5.2",
"@verdant-web/create-app": "0.6.0",
"@verdant-web/s3-file-storage": "1.0.29",
"@verdant-web/react": "38.0.0",
"@verdant-web/react-router": "0.6.4",
"@verdant-web/server": "3.3.2",
"@verdant-web/store": "3.12.1"
},
"changesets": []
}
5 changes: 5 additions & 0 deletions configs/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"devDependencies": {
"vitest": "2.1.3"
}
}
1 change: 1 addition & 0 deletions configs/vitest.workspace.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default ['../packages/*/vitest.config.ts', '../test'];
4 changes: 3 additions & 1 deletion packages/cli/src/typings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,11 @@ export class Client<Presence = any, Profile = any> {
__manualRebase: () => Promise<void>;
}
export interface ClientDescriptorOptions<Presence = any, Profile = any> extends Omit<BaseClientDescriptorOptions<Presence, Profile>, 'schema' | 'migrations'> {
export interface ClientDescriptorOptions<Presence = any, Profile = any> extends Omit<BaseClientDescriptorOptions<Presence, Profile>, 'schema' | 'migrations' | 'oldSchemas'> {
/** WARNING: overriding the schema is dangerous and almost definitely not what you want. */
schema?: StorageSchema;
/** WARNING: overriding old schemas is dangerous and almost definitely not what you want. */
oldSchemas?: StorageSchema[];
/** WARNING: overriding the migrations is dangerous and almost definitely not what you want. */
migrations?: Migration[];
}
Expand Down
4 changes: 3 additions & 1 deletion packages/cli/test/__snapshots__/generated.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,12 @@ export class Client<Presence = any, Profile = any> {
export interface ClientDescriptorOptions<Presence = any, Profile = any>
extends Omit<
BaseClientDescriptorOptions<Presence, Profile>,
"schema" | "migrations"
"schema" | "migrations" | "oldSchemas"
> {
/** WARNING: overriding the schema is dangerous and almost definitely not what you want. */
schema?: StorageSchema;
/** WARNING: overriding old schemas is dangerous and almost definitely not what you want. */
oldSchemas?: StorageSchema[];
/** WARNING: overriding the migrations is dangerous and almost definitely not what you want. */
migrations?: Migration[];
}
Expand Down
3 changes: 3 additions & 0 deletions packages/common/src/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ export enum VerdantErrorCode {
Unexpected = 5000,
ConfigurationError = 5010,
NoFileStorage = 5011,
// Client errors
MigrationPathNotFound = 7001,
ImportFailed = 7002,
}

export class VerdantError extends Error {
Expand Down
22 changes: 19 additions & 3 deletions packages/common/src/patch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
* High-level patch creation for use with complex nested objects.
*/

import { AuthorizationKey } from './authz.js';
import { FileRef } from './files.js';
import { createRef, createSubOid, ObjectIdentifier } from './oids.js';
import {
Expand Down Expand Up @@ -32,8 +33,19 @@ export class PatchCreator {
return diffToPatches(from, to, this.getNow, this.createSubId, [], options);
};

createInitialize = (obj: any, oid: ObjectIdentifier) => {
return initialToPatches(obj, oid, this.getNow, this.createSubId);
createInitialize = (
obj: any,
oid: ObjectIdentifier,
authz?: AuthorizationKey,
) => {
return initialToPatches(
obj,
oid,
this.getNow,
this.createSubId,
undefined,
authz ? { authz } : undefined,
);
};

createSet = (
Expand Down Expand Up @@ -294,13 +306,17 @@ export class PatchCreator {
];
};

createDeleteAll = (oids: ObjectIdentifier[]): Operation[] => {
createDeleteAll = (
oids: ObjectIdentifier[],
authz?: AuthorizationKey,
): Operation[] => {
return oids.map((oid) => ({
oid,
timestamp: this.getNow(),
data: {
op: 'delete',
},
authz,
}));
};
}
2 changes: 2 additions & 0 deletions packages/common/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,3 +185,5 @@ export function throttle<T extends (...args: any[]) => any>(
}
} as any;
}

export function noop() {}
2 changes: 1 addition & 1 deletion packages/react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
"typecheck": "tsc --noEmit"
},
"peerDependencies": {
"@verdant-web/store": "^3.12.0",
"@verdant-web/store": "^3.12.1",
"react": "^18.2.0"
},
"dependencies": {
Expand Down
1 change: 1 addition & 0 deletions packages/server/src/Server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -575,6 +575,7 @@ export class Server extends EventEmitter implements MessageSender {
await this.storage.ready;
await this.storage.fileMetadata.put(info.libraryId, lofiFileInfo);
fs.put(stream, lofiFileInfo);
this.log('info', 'File uploading', lofiFileInfo);
} catch (e) {
reject(e);
}
Expand Down
8 changes: 7 additions & 1 deletion packages/server/src/files/FileStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,20 @@ export interface FileStorage {
export class LocalFileStorage implements FileStorage {
private readonly host: string;
private readonly rootDirectory: string;
private log: (level: string, ...args: any[]) => void;

constructor({
rootDirectory,
host,
log,
}: {
rootDirectory: string;
host: string;
log?: (level: string, ...args: any[]) => void;
}) {
this.host = this.prepareHost(host);
this.rootDirectory = rootDirectory;
this.log = log || (() => {});
}

private prepareHost = (host: string) => {
Expand All @@ -53,8 +57,10 @@ export class LocalFileStorage implements FileStorage {
await fs.promises.mkdir(containingDirectory, {
recursive: true,
});
const dest = fs.createWriteStream(this.getStorageLocation(data));
const location = this.getStorageLocation(data);
const dest = fs.createWriteStream(location);
fileStream.pipe(dest);
this.log('info', 'File saving to', location);
}

getUrl(data: FileInfo): string {
Expand Down
6 changes: 6 additions & 0 deletions packages/store/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# @lo-fi/web

## 3.12.1

### Patch Changes

- 66041118: Make getAll() result readonly

## 3.12.0

### Minor Changes
Expand Down
2 changes: 1 addition & 1 deletion packages/store/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@verdant-web/store",
"version": "3.12.0",
"version": "3.12.1",
"access": "public",
"type": "module",
"exports": {
Expand Down
12 changes: 6 additions & 6 deletions packages/store/src/__tests__/batching.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { describe, it, expect, vi, MockedFunction } from 'vitest';
import { describe, it, expect, vi } from 'vitest';
import { createTestStorage } from './fixtures/testStorage.js';
import { Entity } from '../entities/Entity.js';

Expand Down Expand Up @@ -59,14 +59,15 @@ describe('batching operations', () => {
it('should overwrite superseded sequential set operations on the same key where applicable', async () => {
const onOperation = vi.fn();
const client = await createTestStorage({
onOperation,
// log: console.log,
});
client.subscribe('operation', onOperation);

const item = await client.todos.put({
content: 'hello world',
category: 'general',
});
onOperation.mockReset();
onOperation.mockClear();

item.set('content', 'hello world 2');
item.set('content', 'hello world 3');
Expand All @@ -90,9 +91,8 @@ describe('batching operations', () => {

it('should not interfere with other fields when superseding', async () => {
const onOperation = vi.fn();
const client = await createTestStorage({
onOperation,
});
const client = await createTestStorage();
client.subscribe('operation', onOperation);

const item = await client.todos.put({
content: 'hello world',
Expand Down
2 changes: 1 addition & 1 deletion packages/store/src/__tests__/entities.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -686,7 +686,7 @@ describe('entities', () => {

it('should allow subscribing to one field and not break on deletion', async () => {
const storage = await createTestStorage({
log: console.log,
// log: console.log,
});
const item = await storage.todos.put({
content: 'item',
Expand Down
12 changes: 2 additions & 10 deletions packages/store/src/__tests__/fixtures/testStorage.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,8 @@
import {
ClientMessage,
createMigration,
Operation,
schema,
} from '@verdant-web/common';
import { createMigration, schema } from '@verdant-web/common';
// @ts-ignore
import { IDBFactory } from 'fake-indexeddb';
import { ClientWithCollections, ClientDescriptor } from '../../index.js';
import { METADATA_VERSION_KEY } from '../../client/constants.js';
import { Sync } from '../../sync/Sync.js';

export const todoCollection = schema.collection({
name: 'todo',
Expand Down Expand Up @@ -102,23 +96,21 @@ export function createTestStorage({
disableRebasing = false,
metadataVersion,
log,
onOperation,
}: {
idb?: IDBFactory;
disableRebasing?: boolean;
metadataVersion?: number;
log?: (...args: any[]) => void;
onOperation?: (op: Operation) => void;
} = {}) {
const storage = new ClientDescriptor({
schema: testSchema,
migrations: [createMigration<{}>(testSchema)],
indexedDb: idb,
namespace: 'test',
disableRebasing,
oldSchemas: [testSchema],
log,
[METADATA_VERSION_KEY]: metadataVersion,
onOperation,
}).open();
return storage as Promise<ClientWithCollections>;
}
Loading

0 comments on commit 1c955f0

Please sign in to comment.