diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..269ee13 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +__pycache__/ +*.py[cod] +mica.sqlite3* diff --git a/README.md b/README.md new file mode 100644 index 0000000..f3b04e6 --- /dev/null +++ b/README.md @@ -0,0 +1,62 @@ +# MICA + +**Modular Infrastructure for Content Applications**(面向内容应用的模块化基础设施)是一个 Python 内容后端。社区站可以用它发布短帖,新闻站可以用它发布文章。前端通过同一套 HTTP 接口提交内容和读取已发布内容,自行决定如何展示。 + +名字里的 **Modular** 指核心和插件各有职责,**Infrastructure** 指多个前端可以共用这个后端,**Content Applications** 指围绕写入、发布和展示构建的应用。英文单词 *mica* 意为“云母”,读作 *MY-kuh*。代码使用小写包名 `mica`,核心契约位于 `mica.core`,内置扩展位于 `mica.extensions`。 + +## 第一版 + +核心维护内容 ID、草稿和发布状态,在 SQLite 中保存内容,并通过 HTTP 提供写入鉴权和公开查询。内容扩展声明字段规则,两种前端共用存储和发布流程。 + +| 扩展 | 写入类型 | 必填文本 | 可选文本 | +| --- | --- | --- | --- | +| 短帖 | `posts` | `body` | 无 | +| 文章 | `articles` | `title`、`body` | `summary` | + +首版适合由一个受信任的编辑服务写入。终端用户登录、作者权限、评论、关注和个性化排序留待后续版本。 + +## 在本地试用 + +需要 Python 3.9 或以上版本,仅使用标准库。在仓库根目录运行以下命令。请在同一个终端保留生成的令牌,供写入客户端使用。 + +```sh +export MICA_WRITE_TOKEN="$(python3 -c 'import secrets; print(secrets.token_urlsafe(32))')" +python3 -m mica & +``` + +开发服务器默认监听 `127.0.0.1:8000`,数据库是当前目录下的 `mica.sqlite3`。可通过 `MICA_PORT` 和 `MICA_DATABASE` 修改。部署时可用 WSGI 服务器调用 `mica.api.create_app(database, write_token)`,并在对外入口启用 HTTPS。写入令牌只应由受信任的服务端持有。 + +创建草稿,取出响应里的 ID,发布并公开读取: + +```sh +id=$(curl -fsS http://127.0.0.1:8000/content \ + -H "Authorization: Bearer $MICA_WRITE_TOKEN" -H 'Content-Type: application/json' \ + -d '{"type":"articles","fields":{"title":"社区简报","body":"本周六举行读书会。"}}' \ + | python3 -c 'import json,sys; print(json.load(sys.stdin)["id"])') +curl -fsS -X POST -H "Authorization: Bearer $MICA_WRITE_TOKEN" \ + "http://127.0.0.1:8000/content/$id/publish" +curl -fsS "http://127.0.0.1:8000/content/$id" +curl -fsS 'http://127.0.0.1:8000/content?type=articles&limit=20&offset=0' +``` + +草稿的 `published_at` 为 `null`,公开列表会跳过它,按 ID 读取返回 404。首次发布写入 UTC 时间,重复发布保留原时间。列表按发布时间倒序,相同时间按 ID 倒序。默认每页 20 条,上限 100 条。写入时需提供非空文本,未知字段会返回 400;JSON 请求体上限为 1 MiB。 + +## 加一个内容类型 + +扩展组织参考 [OpenBB Platform](https://github.com/openbq-org/OpenBB/tree/develop/openbb_platform)。MICA 启动时发现并导入 `mica/extensions/` 下名称不以下划线开头的模块。每个模块导出一个名为 `content_type` 的 `ContentType` 实例;类型重名或未提供契约时启动失败。扩展是会在服务进程中执行的受信任 Python 代码。 + +例如新建 `mica/extensions/notices.py`: + +```python +from ..core import ContentType + +content_type = ContentType("notices", required=("subject", "body")) +``` + +重启服务后即可用 `"type":"notices"` 创建公告草稿,并按同一套接口发布和查询。 + +## 检查 + +```sh +python3 -B -m unittest discover -s tests -v +``` diff --git a/mica/__init__.py b/mica/__init__.py new file mode 100644 index 0000000..6d18829 --- /dev/null +++ b/mica/__init__.py @@ -0,0 +1 @@ +"""MICA content service.""" diff --git a/mica/__main__.py b/mica/__main__.py new file mode 100644 index 0000000..de37fa0 --- /dev/null +++ b/mica/__main__.py @@ -0,0 +1,15 @@ +import os +from wsgiref.simple_server import make_server + +from .api import create_app + + +def main(): + app = create_app(os.getenv("MICA_DATABASE", "mica.sqlite3"), os.getenv("MICA_WRITE_TOKEN")) + with make_server("127.0.0.1", int(os.getenv("MICA_PORT", "8000")), app) as server: + print(f"MICA listening on http://127.0.0.1:{server.server_port}", flush=True) + server.serve_forever() + + +if __name__ == "__main__": + main() diff --git a/mica/api.py b/mica/api.py new file mode 100644 index 0000000..e4b2f66 --- /dev/null +++ b/mica/api.py @@ -0,0 +1,89 @@ +"""JSON HTTP API, exposed as a WSGI application.""" + +from contextlib import closing +import hmac +from http import HTTPStatus +import json +import re +from urllib.parse import parse_qs + +from . import store +from .core import discover + + +class RequestError(Exception): + def __init__(self, status, message): + self.status = status + super().__init__(message) + + +def read_draft(env, types): + if env.get("CONTENT_TYPE", "").split(";")[0].strip().lower() != "application/json": + raise RequestError(415, "expected application/json") + length = int(env.get("CONTENT_LENGTH") or 0) + if length > 1024 * 1024: + raise RequestError(413, "body exceeds 1 MiB") + if length <= 0: + raise ValueError("expected a JSON body with a positive Content-Length") + payload = json.loads(env["wsgi.input"].read(length).decode("utf-8")) + if not isinstance(payload, dict) or payload.keys() != {"type", "fields"}: + raise ValueError("expected type and fields") + kind = payload["type"] + if not isinstance(kind, str) or kind not in types: + raise ValueError("unknown content type") + types[kind].validate(payload["fields"]) + return kind, payload["fields"] + + +def create_app(database, write_token): + if not write_token or not write_token.isascii() or any(c.isspace() for c in write_token): + raise ValueError("MICA_WRITE_TOKEN must be a non-empty ASCII token without spaces") + types = discover() + store.initialize(database) + + def dispatch(env, db): + method = env["REQUEST_METHOD"] + path = env["PATH_INFO"] + item = re.fullmatch(r"/content/([0-9a-f]{32})(/publish)?", path) + if path != "/content" and item is None: + raise RequestError(404, "not found") + allowed = ("GET", "POST") if item is None else (("POST",) if item[2] else ("GET",)) + if method not in allowed: + return 405, {"error": "method not allowed"}, [("Allow", ", ".join(allowed))] + if method == "POST": + actual = env.get("HTTP_AUTHORIZATION", "").encode("latin-1") + if not hmac.compare_digest(actual, ("Bearer " + write_token).encode("ascii")): + return 401, {"error": "writer token required"}, [("WWW-Authenticate", "Bearer")] + if item is None: + kind, fields = read_draft(env, types) + return 201, store.draft(db, kind, fields), [] + result = store.publish(db, item[1]) + elif item is None: + query = parse_qs(env.get("QUERY_STRING", "")) + kind = query.get("type", [None])[0] + limit = int(query.get("limit", ["20"])[0]) + offset = int(query.get("offset", ["0"])[0]) + if not (1 <= limit <= 100 and 0 <= offset <= 2**63 - 1): + raise ValueError("invalid pagination") + return 200, store.list_public(db, kind, limit, offset), [] + else: + result = store.get_public(db, item[1]) + if result is None: + raise RequestError(404, "not found") + return 200, result, [] + + def application(env, start_response): + try: + with closing(store.connect(database)) as db, db: + status, payload, headers = dispatch(env, db) + except RequestError as error: + status, payload, headers = error.status, {"error": str(error)}, [] + except (ValueError, RecursionError): + status, payload, headers = 400, {"error": "invalid request"}, [] + body = json.dumps(payload).encode("utf-8") + start_response(f"{status} {HTTPStatus(status).phrase}", headers + [ + ("Content-Type", "application/json"), ("Content-Length", str(len(body))), + ]) + return [body] + + return application diff --git a/mica/core.py b/mica/core.py new file mode 100644 index 0000000..8d973b5 --- /dev/null +++ b/mica/core.py @@ -0,0 +1,41 @@ +"""Content-type contract and extension discovery.""" + +from dataclasses import dataclass +from importlib import import_module +from pkgutil import iter_modules + +from . import extensions + + +@dataclass(frozen=True) +class ContentType: + name: str + required: tuple[str, ...] + optional: tuple[str, ...] = () + + def validate(self, fields): + if not isinstance(fields, dict): + raise ValueError("fields must be an object") + if fields.keys() - set(self.required + self.optional): + raise ValueError("unknown field for " + self.name) + for key in self.required: + if key not in fields: + raise ValueError("missing field: " + key) + for key, value in fields.items(): + if not isinstance(value, str) or not value.strip(): + raise ValueError(key + " must be a non-empty string") + + +def discover(package=extensions): + types = {} + for module in iter_modules(package.__path__): + if module.name.startswith("_"): + continue + path = package.__name__ + "." + module.name + definition = getattr(import_module(path), "content_type", None) + if not isinstance(definition, ContentType): + raise ValueError(path + " must export a ContentType as content_type") + if definition.name in types: + raise ValueError("duplicate content type: " + definition.name) + types[definition.name] = definition + return types diff --git a/mica/extensions/__init__.py b/mica/extensions/__init__.py new file mode 100644 index 0000000..9c079a8 --- /dev/null +++ b/mica/extensions/__init__.py @@ -0,0 +1 @@ +"""Public modules in this package provide content types.""" diff --git a/mica/extensions/articles.py b/mica/extensions/articles.py new file mode 100644 index 0000000..fb957f9 --- /dev/null +++ b/mica/extensions/articles.py @@ -0,0 +1,3 @@ +from ..core import ContentType + +content_type = ContentType("articles", required=("title", "body"), optional=("summary",)) diff --git a/mica/extensions/posts.py b/mica/extensions/posts.py new file mode 100644 index 0000000..283a318 --- /dev/null +++ b/mica/extensions/posts.py @@ -0,0 +1,3 @@ +from ..core import ContentType + +content_type = ContentType("posts", required=("body",)) diff --git a/mica/store.py b/mica/store.py new file mode 100644 index 0000000..c928067 --- /dev/null +++ b/mica/store.py @@ -0,0 +1,69 @@ +"""SQLite storage for drafts and public content.""" + +from contextlib import closing +import json +import sqlite3 +from uuid import uuid4 + + +def connect(path): + db = sqlite3.connect(path) + db.row_factory = sqlite3.Row + return db + + +def initialize(path): + with closing(connect(path)) as db, db: + db.execute(""" + CREATE TABLE IF NOT EXISTS content ( + id TEXT PRIMARY KEY, + type TEXT NOT NULL, + fields TEXT NOT NULL, + published_at TEXT + ) + """) + db.execute(""" + CREATE INDEX IF NOT EXISTS public_content + ON content (published_at DESC, id DESC) + WHERE published_at IS NOT NULL + """) + + +def record(row): + if row is None: + return None + return { + "id": row["id"], + "type": row["type"], + "fields": json.loads(row["fields"]), + "published_at": row["published_at"], + } + + +def draft(db, kind, fields): + identifier = uuid4().hex + db.execute("INSERT INTO content VALUES (?, ?, ?, NULL)", + (identifier, kind, json.dumps(fields))) + return record(db.execute("SELECT * FROM content WHERE id = ?", (identifier,)).fetchone()) + + +def publish(db, identifier): + db.execute(""" + UPDATE content SET published_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now') + WHERE id = ? AND published_at IS NULL + """, (identifier,)) + return get_public(db, identifier) + + +def get_public(db, identifier): + return record(db.execute(""" + SELECT * FROM content WHERE id = ? AND published_at IS NOT NULL + """, (identifier,)).fetchone()) + + +def list_public(db, kind, limit, offset): + rows = db.execute(""" + SELECT * FROM content WHERE published_at IS NOT NULL AND (? IS NULL OR type = ?) + ORDER BY published_at DESC, id DESC LIMIT ? OFFSET ? + """, (kind, kind, limit, offset)) + return [record(row) for row in rows] diff --git a/tests/test_content.py b/tests/test_content.py new file mode 100644 index 0000000..2d68a59 --- /dev/null +++ b/tests/test_content.py @@ -0,0 +1,77 @@ +from importlib import import_module +from io import BytesIO +import json +import sys +from pathlib import Path +from tempfile import TemporaryDirectory +from unittest import TestCase +from unittest.mock import patch + +from mica.api import create_app +from mica.core import discover + + +class ContentAPI(TestCase): + def setUp(self): + directory = TemporaryDirectory() + self.addCleanup(directory.cleanup) + self.database = Path(directory.name) / "content.sqlite3" + self.app = create_app(self.database, "writer") + + def call(self, method, path, payload=None, token=None): + path, _, query = path.partition("?") + raw = json.dumps(payload).encode() if payload is not None else b"" + env = { + "REQUEST_METHOD": method, "PATH_INFO": path, "QUERY_STRING": query, + "CONTENT_TYPE": "application/json", "CONTENT_LENGTH": str(len(raw)), + "wsgi.input": BytesIO(raw), + } + if token: + env["HTTP_AUTHORIZATION"] = "Bearer " + token + status = [] + result = self.app(env, lambda line, headers: status.append(int(line.split()[0]))) + return status[0], json.loads(b"".join(result)) + + def test_both_extensions_use_the_same_publication_flow(self): + for kind, fields in [("articles", {"title": "标题", "body": "文章"}), + ("posts", {"body": "动态"})]: + status, draft = self.call("POST", "/content", {"type": kind, "fields": fields}, "writer") + self.assertEqual(status, 201) + path = "/content/" + draft["id"] + self.assertEqual(self.call("GET", path)[0], 404) + self.assertEqual(self.call("GET", "/content?type=" + kind), (200, [])) + self.assertEqual(self.call("POST", path + "/publish")[0], 401) + status, published = self.call("POST", path + "/publish", token="writer") + self.assertEqual(status, 200) + self.assertTrue(published["published_at"]) + self.assertEqual(published["fields"], fields) + self.app = create_app(self.database, "writer") + self.assertEqual(self.call("GET", path), (200, published)) + self.assertEqual(self.call("POST", path + "/publish", token="writer"), (200, published)) + self.assertEqual(self.call("GET", "/content?type=" + kind), (200, [published])) + self.assertEqual(len(self.call("GET", "/content?limit=1&offset=1")[1]), 1) + + def test_invalid_requests(self): + self.assertEqual(self.call("POST", "/content", {}, "wrong")[0], 401) + for kind, fields in [("posts", {"body": " "}), ("posts", {"body": "a", "title": "b"}), + ("articles", {"body": "a"}), ("unknown", {})]: + status, _ = self.call("POST", "/content", {"type": kind, "fields": fields}, "writer") + self.assertEqual(status, 400) + self.assertEqual(self.call("GET", "/content?limit=-1")[0], 400) + self.assertEqual(self.call("DELETE", "/content")[0], 405) + self.assertEqual(self.call("GET", "/content"), (200, [])) + + def test_extension_discovery(self): + with TemporaryDirectory() as path: + package_dir = Path(path) / "sample_extensions" + package_dir.mkdir() + (package_dir / "__init__.py").touch() + (package_dir / "_helper.py").write_text("") + definition = 'from mica.core import ContentType\ncontent_type = ContentType("notes", ("body",))' + (package_dir / "notes.py").write_text(definition) + with patch("sys.path", [path, *sys.path]): + package = import_module("sample_extensions") + self.assertEqual(set(discover(package)), {"notes"}) + (package_dir / "other.py").write_text(definition) + with self.assertRaisesRegex(ValueError, "duplicate content type"): + discover(package)