# 注解与 ZIP

> 为对象附加注解，在上传时解压 ZIP 归档。

---

LLMS 索引： [llms.txt](/zh/llms.txt)

---

> [!NOTE]
> 对象注解（`?annotation`）与 ZIP 成员提取（`x-minio-extract`）在 MVP 范围内属于**预览**功能。此外，注解依赖的四个 `silo-pkg` 策略动作（`s3:*ObjectAnnotation*`）尚未发布到公开 `silo-pkg` 仓库，通用 Silo 控制台（2.6.0）也不包含注解界面。

本教程使用经过 SigV4 签名的 Python 请求写入、读取、列举和删除对象注解，并在不将 ZIP 拆分为独立 S3 对象的情况下直接列举和读取已上传 ZIP 归档内的成员。开始前请先完成[使用 S3 SDK](/zh/docs/s3/tutorial/sdk/)。

## 接口与权限 {#interfaces-and-permissions}

注解从属于特定的父对象版本。每份注解正文必须是 1 字节至 1 MiB 之间的合法 UTF-8 文本，每个父版本最多支持 1,000 个注解名称。更新或删除注解不会改变父对象的正文、`ETag` 或最后修改时间。

| 操作 | 经过 SigV4 签名的 HTTP 请求 | 所需 IAM 动作 |
| --- | --- | --- |
| 创建或替换 | `PUT /attachments/<key>?annotation=&annotationName=labels.json` | `s3:PutObjectAnnotation` |
| 读取正文 | `GET /attachments/<key>?annotation=&annotationName=labels.json` | `s3:GetObjectAnnotation` |
| 列举名称 | `GET /attachments/<key>?annotation=` | `s3:ListObjectAnnotations` |
| 删除 | `DELETE /attachments/<key>?annotation=&annotationName=labels.json` | `s3:DeleteObjectAnnotation` |
{.wide}

普通对象权限（`s3:GetObject`、`s3:PutObject`）不包含上述四个注解动作。如需操作特定历史版本的注解，可在查询字符串中附加 `versionId`；如需在 `PUT` 或 `DELETE` 时校验父对象的 `ETag`，可传入请求头 `x-amz-object-if-match`。注解正文会自动继承父对象的服务端加密方式。

读取或列举保存在 S3 对象中的 ZIP 归档成员时，在请求中附加请求头 `x-minio-extract: true`：

- **读取或查询单个成员**：对 `/attachments/demo.zip/readme.txt` 发送带 `x-minio-extract: true` 的 `GET` 或 `HEAD`。
- **列举归档内成员**：对 `/attachments?list-type=2&prefix=demo.zip/` 发送带 `x-minio-extract: true` 的 `GET`。

ZIP 提取直接在父对象的一致性快照上解析并解压成员，不会在数据库里生成额外的成员对象或持久化索引。支持 `Store` 与 `Deflate` 压缩（含受限 ZIP64），中央目录最多 10,000 项，单个成员解压后最大 256 MiB。不支持对 ZIP 成员发起 `Range` 或 `partNumber` 请求。

## 完整 Python 示例 {#python-example}

由于标准 S3 SDK 没有内置 `?annotation` 与 `x-minio-extract` 的专用方法，可以使用 `botocore.auth.SigV4Auth` 对请求签名。将以下脚本保存为 `~/.local/share/silo-tutorial/extensions.py`：

```python
import hashlib
import io
import json
import os
import ssl
import urllib.request
import zipfile
from urllib.parse import quote, urlencode

import boto3
from botocore.auth import SigV4Auth
from botocore.awsrequest import AWSRequest
from botocore.config import Config

endpoint = os.environ["SILO_ENDPOINT"].rstrip("/")
ca = os.environ["AWS_CA_BUNDLE"]
region = "us-east-1"
session = boto3.Session(profile_name="silo-admin", region_name=region)
credentials = session.get_credentials().get_frozen_credentials()
context = ssl.create_default_context(cafile=ca)

def signed_request(method, key, query=None, body=None, headers=None):
    url = endpoint + "/attachments/" + quote(key, safe="/")
    if query is not None:
        url += "?" + urlencode(query)
    request_headers = dict(headers or {})
    request_headers["x-amz-content-sha256"] = hashlib.sha256(body or b"").hexdigest()
    signed = AWSRequest(method=method, url=url, data=body, headers=request_headers)
    SigV4Auth(credentials, "s3", region).add_auth(signed)
    prepared = signed.prepare()
    request = urllib.request.Request(
        prepared.url, data=body, headers=dict(prepared.headers), method=method
    )
    with urllib.request.urlopen(request, context=context, timeout=60) as response:
        return response.status, response.read()

s3 = session.client(
    "s3",
    endpoint_url=endpoint,
    verify=ca,
    config=Config(signature_version="s3v4", s3={"addressing_style": "path"}),
)
parent = "extensions/invoice.txt"
s3.put_object(Bucket="attachments", Key=parent, Body=b"invoice 1001\n")
query = {"annotation": "", "annotationName": "labels.json"}
body = json.dumps({"invoice_id": 1001, "status": "paid"}).encode("utf-8")
print(signed_request("PUT", parent, query, body, {"Content-Type": "application/json"})[0])
print(signed_request("GET", parent, query)[1].decode("utf-8"))
print(signed_request("GET", parent, {"annotation": ""})[1].decode("utf-8"))
print(signed_request("DELETE", parent, query)[0])

archive = io.BytesIO()
with zipfile.ZipFile(archive, "w", compression=zipfile.ZIP_DEFLATED) as output:
    output.writestr("readme.txt", "hello from ZIP\n")
s3.put_object(Bucket="attachments", Key="demo.zip", Body=archive.getvalue())
print(signed_request("GET", "demo.zip/readme.txt", headers={"x-minio-extract": "true"})[1].decode("utf-8"))
print(signed_request("HEAD", "demo.zip/readme.txt", headers={"x-minio-extract": "true"})[0])
print(signed_request("GET", "", {"list-type": "2", "prefix": "demo.zip/"},
                     headers={"x-minio-extract": "true"})[1].decode("utf-8"))
```

运行脚本：

```bash
"$HOME/.local/share/silo-tutorial/venv/bin/python" "$HOME/.local/share/silo-tutorial/extensions.py"
```

脚本依次输出注解 `PUT` 状态码（`200`）、注解 JSON、注解列表 XML、`DELETE` 状态码（`204`）、从 ZIP 中提取出的 `hello from ZIP` 正文、`HEAD` 状态码（`200`）以及 `demo.zip/` 的 `ListObjectsV2` XML。完整协议规范与错误码见[注解](/zh/docs/s3/reference/annotations/)与 [ZIP 解压](/zh/docs/s3/reference/zip/)。

---

反链：

- [注解](/zh/docs/s3/reference/annotations/)
- [ZIP 解压](/zh/docs/s3/reference/zip/)
- [教程](/zh/docs/s3/tutorial/)
