跳至正文

存储插件 ​

存储插件负责图片的实际持久化:写入、读取、删除,以及可选的扫描导入。公开链接、副本调度和后台重试都由 Picloom 核心托管。

完整示例 ​

下面的本地目录存储插件完整实现了安全写入(临时文件 + 硬链接防覆盖)、流式读取、凭定位删除以及本地目录声明,可直接复制到 src/index.ts 使用:

ts
import { mkdir, link } from "node:fs/promises";
import { resolve } from "node:path";
import { definePlugin, PluginError } from "@picloom/plugin-sdk";
import { remove, safePath, writeStream } from "@picloom/plugin-sdk/fs";

export default definePlugin({
  id: "example.local-storage",
  version: "1.0.0",
  kind: "storage",
  defaultLocale: "en-US",
  messages: {
    "en-US": {
      "package.name": "Example local storage",
      "settings.root.label": "Root directory",
    },
    "zh-CN": { "package.name": "本地存储示例", "settings.root.label": "根目录" },
  },
  localDirectory: { configPath: "/root" },
  configSchemaVersion: 1,
  configSchema: {
    type: "object",
    properties: {
      root: {
        "x-ui": { labelKey: "settings.root.label" },
        type: "string",
        minLength: 1,
        "x-immutable": true,
      },
    },
    required: ["root"],
    additionalProperties: false,
  },
  async createInstance({ config }) {
    const root = resolve(config.root);
    await mkdir(root, { recursive: true });
    return {
      async write({ storageKey, file }, { signal }) {
        const destination = await safePath(root, storageKey, true);
        const temporary = `${destination}.${crypto.randomUUID()}.part`;
        try {
          await writeStream(
            temporary,
            await file.openRead(),
            file.metadata.byteSize ?? Number.MAX_SAFE_INTEGER,
            signal,
          );
          signal.throwIfAborted();
          // A hard link publishes the complete file atomically without overwriting.
          await link(temporary, destination);
          return { locator: { key: storageKey } };
        } finally {
          await remove(temporary);
        }
      },
      async read({ storageKey }, { signal }) {
        signal.throwIfAborted();
        const file = Bun.file(await safePath(root, storageKey));
        if (!(await file.exists()))
          throw new PluginError("NOT_FOUND", "File not found");
        return { type: "stream", stream: file.stream() };
      },
      async delete({ locator }, { signal }) {
        signal.throwIfAborted();
        if (
          !locator ||
          typeof locator !== "object" ||
          typeof locator.key !== "string"
        )
          throw new PluginError("INVALID_INPUT", "Missing confirmed local locator");
        await remove(await safePath(root, locator.key));
      },
    };
  },
});

安装后,在后台创建存储源(根目录填 ./example-images,相对路径以应用数据目录为基准),加入存储组并绑定上传配置,即可完成上传、访问和删除验证。

核心概念:locator ​

locator 是存储插件自定义的一份 JSON 定位数据(字符串、对象或 null)。write 返回它之后,宿主会持久化保存,并在后续 read 和 delete 时原样传回。

  • 远端对象存储 / 图床:可以存远端 ID 或实际对象键,例如 { objectId: "12345" }。
  • 本地存储:像上面示例一样存 { key: storageKey },删除时只认已确认的 locator.key,避免写入失败后的清理误删目录里原本就存在的同名文件。
  • 扫描去重一致性:若实现了 listFiles,宿主在同一存储源内会对非空 locator 按完整 JSON 值查重(locator 为 null 时按 storageKey 查重)。请让 write 与 listFiles 返回结构稳定的同一份定位,不要混入时间戳或临时签名 URL;另外在 write 省略 locator 或写入失败后的兜底清理中,delete 可能收到 locator: null。
  • 不要在 locator 里塞密钥或带 Token 的 URL,凭据统一走 x-sensitive + services.readSecrets()。

接口说明 ​

write:写入文件 ​

