Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

2.9 KB
Raw Blame
import { readFile, rm } from 'node:fs/promises'
import { join } from 'path'
import { isNil } from '@activepieces/core-utils'
import { fileSystemUtils, memoryLock } from '@activepieces/server-utils'
import writeFileAtomic from 'write-file-atomic'

type CacheMap = Record<string, string>

const cachePath = (folderPath: string): string =>
    join(folderPath, 'cache.json')
export const NO_SAVE_GUARD = (_: string): boolean => false

export const cacheState = (folderPath: string) => {
    return {
        async getOrSetCache({
            cacheMiss,
            key,
            installFn,
            skipSave,
        }: CacheStateParams): Promise<CacheResult> {
            const cache = await readCacheFromFile(folderPath)
            const value = cache[key] as string | null
            if (!isNil(value) && !cacheMiss(value)) {
                return {
                    cacheHit: true,
                    state: value,
                }
            }
            return memoryLock.runExclusive({
                key: `cache-save-${folderPath}`,
                fn: async () => {
                    const cacheFromDisk = await readCacheFromFile(folderPath)
                    const valueFromDisk = cacheFromDisk[key]
                    if (!isNil(valueFromDisk) && !cacheMiss(valueFromDisk)) {
                        return { cacheHit: true, state: valueFromDisk }
                    }
                    const value = await installFn()
                    if (skipSave(value)) {
                        return {
                            cacheHit: false,
                            state: value,
                        }
                    }
                    await cacheState(folderPath).saveCache(key, value)
                    return {
                        cacheHit: false,
                        state: value,
                    }
                },
            })
        },
        clear: async (): Promise<void> => {
            await rm(cachePath(folderPath), { force: true })
        },
        saveCache: async (key: string, value: string): Promise<CacheMap> => {
            await fileSystemUtils.threadSafeMkdir(folderPath)
            const cacheFilePath = cachePath(folderPath)
            const freshCache = await readCacheFromFile(folderPath)
            freshCache[key] = value
            await writeFileAtomic(cacheFilePath, JSON.stringify(freshCache), 'utf8')
            return freshCache
        },
    }
}

async function readCacheFromFile(folderPath: string): Promise<CacheMap> {
    const filePath = cachePath(folderPath)
    const fileExists = await fileSystemUtils.fileExists(filePath)
    if (!fileExists) {
        return {}
    }
    const fileContent = await readFile(filePath, 'utf8')
    return JSON.parse(fileContent)
}

type CacheResult = {
    cacheHit: boolean
    state: string | null
}

type CacheStateParams = {
    key: string
    cacheMiss: (value: string) => boolean
    installFn: () => Promise<string>
    skipSave: (value: string) => boolean
}