-
Notifications
You must be signed in to change notification settings - Fork 6
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
indexer: add kv plugin #84
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
751aa8a
indexer: add kv plugin
jaipaljadeja b44f97e
chore: add no unused import rule in biome
jaipaljadeja 9a9e504
indexer: add useKVStore hook
jaipaljadeja 9280b7f
indexer: add KVStore tests
jaipaljadeja 6ac28bd
chore: fix type error for updated viem type defs
jaipaljadeja ca10222
indexer: remove generic type from KVStore class
jaipaljadeja e788e54
indexer: add successful and rollback transaction tests
jaipaljadeja File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export * from "./useKVStore"; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
import { useIndexerContext } from "../context"; | ||
import type { KVStore } from "../plugins/kv"; | ||
|
||
export type UseKVStoreResult = InstanceType<typeof KVStore>; | ||
|
||
export function useKVStore(): UseKVStoreResult { | ||
const ctx = useIndexerContext(); | ||
|
||
if (!ctx?.kv) throw new Error("KV Plugin is not available in context!"); | ||
|
||
return ctx.kv; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2 changes: 1 addition & 1 deletion
2
packages/indexer/src/plugins.ts → packages/indexer/src/plugins/config.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1 @@ | ||
export * from "./kv"; | ||
export * from "./config"; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,112 @@ | ||
import { type Database, open } from "sqlite"; | ||
import sqlite3 from "sqlite3"; | ||
import { afterAll, beforeAll, describe, expect, it } from "vitest"; | ||
import { KVStore } from "./kv"; | ||
|
||
type ValueType = { data: bigint }; | ||
|
||
describe("KVStore", () => { | ||
let db: Database<sqlite3.Database, sqlite3.Statement>; | ||
let store: KVStore; | ||
const key = "test_key"; | ||
|
||
beforeAll(async () => { | ||
db = await open({ driver: sqlite3.Database, filename: ":memory:" }); | ||
await KVStore.initialize(db); | ||
store = new KVStore(db, "finalized", { orderKey: 5_000_000n }); | ||
}); | ||
|
||
afterAll(async () => { | ||
await db.close(); | ||
}); | ||
|
||
it("should begin transaction", async () => { | ||
await store.beginTransaction(); | ||
}); | ||
|
||
it("should put and get a value", async () => { | ||
const value = { data: 0n }; | ||
|
||
await store.put<ValueType>(key, value); | ||
const result = await store.get<ValueType>(key); | ||
|
||
expect(result).toEqual(value); | ||
}); | ||
|
||
it("should commit transaction", async () => { | ||
await store.commitTransaction(); | ||
|
||
const value = { data: 0n }; | ||
|
||
const result = await store.get<ValueType>(key); | ||
|
||
expect(result).toEqual(value); | ||
}); | ||
|
||
it("should return undefined for non-existing key", async () => { | ||
const result = await store.get<ValueType>("non_existent_key"); | ||
expect(result).toBeUndefined(); | ||
}); | ||
|
||
it("should begin transaction", async () => { | ||
await store.beginTransaction(); | ||
}); | ||
|
||
it("should update an existing value", async () => { | ||
store = new KVStore(db, "finalized", { orderKey: 5_000_020n }); | ||
|
||
const value = { data: 50n }; | ||
|
||
await store.put<ValueType>(key, value); | ||
const result = await store.get<ValueType>(key); | ||
|
||
expect(result).toEqual(value); | ||
}); | ||
|
||
it("should delete a value", async () => { | ||
await store.del(key); | ||
const result = await store.get<ValueType>(key); | ||
|
||
expect(result).toBeUndefined(); | ||
|
||
const rows = await db.all( | ||
` | ||
SELECT from_block, to_block, k, v | ||
FROM kvs | ||
WHERE k = ? | ||
`, | ||
[key], | ||
); | ||
|
||
// Check that the old is correctly marked with to_block | ||
expect(rows[0].to_block).toBe(Number(5_000_020n)); | ||
}); | ||
|
||
it("should rollback transaction", async () => { | ||
await store.rollbackTransaction(); | ||
}); | ||
|
||
it("should revert the changes to last commit", async () => { | ||
const rows = await db.all( | ||
` | ||
SELECT from_block, to_block, k, v | ||
FROM kvs | ||
WHERE k = ? | ||
`, | ||
[key], | ||
); | ||
|
||
expect(rows).toMatchInlineSnapshot(` | ||
[ | ||
{ | ||
"from_block": 5000000, | ||
"k": "test_key", | ||
"to_block": null, | ||
"v": "{ | ||
"data": "0n" | ||
}", | ||
}, | ||
] | ||
`); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,16 +1,128 @@ | ||
import assert from "node:assert"; | ||
import type { Cursor, DataFinality } from "@apibara/protocol"; | ||
import { type Database, type ISqlite, open } from "sqlite"; | ||
import { useIndexerContext } from "../context"; | ||
import { defineIndexerPlugin } from "../plugins"; | ||
import { deserialize, serialize } from "../vcr"; | ||
import { defineIndexerPlugin } from "./config"; | ||
|
||
/** This plugin is a placeholder for a future key-value store plugin. */ | ||
export function kv<TFilter, TBlock, TRet>() { | ||
type SqliteArgs = ISqlite.Config; | ||
|
||
export function kv<TFilter, TBlock, TRet>(args: SqliteArgs) { | ||
return defineIndexerPlugin<TFilter, TBlock, TRet>((indexer) => { | ||
let db: Database; | ||
|
||
indexer.hooks.hook("run:before", async () => { | ||
db = await open(args); | ||
await KVStore.initialize(db); | ||
}); | ||
|
||
indexer.hooks.hook("handler:before", async ({ finality, endCursor }) => { | ||
const ctx = useIndexerContext(); | ||
|
||
assert(endCursor, new Error("endCursor cannot be undefined")); | ||
|
||
ctx.kv = new KVStore(db, finality, endCursor); | ||
|
||
await ctx.kv.beginTransaction(); | ||
}); | ||
|
||
indexer.hooks.hook("handler:after", async () => { | ||
const ctx = useIndexerContext(); | ||
|
||
await ctx.kv.commitTransaction(); | ||
|
||
ctx.kv = null; | ||
}); | ||
|
||
indexer.hooks.hook("handler:exception", async () => { | ||
const ctx = useIndexerContext(); | ||
ctx.kv = {}; | ||
|
||
await ctx.kv.rollbackTransaction(); | ||
|
||
ctx.kv = null; | ||
}); | ||
|
||
indexer.hooks.hook("run:after", async () => { | ||
console.log("kv: ", useIndexerContext().kv); | ||
}); | ||
}); | ||
} | ||
|
||
export class KVStore { | ||
constructor( | ||
private _db: Database, | ||
private _finality: DataFinality, | ||
private _endCursor: Cursor, | ||
) {} | ||
|
||
static async initialize(db: Database) { | ||
await db.exec(` | ||
CREATE TABLE IF NOT EXISTS kvs ( | ||
from_block INTEGER NOT NULL, | ||
to_block INTEGER, | ||
k TEXT NOT NULL, | ||
v BLOB NOT NULL, | ||
PRIMARY KEY (from_block, k) | ||
); | ||
`); | ||
} | ||
|
||
async beginTransaction() { | ||
await this._db.exec("BEGIN TRANSACTION"); | ||
} | ||
|
||
async commitTransaction() { | ||
await this._db.exec("COMMIT TRANSACTION"); | ||
} | ||
|
||
async rollbackTransaction() { | ||
await this._db.exec("ROLLBACK TRANSACTION"); | ||
} | ||
|
||
async get<T>(key: string): Promise<T> { | ||
const row = await this._db.get<{ v: string }>( | ||
` | ||
SELECT v | ||
FROM kvs | ||
WHERE k = ? AND to_block IS NULL | ||
`, | ||
[key], | ||
); | ||
|
||
return row ? deserialize(row.v) : undefined; | ||
} | ||
|
||
async put<T>(key: string, value: T) { | ||
await this._db.run( | ||
` | ||
UPDATE kvs | ||
SET to_block = ? | ||
WHERE k = ? AND to_block IS NULL | ||
`, | ||
[Number(this._endCursor.orderKey), key], | ||
); | ||
|
||
await this._db.run( | ||
` | ||
INSERT INTO kvs (from_block, to_block, k, v) | ||
VALUES (?, NULL, ?, ?) | ||
`, | ||
[ | ||
Number(this._endCursor.orderKey), | ||
key, | ||
serialize(value as Record<string, unknown>), | ||
], | ||
); | ||
} | ||
|
||
async del(key: string) { | ||
await this._db.run( | ||
` | ||
UPDATE kvs | ||
SET to_block = ? | ||
WHERE k = ? AND to_block IS NULL | ||
`, | ||
[Number(this._endCursor.orderKey), key], | ||
); | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is this handler called anywhere? I think we should catch the handler exception and then rethrow it after calling the hook.