实现插件运行时与 PostgreSQL 优先的模型持久化 #2
@@ -4,27 +4,77 @@
|
||||
|
||||
名字里的 **Modular** 指核心和插件各有职责,**Infrastructure** 指多个前端可以共用这个后端,**Content Applications** 指围绕写入、发布和展示构建的应用。英文单词 *mica* 意为“云母”,读作 *MY-kuh*。代码使用小写包名 `mica`,核心契约位于 `mica.core`,内置扩展位于 `mica.extensions`。
|
||||
|
||||
## 第一版
|
||||
## Core 与插件
|
||||
|
||||
核心维护内容 ID、草稿和发布状态,在 SQLite 中保存内容,并通过 HTTP 提供写入鉴权和公开查询。内容扩展声明字段规则,两种前端共用存储和发布流程。
|
||||
Core 在启动时加载插件、建立注册表,并将启用的插件声明同步到数据库。站点可直接使用 Python 运行时,也可以启动自带的内容 HTTP 服务。
|
||||
|
||||
| 扩展 | 写入类型 | 必填文本 | 可选文本 |
|
||||
| --- | --- | --- | --- |
|
||||
| 短帖 | `posts` | `body` | 无 |
|
||||
| 文章 | `articles` | `title`、`body` | `summary` |
|
||||
| 对象 | 职责 |
|
||||
| --- | --- |
|
||||
| `Plugin` | 可独立启用的单元,声明插件名、提供的 snippets 和依赖的 snippet 名。 |
|
||||
| `Snippet` | 将一组领域操作和它们拥有的 SQLAlchemy ORM 模型或表组织在一起。可以只提供操作,也可以只提供模型。 |
|
||||
| `Registry` | 解析插件、snippet 和操作的名称。启动时报告重复注册、表名冲突、缺失依赖或未知的启用项。 |
|
||||
| `Runtime` 与 `Call` | 应用按 `snippet.operation` 调用,处理函数通过 `call.session` 保存 Python 模型实例、通过 `call.db` 执行 SQL、通过 `call.call(...)` 调用其他插件。同一次顶层调用共用一个事务,未处理的异常使整次写入回滚。 |
|
||||
|
||||
首版适合由一个受信任的编辑服务写入。终端用户登录、作者权限、评论、关注和个性化排序留待后续版本。
|
||||
Core 自动发现已安装包在 `mica.plugins` 组声明的入口。默认加载所有已发现的插件;设置 `MICA_PLUGINS=publishing,articles` 可只启用文章及内容服务。Python 入口接受同样的 `enabled` 名单。独立使用 `Runtime` 时,内置内容插件由调用方显式传入。HTTP 服务默认带上 `publishing`、`articles`、`posts`,兼容原有内容扩展和接口。
|
||||
|
||||
## 在本地试用
|
||||
## PostgreSQL 与启动同步
|
||||
|
||||
需要 Python 3.9 或以上版本,仅使用标准库。在仓库根目录运行以下命令。请在同一个终端保留生成的令牌,供写入客户端使用。
|
||||
主数据库为 **PostgreSQL**,默认连接 `postgresql:///mica`,使用 psycopg 3。先准备数据库,并授予运行账户在目标 schema 建表和读写的权限。可以通过 `MICA_DATABASE` 指定连接地址,凭据按部署环境注入。
|
||||
|
||||
| 后端 | 连接示例 | 用途 |
|
||||
| --- | --- | --- |
|
||||
| PostgreSQL | `postgresql://localhost/mica` | 默认及主要部署路径 |
|
||||
| MySQL | `mysql://localhost/mica?charset=utf8mb4` | 可选,安装 `mysql` extra |
|
||||
| SQLite | `sqlite:///mica.sqlite3` | 本地试用。原有 SQLite 文件路径也可继续使用 |
|
||||
|
||||
每次启动先在事务或会话锁保护下核对已启用插件的表结构,创建缺少的表、索引和普通可空列,并在 `mica_plugins` 保存各插件最近一次注册的 snippet、操作名、表名和依赖。运行时按本次启用列表分派调用。禁用插件会保留历史登记和业务数据。Python 函数留在安装包里执行,数据库保存声明目录和操作产生的数据。
|
||||
|
||||
变更主键、删列、改字段类型等需要显式迁移。结构对比基于 Alembic,对复杂 CHECK、数据库触发器等约束请提供独立迁移。MySQL 的 DDL 会隐式提交,中断后可以重新启动并核对已创建的对象。插件使用当前 schema,表名需为小写标识符,`mica_` 前缀保留给宿主。
|
||||
|
||||
## 写一个插件
|
||||
|
||||
例如,`bookmarks` 插件声明一个 Python 对象,以两个字段组成联合主键。Core 启动时从映射类生成表,调用时把实例写入该表:
|
||||
|
||||
```python
|
||||
# site_bookmarks.py
|
||||
from sqlalchemy import String
|
||||
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
||||
from mica.core import Plugin, Snippet
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
class Bookmark(Base):
|
||||
__tablename__ = "bookmarks"
|
||||
reader: Mapped[str] = mapped_column(String(64), primary_key=True)
|
||||
url: Mapped[str] = mapped_column(String(256), primary_key=True)
|
||||
|
||||
def save(call, reader, url):
|
||||
call.session.add(Bookmark(reader=reader, url=url))
|
||||
|
||||
plugin = Plugin("bookmarks", (Snippet("bookmarks", {"save": save}, (Bookmark,)),))
|
||||
```
|
||||
|
||||
在插件包自己的 `pyproject.toml` 声明入口(入口名与插件名相同):
|
||||
|
||||
```toml
|
||||
[project.entry-points."mica.plugins"]
|
||||
bookmarks = "site_bookmarks:plugin"
|
||||
```
|
||||
|
||||
安装插件后,`Runtime("postgresql:///mica", enabled=["bookmarks"])` 即可发现它、创建书签表。应用使用 `runtime.call("bookmarks.save", reader="alice", url="/news/42")`。进程关闭时调用 `runtime.close()`。直接开发时也可把插件对象传给 `Runtime(database, [plugin])`。每张表由一个 snippet 声明;同一个数据库中的其他插件可通过已注册的操作使用它。
|
||||
|
||||
## 运行内容示例
|
||||
|
||||
需要 Python 3.10 或以上。在激活的虚拟环境中安装依赖,可用 `uv pip install --only-binary :all: -r pyproject.toml`。MySQL 另加 `--extra mysql`。从仓库根目录运行:
|
||||
|
||||
```sh
|
||||
export MICA_DATABASE='postgresql:///mica'
|
||||
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。写入令牌只应由受信任的服务端持有。
|
||||
服务默认监听 `127.0.0.1:8000`,端口可通过 `MICA_PORT` 配置。写入令牌由受信任的服务端持有。内容插件定义草稿和公开读取规则:短帖需要正文,文章需要标题和正文,可选摘要。
|
||||
|
||||
创建草稿,取出响应里的 ID,发布并公开读取:
|
||||
|
||||
@@ -41,22 +91,10 @@ 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
|
||||
```
|
||||
|
||||
数据库契约测试可使用 `MICA_TEST_POSTGRESQL` 和 `MICA_TEST_MYSQL` 指定两个专用、可丢弃的测试库。测试会创建表、写入数据并核对再次启动、跨插件事务、并发初始化和兼容性;未设置的服务端用例显示为 skipped。
|
||||
|
||||
+6
-2
@@ -1,3 +1,4 @@
|
||||
from contextlib import closing
|
||||
import os
|
||||
from wsgiref.simple_server import make_server
|
||||
|
||||
@@ -5,8 +6,11 @@ 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:
|
||||
names = os.getenv("MICA_PLUGINS")
|
||||
enabled = None if names is None else [name.strip() for name in names.split(",") if name.strip()]
|
||||
app = create_app(os.getenv("MICA_DATABASE", "postgresql:///mica"),
|
||||
os.getenv("MICA_WRITE_TOKEN"), enabled=enabled)
|
||||
with closing(app), 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()
|
||||
|
||||
|
||||
+16
-20
@@ -1,14 +1,13 @@
|
||||
"""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
|
||||
from .core import Runtime
|
||||
from .publishing import bundled_plugins
|
||||
|
||||
|
||||
class RequestError(Exception):
|
||||
@@ -17,7 +16,7 @@ class RequestError(Exception):
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
def read_draft(env, types):
|
||||
def read_draft(env):
|
||||
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)
|
||||
@@ -28,20 +27,17 @@ def read_draft(env, types):
|
||||
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"]
|
||||
return payload["type"], payload["fields"]
|
||||
|
||||
|
||||
def create_app(database, write_token):
|
||||
def create_app(database, write_token, *, enabled=None):
|
||||
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)
|
||||
runtime = Runtime(database, bundled_plugins(), enabled=enabled)
|
||||
|
||||
def dispatch(env, db):
|
||||
def dispatch(env):
|
||||
if "content" not in runtime.registry.snippets:
|
||||
raise RequestError(404, "not found")
|
||||
method = env["REQUEST_METHOD"]
|
||||
path = env["PATH_INFO"]
|
||||
item = re.fullmatch(r"/content/([0-9a-f]{32})(/publish)?", path)
|
||||
@@ -55,9 +51,9 @@ def create_app(database, write_token):
|
||||
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])
|
||||
kind, fields = read_draft(env)
|
||||
return 201, runtime.call("content.draft", kind=kind, fields=fields), []
|
||||
result = runtime.call("content.publish", identifier=item[1])
|
||||
elif item is None:
|
||||
query = parse_qs(env.get("QUERY_STRING", ""))
|
||||
kind = query.get("type", [None])[0]
|
||||
@@ -65,17 +61,16 @@ def create_app(database, write_token):
|
||||
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), []
|
||||
return 200, runtime.call("content.list", kind=kind, limit=limit, offset=offset), []
|
||||
else:
|
||||
result = store.get_public(db, item[1])
|
||||
result = runtime.call("content.get", identifier=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)
|
||||
status, payload, headers = dispatch(env)
|
||||
except RequestError as error:
|
||||
status, payload, headers = error.status, {"error": str(error)}, []
|
||||
except (ValueError, RecursionError):
|
||||
@@ -86,4 +81,5 @@ def create_app(database, write_token):
|
||||
])
|
||||
return [body]
|
||||
|
||||
application.close = runtime.close
|
||||
return application
|
||||
|
||||
@@ -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
|
||||
+36
-32
@@ -1,41 +1,45 @@
|
||||
"""Content-type contract and extension discovery."""
|
||||
"""Load plugins, materialize their models and dispatch transactional calls."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from importlib import import_module
|
||||
from pkgutil import iter_modules
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from . import extensions
|
||||
from .database import connect, materialize
|
||||
from .plugins import Plugin, Registry, Snippet
|
||||
|
||||
# Keep the original content extension imports usable by installed plugins.
|
||||
from .content_types import ContentType, discover
|
||||
|
||||
__all__ = ["Runtime", "Call", "Plugin", "Registry", "Snippet", "ContentType", "discover"]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ContentType:
|
||||
name: str
|
||||
required: tuple[str, ...]
|
||||
optional: tuple[str, ...] = ()
|
||||
class Call:
|
||||
registry: Registry
|
||||
session: Session
|
||||
|
||||
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")
|
||||
@property
|
||||
def db(self):
|
||||
self.session.flush()
|
||||
return self.session.connection()
|
||||
|
||||
def call(self, operation, **parameters):
|
||||
handler = self.registry.operations[operation]
|
||||
return handler(self, **parameters)
|
||||
|
||||
|
||||
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
|
||||
class Runtime:
|
||||
def __init__(self, database, plugins=(), *, enabled=None):
|
||||
self.registry = Registry.load(plugins, enabled)
|
||||
self.engine = connect(database)
|
||||
try:
|
||||
materialize(self.engine, self.registry)
|
||||
except BaseException:
|
||||
self.engine.dispose()
|
||||
raise
|
||||
|
||||
def call(self, operation, **parameters):
|
||||
with Session(self.engine, expire_on_commit=False) as session, session.begin():
|
||||
return Call(self.registry, session).call(operation, **parameters)
|
||||
|
||||
def close(self):
|
||||
self.engine.dispose()
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
"""Connect and materialize registered snippets before accepting calls."""
|
||||
|
||||
from contextlib import contextmanager
|
||||
from os import PathLike
|
||||
|
||||
from alembic.autogenerate import compare_metadata
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
from sqlalchemy import JSON, Column, MetaData, String, Table, create_engine, event, inspect, select, text
|
||||
from sqlalchemy.engine import URL, make_url
|
||||
|
||||
|
||||
def connect(database):
|
||||
if isinstance(database, PathLike) or "://" not in database:
|
||||
url = URL.create("sqlite+pysqlite", database=str(database))
|
||||
else:
|
||||
url = make_url(database)
|
||||
drivers = {"postgresql": "psycopg", "mysql": "pymysql", "sqlite": "pysqlite"}
|
||||
backend = url.get_backend_name()
|
||||
if backend not in drivers:
|
||||
raise ValueError(f"unsupported database: {backend}")
|
||||
engine = create_engine(url.set(drivername=f"{backend}+{drivers[backend]}"), pool_pre_ping=True)
|
||||
if backend == "sqlite":
|
||||
@event.listens_for(engine, "connect")
|
||||
def enable_foreign_keys(dbapi, record):
|
||||
dbapi.execute("PRAGMA foreign_keys=ON")
|
||||
return engine
|
||||
|
||||
|
||||
@contextmanager
|
||||
def startup_transaction(engine):
|
||||
# Serialize inspection and DDL across workers. MySQL DDL commits implicitly,
|
||||
# so its session lock has to outlive the SQL transaction.
|
||||
with engine.connect() as db:
|
||||
mysql_locked = False
|
||||
try:
|
||||
with db.begin():
|
||||
if db.dialect.name == "postgresql":
|
||||
db.execute(text("SELECT pg_advisory_xact_lock(1296646977)"))
|
||||
elif db.dialect.name == "sqlite":
|
||||
db.exec_driver_sql("BEGIN IMMEDIATE")
|
||||
else:
|
||||
mysql_locked = db.scalar(text("SELECT GET_LOCK('mica.core.startup', 30)")) == 1
|
||||
if not mysql_locked:
|
||||
raise RuntimeError("timed out waiting for the MICA startup lock")
|
||||
yield db
|
||||
finally:
|
||||
if mysql_locked:
|
||||
db.execute(text("SELECT RELEASE_LOCK('mica.core.startup')"))
|
||||
|
||||
|
||||
def materialize(engine, registry):
|
||||
metadata = MetaData()
|
||||
for table in registry.metadata.tables.values():
|
||||
table.to_metadata(metadata)
|
||||
catalog = Table("mica_plugins", metadata, Column("name", String(63), primary_key=True),
|
||||
Column("description", JSON, nullable=False))
|
||||
|
||||
def include_name(name, kind, parents):
|
||||
return kind != "table" or name in metadata.tables
|
||||
|
||||
with startup_transaction(engine) as db:
|
||||
context = MigrationContext.configure(db, opts={"include_name": include_name})
|
||||
inspector = inspect(db)
|
||||
for table in metadata.tables.values():
|
||||
if inspector.has_table(table.name):
|
||||
pk = inspector.get_pk_constraint(table.name)["constrained_columns"]
|
||||
if pk != list(table.primary_key.columns.keys()):
|
||||
raise ValueError(f"explicit schema migration required: {table.name} primary key")
|
||||
changes = compare_metadata(context, metadata)
|
||||
additions = []
|
||||
for change in changes:
|
||||
if change[0] in ("add_table", "add_index"):
|
||||
continue
|
||||
if change[0] == "add_column":
|
||||
column = change[3]
|
||||
if column.nullable and not column.foreign_keys and not column.unique:
|
||||
additions.append(change)
|
||||
continue
|
||||
# Legacy SQLite TEXT PRIMARY KEY columns can reflect as nullable.
|
||||
# Allow only this opted-in difference; keep all other checks active.
|
||||
if db.dialect.name == "sqlite" and isinstance(change, list) and len(change) == 1:
|
||||
diff = change[0]
|
||||
if diff[0] == "modify_nullable" and diff[-2:] == (True, False):
|
||||
column = metadata.tables[diff[2]].c[diff[3]]
|
||||
if column.primary_key and column.info.get("sqlite_legacy_nullable_pk"):
|
||||
continue
|
||||
raise ValueError(f"explicit schema migration required: {change}")
|
||||
|
||||
ops = Operations(context)
|
||||
for _, schema, table_name, column in additions:
|
||||
ops.add_column(table_name, column, schema=schema)
|
||||
metadata.create_all(db)
|
||||
for change in changes:
|
||||
if change[0] == "add_index":
|
||||
change[1].create(db, checkfirst=True)
|
||||
|
||||
existing = set(db.scalars(select(catalog.c.name)))
|
||||
for plugin in registry.plugins.values():
|
||||
description = {
|
||||
"requires": list(plugin.requires),
|
||||
"snippets": {s.name: {"operations": sorted(s.operations),
|
||||
"tables": [t.name for t in s.tables]} for s in plugin.snippets},
|
||||
}
|
||||
if plugin.name in existing:
|
||||
stmt = catalog.update().where(catalog.c.name == plugin.name)
|
||||
else:
|
||||
stmt = catalog.insert().values(name=plugin.name)
|
||||
db.execute(stmt.values(description=description))
|
||||
@@ -1,3 +1,3 @@
|
||||
from ..core import ContentType
|
||||
from ..content_types import ContentType
|
||||
|
||||
content_type = ContentType("articles", required=("title", "body"), optional=("summary",))
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
from ..core import ContentType
|
||||
from ..content_types import ContentType
|
||||
|
||||
content_type = ContentType("posts", required=("body",))
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Plugin descriptions, entry-point discovery and the runtime registry."""
|
||||
|
||||
from collections.abc import Callable, Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from importlib.metadata import entry_points
|
||||
import re
|
||||
|
||||
from sqlalchemy import MetaData, Table, inspect
|
||||
from sqlalchemy.orm import Mapper
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Snippet:
|
||||
name: str
|
||||
operations: Mapping[str, Callable] = field(default_factory=dict)
|
||||
models: tuple[Table | type, ...] = ()
|
||||
|
||||
@property
|
||||
def tables(self):
|
||||
tables = []
|
||||
for model in self.models:
|
||||
if isinstance(model, Table):
|
||||
tables.append(model)
|
||||
continue
|
||||
mapper = inspect(model, raiseerr=False)
|
||||
if not isinstance(mapper, Mapper) or not isinstance(mapper.local_table, Table):
|
||||
raise ValueError(f"{self.name} must declare a Table or an ORM mapped class")
|
||||
tables.append(mapper.local_table)
|
||||
return tuple(tables)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Plugin:
|
||||
name: str
|
||||
snippets: tuple[Snippet, ...]
|
||||
requires: tuple[str, ...] = ()
|
||||
|
||||
|
||||
def check_name(name):
|
||||
if not isinstance(name, str) or not re.fullmatch(r"[a-z][a-z0-9_]{0,62}", name):
|
||||
raise ValueError(f"invalid registry name: {name!r}")
|
||||
|
||||
|
||||
class Registry:
|
||||
def __init__(self, plugins):
|
||||
self.plugins = {}
|
||||
self.snippets = {}
|
||||
self.operations = {}
|
||||
self.metadata = MetaData()
|
||||
for plugin in plugins:
|
||||
check_name(plugin.name)
|
||||
if plugin.name in self.plugins:
|
||||
raise ValueError(f"duplicate plugin: {plugin.name}")
|
||||
self.plugins[plugin.name] = plugin
|
||||
for snippet in plugin.snippets:
|
||||
self._register(snippet)
|
||||
for plugin in self.plugins.values():
|
||||
missing = set(plugin.requires) - self.snippets.keys()
|
||||
if missing:
|
||||
raise ValueError(f"{plugin.name} requires missing snippets: {sorted(missing)}")
|
||||
|
||||
def _register(self, snippet):
|
||||
check_name(snippet.name)
|
||||
if snippet.name in self.snippets:
|
||||
raise ValueError(f"duplicate snippet: {snippet.name}")
|
||||
self.snippets[snippet.name] = snippet
|
||||
for name, handler in snippet.operations.items():
|
||||
check_name(name)
|
||||
if not callable(handler):
|
||||
raise ValueError(f"invalid operation: {snippet.name}.{name}")
|
||||
self.operations[f"{snippet.name}.{name}"] = handler
|
||||
for table in snippet.tables:
|
||||
check_name(table.name)
|
||||
if table.schema or table.name.startswith("mica_") or table.key in self.metadata.tables:
|
||||
raise ValueError(f"reserved or duplicate plugin table: {table.fullname}")
|
||||
table.to_metadata(self.metadata)
|
||||
|
||||
@classmethod
|
||||
def load(cls, bundled=(), enabled=None):
|
||||
"""Discover installed mica.plugins entries. Only import selected entries."""
|
||||
selected = None if enabled is None else set(enabled)
|
||||
plugins = [p for p in bundled if selected is None or p.name in selected]
|
||||
for entry in sorted(entry_points(group="mica.plugins"), key=lambda ep: ep.name):
|
||||
if selected is not None and entry.name not in selected:
|
||||
continue
|
||||
plugin = entry.load()
|
||||
if not isinstance(plugin, Plugin) or plugin.name != entry.name:
|
||||
raise ValueError(f"invalid mica.plugins entry point: {entry.name}")
|
||||
plugins.append(plugin)
|
||||
registry = cls(plugins)
|
||||
if selected is not None and (missing := selected - registry.plugins.keys()):
|
||||
raise ValueError(f"unknown plugins: {sorted(missing)}")
|
||||
return registry
|
||||
@@ -0,0 +1,80 @@
|
||||
"""Bundled publishing plugin shared by the article and post snippets."""
|
||||
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
from uuid import uuid4
|
||||
|
||||
from sqlalchemy import Column, Index, MetaData, String, Table, Text, select
|
||||
|
||||
from .content_types import discover
|
||||
from .plugins import Plugin, Snippet
|
||||
|
||||
|
||||
def key_type(length):
|
||||
# The original SQLite database stored these fields as TEXT.
|
||||
return String(length).with_variant(Text(), "sqlite")
|
||||
|
||||
|
||||
content = Table(
|
||||
"content", MetaData(),
|
||||
Column("id", key_type(32), primary_key=True, info={"sqlite_legacy_nullable_pk": True}),
|
||||
Column("type", key_type(63), nullable=False),
|
||||
Column("fields", Text, nullable=False),
|
||||
Column("published_at", key_type(32)),
|
||||
)
|
||||
public = content.c.published_at.is_not(None)
|
||||
Index("public_content", content.c.published_at.desc(), content.c.id.desc(),
|
||||
sqlite_where=public, postgresql_where=public)
|
||||
|
||||
|
||||
def record(row):
|
||||
if row is None:
|
||||
return None
|
||||
return {**row, "fields": json.loads(row["fields"])}
|
||||
|
||||
|
||||
def draft(call, kind, fields):
|
||||
operation = f"{kind}.validate"
|
||||
if not isinstance(kind, str) or operation not in call.registry.operations:
|
||||
raise ValueError("unknown content type")
|
||||
call.call(operation, fields=fields)
|
||||
row = dict(id=uuid4().hex, type=kind, fields=json.dumps(fields), published_at=None)
|
||||
call.db.execute(content.insert().values(**row))
|
||||
return record(row)
|
||||
|
||||
|
||||
def get_public(call, identifier):
|
||||
stmt = select(content).where(content.c.id == identifier, public)
|
||||
return record(call.db.execute(stmt).mappings().one_or_none())
|
||||
|
||||
|
||||
def publish(call, identifier):
|
||||
timestamp = datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
|
||||
call.db.execute(content.update().where(content.c.id == identifier, content.c.published_at.is_(None))
|
||||
.values(published_at=timestamp))
|
||||
return get_public(call, identifier)
|
||||
|
||||
|
||||
def list_public(call, kind, limit, offset):
|
||||
stmt = select(content).where(public)
|
||||
if kind is not None:
|
||||
stmt = stmt.where(content.c.type == kind)
|
||||
stmt = stmt.order_by(content.c.published_at.desc(), content.c.id.desc()).limit(limit).offset(offset)
|
||||
return [record(row) for row in call.db.execute(stmt).mappings()]
|
||||
|
||||
|
||||
publishing = Plugin("publishing", (Snippet("content", {
|
||||
"draft": draft, "get": get_public, "publish": publish, "list": list_public,
|
||||
}, (content,)),))
|
||||
|
||||
|
||||
def validation_operation(definition):
|
||||
def validate(call, fields):
|
||||
definition.validate(fields)
|
||||
return validate
|
||||
|
||||
|
||||
def bundled_plugins():
|
||||
yield publishing
|
||||
for name, definition in discover().items():
|
||||
yield Plugin(name, (Snippet(name, {"validate": validation_operation(definition)}),))
|
||||
@@ -1,69 +0,0 @@
|
||||
"""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]
|
||||
@@ -0,0 +1,16 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=68"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "mica-core"
|
||||
version = "0.1.0"
|
||||
description = "Modular Infrastructure for Content Applications"
|
||||
requires-python = ">=3.10"
|
||||
dependencies = ["SQLAlchemy>=2.0,<2.1", "alembic>=1.14,<2", "psycopg[binary]>=3.2,<4"]
|
||||
|
||||
[project.optional-dependencies]
|
||||
mysql = ["PyMySQL[rsa]>=1.1,<2"]
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
include = ["mica", "mica.*"]
|
||||
@@ -17,6 +17,7 @@ class ContentAPI(TestCase):
|
||||
self.addCleanup(directory.cleanup)
|
||||
self.database = Path(directory.name) / "content.sqlite3"
|
||||
self.app = create_app(self.database, "writer")
|
||||
self.addCleanup(lambda: self.app.close())
|
||||
|
||||
def call(self, method, path, payload=None, token=None):
|
||||
path, _, query = path.partition("?")
|
||||
@@ -45,6 +46,7 @@ class ContentAPI(TestCase):
|
||||
self.assertEqual(status, 200)
|
||||
self.assertTrue(published["published_at"])
|
||||
self.assertEqual(published["fields"], fields)
|
||||
self.app.close()
|
||||
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))
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
from tempfile import TemporaryDirectory
|
||||
from threading import Barrier
|
||||
from uuid import uuid4
|
||||
from unittest import TestCase
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
from sqlalchemy import Column, Integer, MetaData, String, Table, inspect, select, text
|
||||
|
||||
from sqlalchemy.orm import registry
|
||||
|
||||
from mica.core import Plugin, Registry, Runtime, Snippet
|
||||
from mica.publishing import bundled_plugins
|
||||
|
||||
|
||||
def counter_plugins(name, extra=()):
|
||||
table = Table(name, MetaData(), Column("id", Integer, primary_key=True),
|
||||
Column("label", String(50), nullable=False), *extra)
|
||||
|
||||
class Counter:
|
||||
pass
|
||||
|
||||
registry().map_imperatively(Counter, table)
|
||||
|
||||
def write(call, label):
|
||||
call.session.add(Counter(label=label))
|
||||
|
||||
def relay(call, label, fail=False):
|
||||
call.call("counter.write", label=label)
|
||||
if fail:
|
||||
raise ValueError("rollback")
|
||||
|
||||
storage = Plugin("storage", (Snippet("counter", {"write": write}, (Counter,)),))
|
||||
actions = Plugin("actions", (Snippet("relay", {"run": relay}),), requires=("counter",))
|
||||
return storage, actions
|
||||
|
||||
|
||||
class RegistryTest(TestCase):
|
||||
def test_entry_point_selection_and_dependencies(self):
|
||||
plugin, relay = counter_plugins("counter_rows")
|
||||
entry = Mock()
|
||||
entry.name = plugin.name
|
||||
entry.load.return_value = plugin
|
||||
with patch("mica.plugins.entry_points", return_value=[entry]):
|
||||
self.assertFalse(Registry.load(enabled=[]).plugins)
|
||||
entry.load.assert_not_called()
|
||||
self.assertIn("relay.run", Registry.load([relay]).operations)
|
||||
with self.assertRaisesRegex(ValueError, "unknown plugins"):
|
||||
Registry.load(enabled=["absent"])
|
||||
with self.assertRaisesRegex(ValueError, "requires missing"):
|
||||
Registry([relay])
|
||||
with self.assertRaisesRegex(ValueError, "duplicate plugin"):
|
||||
Registry([plugin, plugin])
|
||||
with self.assertRaisesRegex(ValueError, "duplicate snippet"):
|
||||
Registry([plugin, Plugin("second", plugin.snippets)])
|
||||
|
||||
def test_existing_sqlite_content(self):
|
||||
with TemporaryDirectory() as path:
|
||||
database = Path(path) / "legacy.sqlite3"
|
||||
db = sqlite3.connect(database)
|
||||
db.executescript("""
|
||||
CREATE TABLE content (id TEXT PRIMARY KEY, type TEXT NOT NULL,
|
||||
fields TEXT NOT NULL, published_at TEXT);
|
||||
CREATE INDEX public_content ON content (published_at DESC, id DESC)
|
||||
WHERE published_at IS NOT NULL;
|
||||
INSERT INTO content VALUES ('old', 'posts', '{"body":"旧数据"}', NULL);
|
||||
""")
|
||||
db.close()
|
||||
runtime = Runtime(database, bundled_plugins())
|
||||
try:
|
||||
row = runtime.call("content.publish", identifier="old")
|
||||
self.assertEqual(row["fields"], {"body": "旧数据"})
|
||||
finally:
|
||||
runtime.close()
|
||||
|
||||
|
||||
class DatabaseContract(TestCase):
|
||||
"""Optional server URLs must identify dedicated, disposable test databases."""
|
||||
|
||||
def exercise(self, url):
|
||||
name = "counter_" + uuid4().hex[:12]
|
||||
plugins = counter_plugins(name)
|
||||
barrier = Barrier(2)
|
||||
def start_worker():
|
||||
barrier.wait(timeout=10)
|
||||
Runtime(url, plugins).close()
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as workers:
|
||||
futures = [workers.submit(start_worker) for _ in range(2)]
|
||||
for future in futures:
|
||||
future.result(timeout=45)
|
||||
runtime = Runtime(url, plugins)
|
||||
try:
|
||||
runtime.call("relay.run", label="一次写入")
|
||||
with self.assertRaisesRegex(ValueError, "rollback"):
|
||||
runtime.call("relay.run", label="rolled back", fail=True)
|
||||
with runtime.engine.connect() as db:
|
||||
self.assertEqual(db.scalars(select(plugins[0].snippets[0].tables[0].c.label)).all(),
|
||||
["一次写入"])
|
||||
self.assertIn("relay", str(db.scalar(text(
|
||||
"SELECT description FROM mica_plugins WHERE name = 'actions'"))))
|
||||
finally:
|
||||
runtime.close()
|
||||
|
||||
updated = counter_plugins(name, [Column("note", String(80))])
|
||||
for _ in range(2):
|
||||
runtime = Runtime(url, updated)
|
||||
try:
|
||||
with runtime.engine.connect() as db:
|
||||
self.assertEqual(db.execute(select(updated[0].snippets[0].tables[0].c.note)).all(),
|
||||
[(None,)])
|
||||
self.assertIn("note", [c["name"] for c in inspect(db).get_columns(name)])
|
||||
finally:
|
||||
runtime.close()
|
||||
with self.assertRaisesRegex(ValueError, "explicit schema migration"):
|
||||
Runtime(url, plugins)
|
||||
runtime = Runtime(url, bundled_plugins())
|
||||
try:
|
||||
row = runtime.call("content.draft", kind="articles", fields={"title": "标题", "body": "文"})
|
||||
self.assertIsNone(runtime.call("content.get", identifier=row["id"]))
|
||||
published = runtime.call("content.publish", identifier=row["id"])
|
||||
self.assertEqual(published, runtime.call("content.publish", identifier=row["id"]))
|
||||
finally:
|
||||
runtime.close()
|
||||
Runtime(url, bundled_plugins()).close()
|
||||
|
||||
def test_sqlite(self):
|
||||
with TemporaryDirectory() as directory:
|
||||
self.exercise(Path(directory) / "mica.sqlite3")
|
||||
|
||||
def test_postgresql(self):
|
||||
url = os.getenv("MICA_TEST_POSTGRESQL")
|
||||
if not url:
|
||||
self.skipTest("set MICA_TEST_POSTGRESQL to a disposable database")
|
||||
self.exercise(url)
|
||||
|
||||
def test_mysql(self):
|
||||
url = os.getenv("MICA_TEST_MYSQL")
|
||||
if not url:
|
||||
self.skipTest("set MICA_TEST_MYSQL to a disposable database")
|
||||
self.exercise(url)
|
||||
Reference in New Issue
Block a user