import { StateStore } from './state-store' ; import { PinningBackend , StreamUtils } from '@ceramicnetwork/common' ; import CID from 'cids' ; import StreamID from '@ceramicnetwork/streamid' ; import { RunningState } from '../state-management/running-state' ; /**
 * Encapsulates logic for pinning streams
 */ export class PinStore { constructor ( readonly stateStore , readonly pinning , readonly retrieve , readonly resolve ) { } open ( networkName ) { this . stateStore . open ( networkName ) ; this . pinning . open ( ) ; } async close ( ) { await this . stateStore . close ( ) ; await this . pinning . close ( ) ; } param runningState param force async add ( runningState , force ? ) { const commitLog = runningState . state . log . map ( ( logEntry ) => logEntry . cid ) ; const newCommits = runningState . pinnedCommits && ! force ? commitLog . filter ( ( cid ) => ! runningState . pinnedCommits . has ( cid . toString ( ) ) ) : commitLog ; if ( newCommits . length == 0 ) { return ; } const points = await this . getComponentCIDsOfCommits ( newCommits ) ; await Promise . all ( points . map ( ( point ) => this . pinning . pin ( point ) ) ) ; await this . stateStore . save ( runningState ) ; runningState . markAsPinned ( ) ; } async rm ( runningState ) { const commitLog = runningState . state . log . map ( ( logEntry ) => logEntry . cid ) ; const points = await this . getComponentCIDsOfCommits ( commitLog ) ; Promise . all ( points . map ( ( point ) => this . pinning . unpin ( point ) ) ) . catch ( ( ) => { } ) ; await this . stateStore . remove ( runningState . id ) ; runningState . markAsUnpinned ( ) ; } async ls ( streamId ? ) { return this . stateStore . list ( streamId ) ; } param commits protected protected async getComponentCIDsOfCommits ( commits ) { const points = [ ] ; for ( const cid of commits ) { points . push ( cid ) ; const commit = await this . retrieve ( cid ) ; if ( StreamUtils . isAnchorCommit ( commit ) ) { points . push ( commit . proof ) ; const path = commit . path ? 'root/' + commit . path : 'root' ; const subPaths = path . split ( '/' ) . filter ( ( p ) => ! ! p ) ; let currentPath = '' ; for ( const subPath of subPaths ) { currentPath += '/' + subPath ; const subPathResolved = await this . resolve ( commit . proof . toString ( ) + currentPath ) ; points . push ( subPathResolved ) ; } } if ( StreamUtils . isSignedCommit ( commit ) ) { points . push ( commit . link ) ; } } return points ; } }