import { getManager } from "typeorm" ; import { LedgerHeader } from "../model" ; import { LedgersStorage } from "../storage/ledgers" ; import { STELLAR_CORE_CURSOR_NAME } from "../util/secrets" ; export class Cursor { public static async build ( seq ? ) { let cursorValue ; if ( seq ) { cursorValue = seq === - 1 ? await LedgersStorage . minSeq ( ) : seq ; } else { const coreCursor = await Cursor . getCursorFromDatabase ( ) ; if ( coreCursor ) { cursorValue = coreCursor ; } else { cursorValue = ( await LedgersStorage . maxSeq ( ) ) + 1 ; } } await Cursor . updateCursorInDatabase ( cursorValue ) ; return new Cursor ( cursorValue ) ; } private static async getCursorFromDatabase ( ) { const rows = await getManager ( ) . query ( "SELECT lastread FROM pubsub WHERE resid = $1" , [ STELLAR_CORE_CURSOR_NAME ] ) ; return rows [ 0 ] ? rows [ 0 ] . lastread : null ; } private static async updateCursorInDatabase ( value ) { await getManager ( ) . query ( "UPDATE pubsub SET lastread = $1 WHERE resid = $2" , [ value , STELLAR_CORE_CURSOR_NAME ] ) ; } constructor ( private seq ) { } get current ( ) : number { return this . seq ; } public async nextLedger ( ) { const header = await LedgersStorage . findBySeq ( this . seq ) ; if ( header == null ) { const maxSeq = await LedgersStorage . maxSeq ( ) ; if ( this . seq < maxSeq ) { this . seq = maxSeq ; } return null ; } this . seq += 1 ; await Cursor . updateCursorInDatabase ( this . seq ) ; return header ; } }