ts
write(
  input: {
    operationId: string;
    fileId: string;
    storageKey: string;
    file: FileInput;
  },
  context: Context,
): Promise<{ locator?: Locator }>;
  • fileId 为当前文件记录 ID(同 record.id),storageKey 为路径插件生成的相对存储键。
  • 通过 input.file.openRead() 流式读取图片,或用 input.file.readBytes() 一次性读入内存。
  • operationId 在同一次写入重试时保持不变,可用于远端去重。
  • 确认内容已经完整落盘或上传成功后再返回 { locator };省略 locator 时按 null 保存。

read:读取文件 ​

ts
read(
  input: {
    storageKey: string;
    locator: Locator;
    mode: "auto" | "stream";
  },
  context: Context,
): Promise<ReadResult>;

返回值二选一:

模式返回结构说明
返回内容流{ type: "stream", stream }stream 为 Web ReadableStream<Uint8Array>;mode === "stream" 时必须返回流,响应头由宿主根据文件记录元数据生成
返回重定向{ type: "redirect", url, expiresAt? }仅 mode === "auto" 时允许;需为合法未过期的无凭据 http(s) URL,expiresAt 为 Unix 毫秒时间戳(省略时按站点 imageCacheMaxAge 缓存,无效或已过期时宿主会自动回退其他就绪副本)

返回的流会在函数返回后继续被宿主消费,请在流结束、出错或取消时释放底层连接。

delete:删除对象 ​

ts
delete(
  input: {
    operationId: string;
    storageKey: string;
    locator: Locator;
  },
  context: Context,
): Promise<void>;
  • 对象删除成功、或已确认不存在时正常返回即可。
  • 若依赖 locator 识别对象且 locator 缺失,应抛出 PluginError("INVALID_INPUT", ...),不要回退猜测路径。
  • 如果底层服务不支持远端删除,在 delete 中直接抛出 PluginError("UNSUPPORTED", ...) 即可。

listFiles:扫描导入(可选) ​

运行实例提供了 listFiles 方法时,管理员即可在后台扫描该存储源中的存量图片并批量导入(若需按实例配置关闭导入,在 createInstance 返回对象时省略 listFiles 即可):

ts
listFiles(
  input: { scope?: string; cursor?: string; limit: number },
  context: Context,
): Promise<{
  items: Array<{
    storageKey: string;
    locator?: Locator;
    byteSize?: number;
    mimeType?: string;
  }>;
  nextCursor: string | null;
}>;
  • scope 只缩小扫描前缀(可用 @picloom/plugin-sdk/scan 的 scanScope(scope) 规范化并去掉首尾 /),返回的 storageKey 仍应相对整个存储源根目录,不要自行裁掉 scope。
  • 宿主每次传入 limit = 200(单页返回最多允许 1000 条);扫描未结束时允许本页 items 少于 limit(甚至为空数组),只要 nextCursor 与传入的 cursor 不同即可继续翻页;扫描结束时 nextCursor 必须返回 null。
  • cursor 格式由插件自定义,可使用 @picloom/plugin-sdk/scan 的 encodeCursor / decodeCursor(签名见SDK 辅助函数)。
  • 每条记录建议显式带上 locator,供后续安全删除。

可选顶层声明:maxFileBytes 与 localDirectory ​

在 definePlugin({...}) 顶层可按需声明两项存储属性:

单文件大小上限 maxFileBytes ​

ts
maxFileBytes: 20_000_000, // 可选安全正整数(字节)

当底层服务对单文件大小有硬限制(如 Telegram Bot API 的 20 MB 下载上限)时声明。宿主会在存储组选源、分片上传建会话、保存后替换及手动重试前按最终文件大小自动跳过超限存储源,或直接拦截返回 413 TOO_LARGE。

本地目录声明 localDirectory ​

如果你的插件把图片存在本地磁盘目录,声明指向该配置字段的 JSON Pointer:

ts
localDirectory: { configPath: "/root" },

指向的字段在 configSchema 中必须是非敏感、不可变("x-immutable": true)的字符串。声明后:

  1. 管理员填写相对路径(如 ./example-images)时,宿主会先以应用数据目录为基准规范化为绝对路径,再执行 Schema 与 validateConfig 校验并持久化,插件拿到的是已解析好的绝对路径;
  2. 宿主会自动把它纳入容量统计与应用内备份范围。