Skip to content
This repository has been archived by the owner on Jul 1, 2023. It is now read-only.

Commit

Permalink
Merge pull request #51 from dbpunk-labs/feat/support_free_node
Browse files Browse the repository at this point in the history
feat: support normal free node
  • Loading branch information
imotai authored Mar 30, 2023
2 parents 94794ce + 0cecdd4 commit 114d8c0
Show file tree
Hide file tree
Showing 9 changed files with 98 additions and 54 deletions.
1 change: 0 additions & 1 deletion examples/helloworld/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
"dependencies": {
"antd": "^5.0.2",
"buffer": "^6.0.3",
"db3.js": "^0.2.17",
"node-stdlib-browser": "^1.2.0",
"rc-virtual-list": "^3.4.13",
"react": "^18.2.0",
Expand Down
2 changes: 1 addition & 1 deletion examples/helloworld/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ globalThis.Buffer = Buffer
const { TextArea } = Input
const { Title, Text } = Typography
const wallet = new MetamaskWallet(window)
const client = new DB3Client('https://grpc.devnet.db3.network', wallet)
const client = new DB3Client('http://127.0.0.1:46659', wallet)

interface Todo {
text: string
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "db3.js",
"version": "0.2.19",
"version": "0.2.20",
"description": "DB3 Network Javascript API",
"author": "dbpunk labs",
"keywords": [
Expand Down
44 changes: 35 additions & 9 deletions src/client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,14 +56,17 @@ export class DB3Client {
querySessionInfo: QuerySessionInfo | undefined
sessionToken: string | undefined
wallet: Wallet

querySessionEnabled: boolean
hasCheckedQuerySession: boolean
/**
* new a db3 client with db3 node url and wallet
*
*/
constructor(url: string, wallet: Wallet) {
this.provider = new StorageProvider(url, wallet)
this.wallet = wallet
this.querySessionEnabled = true
this.hasCheckedQuerySession = false
}

/**
Expand Down Expand Up @@ -93,21 +96,26 @@ export class DB3Client {
return [dbId.getHexAddr(), txId.getB64()]
}

async getMyDatabases() {
async listDatabases(sender: string) {
const token = await this.keepSessionAlive()
const dbs = await this.provider.getMyDatabases(token)
this.querySessionInfo!.queryCount += 1
const dbs = await this.provider.listDatabases(token, sender)
this.incrQueryCount()
return dbs
}

incrQueryCount() {
if (this.querySessionEnable && this.querySessionInfo) {
this.querySessionInfo!.queryCount += 1
}
}
/**
* get a database information
*
*/
async getDatabase(addr: string) {
const token = await this.keepSessionAlive()
const response = await this.provider.getDatabase(addr, token)
this.querySessionInfo!.queryCount += 1
this.incrQueryCount()
if (response.dbs.length > 0) {
return response.dbs[0]
} else {
Expand Down Expand Up @@ -204,6 +212,7 @@ export class DB3Client {
async getDocument(id: string) {
const token = await this.keepSessionAlive()
const response = await this.provider.getDocument(token, id)
this.incrQueryCount()
return {
id: toB64(response.document.id),
doc: BSON.deserialize(response.document.doc),
Expand All @@ -215,6 +224,7 @@ export class DB3Client {
async runQuery<T>(dbAddress: string, query: StructuredQuery) {
const token = await this.keepSessionAlive()
const response = await this.provider.runQuery(token, dbAddress, query)
this.incrQueryCount()
return response.documents.map(
(item) =>
({
Expand All @@ -227,9 +237,16 @@ export class DB3Client {
}

async subscribe(messageHandle: (e: EventMessage) => void) {
const token = await this.keepSessionAlive()
const ctrl = this.provider.subscribe(token, messageHandle)
return ctrl
if (!this.querySessionEnabled) {
const response = await this.provider.openSession()
const token = response.sessionToken
const ctrl = this.provider.subscribe(token, messageHandle)
return ctrl
} else {
const token = await this.keepSessionAlive()
const ctrl = this.provider.subscribe(token, messageHandle)
return ctrl
}
}

async deleteDocument(
Expand All @@ -242,7 +259,6 @@ export class DB3Client {
chainId: ChainId.MainNet,
chainRole: ChainRole.StorageShardChain,
}

const documentMutation: DocumentMutation = {
collectionName,
documents: [],
Expand Down Expand Up @@ -301,6 +317,16 @@ export class DB3Client {
}

async keepSessionAlive() {
if (!this.hasCheckedQuerySession) {
const state = await this.getState()
this.querySessionEnabled = state.querySessionEnabled
this.hasCheckedQuerySession = true
}

if (!this.querySessionEnabled) {
return ''
}

if (!this.querySessionInfo || !this.sessionToken) {
const response = await this.provider.openSession()
this.sessionToken = response.sessionToken
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export { EventMessage, EventType } from './proto/db3_event'
export { DB3BrowserWallet } from './wallet/db3_browser_wallet'
export { MetamaskWallet } from './wallet/metamask'
export { DB3Client } from './client/client'
export { initializeDB3, listMyDatabases } from './store/app'
export { initializeDB3, listMyDatabases, listDatabases } from './store/app'
export { DB3Store } from './store/database'
export { collection } from './store/collection'
export {
Expand Down
3 changes: 1 addition & 2 deletions src/provider/storage_provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -265,8 +265,7 @@ export class StorageProvider {
return sessionRequest
}

async getMyDatabases(token: string) {
const sender = this.wallet.getAddress()
async listDatabases(token: string, sender: string) {
const request: ShowDatabaseRequest = {
sessionToken: token,
address: '',
Expand Down
12 changes: 10 additions & 2 deletions src/store/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,22 @@ export function initializeDB3(
return runtime
}

export function listMyDatabases(
export function listDatabases(
node: string,
sender: string,
wallet: Wallet
): Promise<Database[]> {
const client = new DB3Client(node, wallet)
return new Promise((resolve, reject) => {
client.getMyDatabases().then((dbs) => {
client.listDatabases(sender).then((dbs) => {
resolve(dbs)
})
})
}

export function listMyDatabases(
node: string,
wallet: Wallet
): Promise<Database[]> {
return listDatabases(node, wallet.getAddress(), wallet)
}
76 changes: 40 additions & 36 deletions tests/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ describe('test db3.js client module', () => {
await new Promise((r) => setTimeout(r, 2000))
const db = await client.getDatabase(dbId)
expect(dbId).toEqual(`0x${toHEX(db!.address)}`)
const dbs = await client.getMyDatabases()
const dbs = await client.listDatabases(wallet.getAddress())
expect(dbs.length == 1).toEqual(true)
})

Expand All @@ -46,42 +46,46 @@ describe('test db3.js client module', () => {
const client = new DB3Client('http://127.0.0.1:26659', wallet)
const [dbId, txId] = await client.createDatabase()
await new Promise((r) => setTimeout(r, 2000))
const db = await client.getDatabase(dbId)
expect(dbId).toEqual(`0x${toHEX(db!.address)}`)
const dbs = await client.getMyDatabases()
expect(dbs.length > 0).toEqual(true)
const indexList: Index[] = [
{
name: 'idx1',
id: 1,
fields: [
{
fieldPath: 'name',
valueMode: {
oneofKind: 'order',
order: Index_IndexField_Order.ASCENDING,
try {
const db = await client.getDatabase(dbId)
expect(dbId).toEqual(`0x${toHEX(db!.address)}`)
const dbs = await client.listDatabases(wallet.getAddress())
expect(dbs.length > 0).toEqual(true)
const indexList: Index[] = [
{
name: 'idx1',
id: 1,
fields: [
{
fieldPath: 'name',
valueMode: {
oneofKind: 'order',
order: Index_IndexField_Order.ASCENDING,
},
},
},
],
},
]
await client.createCollection(dbId, 'books', indexList)
await new Promise((r) => setTimeout(r, 2000))
const collections = await client.listCollection(dbId)
expect(collections.length).toEqual(1)
await client.createDocument(dbId, 'books', {
name: 'book1',
author: 'db3 developers',
})
await new Promise((r) => setTimeout(r, 2000))
const query: StructuredQuery = {
collectionName: 'books',
],
},
]
await client.createCollection(dbId, 'books', indexList)
await new Promise((r) => setTimeout(r, 2000))
const collections = await client.listCollection(dbId)
expect(collections.length).toEqual(1)
await client.createDocument(dbId, 'books', {
name: 'book1',
author: 'db3 developers',
})
await new Promise((r) => setTimeout(r, 2000))
const query: StructuredQuery = {
collectionName: 'books',
}
const books = await client.runQuery(dbId, query)
expect(books.length).toBe(1)
expect(books[0].doc['name']).toBe('book1')
const bookId = books[0].id
const result = await client.deleteDocument(dbId, 'books', [bookId])
expect(result).toBeDefined()
} catch (e) {
console.log(e)
}
const books = await client.runQuery(dbId, query)
expect(books.length).toBe(1)
expect(books[0].doc['name']).toBe('book1')
const bookId = books[0].id
const result = await client.deleteDocument(dbId, 'books', [bookId])
expect(result).toBeDefined()
})
})
10 changes: 9 additions & 1 deletion tests/store.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import {
query,
limit,
listMyDatabases,
listDatabases,
} from '../src/index'
import { Index, Index_IndexField_Order } from '../src/proto/db3_database'
import { toHEX } from '../src/crypto/crypto_utils'
Expand All @@ -51,6 +52,13 @@ describe('test db3.js store module', () => {
const dbs = await listMyDatabases('http://127.0.0.1:26659', wallet)
expect(dbs.length).toEqual(1)
expect(dbs[0].desc).toEqual('test')
const dbs2 = await listDatabases(
'http://127.0.0.1:26659',
wallet.getAddress(),
wallet
)
expect(dbs2.length).toEqual(1)
expect(dbs2[0].desc).toEqual('test')
})
test('test document curd', async () => {
const client = new DB3Client('http://127.0.0.1:26659', wallet)
Expand Down Expand Up @@ -82,7 +90,7 @@ describe('test db3.js store module', () => {
owner: wallet.getAddress(),
} as Todo)

await new Promise((r) => setTimeout(r, 1000))
await new Promise((r) => setTimeout(r, 1550))
const docs = await getDocs<Todo>(collectionRef)
expect(docs.size).toBe(1)
expect(docs.docs[0].entry.doc['text']).toBe('beijing')
Expand Down

0 comments on commit 114d8c0

Please sign in to comment.