Add trylock for push and fix seqID generation bugs

This commit is contained in:
Garrett Mills 2021-04-10 15:11:21 -05:00
parent 092f3d49f1
commit 70aa8c6a5e
Signed by: garrettmills
GPG Key ID: D2BF5FBA8298F246
2 changed files with 13 additions and 3 deletions

View File

@ -71,7 +71,16 @@ export class FirebaseResource<T extends FirebaseResourceItem> extends Iterable<T
findNextId(collection: FirebaseResourceItem[]) { findNextId(collection: FirebaseResourceItem[]) {
if ( !collection.length ) return 0 if ( !collection.length ) return 0
return collect<FirebaseResourceItem>(collection).max<number>('seqID') + 1
let maxSeq = -1
for ( const item of collection ) {
if ( !item ) continue
if ( !isNaN(item.seqID) && item.seqID > maxSeq ) {
maxSeq = item.seqID
}
}
return maxSeq + 1
} }
/** /**
@ -81,6 +90,7 @@ export class FirebaseResource<T extends FirebaseResourceItem> extends Iterable<T
async push(item: T): Promise<T> { async push(item: T): Promise<T> {
await this.ref().transaction((collection) => { await this.ref().transaction((collection) => {
if ( !collection ) collection = [] if ( !collection ) collection = []
if ( typeof collection === 'object' ) collection = Object.values(collection)
item.seqID = this.findNextId(collection) item.seqID = this.findNextId(collection)
// @ts-ignore // @ts-ignore
@ -96,7 +106,6 @@ export class FirebaseResource<T extends FirebaseResourceItem> extends Iterable<T
.startAt(item.seqID) .startAt(item.seqID)
.limitToFirst(1) .limitToFirst(1)
.on('value', snapshot => { .on('value', snapshot => {
console.log('got push ID back', snapshot.val(), snapshot.key)
res() res()
}) })
}) })

View File

@ -179,7 +179,6 @@ export class Blockchain extends Unit {
const blocks: unknown = result.data?.data?.records const blocks: unknown = result.data?.data?.records
if ( Array.isArray(blocks) && blocks.every(block => { if ( Array.isArray(blocks) && blocks.every(block => {
const match = isBlockResourceItem(block) const match = isBlockResourceItem(block)
console.log(match, block)
return match return match
}) ) { }) ) {
return blocks.map(x => new Block(x)) return blocks.map(x => new Block(x))
@ -353,6 +352,7 @@ export class Blockchain extends Unit {
} }
public async getSubmitChain(): Promise<BlockResourceItem[]> { public async getSubmitChain(): Promise<BlockResourceItem[]> {
await this.firebase.trylock('block', 'Blockchain_getSubmitChain')
const blocks = await this.read() const blocks = await this.read()
const submit = await this.attemptSubmit() const submit = await this.attemptSubmit()
if ( submit ) { if ( submit ) {
@ -360,6 +360,7 @@ export class Blockchain extends Unit {
blocks.push(submit.toItem()) blocks.push(submit.toItem())
} }
await this.firebase.unlock('block')
this.refresh() this.refresh()
return blocks return blocks
} }