跳至正文

访问处理 ​

访问处理在访问公开图片且未命中派生缓存时按需执行(无查询参数的访问也会执行,可用于固定水印等场景;带查询参数如 ?width=320 时可用于按需缩略图)。它只改变本次返回的图片,不覆盖原图,结果默认会被宿主缓存。

完整示例 ​

下面的示例实现了按 ?width=320 动态生成缩略图;没有传 width 时直接 pass,甚至不会去存储读取原图字节:

ts
import { Readable } from "node:stream";
import {
  definePlugin,
  PluginError,
  withAbortSignal,
} from "@picloom/plugin-sdk";

export default definePlugin({
  id: "example.thumbnail",
  version: "1.0.0",
  kind: "processor",
  defaultLocale: "en-US",
  messages: {
    "en-US": {
      "package.name": "Example thumbnail",
      "settings.width.label": "Maximum width",
    },
    "zh-CN": {
      "package.name": "缩略图示例",
      "settings.width.label": "最大宽度",
    },
  },
  stages: {
    access: {
      configSchemaVersion: 1,
      paramsSchema: {
        type: "object",
        properties: {
          width: {
            "x-ui": { labelKey: "settings.width.label" },
            type: "integer",
            minimum: 1,
            maximum: 8192,
          },
        },
        additionalProperties: false,
      },
      async createInstance({ services }) {
        return {
          async process(
            { metadata, getFile, params, limits, writeOutput },
            { signal },
          ) {
            if (params.width === undefined) return { status: "pass" };
            if (
              metadata.animated ||
              !["image/jpeg", "image/png", "image/webp"].includes(
                metadata.mimeType ?? "",
              )
            )
              return {
                status: "unsupported",
                reason: "Only static JPEG, PNG and WebP images are supported",
              };
            const width = params.width;
            if (width > limits.maxDimension)
              throw new PluginError(
                "RESOURCE_LIMIT",
                "Width exceeds processing limit",
              );
            signal.throwIfAborted();
            const file = await getFile();
            const bytes = await file.readBytes();
            // Sharp is supplied by the host; the package does not bundle its own copy.
            const image = services.images
              .sharp(bytes, { limitInputPixels: limits.maxPixels })
              .rotate()
              .resize({ width, withoutEnlargement: true })
              .toFormat(
                file.metadata.mimeType === "image/jpeg"
                  ? "jpeg"
                  : file.metadata.mimeType === "image/webp"
                    ? "webp"
                    : "png",
              );
            const output = await withAbortSignal(image, signal, () =>
              writeOutput(
                Readable.toWeb(image) as unknown as ReadableStream<Uint8Array>,
              ),
            );
            signal.throwIfAborted();
            return { status: "replace", output };
          },
        };
      },
    },
  },
});

安装后,在后台全局访问处理链中添加 缩略图示例 并启用 width 参数,打开带 ?width=320 的图片链接即可看到缩放效果。

接口说明 ​

ts
process(
  input: AccessProcessorInput,
  context: PipelineContext,
): Promise<ImageProcessResult>;

输入 ​

字段说明
paramsURL 查询字符串解析并校验后的请求参数
metadata当前图片的元数据,先用它判断是否需要处理
getFile()() => Promise<FileInput>,按需异步获取当前图片对象;如果不需要改图,直接返回 pass 即可避免无谓的存储读取
limits{ maxDimension: number; maxPixels: number },单边像素与总像素上限
writeOutput(source)(source: ReadableStream<Uint8Array> | Uint8Array) => Promise<OutputToken>,写入派生图片并异步返回 OutputToken

context 包含取消信号 signal、requestId、结构化日志 log,以及同一次访问处理链步骤间共享的 data(访问阶段无 record 和 organization)。

返回值 ​

ts
type ImageProcessResult =
  | { status: "pass" }
  | { status: "replace"; output: OutputToken }
  | { status: "reject"; reason: string }
  | { status: "unsupported"; reason?: string };

各状态含义与上传处理一致。

缓存控制 ​

访问处理默认允许宿主共享派生缓存(命中缓存会直接跳过处理)。如果你的插件结果依赖时间、随机性或其他不可缓存条件,在 stages.access 声明中静态关闭缓存:

ts
stages: {
  access: {
    configSchemaVersion: 1,
    cacheable: false,
    // ...
  },
},

不要用访问处理插件做“每次访问必触发的统计或通知”——除了宿主缓存,浏览器和 CDN 缓存也会让请求不抵达 Picloom。