Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

4.1 KB
Raw Blame
import type { Printable } from '@/sys/io/view'
import { join } from 'node:path'
import { z } from 'zod'
import { BaseError } from '@/errors/base'
import { ErrorCode } from '@/errors/codes'
import { definePlugin } from '@/kernel/plugin'
import { env } from '@/plugins/env'
import { io } from '@/plugins/io'
import { localFile } from '@/store/local-file'
import { isRecord } from '@/util/is-record'

export const CONFIG_FILE_NAME = 'config.yml'

const CONFIG_SCHEMA = z.object({
  http: z.object({ timeout: z.number().int().positive().default(30_000) }).prefault({}),
})

export type ConfigDoc = z.infer<typeof CONFIG_SCHEMA>

export const CONFIG_KEYS = ['http.timeout'] as const
export type ConfigKey = (typeof CONFIG_KEYS)[number]

export type ConfigService = {
  readonly path: string
  readonly doc: () => Promise<ConfigDoc>
  readonly get: (key?: string) => Promise<Printable | undefined>
  readonly set: (key: string, raw: string) => Promise<void>
  readonly unset: (key: string) => Promise<void>
}

function isConfigKey(key: string): key is ConfigKey {
  return (CONFIG_KEYS as readonly string[]).includes(key)
}

function requireConfigKey(key: string): ConfigKey {
  if (!isConfigKey(key)) {
    throw new BaseError({
      code: ErrorCode.ConfigInvalidKey,
      message: `unknown config key "${key}"`,
      hint: `known keys: ${CONFIG_KEYS.join(', ')}`,
    })
  }
  return key
}

function readPath(doc: ConfigDoc, dotted: string): Printable | undefined {
  return dotted.split('.').reduce<unknown>((acc, part) => {
    return isRecord(acc) ? acc[part] : undefined
  }, doc) as Printable | undefined
}

function writePath(target: Record<string, unknown>, dotted: string, value: unknown): void {
  const parts = dotted.split('.')
  const lastKey = parts.pop() as string
  let current = target
  for (const part of parts) {
    const next = current[part]
    if (next === null || typeof next !== 'object') current[part] = {}
    current = current[part] as Record<string, unknown>
  }
  current[lastKey] = value
}

function deletePath(target: Record<string, unknown>, dotted: string): void {
  const parts = dotted.split('.')
  const lastKey = parts.pop() as string
  let current: Record<string, unknown> = target
  for (const part of parts) {
    const next = current[part]
    if (next === null || typeof next !== 'object') return
    current = next as Record<string, unknown>
  }
  delete current[lastKey]
}

function parseRawValue(raw: string): unknown {
  try {
    return JSON.parse(raw)
  } catch {
    return raw
  }
}

function validateDoc(raw: unknown, path: string): ConfigDoc {
  const result = CONFIG_SCHEMA.safeParse(raw)
  if (!result.success) {
    throw new BaseError({
      code: ErrorCode.ConfigInvalidValue,
      message: result.error.issues.map((issue) => issue.message).join('; '),
      hint: `the value was not saved to ${path}`,
    })
  }
  return result.data
}

export const config = definePlugin({
  name: 'config',
  needs: [env, io],
  build: async (ctx): Promise<ConfigService> => {
    const path = join((await ctx.get(env)).configDir, CONFIG_FILE_NAME)
    const file = localFile(path, CONFIG_SCHEMA, (await ctx.get(io)).notice)

    async function doc(): Promise<ConfigDoc> {
      return (await file.read()) ?? CONFIG_SCHEMA.parse({})
    }

    async function persist(mutate: (target: Record<string, unknown>) => void): Promise<void> {
      await file.update((current) => {
        const target: Record<string, unknown> = current ?? CONFIG_SCHEMA.parse({})
        mutate(target)
        return validateDoc(target, path)
      })
    }

    return {
      path,
      doc,
      get: async (key?: string) => {
        const current = await doc()
        if (key === undefined) return { ...current, path }
        return readPath(current, requireConfigKey(key))
      },
      set: async (key: string, raw: string) => {
        const configKey = requireConfigKey(key)
        const value = parseRawValue(raw)
        await persist((target) => writePath(target, configKey, value))
      },
      unset: async (key: string) => {
        const configKey = requireConfigKey(key)
        await persist((target) => deletePath(target, configKey))
      },
    }
  },
})