@docstack/pouchdb-adapter-googledrive 0.0.2 β 0.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +27 -58
- package/lib/index.d.ts +10 -1
- package/lib/index.js +51 -3
- package/package.json +1 -1
- package/DOCUMENTATION.md +0 -54
- package/error.log +0 -21
package/README.md
CHANGED
|
@@ -6,10 +6,8 @@ A persistent, serverless PouchDB adapter that uses Google Drive as a backend sto
|
|
|
6
6
|
|
|
7
7
|
- **π Append-Only Log**: Uses an efficient append-only log pattern for fast, conflict-free writes.
|
|
8
8
|
- **β‘ Lazy Loading**: Optimizes memory and bandwidth by loading only the **Index** into memory. Document bodies are fetched on-demand.
|
|
9
|
-
- **π‘οΈ Optimistic Concurrency Control**: Uses ETag-based locking on metadata to prevent race conditions
|
|
10
|
-
-
|
|
11
|
-
- **π¦ Auto-Compaction**: Automatically merges logs into snapshots to keep performance high.
|
|
12
|
-
- **πΎ Offline/Resilient**: Retry logic with exponential backoff handles network instability and "thundering herd" scenarios.
|
|
9
|
+
- **π‘οΈ Optimistic Concurrency Control**: Uses ETag-based locking on metadata to prevent race conditions.
|
|
10
|
+
- **π¦ Auto-Compaction**: Automatically merges logs for performance.
|
|
13
11
|
|
|
14
12
|
## Installation
|
|
15
13
|
|
|
@@ -19,74 +17,45 @@ npm install @docstack/pouchdb-adapter-googledrive
|
|
|
19
17
|
|
|
20
18
|
## Usage
|
|
21
19
|
|
|
20
|
+
The adapter is initialized as a plugin with your Google Drive configuration.
|
|
21
|
+
|
|
22
22
|
```typescript
|
|
23
23
|
import PouchDB from 'pouchdb-core';
|
|
24
24
|
import GoogleDriveAdapter from '@docstack/pouchdb-adapter-googledrive';
|
|
25
25
|
import { google } from 'googleapis';
|
|
26
26
|
|
|
27
|
-
//
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
// Setup Google Drive Client (Authenticated)
|
|
31
|
-
const oauth2Client = new google.auth.OAuth2(
|
|
32
|
-
YOUR_CLIENT_ID,
|
|
33
|
-
YOUR_CLIENT_SECRET,
|
|
34
|
-
YOUR_REDIRECT_URL
|
|
35
|
-
);
|
|
27
|
+
// 1. Setup Google Drive Client
|
|
28
|
+
const oauth2Client = new google.auth.OAuth2(CLIENT_ID, SECRET, REDIRECT);
|
|
36
29
|
oauth2Client.setCredentials({ access_token: '...' });
|
|
37
|
-
|
|
38
30
|
const drive = google.drive({ version: 'v3', auth: oauth2Client });
|
|
39
31
|
|
|
40
|
-
//
|
|
41
|
-
const
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
32
|
+
// 2. Initialize the Adapter Plugin with Config
|
|
33
|
+
const adapterPlugin = GoogleDriveAdapter({
|
|
34
|
+
drive: drive,
|
|
35
|
+
folderName: 'my-app-db-folder', // Root folder
|
|
36
|
+
pollingIntervalMs: 2000
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
// 3. Register Plugin
|
|
40
|
+
PouchDB.plugin(adapterPlugin);
|
|
41
|
+
// Also needs replication plugin if using replicate()
|
|
42
|
+
// PouchDB.plugin(require('pouchdb-replication'));
|
|
43
|
+
|
|
44
|
+
// 4. Create Database
|
|
45
|
+
// No need to pass 'drive' here anymore!
|
|
46
|
+
const db = new PouchDB('user_db', {
|
|
47
|
+
adapter: 'googledrive'
|
|
49
48
|
});
|
|
50
49
|
|
|
51
|
-
|
|
52
|
-
await db.put({ _id: 'doc1', title: 'Hello Drive!' });
|
|
53
|
-
const doc = await db.get('doc1');
|
|
50
|
+
await db.post({ title: 'Hello World' });
|
|
54
51
|
```
|
|
55
52
|
|
|
56
53
|
## Architecture
|
|
57
54
|
|
|
58
|
-
The adapter implements a **"Remote-First"** architecture
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
- `_meta.json`: The "Lock File". Tracks the sequence number and active log pointers.
|
|
63
|
-
- `snapshot-index.json`: A lightweight map of `DocID -> { Revision, FilePointer }`. Loaded at startup.
|
|
64
|
-
- `snapshot-data.json`: Large payload files containing document bodies. **Not loaded** until requested.
|
|
65
|
-
- `changes-{seq}-{uuid}.ndjson`: Immutable append-only logs for recent updates.
|
|
66
|
-
|
|
67
|
-
### 2. Lazy Loading & Caching
|
|
68
|
-
- **Startup**: The client downloads only `_meta.json` and `snapshot-index.json` (~MBs even for large DBs).
|
|
69
|
-
- **Access**: `db.get(id)` checks a local **LRU Cache**. If missing, it fetches the specific file containing that document from Drive.
|
|
70
|
-
- **Sync**: `db.changes()` iterates the local index, ensuring fast replication without downloading full content.
|
|
71
|
-
|
|
72
|
-
### 3. Concurrency
|
|
73
|
-
- **Writes**: Every write creates a new unique `changes-*.ndjson` file.
|
|
74
|
-
- **Commit**: The adapter attempts to update `_meta.json` with an ETag check (`If-Match`).
|
|
75
|
-
- **Conflict**: If `_meta.json` was changed by another client, the write retries automatically after re-syncing the index.
|
|
76
|
-
|
|
77
|
-
## Testing
|
|
78
|
-
|
|
79
|
-
To run the tests, you need to provide Google Drive API credentials.
|
|
80
|
-
|
|
81
|
-
1. Copy `.env.example` to `.env`:
|
|
82
|
-
```bash
|
|
83
|
-
cp .env.example .env
|
|
84
|
-
```
|
|
85
|
-
2. Fill in your Google Cloud credentials in `.env`.
|
|
86
|
-
3. Run the tests:
|
|
87
|
-
```bash
|
|
88
|
-
npm test
|
|
89
|
-
```
|
|
55
|
+
The adapter implements a **"Remote-First"** architecture:
|
|
56
|
+
- **Lazy Loading**: `db.get(id)` fetches data on-demand from Drive.
|
|
57
|
+
- **Caching**: Changes are indexed locally but bodies are cached in an LRU cache.
|
|
58
|
+
- **Resilience**: Writes use optimistic locking to handle multi-client concurrency safer.
|
|
90
59
|
|
|
91
60
|
## License
|
|
92
61
|
|
package/lib/index.d.ts
CHANGED
|
@@ -1 +1,10 @@
|
|
|
1
|
-
|
|
1
|
+
import { GoogleDriveAdapterOptions } from './types';
|
|
2
|
+
export * from './types';
|
|
3
|
+
/**
|
|
4
|
+
* Google Drive Adapter Plugin Factory
|
|
5
|
+
*
|
|
6
|
+
* Usage:
|
|
7
|
+
* const plugin = GoogleDriveAdapter({ drive: myDriveClient, ... });
|
|
8
|
+
* PouchDB.plugin(plugin);
|
|
9
|
+
*/
|
|
10
|
+
export default function GoogleDriveAdapter(config: GoogleDriveAdapterOptions): (PouchDB: any) => void;
|
package/lib/index.js
CHANGED
|
@@ -1,7 +1,55 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
2
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.default =
|
|
17
|
+
exports.default = GoogleDriveAdapter;
|
|
4
18
|
const adapter_1 = require("./adapter");
|
|
5
|
-
|
|
6
|
-
|
|
19
|
+
// Export types
|
|
20
|
+
__exportStar(require("./types"), exports);
|
|
21
|
+
/**
|
|
22
|
+
* Google Drive Adapter Plugin Factory
|
|
23
|
+
*
|
|
24
|
+
* Usage:
|
|
25
|
+
* const plugin = GoogleDriveAdapter({ drive: myDriveClient, ... });
|
|
26
|
+
* PouchDB.plugin(plugin);
|
|
27
|
+
*/
|
|
28
|
+
function GoogleDriveAdapter(config) {
|
|
29
|
+
return function (PouchDB) {
|
|
30
|
+
// Get the base adapter constructor (scoped to this PouchDB instance)
|
|
31
|
+
const BaseAdapter = (0, adapter_1.GoogleDriveAdapter)(PouchDB);
|
|
32
|
+
// Create a wrapper constructor that injects the config
|
|
33
|
+
function ConfiguredAdapter(opts, callback) {
|
|
34
|
+
// Merge factory config with constructor options
|
|
35
|
+
// Constructor options take precedence (overrides)
|
|
36
|
+
const mergedOpts = Object.assign({}, config, opts);
|
|
37
|
+
// Call the base adapter
|
|
38
|
+
BaseAdapter.call(this, mergedOpts, callback);
|
|
39
|
+
}
|
|
40
|
+
// Copy static properties required by PouchDB
|
|
41
|
+
// @ts-ignore
|
|
42
|
+
ConfiguredAdapter.valid = BaseAdapter.valid;
|
|
43
|
+
// @ts-ignore
|
|
44
|
+
ConfiguredAdapter.use_prefix = BaseAdapter.use_prefix;
|
|
45
|
+
// Register the adapter manually
|
|
46
|
+
// We use PouchDB.adapters object directly to avoid using the .adapter() method
|
|
47
|
+
if (PouchDB.adapters) {
|
|
48
|
+
PouchDB.adapters['googledrive'] = ConfiguredAdapter;
|
|
49
|
+
}
|
|
50
|
+
else {
|
|
51
|
+
// Fallback/Warning if adapters object is somehow missing (should not happen in core)
|
|
52
|
+
console.warn('PouchDB.adapters not found, unable to register googledrive adapter');
|
|
53
|
+
}
|
|
54
|
+
};
|
|
7
55
|
}
|
package/package.json
CHANGED
package/DOCUMENTATION.md
DELETED
|
@@ -1,54 +0,0 @@
|
|
|
1
|
-
# Architecture & Design Documentation
|
|
2
|
-
|
|
3
|
-
## 1. Core Principles
|
|
4
|
-
The `pouchdb-adapter-googledrive` implementation is built on three core pillars to ensure data integrity and performance on a file-based remote storage system.
|
|
5
|
-
|
|
6
|
-
### A. Append-Only Log (Storage)
|
|
7
|
-
Instead of modifying a single database file (which is prone to conflicts), we use an **Append-Only** strategy.
|
|
8
|
-
- **Changes**: Every write operation (or batch of writes) creates a **new, immutable file** (e.g., `changes-{seq}-{uuid}.ndjson`).
|
|
9
|
-
- **Snapshots**: Periodically, the log is compacted into a `snapshot` file.
|
|
10
|
-
- **Benefit**: Historical data is preserved until compaction, and file-write conflicts are minimized.
|
|
11
|
-
|
|
12
|
-
### B. Optimistic Concurrency Control (OCC)
|
|
13
|
-
To prevent race conditions (two clients writing simultaneously), we use **ETag-based locking** on a single entry point: `_meta.json`.
|
|
14
|
-
- **The Lock**: `_meta.json` holds the current Sequence Number and the list of active log files.
|
|
15
|
-
- **The Protocol**:
|
|
16
|
-
1. Reader fetches `_meta.json` and its `ETag`.
|
|
17
|
-
2. Writer prepares a new change file and uploads it (orphaned initially).
|
|
18
|
-
3. Writer attempts to update `_meta.json` with the new file reference, sending `If-Match: <Old-ETag>`.
|
|
19
|
-
4. **Success**: The change is now officially part of the DB.
|
|
20
|
-
5. **Failure (412/409)**: Another client updated the DB. The writer deletes its orphaned file, pulls the new state, and retries the logical operation.
|
|
21
|
-
|
|
22
|
-
### C. Remote-First "Lazy" Loading (Memory Optimization)
|
|
23
|
-
To support large databases without exhausting client memory, we separate **Metadata** from **Content**.
|
|
24
|
-
|
|
25
|
-
#### Storage Structure
|
|
26
|
-
- `_meta.json`: Root pointer. Small.
|
|
27
|
-
- `snapshot-index.json`: A map of `{ docId: { rev, filePointer } }`. Medium size (~100 bytes/doc). Loaded at startup.
|
|
28
|
-
- `snapshot-data.json`: The actual document bodies. Large. **Never fully loaded.**
|
|
29
|
-
- `changes-*.ndjson`: Recent updates.
|
|
30
|
-
|
|
31
|
-
#### Client Startup Sequence
|
|
32
|
-
1. **Fetch Meta**: Download `_meta.json` and get the `snapshotIndexId`.
|
|
33
|
-
2. **Fetch Index**: Download `snapshot-index.json`. This builds the "Revision Tree" in memory.
|
|
34
|
-
3. **Replay Logs**: Download and parse only the small `changes-*.ndjson` files created since the snapshot to update the in-memory Index.
|
|
35
|
-
4. **Ready**: The client is now ready to query keys. No document content has been downloaded yet.
|
|
36
|
-
|
|
37
|
-
#### On-Demand Usage
|
|
38
|
-
- **`db.get(id)`**:
|
|
39
|
-
1. Look up `id` in the **Memory Index** to find the `filePointer`.
|
|
40
|
-
2. Check **LRU Cache**.
|
|
41
|
-
3. If missing, fetch the specific file/range from Google Drive.
|
|
42
|
-
- **`db.allDocs({ keys: [...] })`**: Efficiently looks up pointers and fetches only requested docs.
|
|
43
|
-
|
|
44
|
-
## 2. Technical Patterns
|
|
45
|
-
|
|
46
|
-
### Atomic Compaction
|
|
47
|
-
Compaction is a critical maintenance task that merges the `snapshot-data` with recent `changes` to create a new baseline.
|
|
48
|
-
- **Safe**: Limits memory usage by streaming/batching.
|
|
49
|
-
- **Atomic**: Uploads the new snapshot as a new file. Swaps the pointer in `_meta.json` using OCC.
|
|
50
|
-
- **Zero-Downtime**: Clients can continue reading/writing to the old logs while compaction runs. Writes that happen *during* compaction are detected via the ETag check, causing the compaction to abort/retry safeley.
|
|
51
|
-
|
|
52
|
-
### Conflict Handling
|
|
53
|
-
- **PouchDB Level**: Standard CouchDB revision conflicts (409) are preserved. A "winner" is chosen deterministically, but conflicting revisions are kept in the tree (requires `snapshot-index` to store the full revision tree, not just the winner).
|
|
54
|
-
- **Adapter Level**: Drive API 409s handling (retry logic) ensures the transport layer is reliable.
|
package/error.log
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
FAIL tests/adapter.test.ts
|
|
2
|
-
ΞΓΉΓ
Test suite failed to run
|
|
3
|
-
|
|
4
|
-
tests/adapter.test.ts:51:13 - error TS2353: Object literal may only specify known properties, and 'drive' does not exist in type 'DatabaseConfiguration'.
|
|
5
|
-
|
|
6
|
-
51 drive: drive,
|
|
7
|
-
~~~~~
|
|
8
|
-
tests/adapter.test.ts:57:21 - error TS2339: Property 'backend_adapter' does not exist on type 'DatabaseInfo'.
|
|
9
|
-
|
|
10
|
-
57 expect(info.backend_adapter).toBe('googledrive');
|
|
11
|
-
~~~~~~~~~~~~~~~
|
|
12
|
-
tests/adapter.test.ts:65:24 - error TS2339: Property 'title' does not exist on type 'IdMeta & GetMeta'.
|
|
13
|
-
|
|
14
|
-
65 expect(fetched.title).toBe('Start Wars');
|
|
15
|
-
~~~~~
|
|
16
|
-
|
|
17
|
-
Test Suites: 1 failed, 1 total
|
|
18
|
-
Tests: 0 total
|
|
19
|
-
Snapshots: 0 total
|
|
20
|
-
Time: 14.401 s
|
|
21
|
-
Ran all test suites matching tests/adapter.test.ts.
|