UNPKG

nsolid-manager

Version:

A manager that sets up and runs N|Solid for you

145 lines (120 loc) 3.34 kB
/** * Process structure extraction & definition. */ import fs from 'fs' import path from 'path' import computeAppId from '../compute-app-id' import createArrayStore from './array-store' import getConfig from './config' const utf8enc = { encoding: 'utf8' } export default class Cache { constructor (storagePath) { this.getApp = createArrayStore({ hosts: [], processes: [] }) this.processToHub = {} this.hosts = {} this.fileResources = {} this.storagePath = storagePath || getConfig.getDefaults().storage this.appFile = path.join(this.storagePath, 'applications.json') } /** * Serialize and store cache contents on disk */ save (done) { fs.writeFile(this.appFile, JSON.stringify(this.toJSON(true)), utf8enc, done) } /** * Restore the cache contents from disk */ restore (done) { fs.readFile(this.appFile, utf8enc, (e, json) => { if (e) return done(e) try { this.fromJSON(JSON.parse(json)) return done() } catch (e) { return done(e) } }) } /** * Each polling cycle gets its own cache so we can perform diffing and similar */ collectPollingResult (fn) { const cache = new Cache() // each polling cycle fn(cache) // merge the polling cache this.processToHub = cache.processToHub this.getApp = cache.getApp this.hosts = cache.hosts // ensure app order is always the same this.getApp.array.sort(function (a, b) { return a.name.localeCompare(b.name) }) // TODO: compute and return diff } /** * Extract process structure from process & host. * Mutates Application instance gathered from getApp. * * @param {Process} proc * @param {Host} host * @param {Function} getApp pass app name to retrieve Application instance * @return {Application} */ addProcess (proc, time) { const application = this.getApp(proc.app, { id: computeAppId(proc.app), name: proc.app, time: time || Date.now() }) // cache what proxy the process was collected on this.processToHub[proc.id] = proc.hub application.processes.push(proc) // only insert one instance of the host object per application. if (application.hosts.indexOf(proc.host) === -1) { application.hosts.push(proc.host) } return application } addFileResource (type, meta) { if (!this.fileResources[type]) { this.fileResources[type] = {} } const resource = this.fileResources[type] const app = computeAppId(meta.app) if (!resource[app]) { resource[app] = [] } // TODO: track this as an addition resource[app].unshift(meta) } getHubByProcessId (processId) { return this.processToHub[processId] || null } fromJSON (obj) { this.hosts = obj.hosts || {} this.fileResources = { snapshots: obj.snapshots || {}, profiles: obj.profiles || {} } if (obj.applications && obj.applications.length) { obj.applications.forEach((app) => { app.processes.forEach((proc) => { this.addProcess(proc, app.time) }) }) } } toJSON () { return Object.assign({ hosts: this.hosts, applications: this.getApp.array, snapshots: {}, profiles: {} }, this.fileResources) } }