UNPKG

@ceramicnetwork/core

Version:

Typescript implementation of the Ceramic protocol

84 lines 3.61 kB
import { StreamUtils } from '@ceramicnetwork/common'; import { Model } from '@ceramicnetwork/stream-model'; import { Semaphore } from 'await-semaphore'; const DEFAULT_CONCURRENT_PIN_LIMIT = 50; export class PinStore { constructor(stateStore, pinning, retrieve, resolve, loadStream, concurrentPinsLimit = DEFAULT_CONCURRENT_PIN_LIMIT) { this.stateStore = stateStore; this.pinning = pinning; this.retrieve = retrieve; this.resolve = resolve; this.loadStream = loadStream; this.concurrentPinsLimit = concurrentPinsLimit; const concurrencyLimit = process.env.CERAMIC_CONCURRENT_PINS_LIMIT ? parseInt(process.env.CERAMIC_CONCURRENT_PINS_LIMIT) : concurrentPinsLimit; this.semaphore = new Semaphore(concurrencyLimit); } async open(factory) { await this.stateStore.open(factory); this.pinning.open(); } async close() { await this.stateStore.close(); await this.pinning.close(); } 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.semaphore.use(() => this.pinning.pin(point)))); await this.stateStore.saveFromStreamStateHolder(runningState); runningState.markAsPinned(); const model = runningState.state.metadata.model; if (model && !model.equals(Model.MODEL)) { const modelStream = await this.loadStream(model); await this.add(modelStream); } } async rm(runningState) { const commitLog = runningState.state.log.map((logEntry) => logEntry.cid); const points = await this.getComponentCIDsOfCommits(commitLog, false); Promise.all(points.map((point) => this.pinning.unpin(point))).catch(() => { }); await this.stateStore.remove(runningState.id); runningState.markAsUnpinned(); } async ls(streamId) { return this.stateStore.listStoredStreamIDs(streamId); } async getComponentCIDsOfCommits(commits, includeAnchorAndCACAO = true) { const points = []; for (const cid of commits) { points.push(cid); const commit = await this.retrieve(cid); if (StreamUtils.isAnchorCommit(commit) && includeAnchorAndCACAO) { 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)) { if (includeAnchorAndCACAO) { const capCID = StreamUtils.getCacaoCidFromCommit(commit); if (capCID) { points.push(capCID); } } points.push(commit.link); } } return points; } } //# sourceMappingURL=pin-store.js.map