Compare changes

Choose any two refs to compare.

+6 -1
.gitignore
···
__marimo__/
# Streamlit
-
.streamlit/secrets.toml
···
__marimo__/
# Streamlit
+
.streamlit/secrets.toml
+
+
#####
+
+
# Added by DWN - temp dir
+
tmp/
+10 -2
README.md
···
-
# ATPasser ╬<!
A simple library for the [Authenticated Transfer Protocol](https://atproto.com/specs/atp) (AT Protocol or atproto for short).
···
---
-
[See the roadmap](docs/roadmap.md)
---
···
+
# ATPasser!
A simple library for the [Authenticated Transfer Protocol](https://atproto.com/specs/atp) (AT Protocol or atproto for short).
···
---
+
## Other ATProto libraries
+
+
[There's an ATProto SDK already (and used by lots of projects) by MarshalX,](https://github.com/MarshalX/atproto) and why do this exists?
+
+
The first reason is that I'm recovering the now-closed [Tietiequan](https://tangled.org/@dwn.dwnfonts.cc/bluesky-circle) app and found that some API has changed so I have to rewrite it via vanilla JS.
+
+
The second reason is that I'm a newbie in ATProto, wanting to know how ATProto is, and how this can be represented in Python.
+
+
The architecture will be small, only containing the data model and the client.
---
-16
src/atpasser/blob/__init__.py
···
-
import cid
-
import multihash, hashlib
-
-
-
def generateCID(file):
-
hasher = hashlib.new("sha-256")
-
while True:
-
chunk = file.read(8192)
-
if not chunk:
-
break
-
hasher.update(chunk)
-
-
digest = hasher.digest
-
mh = multihash.encode(digest, "sha-256")
-
-
return cid.CIDv1(codec="raw", multihash=mh)
···
-76
src/atpasser/data/_data.py
···
-
import base64
-
from cid import CIDv0, CIDv1, cid, make_cid
-
import json
-
-
-
class Data:
-
"""
-
A class representing data with "$type" key.
-
-
Attributes:
-
type (str): The type of the data.
-
json (str): Original object in JSON format.
-
"""
-
-
def __init__(self, dataType: str, json: str = "{}") -> None:
-
"""
-
Initalizes data object.
-
-
Parameters:
-
type (str): The type of the data.
-
json (str): Original object in JSON format.
-
"""
-
self.type = dataType
-
self.json = json
-
-
def data(self):
-
"""
-
Loads data as a Python-friendly format.
-
-
Returns:
-
dict: Converted data from JSON object.
-
"""
-
return json.loads(self.json, object_hook=dataHook)
-
-
-
def dataHook(data: dict):
-
"""
-
Treated as `JSONDecoder`'s `object_hook`
-
-
Parameters:
-
data: data in format that `JSONDecoder` like ;)
-
"""
-
if "$bytes" in data:
-
return base64.b64decode(data["$bytes"])
-
elif "$link" in data:
-
return make_cid(data["$link"])
-
elif "$type" in data:
-
dataType = data["$type"]
-
del data["$type"]
-
return Data(dataType, json.dumps(data))
-
else:
-
return data
-
-
-
def _convertDataToFakeJSON(data):
-
if isinstance(data, bytes):
-
return {"$bytes": base64.b64encode(data)}
-
elif isinstance(data, (CIDv0, CIDv1)):
-
return {"link": data.encode()}
-
elif isinstance(data, dict):
-
for item in data:
-
data[item] = _convertDataToFakeJSON(data[item])
-
elif isinstance(data, (tuple, list, set)):
-
return [_convertDataToFakeJSON(item) for item in data]
-
else:
-
return data
-
-
-
class DataEncoder(json.JSONEncoder):
-
"""
-
A superset of `JSONEncoder` to support ATProto data.
-
"""
-
-
def default(self, o):
-
result = _convertDataToFakeJSON(o)
-
return super().default(result)
···
-61
src/atpasser/data/_wrapper.py
···
-
from json import loads
-
from typing import Callable, Any
-
from ._data import *
-
import functools
-
-
# Pyright did the whole job. Thank it.
-
-
-
class DataDecoder(json.JSONDecoder):
-
"""
-
A superset of `JSONDecoder` to support ATProto data.
-
"""
-
-
def __init__(
-
self,
-
*,
-
object_hook: Callable[[dict[str, Any]], Any] | None = dataHook,
-
parse_float: Callable[[str], Any] | None = None,
-
parse_int: Callable[[str], Any] | None = None,
-
parse_constant: Callable[[str], Any] | None = None,
-
strict: bool = True,
-
object_pairs_hook: Callable[[list[tuple[str, Any]]], Any] | None = None,
-
) -> None:
-
super().__init__(
-
object_hook=object_hook,
-
parse_float=parse_float,
-
parse_int=parse_int,
-
parse_constant=parse_constant,
-
strict=strict,
-
object_pairs_hook=object_pairs_hook,
-
)
-
-
-
# Screw it. I have to make 4 `json`-like functions.
-
-
-
def _dataDecoratorForDump(func):
-
@functools.wraps(func)
-
def wrapper(obj, *args, **kwargs):
-
kwargs.setdefault("cls", DataEncoder)
-
return func(obj, *args, **kwargs)
-
-
return wrapper
-
-
-
def _dataDecoratorForLoad(func):
-
@functools.wraps(func)
-
def wrapper(obj, *args, **kwargs):
-
kwargs.setdefault("cls", DataDecoder)
-
return func(obj, *args, **kwargs)
-
-
return wrapper
-
-
-
dump = _dataDecoratorForDump(json.dump)
-
dumps = _dataDecoratorForDump(json.dumps)
-
load = _dataDecoratorForLoad(json.load)
-
loads = _dataDecoratorForLoad(json.loads)
-
"""
-
Wrapper of the JSON functions to support ATProto data.
-
"""
···
-137
src/atpasser/data/cbor.py
···
-
from datetime import tzinfo
-
import typing
-
import cbor2
-
import cid
-
-
from .data import dataHook, Data
-
-
-
def tagHook(decoder: cbor2.CBORDecoder, tag: cbor2.CBORTag, shareable_index=None):
-
"""
-
A simple tag hook for CID support.
-
"""
-
return cid.from_bytes(tag.value) if tag.tag == 42 else tag
-
-
-
class CBOREncoder(cbor2.CBOREncoder):
-
"""
-
Wrapper of cbor2.CBOREncoder.
-
"""
-
-
def __init__(
-
self,
-
fp: typing.IO[bytes],
-
datetime_as_timestamp: bool = False,
-
timezone: tzinfo | None = None,
-
value_sharing: bool = False,
-
default: (
-
typing.Callable[[cbor2.CBOREncoder, typing.Any], typing.Any] | None
-
) = None,
-
canonical: bool = False,
-
date_as_datetime: bool = False,
-
string_referencing: bool = False,
-
indefinite_containers: bool = False,
-
):
-
super().__init__(
-
fp,
-
datetime_as_timestamp,
-
timezone,
-
value_sharing,
-
default,
-
canonical,
-
date_as_datetime,
-
string_referencing,
-
indefinite_containers,
-
)
-
-
@cbor2.shareable_encoder
-
def cidOrDataEncoder(self: cbor2.CBOREncoder, value: cid.CIDv0 | cid.CIDv1 | Data):
-
"""
-
Encode CID or Data to CBOR Tag.
-
"""
-
if isinstance(value, (cid.CIDv0, cid.CIDv1)):
-
self.encode(cbor2.CBORTag(42, value.encode()))
-
elif isinstance(value, Data):
-
self.encode(value.data())
-
-
-
def _cborObjectHook(decoder: cbor2.CBORDecoder, value):
-
return dataHook(value)
-
-
-
class CBORDecoder(cbor2.CBORDecoder):
-
"""
-
Wrapper of cbor2.CBORDecoder.
-
"""
-
-
def __init__(
-
self,
-
fp: typing.IO[bytes],
-
tag_hook: (
-
typing.Callable[[cbor2.CBORDecoder, cbor2.CBORTag], typing.Any] | None
-
) = tagHook,
-
object_hook: (
-
typing.Callable[
-
[cbor2.CBORDecoder, dict[typing.Any, typing.Any]], typing.Any
-
]
-
| None
-
) = _cborObjectHook,
-
str_errors: typing.Literal["strict", "error", "replace"] = "strict",
-
):
-
super().__init__(fp, tag_hook, object_hook, str_errors)
-
-
-
# Make things for CBOR again.
-
-
from io import BytesIO
-
-
-
def dumps(
-
obj: object,
-
datetime_as_timestamp: bool = False,
-
timezone: tzinfo | None = None,
-
value_sharing: bool = False,
-
default: typing.Callable[[cbor2.CBOREncoder, typing.Any], typing.Any] | None = None,
-
canonical: bool = False,
-
date_as_datetime: bool = False,
-
string_referencing: bool = False,
-
indefinite_containers: bool = False,
-
) -> bytes:
-
with BytesIO() as fp:
-
CBOREncoder(
-
fp,
-
datetime_as_timestamp=datetime_as_timestamp,
-
timezone=timezone,
-
value_sharing=value_sharing,
-
default=default,
-
canonical=canonical,
-
date_as_datetime=date_as_datetime,
-
string_referencing=string_referencing,
-
indefinite_containers=indefinite_containers,
-
).encode(obj)
-
return fp.getvalue()
-
-
-
def dump(
-
obj: object,
-
fp: typing.IO[bytes],
-
datetime_as_timestamp: bool = False,
-
timezone: tzinfo | None = None,
-
value_sharing: bool = False,
-
default: typing.Callable[[cbor2.CBOREncoder, typing.Any], typing.Any] | None = None,
-
canonical: bool = False,
-
date_as_datetime: bool = False,
-
string_referencing: bool = False,
-
indefinite_containers: bool = False,
-
) -> None:
-
CBOREncoder(
-
fp,
-
datetime_as_timestamp=datetime_as_timestamp,
-
timezone=timezone,
-
value_sharing=value_sharing,
-
default=default,
-
canonical=canonical,
-
date_as_datetime=date_as_datetime,
-
string_referencing=string_referencing,
-
indefinite_containers=indefinite_containers,
-
).encode(obj)
···
-4
tests/__init__.py
···
-
if __name__ != "__main__":
-
raise Exception("name != main")
-
-
import _strings
···
-179
tests/_strings.py
···
-
from atpasser import did, handle, nsid, rKey, uri
-
-
-
testStrings, testMethods = {}, {}
-
-
-
testStrings[
-
"did"
-
-
] = """did:plc:z72i7hdynmk6r22z27h6tvur
-
-
did:web:blueskyweb.xyz
-
-
did:method:val:two
-
-
did:m:v
-
-
did:method::::val
-
-
did:method:-:_:.
-
-
did:key:zQ3shZc2QzApp2oymGvQbzP8eKheVshBHbU4ZYjeXqwSKEn6N
-
-
did:METHOD:val
-
-
did:m123:val
-
-
DID:method:val
-
did:method:
-
-
did:method:val/two
-
-
did:method:val?two
-
-
did:method:val#two"""
-
-
testMethods["did"] = did.DID
-
-
-
testStrings[
-
"handle"
-
-
] = """jay.bsky.social
-
-
8.cn
-
-
name.t--t
-
-
XX.LCS.MIT.EDU
-
a.co
-
-
xn--notarealidn.com
-
-
xn--fiqa61au8b7zsevnm8ak20mc4a87e.xn--fiqs8s
-
-
xn--ls8h.test
-
example.t
-
-
jo@hn.test
-
-
💩.tes
-
t
-
john..test
-
-
xn--bcher-.tld
-
-
john.0
-
-
cn.8
-
-
www.masełkowski.pl.com
-
-
org
-
-
name.org.
-
-
2gzyxa5ihm7nsggfxnu52rck2vv4rvmdlkiu3zzui5du4xyclen53wid.onion
-
laptop.local
-
-
blah.arpa"""
-
-
testMethods["handle"] = handle.Handle
-
-
-
testStrings[
-
"nsid"
-
-
] = """com.example.fooBar
-
-
net.users.bob.ping
-
-
a-0.b-1.c
-
-
a.b.c
-
-
com.example.fooBarV2
-
-
cn.8.lex.stuff
-
-
com.exa💩ple.thin
-
com.example
-
-
com.example.3"""
-
-
testMethods["nsid"] = nsid.NSID
-
-
-
testStrings[
-
-
"rkey"
-
-
] = """3jui7kd54zh2y
-
self
-
example.com
-
-
~1.2-3_
-
-
dHJ1ZQ
-
pre:fix
-
-
_
-
-
alpha/beta
-
.
-
..
-
-
#extra
-
-
@handle
-
-
any space
-
-
any+space
-
-
number[3]
-
-
number(3)
-
-
"quote"
-
-
dHJ1ZQ=="""
-
-
testMethods["rkey"] = rKey.RKey
-
-
-
testStrings[
-
"uri"
-
-
] = """at://foo.com/com.example.foo/123
-
-
at://foo.com/example/123
-
-
at://computer
-
-
at://example.com:3000
-
-
at://foo.com/
-
-
at://user:pass@foo.com"""
-
-
testMethods["uri"] = uri.URI
-
-
-
for item in testMethods:
-
-
print(f"START TEST {item}")
-
-
for value in testStrings[item].splitlines():
-
-
print(f"Value: {value}")
-
-
try:
-
-
print(f"str(): {str(testMethods[item](value))}")
-
-
except Exception as e:
-
-
print(f"× {e}")
-
···
+174 -1
poetry.lock
···
# This file is automatically @generated by Poetry 2.1.3 and should not be changed by hand.
[[package]]
name = "base58"
version = "1.0.3"
···
{file = "pycparser-2.23.tar.gz", hash = "sha256:78816d4f24add8f10a06d6f05b4d424ad9e96cfebf68a4ddc99c65c0720d00c2"},
]
[[package]]
name = "pyld"
version = "2.0.4"
···
{file = "six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81"},
]
[[package]]
name = "urllib3"
version = "2.5.0"
···
[metadata]
lock-version = "2.1"
python-versions = ">=3.13"
-
content-hash = "5f4e5fd166bf6b2010ec5acaf545a0cfe376dcc5437530f3add4b58f10ce439f"
···
# This file is automatically @generated by Poetry 2.1.3 and should not be changed by hand.
+
[[package]]
+
name = "annotated-types"
+
version = "0.7.0"
+
description = "Reusable constraint types to use with typing.Annotated"
+
optional = false
+
python-versions = ">=3.8"
+
groups = ["main"]
+
files = [
+
{file = "annotated_types-0.7.0-py3-none-any.whl", hash = "sha256:1f02e8b43a8fbbc3f3e0d4f0f4bfc8131bcb4eebe8849b8e5c773f3a1c582a53"},
+
{file = "annotated_types-0.7.0.tar.gz", hash = "sha256:aff07c09a53a08bc8cfccb9c85b05f1aa9a2a6f23728d790723543408344ce89"},
+
]
+
[[package]]
name = "base58"
version = "1.0.3"
···
{file = "pycparser-2.23.tar.gz", hash = "sha256:78816d4f24add8f10a06d6f05b4d424ad9e96cfebf68a4ddc99c65c0720d00c2"},
]
+
[[package]]
+
name = "pydantic"
+
version = "2.11.9"
+
description = "Data validation using Python type hints"
+
optional = false
+
python-versions = ">=3.9"
+
groups = ["main"]
+
files = [
+
{file = "pydantic-2.11.9-py3-none-any.whl", hash = "sha256:c42dd626f5cfc1c6950ce6205ea58c93efa406da65f479dcb4029d5934857da2"},
+
{file = "pydantic-2.11.9.tar.gz", hash = "sha256:6b8ffda597a14812a7975c90b82a8a2e777d9257aba3453f973acd3c032a18e2"},
+
]
+
+
[package.dependencies]
+
annotated-types = ">=0.6.0"
+
pydantic-core = "2.33.2"
+
typing-extensions = ">=4.12.2"
+
typing-inspection = ">=0.4.0"
+
+
[package.extras]
+
email = ["email-validator (>=2.0.0)"]
+
timezone = ["tzdata ; python_version >= \"3.9\" and platform_system == \"Windows\""]
+
+
[[package]]
+
name = "pydantic-core"
+
version = "2.33.2"
+
description = "Core functionality for Pydantic validation and serialization"
+
optional = false
+
python-versions = ">=3.9"
+
groups = ["main"]
+
files = [
+
{file = "pydantic_core-2.33.2-cp310-cp310-macosx_10_12_x86_64.whl", hash = "sha256:2b3d326aaef0c0399d9afffeb6367d5e26ddc24d351dbc9c636840ac355dc5d8"},
+
{file = "pydantic_core-2.33.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:0e5b2671f05ba48b94cb90ce55d8bdcaaedb8ba00cc5359f6810fc918713983d"},
+
{file = "pydantic_core-2.33.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0069c9acc3f3981b9ff4cdfaf088e98d83440a4c7ea1bc07460af3d4dc22e72d"},
+
{file = "pydantic_core-2.33.2-cp310-cp310-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:d53b22f2032c42eaaf025f7c40c2e3b94568ae077a606f006d206a463bc69572"},
+
{file = "pydantic_core-2.33.2-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:0405262705a123b7ce9f0b92f123334d67b70fd1f20a9372b907ce1080c7ba02"},
+
{file = "pydantic_core-2.33.2-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:4b25d91e288e2c4e0662b8038a28c6a07eaac3e196cfc4ff69de4ea3db992a1b"},
+
{file = "pydantic_core-2.33.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6bdfe4b3789761f3bcb4b1ddf33355a71079858958e3a552f16d5af19768fef2"},
+
{file = "pydantic_core-2.33.2-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:efec8db3266b76ef9607c2c4c419bdb06bf335ae433b80816089ea7585816f6a"},
+
{file = "pydantic_core-2.33.2-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:031c57d67ca86902726e0fae2214ce6770bbe2f710dc33063187a68744a5ecac"},
+
{file = "pydantic_core-2.33.2-cp310-cp310-musllinux_1_1_armv7l.whl", hash = "sha256:f8de619080e944347f5f20de29a975c2d815d9ddd8be9b9b7268e2e3ef68605a"},
+
{file = "pydantic_core-2.33.2-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:73662edf539e72a9440129f231ed3757faab89630d291b784ca99237fb94db2b"},
+
{file = "pydantic_core-2.33.2-cp310-cp310-win32.whl", hash = "sha256:0a39979dcbb70998b0e505fb1556a1d550a0781463ce84ebf915ba293ccb7e22"},
+
{file = "pydantic_core-2.33.2-cp310-cp310-win_amd64.whl", hash = "sha256:b0379a2b24882fef529ec3b4987cb5d003b9cda32256024e6fe1586ac45fc640"},
+
{file = "pydantic_core-2.33.2-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:4c5b0a576fb381edd6d27f0a85915c6daf2f8138dc5c267a57c08a62900758c7"},
+
{file = "pydantic_core-2.33.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:e799c050df38a639db758c617ec771fd8fb7a5f8eaaa4b27b101f266b216a246"},
+
{file = "pydantic_core-2.33.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:dc46a01bf8d62f227d5ecee74178ffc448ff4e5197c756331f71efcc66dc980f"},
+
{file = "pydantic_core-2.33.2-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:a144d4f717285c6d9234a66778059f33a89096dfb9b39117663fd8413d582dcc"},
+
{file = "pydantic_core-2.33.2-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:73cf6373c21bc80b2e0dc88444f41ae60b2f070ed02095754eb5a01df12256de"},
+
{file = "pydantic_core-2.33.2-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:3dc625f4aa79713512d1976fe9f0bc99f706a9dee21dfd1810b4bbbf228d0e8a"},
+
{file = "pydantic_core-2.33.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:881b21b5549499972441da4758d662aeea93f1923f953e9cbaff14b8b9565aef"},
+
{file = "pydantic_core-2.33.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:bdc25f3681f7b78572699569514036afe3c243bc3059d3942624e936ec93450e"},
+
{file = "pydantic_core-2.33.2-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:fe5b32187cbc0c862ee201ad66c30cf218e5ed468ec8dc1cf49dec66e160cc4d"},
+
{file = "pydantic_core-2.33.2-cp311-cp311-musllinux_1_1_armv7l.whl", hash = "sha256:bc7aee6f634a6f4a95676fcb5d6559a2c2a390330098dba5e5a5f28a2e4ada30"},
+
{file = "pydantic_core-2.33.2-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:235f45e5dbcccf6bd99f9f472858849f73d11120d76ea8707115415f8e5ebebf"},
+
{file = "pydantic_core-2.33.2-cp311-cp311-win32.whl", hash = "sha256:6368900c2d3ef09b69cb0b913f9f8263b03786e5b2a387706c5afb66800efd51"},
+
{file = "pydantic_core-2.33.2-cp311-cp311-win_amd64.whl", hash = "sha256:1e063337ef9e9820c77acc768546325ebe04ee38b08703244c1309cccc4f1bab"},
+
{file = "pydantic_core-2.33.2-cp311-cp311-win_arm64.whl", hash = "sha256:6b99022f1d19bc32a4c2a0d544fc9a76e3be90f0b3f4af413f87d38749300e65"},
+
{file = "pydantic_core-2.33.2-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:a7ec89dc587667f22b6a0b6579c249fca9026ce7c333fc142ba42411fa243cdc"},
+
{file = "pydantic_core-2.33.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:3c6db6e52c6d70aa0d00d45cdb9b40f0433b96380071ea80b09277dba021ddf7"},
+
{file = "pydantic_core-2.33.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4e61206137cbc65e6d5256e1166f88331d3b6238e082d9f74613b9b765fb9025"},
+
{file = "pydantic_core-2.33.2-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:eb8c529b2819c37140eb51b914153063d27ed88e3bdc31b71198a198e921e011"},
+
{file = "pydantic_core-2.33.2-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:c52b02ad8b4e2cf14ca7b3d918f3eb0ee91e63b3167c32591e57c4317e134f8f"},
+
{file = "pydantic_core-2.33.2-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:96081f1605125ba0855dfda83f6f3df5ec90c61195421ba72223de35ccfb2f88"},
+
{file = "pydantic_core-2.33.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8f57a69461af2a5fa6e6bbd7a5f60d3b7e6cebb687f55106933188e79ad155c1"},
+
{file = "pydantic_core-2.33.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:572c7e6c8bb4774d2ac88929e3d1f12bc45714ae5ee6d9a788a9fb35e60bb04b"},
+
{file = "pydantic_core-2.33.2-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:db4b41f9bd95fbe5acd76d89920336ba96f03e149097365afe1cb092fceb89a1"},
+
{file = "pydantic_core-2.33.2-cp312-cp312-musllinux_1_1_armv7l.whl", hash = "sha256:fa854f5cf7e33842a892e5c73f45327760bc7bc516339fda888c75ae60edaeb6"},
+
{file = "pydantic_core-2.33.2-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:5f483cfb75ff703095c59e365360cb73e00185e01aaea067cd19acffd2ab20ea"},
+
{file = "pydantic_core-2.33.2-cp312-cp312-win32.whl", hash = "sha256:9cb1da0f5a471435a7bc7e439b8a728e8b61e59784b2af70d7c169f8dd8ae290"},
+
{file = "pydantic_core-2.33.2-cp312-cp312-win_amd64.whl", hash = "sha256:f941635f2a3d96b2973e867144fde513665c87f13fe0e193c158ac51bfaaa7b2"},
+
{file = "pydantic_core-2.33.2-cp312-cp312-win_arm64.whl", hash = "sha256:cca3868ddfaccfbc4bfb1d608e2ccaaebe0ae628e1416aeb9c4d88c001bb45ab"},
+
{file = "pydantic_core-2.33.2-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:1082dd3e2d7109ad8b7da48e1d4710c8d06c253cbc4a27c1cff4fbcaa97a9e3f"},
+
{file = "pydantic_core-2.33.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f517ca031dfc037a9c07e748cefd8d96235088b83b4f4ba8939105d20fa1dcd6"},
+
{file = "pydantic_core-2.33.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0a9f2c9dd19656823cb8250b0724ee9c60a82f3cdf68a080979d13092a3b0fef"},
+
{file = "pydantic_core-2.33.2-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:2b0a451c263b01acebe51895bfb0e1cc842a5c666efe06cdf13846c7418caa9a"},
+
{file = "pydantic_core-2.33.2-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:1ea40a64d23faa25e62a70ad163571c0b342b8bf66d5fa612ac0dec4f069d916"},
+
{file = "pydantic_core-2.33.2-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:0fb2d542b4d66f9470e8065c5469ec676978d625a8b7a363f07d9a501a9cb36a"},
+
{file = "pydantic_core-2.33.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9fdac5d6ffa1b5a83bca06ffe7583f5576555e6c8b3a91fbd25ea7780f825f7d"},
+
{file = "pydantic_core-2.33.2-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:04a1a413977ab517154eebb2d326da71638271477d6ad87a769102f7c2488c56"},
+
{file = "pydantic_core-2.33.2-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:c8e7af2f4e0194c22b5b37205bfb293d166a7344a5b0d0eaccebc376546d77d5"},
+
{file = "pydantic_core-2.33.2-cp313-cp313-musllinux_1_1_armv7l.whl", hash = "sha256:5c92edd15cd58b3c2d34873597a1e20f13094f59cf88068adb18947df5455b4e"},
+
{file = "pydantic_core-2.33.2-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:65132b7b4a1c0beded5e057324b7e16e10910c106d43675d9bd87d4f38dde162"},
+
{file = "pydantic_core-2.33.2-cp313-cp313-win32.whl", hash = "sha256:52fb90784e0a242bb96ec53f42196a17278855b0f31ac7c3cc6f5c1ec4811849"},
+
{file = "pydantic_core-2.33.2-cp313-cp313-win_amd64.whl", hash = "sha256:c083a3bdd5a93dfe480f1125926afcdbf2917ae714bdb80b36d34318b2bec5d9"},
+
{file = "pydantic_core-2.33.2-cp313-cp313-win_arm64.whl", hash = "sha256:e80b087132752f6b3d714f041ccf74403799d3b23a72722ea2e6ba2e892555b9"},
+
{file = "pydantic_core-2.33.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:61c18fba8e5e9db3ab908620af374db0ac1baa69f0f32df4f61ae23f15e586ac"},
+
{file = "pydantic_core-2.33.2-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:95237e53bb015f67b63c91af7518a62a8660376a6a0db19b89acc77a4d6199f5"},
+
{file = "pydantic_core-2.33.2-cp313-cp313t-win_amd64.whl", hash = "sha256:c2fc0a768ef76c15ab9238afa6da7f69895bb5d1ee83aeea2e3509af4472d0b9"},
+
{file = "pydantic_core-2.33.2-cp39-cp39-macosx_10_12_x86_64.whl", hash = "sha256:a2b911a5b90e0374d03813674bf0a5fbbb7741570dcd4b4e85a2e48d17def29d"},
+
{file = "pydantic_core-2.33.2-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:6fa6dfc3e4d1f734a34710f391ae822e0a8eb8559a85c6979e14e65ee6ba2954"},
+
{file = "pydantic_core-2.33.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c54c939ee22dc8e2d545da79fc5381f1c020d6d3141d3bd747eab59164dc89fb"},
+
{file = "pydantic_core-2.33.2-cp39-cp39-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:53a57d2ed685940a504248187d5685e49eb5eef0f696853647bf37c418c538f7"},
+
{file = "pydantic_core-2.33.2-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:09fb9dd6571aacd023fe6aaca316bd01cf60ab27240d7eb39ebd66a3a15293b4"},
+
{file = "pydantic_core-2.33.2-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:0e6116757f7959a712db11f3e9c0a99ade00a5bbedae83cb801985aa154f071b"},
+
{file = "pydantic_core-2.33.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8d55ab81c57b8ff8548c3e4947f119551253f4e3787a7bbc0b6b3ca47498a9d3"},
+
{file = "pydantic_core-2.33.2-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:c20c462aa4434b33a2661701b861604913f912254e441ab8d78d30485736115a"},
+
{file = "pydantic_core-2.33.2-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:44857c3227d3fb5e753d5fe4a3420d6376fa594b07b621e220cd93703fe21782"},
+
{file = "pydantic_core-2.33.2-cp39-cp39-musllinux_1_1_armv7l.whl", hash = "sha256:eb9b459ca4df0e5c87deb59d37377461a538852765293f9e6ee834f0435a93b9"},
+
{file = "pydantic_core-2.33.2-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:9fcd347d2cc5c23b06de6d3b7b8275be558a0c90549495c699e379a80bf8379e"},
+
{file = "pydantic_core-2.33.2-cp39-cp39-win32.whl", hash = "sha256:83aa99b1285bc8f038941ddf598501a86f1536789740991d7d8756e34f1e74d9"},
+
{file = "pydantic_core-2.33.2-cp39-cp39-win_amd64.whl", hash = "sha256:f481959862f57f29601ccced557cc2e817bce7533ab8e01a797a48b49c9692b3"},
+
{file = "pydantic_core-2.33.2-pp310-pypy310_pp73-macosx_10_12_x86_64.whl", hash = "sha256:5c4aa4e82353f65e548c476b37e64189783aa5384903bfea4f41580f255fddfa"},
+
{file = "pydantic_core-2.33.2-pp310-pypy310_pp73-macosx_11_0_arm64.whl", hash = "sha256:d946c8bf0d5c24bf4fe333af284c59a19358aa3ec18cb3dc4370080da1e8ad29"},
+
{file = "pydantic_core-2.33.2-pp310-pypy310_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:87b31b6846e361ef83fedb187bb5b4372d0da3f7e28d85415efa92d6125d6e6d"},
+
{file = "pydantic_core-2.33.2-pp310-pypy310_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:aa9d91b338f2df0508606f7009fde642391425189bba6d8c653afd80fd6bb64e"},
+
{file = "pydantic_core-2.33.2-pp310-pypy310_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:2058a32994f1fde4ca0480ab9d1e75a0e8c87c22b53a3ae66554f9af78f2fe8c"},
+
{file = "pydantic_core-2.33.2-pp310-pypy310_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:0e03262ab796d986f978f79c943fc5f620381be7287148b8010b4097f79a39ec"},
+
{file = "pydantic_core-2.33.2-pp310-pypy310_pp73-musllinux_1_1_armv7l.whl", hash = "sha256:1a8695a8d00c73e50bff9dfda4d540b7dee29ff9b8053e38380426a85ef10052"},
+
{file = "pydantic_core-2.33.2-pp310-pypy310_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:fa754d1850735a0b0e03bcffd9d4b4343eb417e47196e4485d9cca326073a42c"},
+
{file = "pydantic_core-2.33.2-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:a11c8d26a50bfab49002947d3d237abe4d9e4b5bdc8846a63537b6488e197808"},
+
{file = "pydantic_core-2.33.2-pp311-pypy311_pp73-macosx_10_12_x86_64.whl", hash = "sha256:dd14041875d09cc0f9308e37a6f8b65f5585cf2598a53aa0123df8b129d481f8"},
+
{file = "pydantic_core-2.33.2-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:d87c561733f66531dced0da6e864f44ebf89a8fba55f31407b00c2f7f9449593"},
+
{file = "pydantic_core-2.33.2-pp311-pypy311_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2f82865531efd18d6e07a04a17331af02cb7a651583c418df8266f17a63c6612"},
+
{file = "pydantic_core-2.33.2-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2bfb5112df54209d820d7bf9317c7a6c9025ea52e49f46b6a2060104bba37de7"},
+
{file = "pydantic_core-2.33.2-pp311-pypy311_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:64632ff9d614e5eecfb495796ad51b0ed98c453e447a76bcbeeb69615079fc7e"},
+
{file = "pydantic_core-2.33.2-pp311-pypy311_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:f889f7a40498cc077332c7ab6b4608d296d852182211787d4f3ee377aaae66e8"},
+
{file = "pydantic_core-2.33.2-pp311-pypy311_pp73-musllinux_1_1_armv7l.whl", hash = "sha256:de4b83bb311557e439b9e186f733f6c645b9417c84e2eb8203f3f820a4b988bf"},
+
{file = "pydantic_core-2.33.2-pp311-pypy311_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:82f68293f055f51b51ea42fafc74b6aad03e70e191799430b90c13d643059ebb"},
+
{file = "pydantic_core-2.33.2-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:329467cecfb529c925cf2bbd4d60d2c509bc2fb52a20c1045bf09bb70971a9c1"},
+
{file = "pydantic_core-2.33.2-pp39-pypy39_pp73-macosx_10_12_x86_64.whl", hash = "sha256:87acbfcf8e90ca885206e98359d7dca4bcbb35abdc0ff66672a293e1d7a19101"},
+
{file = "pydantic_core-2.33.2-pp39-pypy39_pp73-macosx_11_0_arm64.whl", hash = "sha256:7f92c15cd1e97d4b12acd1cc9004fa092578acfa57b67ad5e43a197175d01a64"},
+
{file = "pydantic_core-2.33.2-pp39-pypy39_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d3f26877a748dc4251cfcfda9dfb5f13fcb034f5308388066bcfe9031b63ae7d"},
+
{file = "pydantic_core-2.33.2-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dac89aea9af8cd672fa7b510e7b8c33b0bba9a43186680550ccf23020f32d535"},
+
{file = "pydantic_core-2.33.2-pp39-pypy39_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:970919794d126ba8645f3837ab6046fb4e72bbc057b3709144066204c19a455d"},
+
{file = "pydantic_core-2.33.2-pp39-pypy39_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:3eb3fe62804e8f859c49ed20a8451342de53ed764150cb14ca71357c765dc2a6"},
+
{file = "pydantic_core-2.33.2-pp39-pypy39_pp73-musllinux_1_1_armv7l.whl", hash = "sha256:3abcd9392a36025e3bd55f9bd38d908bd17962cc49bc6da8e7e96285336e2bca"},
+
{file = "pydantic_core-2.33.2-pp39-pypy39_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:3a1c81334778f9e3af2f8aeb7a960736e5cab1dfebfb26aabca09afd2906c039"},
+
{file = "pydantic_core-2.33.2-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:2807668ba86cb38c6817ad9bc66215ab8584d1d304030ce4f0887336f28a5e27"},
+
{file = "pydantic_core-2.33.2.tar.gz", hash = "sha256:7cb8bc3605c29176e1b105350d2e6474142d7c1bd1d9327c4a9bdb46bf827acc"},
+
]
+
+
[package.dependencies]
+
typing-extensions = ">=4.6.0,<4.7.0 || >4.7.0"
+
[[package]]
name = "pyld"
version = "2.0.4"
···
{file = "six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81"},
]
+
[[package]]
+
name = "typing-extensions"
+
version = "4.15.0"
+
description = "Backported and Experimental Type Hints for Python 3.9+"
+
optional = false
+
python-versions = ">=3.9"
+
groups = ["main"]
+
files = [
+
{file = "typing_extensions-4.15.0-py3-none-any.whl", hash = "sha256:f0fa19c6845758ab08074a0cfa8b7aecb71c999ca73d62883bc25cc018c4e548"},
+
{file = "typing_extensions-4.15.0.tar.gz", hash = "sha256:0cea48d173cc12fa28ecabc3b837ea3cf6f38c6d1136f85cbaaf598984861466"},
+
]
+
+
[[package]]
+
name = "typing-inspection"
+
version = "0.4.1"
+
description = "Runtime typing introspection tools"
+
optional = false
+
python-versions = ">=3.9"
+
groups = ["main"]
+
files = [
+
{file = "typing_inspection-0.4.1-py3-none-any.whl", hash = "sha256:389055682238f53b04f7badcb49b989835495a96700ced5dab2d8feae4b26f51"},
+
{file = "typing_inspection-0.4.1.tar.gz", hash = "sha256:6ae134cc0203c33377d43188d4064e9b357dba58cff3185f22924610e70a9d28"},
+
]
+
+
[package.dependencies]
+
typing-extensions = ">=4.12.0"
+
[[package]]
name = "urllib3"
version = "2.5.0"
···
[metadata]
lock-version = "2.1"
python-versions = ">=3.13"
+
content-hash = "4919ab150fee9e4e358e57bada62225cb2d92c52509b26169db269691b86cefe"
+1
pyproject.toml
···
"jsonpath-ng (>=1.7.0,<2.0.0)", # for URI fragment support
"cryptography (>=45.0.7,<46.0.0)", # just keep it
"langcodes (>=3.5.0,<4.0.0)", # language codes support
]
license = "MIT OR Apache-2.0"
license-files = ["LICEN[CS]E.*"]
···
"jsonpath-ng (>=1.7.0,<2.0.0)", # for URI fragment support
"cryptography (>=45.0.7,<46.0.0)", # just keep it
"langcodes (>=3.5.0,<4.0.0)", # language codes support
+
"pydantic (>=2.11.9,<3.0.0)",
]
license = "MIT OR Apache-2.0"
license-files = ["LICEN[CS]E.*"]
+205
ARCHITECTURE_OVERVIEW.md
···
···
+
# ATProto Data 和 Lexicon 模块架构总览
+
+
## 项目概述
+
+
本项目为 ATProto (Authenticated Transfer Protocol) 提供 Python 实现,专注于数据模型和 Lexicon 定义的处理。基于现有的 URI 模块架构模式,提供类型安全的数据验证、序列化和 Lexicon 解析功能。
+
+
## 整体架构设计
+
+
### 1. 系统架构图
+
+
```mermaid
+
graph TB
+
subgraph "ATProto 核心模块"
+
URI[URI 模块]
+
Data[Data 模块]
+
Lexicon[Lexicon 模块]
+
end
+
+
subgraph "外部依赖"
+
Pydantic[Pydantic]
+
CBOR[cbor2]
+
CID[py-cid]
+
end
+
+
subgraph "数据流"
+
LexiconJSON[Lexicon JSON 文件]
+
RawData[原始数据]
+
end
+
+
LexiconJSON --> Lexicon
+
Lexicon --> Data
+
RawData --> Data
+
Data --> Serialized[序列化数据]
+
+
URI --> Data
+
URI --> Lexicon
+
+
Pydantic --> Data
+
Pydantic --> Lexicon
+
CBOR --> Data
+
CID --> Data
+
```
+
+
### 2. 模块职责划分
+
+
#### 2.1 Data 模块 (`src/atpasser/data`)
+
- **数据序列化**: JSON 和 DAG-CBOR 格式的序列化/反序列化
+
- **数据验证**: 类型验证、格式验证、约束验证
+
- **特殊类型处理**: CID 链接、Blob 引用、日期时间格式等
+
- **错误处理**: 详细的验证错误和序列化错误
+
+
#### 2.2 Lexicon 模块 (`src/atpasser/lexicon`)
+
- **定义解析**: 解析 Lexicon JSON 定义文件
+
- **模型生成**: 动态生成 Pydantic 模型类
+
- **引用解析**: 处理跨定义引用和联合类型
+
- **注册管理**: 模型注册表和缓存管理
+
- **兼容性验证**: 前向和后向兼容性检查
+
+
### 3. 核心功能特性
+
+
#### 3.1 类型安全
+
- 基于 Pydantic 的强类型系统
+
- 运行时类型验证
+
- 自动类型转换和规范化
+
+
#### 3.2 格式支持
+
- **JSON**: 符合 ATProto JSON 编码规范
+
- **DAG-CBOR**: 支持规范的 DAG-CBOR 编码
+
- **混合格式**: 支持两种格式间的转换
+
+
#### 3.3 验证系统
+
- 语法验证 (基础数据类型)
+
- 语义验证 (业务规则和约束)
+
- 格式验证 (字符串格式如 datetime、uri、did 等)
+
- 引用验证 (CID、blob、跨定义引用)
+
+
### 4. 集成架构
+
+
#### 4.1 与现有 URI 模块的集成
+
+
```python
+
# 示例:URI 与 Data 模块的集成
+
from atpasser.uri import URI, NSID
+
from atpasser.data import ATProtoSerializer
+
from atpasser.lexicon import LexiconRegistry
+
+
# 解析 URI
+
uri = URI("at://example.com/com.example.blog.post/123")
+
+
# 根据 NSID 获取对应的数据模型
+
model_class = LexiconRegistry.get_model(uri.collection.nsid)
+
+
# 使用 Data 模块处理数据
+
serializer = ATProtoSerializer()
+
data = serializer.from_json(raw_data, model_class)
+
```
+
+
#### 4.2 数据流架构
+
+
```
+
原始数据 → Data 模块验证 → Lexicon 模型转换 → 序列化输出
+
Lexicon JSON → Lexicon 模块解析 → 生成 Pydantic 模型 → 注册到注册表
+
```
+
+
### 5. 错误处理架构
+
+
#### 5.1 统一的错误体系
+
+
```python
+
class ATProtoError(Exception):
+
"""基础错误类"""
+
pass
+
+
class DataError(ATProtoError):
+
"""数据相关错误"""
+
pass
+
+
class LexiconError(ATProtoError):
+
"""Lexicon 相关错误"""
+
pass
+
+
class URIError(ATProtoError):
+
"""URI 相关错误"""
+
pass
+
```
+
+
#### 5.2 错误诊断
+
- **字段级错误定位**: 精确到具体字段的路径信息
+
- **上下文信息**: 包含验证时的输入数据和期望格式
+
- **建议修复**: 提供具体的修复建议
+
+
### 6. 性能优化策略
+
+
#### 6.1 缓存机制
+
- **模型缓存**: 缓存已解析的 Lexicon 模型
+
- **序列化缓存**: 缓存序列化结果
+
- **引用解析缓存**: 缓存跨定义引用解析结果
+
+
#### 6.2 懒加载
+
- 按需解析 Lexicon 定义
+
- 延迟模型生成直到实际使用
+
- 动态导入依赖模块
+
+
### 7. 扩展性设计
+
+
#### 7.1 插件系统
+
- 支持自定义类型处理器
+
- 支持自定义验证规则
+
- 支持自定义序列化格式
+
+
#### 7.2 中间件支持
+
- 预处理钩子 (数据清洗、转换)
+
- 后处理钩子 (日志记录、监控)
+
- 验证钩子 (自定义验证逻辑)
+
+
### 8. 实施路线图
+
+
#### 阶段 1: 基础实现 (2-3 周)
+
- 实现 Data 模块基础类型和 JSON 序列化
+
- 实现 Lexicon 模块基础解析器
+
- 建立基本的错误处理系统
+
+
#### 阶段 2: 完整功能 (3-4 周)
+
- 添加 CBOR 序列化支持
+
- 实现完整的验证系统
+
- 添加引用解析和联合类型支持
+
+
#### 阶段 3: 优化增强 (2 周)
+
- 实现缓存和性能优化
+
- 添加高级格式验证
+
- 完善错误处理和诊断信息
+
+
#### 阶段 4: 测试部署 (1-2 周)
+
- 编写完整的测试套件
+
- 性能测试和优化
+
- 文档编写和示例代码
+
+
### 9. 依赖管理
+
+
#### 9.1 核心依赖
+
- `pydantic >=2.11.9`: 数据验证和模型定义
+
- `cbor2 >=5.7.0`: CBOR 序列化支持
+
- `py-cid >=0.3.0`: CID 处理支持
+
+
#### 9.2 可选依赖
+
- `jsonpath-ng >=1.7.0`: JSONPath 支持
+
- `langcodes >=3.5.0`: 语言代码验证
+
+
### 10. 质量保证
+
+
#### 10.1 测试策略
+
- **单元测试**: 覆盖所有核心功能
+
- **集成测试**: 测试模块间集成
+
- **兼容性测试**: 确保与规范兼容
+
- **性能测试**: 验证性能指标
+
+
#### 10.2 代码质量
+
- 类型注解覆盖率达到 100%
+
- 测试覆盖率超过 90%
+
- 遵循 PEP 8 编码规范
+
- 详细的文档和示例
+
+
## 总结
+
+
本架构设计提供了一个完整、可扩展的 ATProto 数据处理解决方案,充分利用了 Python 的类型系统和现有生态,同时保持了与 ATProto 规范的完全兼容性。模块化的设计使得各个组件可以独立开发和测试,同时也便于未来的扩展和维护。
+119
examples/basic_usage.py
···
···
+
"""Basic usage examples for ATProto data and lexicon modules."""
+
+
import json
+
from atpasser.data import serializer, CIDLink, DateTimeString
+
from atpasser.lexicon import parser, registry
+
+
+
def demonstrate_data_serialization():
+
"""Demonstrate basic data serialization."""
+
print("=== Data Serialization Demo ===")
+
+
# Create some sample data
+
sample_data = {
+
"title": "Hello ATProto",
+
"content": "This is a test post",
+
"createdAt": "2024-01-15T10:30:00.000Z",
+
"tags": ["atproto", "test", "demo"],
+
"cidLink": CIDLink(
+
"bafyreidfayvfuwqa7qlnopdjiqrxzs6blmoeu4rujcjtnci5beludirz2a"
+
),
+
}
+
+
# Serialize to JSON
+
json_output = serializer.to_json(sample_data, indent=2)
+
print("JSON Output:")
+
print(json_output)
+
+
# Deserialize back
+
deserialized = serializer.from_json(json_output)
+
print("\nDeserialized:")
+
print(deserialized)
+
+
print()
+
+
+
def demonstrate_lexicon_parsing():
+
"""Demonstrate Lexicon parsing."""
+
print("=== Lexicon Parsing Demo ===")
+
+
# Sample Lexicon definition
+
sample_lexicon = {
+
"lexicon": 1,
+
"id": "com.example.blog.post",
+
"description": "A simple blog post record",
+
"defs": {
+
"main": {
+
"type": "record",
+
"key": "literal:post",
+
"record": {
+
"type": "object",
+
"properties": {
+
"title": {"type": "string", "maxLength": 300},
+
"content": {"type": "string"},
+
"createdAt": {"type": "string", "format": "datetime"},
+
"tags": {
+
"type": "array",
+
"items": {"type": "string"},
+
"maxLength": 10,
+
},
+
},
+
"required": ["title", "content", "createdAt"],
+
},
+
}
+
},
+
}
+
+
try:
+
# Parse and register the Lexicon
+
parser.parse_and_register(sample_lexicon)
+
print("Lexicon parsed and registered successfully!")
+
+
# Get the generated model
+
model_class = registry.get_model("com.example.blog.post")
+
if model_class:
+
print(f"Generated model: {model_class.__name__}")
+
+
# Create an instance using the model
+
post_data = {
+
"title": "Test Post",
+
"content": "This is a test post content",
+
"createdAt": "2024-01-15T10:30:00.000Z",
+
"tags": ["test", "demo"],
+
}
+
+
validated_post = model_class(**post_data)
+
print(f"Validated post: {validated_post.model_dump()}")
+
+
except Exception as e:
+
print(f"Error: {e}")
+
+
print()
+
+
+
def demonstrate_custom_types():
+
"""Demonstrate custom type validation."""
+
print("=== Custom Type Validation Demo ===")
+
+
# DateTimeString validation
+
try:
+
valid_dt = DateTimeString("2024-01-15T10:30:00.000Z")
+
print(f"Valid datetime: {valid_dt}")
+
except Exception as e:
+
print(f"DateTime validation error: {e}")
+
+
# Invalid datetime
+
try:
+
invalid_dt = DateTimeString("invalid-date")
+
print(f"Invalid datetime: {invalid_dt}")
+
except Exception as e:
+
print(f"DateTime validation caught: {e}")
+
+
print()
+
+
+
if __name__ == "__main__":
+
demonstrate_data_serialization()
+
demonstrate_lexicon_parsing()
+
demonstrate_custom_types()
+
print("Demo completed!")
+11
src/atpasser/__init__.py
···
···
+
"""ATProto Python implementation - Tools for Authenticated Transfer Protocol."""
+
+
from . import uri
+
from . import data
+
from . import lexicon
+
+
__all__ = ["uri", "data", "lexicon"]
+
+
__version__ = "0.1.0"
+
__author__ = "diaowinner"
+
__email__ = "diaowinner@qq.com"
+215
src/atpasser/data/ARCHITECTURE.md
···
···
+
# ATProto 数据模型模块架构设计
+
+
## 概述
+
+
本模块负责实现 ATProto 数据模型的序列化、反序列化和验证功能,支持 JSON 和 DAG-CBOR 两种格式的数据编码。
+
+
## 核心架构设计
+
+
### 1. 基础类型系统
+
+
#### 1.1 基础类型映射
+
+
```python
+
# 基础类型映射
+
DATA_MODEL_TYPE_MAPPING = {
+
"null": NoneType,
+
"boolean": bool,
+
"integer": int,
+
"string": str,
+
"bytes": bytes,
+
"cid-link": CIDLink,
+
"blob": BlobRef,
+
"array": list,
+
"object": dict
+
}
+
```
+
+
#### 1.2 自定义字段类型
+
+
- **CIDLink**: 处理 CID 链接,支持二进制和字符串表示
+
- **BlobRef**: 处理 blob 引用,支持新旧格式兼容
+
- **DateTimeString**: RFC 3339 日期时间格式验证
+
- **LanguageTag**: BCP 47 语言标签验证
+
+
### 2. 序列化器架构
+
+
#### 2.1 序列化器层级结构
+
+
```
+
ATProtoSerializer
+
├── JSONSerializer
+
│ ├── Normalizer
+
│ └── Denormalizer
+
└── CBORSerializer
+
├── DAGCBOREncoder
+
└── DAGCBORDecoder
+
```
+
+
#### 2.2 序列化流程
+
+
1. **数据验证**: 使用 Pydantic 模型验证数据
+
2. **格式转换**: 特殊类型转换(CID、bytes 等)
+
3. **编码**: 根据目标格式进行编码
+
4. **规范化**: 确保输出符合 ATProto 规范
+
+
### 3. 验证系统
+
+
#### 3.1 验证层级
+
+
1. **语法验证**: 基础数据类型验证
+
2. **格式验证**: 字符串格式验证(datetime、uri、did 等)
+
3. **约束验证**: 长度、范围、枚举等约束验证
+
4. **引用验证**: CID 和 blob 引用有效性验证
+
+
#### 3.2 自定义验证器
+
+
```python
+
class DataModelValidator:
+
def validate_cid(self, value: str) -> bool:
+
"""验证 CID 格式"""
+
pass
+
+
def validate_datetime(self, value: str) -> bool:
+
"""验证 RFC 3339 datetime 格式"""
+
pass
+
+
def validate_did(self, value: str) -> bool:
+
"""验证 DID 格式"""
+
pass
+
+
def validate_handle(self, value: str) -> bool:
+
"""验证 handle 格式"""
+
pass
+
+
def validate_nsid(self, value: str) -> bool:
+
"""验证 NSID 格式"""
+
pass
+
```
+
+
### 4. 特殊类型处理
+
+
#### 4.1 CID 链接处理
+
+
```python
+
class CIDLink:
+
"""处理 CID 链接类型"""
+
+
def __init__(self, cid: Union[str, bytes]):
+
self.cid = cid
+
+
def to_json(self) -> dict:
+
"""序列化为 JSON 格式: {"$link": "cid-string"}"""
+
return {"$link": str(self.cid)}
+
+
def to_cbor(self) -> bytes:
+
"""序列化为 DAG-CBOR 格式"""
+
pass
+
```
+
+
#### 4.2 Blob 引用处理
+
+
```python
+
class BlobRef:
+
"""处理 blob 引用,支持新旧格式"""
+
+
def __init__(self, ref: CIDLink, mime_type: str, size: int):
+
self.ref = ref
+
self.mime_type = mime_type
+
self.size = size
+
+
def to_json(self) -> dict:
+
"""序列化为 JSON 格式"""
+
return {
+
"$type": "blob",
+
"ref": self.ref.to_json(),
+
"mimeType": self.mime_type,
+
"size": self.size
+
}
+
+
@classmethod
+
def from_legacy(cls, data: dict):
+
"""从旧格式解析"""
+
pass
+
```
+
+
### 5. 错误处理系统
+
+
#### 5.1 错误类型体系
+
+
```python
+
class DataModelError(Exception):
+
"""基础数据模型错误"""
+
pass
+
+
class SerializationError(DataModelError):
+
"""序列化错误"""
+
pass
+
+
class ValidationError(DataModelError):
+
"""验证错误"""
+
pass
+
+
class FormatError(DataModelError):
+
"""格式错误"""
+
pass
+
```
+
+
#### 5.2 错误消息格式
+
+
- **详细路径信息**: 包含字段路径
+
- **期望值描述**: 明确的期望格式说明
+
- **上下文信息**: 验证时的上下文数据
+
+
### 6. 模块文件结构
+
+
```
+
src/atpasser/data/
+
├── __init__.py # 模块导出
+
├── ARCHITECTURE.md # 架构文档
+
├── types.py # 基础类型定义
+
├── serializer.py # 序列化器实现
+
├── validator.py # 验证器实现
+
├── exceptions.py # 异常定义
+
├── cid.py # CID 链接处理
+
├── blob.py # Blob 引用处理
+
└── formats.py # 格式验证器
+
```
+
+
### 7. 依赖关系
+
+
- **内部依赖**: `src/atpasser/uri` (NSID、DID、Handle 验证)
+
- **外部依赖**:
+
- `pydantic`: 数据验证
+
- `cbor2`: CBOR 序列化
+
- `py-cid`: CID 处理
+
+
## 实现策略
+
+
### 1. 渐进式实现
+
+
1. **阶段一**: 实现基础类型和 JSON 序列化
+
2. **阶段二**: 添加 CBOR 序列化和验证器
+
3. **阶段三**: 实现高级格式验证
+
4. **阶段四**: 性能优化和内存管理
+
+
### 2. 测试策略
+
+
- **单元测试**: 测试各个组件功能
+
- **集成测试**: 测试端到端数据流
+
- **兼容性测试**: 确保与现有实现兼容
+
- **性能测试**: 验证序列化性能
+
+
### 3. 扩展性考虑
+
+
- **插件系统**: 支持自定义格式验证
+
- **中间件**: 支持预处理和后处理钩子
+
- **缓存**: 序列化结果缓存优化
+
+
## 优势
+
+
1. **类型安全**: 基于 Pydantic 的强类型系统
+
2. **性能**: 优化的序列化实现
+
3. **兼容性**: 支持新旧格式兼容
+
4. **可扩展**: 模块化设计支持未来扩展
+
5. **错误友好**: 详细的错误消息和诊断信息
+87
src/atpasser/data/exceptions.py
···
···
+
"""Exceptions for ATProto data model module."""
+
+
from typing import Optional
+
+
+
class DataModelError(Exception):
+
"""Base exception for data model errors."""
+
+
def __init__(self, message: str, details: Optional[str] = None):
+
self.message = message
+
self.details = details
+
super().__init__(message)
+
+
+
class SerializationError(DataModelError):
+
"""Raised when serialization fails."""
+
+
def __init__(self, message: str, details: Optional[str] = None):
+
super().__init__(f"Serialization error: {message}", details)
+
+
+
class ValidationError(DataModelError):
+
"""Raised when data validation fails."""
+
+
def __init__(
+
self,
+
message: str,
+
field_path: Optional[str] = None,
+
expected: Optional[str] = None,
+
actual: Optional[str] = None,
+
):
+
self.fieldPath = field_path
+
self.expected = expected
+
self.actual = actual
+
+
details = []
+
if field_path:
+
details.append(f"Field: {field_path}")
+
if expected:
+
details.append(f"Expected: {expected}")
+
if actual:
+
details.append(f"Actual: {actual}")
+
+
super().__init__(
+
f"Validation error: {message}", "; ".join(details) if details else None
+
)
+
+
+
class FormatError(DataModelError):
+
"""Raised when format validation fails."""
+
+
def __init__(
+
self,
+
message: str,
+
format_type: Optional[str] = None,
+
value: Optional[str] = None,
+
):
+
self.formatType = format_type
+
self.value = value
+
+
details = []
+
if format_type:
+
details.append(f"Format: {format_type}")
+
if value:
+
details.append(f"Value: {value}")
+
+
super().__init__(
+
f"Format error: {message}", "; ".join(details) if details else None
+
)
+
+
+
class CIDError(DataModelError):
+
"""Raised when CID processing fails."""
+
+
def __init__(self, message: str, cid: Optional[str] = None):
+
self.cid = cid
+
super().__init__(f"CID error: {message}", f"CID: {cid}" if cid else None)
+
+
+
class BlobError(DataModelError):
+
"""Raised when blob processing fails."""
+
+
def __init__(self, message: str, blob_ref: Optional[str] = None):
+
self.blobRef = blob_ref
+
super().__init__(
+
f"Blob error: {message}", f"Blob ref: {blob_ref}" if blob_ref else None
+
)
+190
src/atpasser/data/formats.py
···
···
+
"""Format validators for ATProto data model."""
+
+
import re
+
from typing import Any, Optional
+
from .exceptions import FormatError
+
+
+
class FormatValidator:
+
"""Validates string formats according to ATProto specifications."""
+
+
@staticmethod
+
def validate_datetime(value: str) -> str:
+
"""Validate RFC 3339 datetime format."""
+
# RFC 3339 pattern with strict validation
+
pattern = (
+
r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$"
+
)
+
if not re.match(pattern, value):
+
raise FormatError("Invalid RFC 3339 datetime format", "datetime", value)
+
+
# Additional semantic validation
+
try:
+
# Extract date parts for validation
+
date_part, time_part = value.split("T", 1)
+
year, month, day = map(int, date_part.split("-"))
+
+
# Basic date validation
+
if not (1 <= month <= 12):
+
raise FormatError("Month must be between 01 and 12", "datetime", value)
+
if not (1 <= day <= 31):
+
raise FormatError("Day must be between 01 and 31", "datetime", value)
+
if year < 0:
+
raise FormatError("Year must be positive", "datetime", value)
+
+
except ValueError:
+
raise FormatError("Invalid datetime structure", "datetime", value)
+
+
return value
+
+
@staticmethod
+
def validate_did(value: str) -> str:
+
"""Validate DID format."""
+
pattern = r"^did:[a-z]+:[a-zA-Z0-9._:%-]*[a-zA-Z0-9._-]$"
+
if not re.match(pattern, value):
+
raise FormatError("Invalid DID format", "did", value)
+
+
if len(value) > 2048:
+
raise FormatError("DID too long", "did", value)
+
+
return value
+
+
@staticmethod
+
def validate_handle(value: str) -> str:
+
"""Validate handle format."""
+
if len(value) > 253:
+
raise FormatError("Handle too long", "handle", value)
+
+
labels = value.lower().split(".")
+
if len(labels) < 2:
+
raise FormatError("Handle must contain at least one dot", "handle", value)
+
+
for i, label in enumerate(labels):
+
if not (1 <= len(label) <= 63):
+
raise FormatError(
+
f"Label {i+1} length must be 1-63 characters", "handle", value
+
)
+
+
if not re.match(r"^[a-z0-9-]+$", label):
+
raise FormatError(
+
f"Label {i+1} contains invalid characters", "handle", value
+
)
+
+
if label.startswith("-") or label.endswith("-"):
+
raise FormatError(
+
f"Label {i+1} cannot start or end with hyphen", "handle", value
+
)
+
+
if labels[-1][0].isdigit():
+
raise FormatError("TLD cannot start with digit", "handle", value)
+
+
return value
+
+
@staticmethod
+
def validate_nsid(value: str) -> str:
+
"""Validate NSID format."""
+
if len(value) > 317:
+
raise FormatError("NSID too long", "nsid", value)
+
+
if not all(ord(c) < 128 for c in value):
+
raise FormatError("NSID must contain only ASCII characters", "nsid", value)
+
+
if value.startswith(".") or value.endswith("."):
+
raise FormatError("NSID cannot start or end with dot", "nsid", value)
+
+
segments = value.split(".")
+
if len(segments) < 3:
+
raise FormatError("NSID must have at least 3 segments", "nsid", value)
+
+
# Validate domain authority segments
+
for i, segment in enumerate(segments[:-1]):
+
if not (1 <= len(segment) <= 63):
+
raise FormatError(
+
f"Domain segment {i+1} length must be 1-63", "nsid", value
+
)
+
+
if not re.match(r"^[a-z0-9-]+$", segment):
+
raise FormatError(
+
f"Domain segment {i+1} contains invalid chars", "nsid", value
+
)
+
+
if segment.startswith("-") or segment.endswith("-"):
+
raise FormatError(
+
f"Domain segment {i+1} cannot start/end with hyphen", "nsid", value
+
)
+
+
# Validate name segment
+
name = segments[-1]
+
if not (1 <= len(name) <= 63):
+
raise FormatError("Name segment length must be 1-63", "nsid", value)
+
+
if not re.match(r"^[a-zA-Z0-9]+$", name):
+
raise FormatError("Name segment contains invalid characters", "nsid", value)
+
+
if name[0].isdigit():
+
raise FormatError("Name segment cannot start with digit", "nsid", value)
+
+
return value
+
+
@staticmethod
+
def validate_uri(value: str) -> str:
+
"""Validate URI format."""
+
if len(value) > 8192: # 8 KB limit
+
raise FormatError("URI too long", "uri", value)
+
+
# Basic URI pattern validation
+
uri_pattern = r"^[a-zA-Z][a-zA-Z0-9+.-]*:.*$"
+
if not re.match(uri_pattern, value):
+
raise FormatError("Invalid URI format", "uri", value)
+
+
return value
+
+
@staticmethod
+
def validate_cid(value: str) -> str:
+
"""Validate CID format."""
+
# Basic CID pattern validation (simplified)
+
cid_pattern = r"^[a-zA-Z0-9]+$"
+
if not re.match(cid_pattern, value):
+
raise FormatError("Invalid CID format", "cid", value)
+
+
return value
+
+
@staticmethod
+
def validate_at_identifier(value: str) -> str:
+
"""Validate at-identifier format (DID or handle)."""
+
try:
+
# Try DID first
+
return FormatValidator.validate_did(value)
+
except FormatError:
+
try:
+
# Fall back to handle
+
return FormatValidator.validate_handle(value)
+
except FormatError:
+
raise FormatError(
+
"Invalid at-identifier (not a DID or handle)",
+
"at-identifier",
+
value,
+
)
+
+
@staticmethod
+
def validate_at_uri(value: str) -> str:
+
"""Validate at-uri format."""
+
if not value.startswith("at://"):
+
raise FormatError("AT URI must start with 'at://'", "at-uri", value)
+
+
# Additional validation can be added here
+
return value
+
+
@staticmethod
+
def validate_language(value: str) -> str:
+
"""Validate language tag format."""
+
# BCP 47 pattern validation
+
pattern = r"^[a-zA-Z]{1,8}(?:-[a-zA-Z0-9]{1,8})*$"
+
if not re.match(pattern, value):
+
raise FormatError("Invalid language tag format", "language", value)
+
+
return value
+
+
+
# Global validator instance
+
format_validator = FormatValidator()
+125
src/atpasser/data/serializer.py
···
···
+
"""Serializer for ATProto data model formats."""
+
+
import json
+
import base64
+
from typing import Any, Dict, Type, Union, Optional
+
from pydantic import BaseModel
+
from .exceptions import SerializationError, ValidationError
+
from .types import CIDLink
+
+
+
class ATProtoSerializer:
+
"""Serializer for ATProto JSON and CBOR formats."""
+
+
def __init__(self):
+
self.json_encoder = JSONEncoder()
+
self.json_decoder = JSONDecoder()
+
+
def to_json(self, obj: Any, indent: Optional[int] = None) -> str:
+
"""Serialize object to ATProto JSON format."""
+
try:
+
if isinstance(obj, BaseModel):
+
obj = obj.model_dump(mode="json")
+
+
serialized = self.json_encoder.encode(obj)
+
return json.dumps(serialized, indent=indent, ensure_ascii=False)
+
except Exception as e:
+
raise SerializationError(f"JSON serialization failed: {str(e)}")
+
+
def from_json(
+
self, data: Union[str, bytes, dict], model: Optional[Type[BaseModel]] = None
+
) -> Any:
+
"""Deserialize from ATProto JSON format."""
+
try:
+
if isinstance(data, (str, bytes)):
+
data = json.loads(data)
+
+
decoded = self.json_decoder.decode(data)
+
+
if model and issubclass(model, BaseModel):
+
return model.model_validate(decoded)
+
return decoded
+
except Exception as e:
+
raise SerializationError(f"JSON deserialization failed: {str(e)}")
+
+
def to_cbor(self, obj: Any) -> bytes:
+
"""Serialize object to DAG-CBOR format."""
+
try:
+
# This is a placeholder - actual CBOR implementation would go here
+
# For now, we'll convert to JSON and then encode as bytes
+
json_str = self.to_json(obj)
+
return json_str.encode("utf-8")
+
except Exception as e:
+
raise SerializationError(f"CBOR serialization failed: {str(e)}")
+
+
def from_cbor(self, data: bytes, model: Optional[Type[BaseModel]] = None) -> Any:
+
"""Deserialize from DAG-CBOR format."""
+
try:
+
# This is a placeholder - actual CBOR implementation would go here
+
# For now, we'll decode from bytes and then parse JSON
+
json_str = data.decode("utf-8")
+
return self.from_json(json_str, model)
+
except Exception as e:
+
raise SerializationError(f"CBOR deserialization failed: {str(e)}")
+
+
+
class JSONEncoder:
+
"""Encodes Python objects to ATProto JSON format."""
+
+
def encode(self, obj: Any) -> Any:
+
"""Recursively encode object to ATProto JSON format."""
+
if isinstance(obj, dict):
+
return {k: self.encode(v) for k, v in obj.items()}
+
elif isinstance(obj, list):
+
return [self.encode(item) for item in obj]
+
elif isinstance(obj, CIDLink):
+
return obj.to_json()
+
elif isinstance(obj, bytes):
+
return self._encode_bytes(obj)
+
else:
+
return obj
+
+
def _encode_bytes(self, data: bytes) -> Dict[str, str]:
+
"""Encode bytes to ATProto bytes format."""
+
return {"$bytes": base64.b64encode(data).decode("ascii")}
+
+
+
class JSONDecoder:
+
"""Decodes ATProto JSON format to Python objects."""
+
+
def decode(self, obj: Any) -> Any:
+
"""Recursively decode ATProto JSON format to Python objects."""
+
if isinstance(obj, dict):
+
return self._decode_object(obj)
+
elif isinstance(obj, list):
+
return [self.decode(item) for item in obj]
+
else:
+
return obj
+
+
def _decode_object(self, obj: Dict[str, Any]) -> Any:
+
"""Decode a JSON object, handling special ATProto formats."""
+
if len(obj) == 1:
+
key = next(iter(obj.keys()))
+
value = obj[key]
+
+
if key == "$link" and isinstance(value, str):
+
return CIDLink(value)
+
elif key == "$bytes" and isinstance(value, str):
+
return self._decode_bytes(value)
+
elif key == "$type" and value == "blob":
+
# This would be handled by a blob-specific decoder
+
return obj
+
+
# Regular object - decode recursively
+
return {k: self.decode(v) for k, v in obj.items()}
+
+
def _decode_bytes(self, value: str) -> bytes:
+
"""Decode ATProto bytes format."""
+
try:
+
return base64.b64decode(value)
+
except Exception as e:
+
raise SerializationError(f"Invalid base64 encoding: {str(e)}")
+
+
+
# Global serializer instance
+
serializer = ATProtoSerializer()
+179
src/atpasser/data/types.py
···
···
+
"""Base types for ATProto data model."""
+
+
from typing import Any, Union, Optional, TypeVar
+
from datetime import datetime
+
import re
+
import base64
+
from pydantic import BaseModel, Field, validator
+
from .exceptions import ValidationError, FormatError
+
+
T = TypeVar("T")
+
+
+
class CIDLink:
+
"""Represents a CID link in ATProto data model."""
+
+
def __init__(self, cid: Union[str, bytes]):
+
if isinstance(cid, bytes):
+
# Convert bytes to string representation
+
# This is a simplified implementation
+
self.cid = f"bafy{base64.b64encode(cid).decode()[:44]}"
+
else:
+
self.cid = cid
+
+
def __str__(self) -> str:
+
return self.cid
+
+
def __eq__(self, other: Any) -> bool:
+
if isinstance(other, CIDLink):
+
return self.cid == other.cid
+
elif isinstance(other, str):
+
return self.cid == other
+
return False
+
+
def to_json(self) -> dict:
+
"""Convert to JSON representation."""
+
return {"$link": self.cid}
+
+
@classmethod
+
def from_json(cls, data: dict) -> "CIDLink":
+
"""Create from JSON representation."""
+
if not isinstance(data, dict) or "$link" not in data:
+
raise ValidationError(
+
"Invalid CID link format", expected="{'$link': 'cid_string'}"
+
)
+
return cls(data["$link"])
+
+
+
class DateTimeString(str):
+
"""RFC 3339 datetime string with validation."""
+
+
@classmethod
+
def __get_validators__(cls):
+
yield cls.validate
+
+
@classmethod
+
def validate(cls, v: Any) -> "DateTimeString":
+
if not isinstance(v, str):
+
raise ValidationError("Must be a string", actual=type(v).__name__)
+
+
# RFC 3339 pattern validation
+
pattern = (
+
r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$"
+
)
+
if not re.match(pattern, v):
+
raise FormatError("Invalid RFC 3339 datetime format", "datetime", v)
+
+
# Additional semantic validation
+
try:
+
# Try to parse to ensure it's a valid datetime
+
datetime.fromisoformat(v.replace("Z", "+00:00").replace("z", "+00:00"))
+
except ValueError:
+
raise FormatError("Invalid datetime value", "datetime", v)
+
+
return cls(v)
+
+
+
class LanguageTag(str):
+
"""BCP 47 language tag with validation."""
+
+
@classmethod
+
def __get_validators__(cls):
+
yield cls.validate
+
+
@classmethod
+
def validate(cls, v: Any) -> "LanguageTag":
+
if not isinstance(v, str):
+
raise ValidationError("Must be a string", actual=type(v).__name__)
+
+
# Basic BCP 47 pattern validation
+
pattern = r"^[a-zA-Z]{1,8}(?:-[a-zA-Z0-9]{1,8})*$"
+
if not re.match(pattern, v):
+
raise FormatError("Invalid BCP 47 language tag format", "language", v)
+
+
return cls(v)
+
+
+
class ATUri(str):
+
"""AT Protocol URI with validation."""
+
+
@classmethod
+
def __get_validators__(cls):
+
yield cls.validate
+
+
@classmethod
+
def validate(cls, v: Any) -> "ATUri":
+
if not isinstance(v, str):
+
raise ValidationError("Must be a string", actual=type(v).__name__)
+
+
# Basic AT URI validation
+
if not v.startswith("at://"):
+
raise FormatError("AT URI must start with 'at://'", "at-uri", v)
+
+
# Additional validation can be added here
+
return cls(v)
+
+
+
class DIDString(str):
+
"""DID string with validation."""
+
+
@classmethod
+
def __get_validators__(cls):
+
yield cls.validate
+
+
@classmethod
+
def validate(cls, v: Any) -> "DIDString":
+
if not isinstance(v, str):
+
raise ValidationError("Must be a string", actual=type(v).__name__)
+
+
# Basic DID format validation
+
pattern = r"^did:[a-z]+:[a-zA-Z0-9._:%-]*[a-zA-Z0-9._-]$"
+
if not re.match(pattern, v):
+
raise FormatError("Invalid DID format", "did", v)
+
+
return cls(v)
+
+
+
class HandleString(str):
+
"""Handle string with validation."""
+
+
@classmethod
+
def __get_validators__(cls):
+
yield cls.validate
+
+
@classmethod
+
def validate(cls, v: Any) -> "HandleString":
+
if not isinstance(v, str):
+
raise ValidationError("Must be a string", actual=type(v).__name__)
+
+
# Basic handle validation
+
if len(v) > 253:
+
raise FormatError("Handle too long", "handle", v)
+
+
labels = v.lower().split(".")
+
if len(labels) < 2:
+
raise FormatError("Handle must contain at least one dot", "handle", v)
+
+
return cls(v)
+
+
+
class NSIDString(str):
+
"""NSID string with validation."""
+
+
@classmethod
+
def __get_validators__(cls):
+
yield cls.validate
+
+
@classmethod
+
def validate(cls, v: Any) -> "NSIDString":
+
if not isinstance(v, str):
+
raise ValidationError("Must be a string", actual=type(v).__name__)
+
+
# Basic NSID validation
+
if len(v) > 317:
+
raise FormatError("NSID too long", "nsid", v)
+
+
if not all(ord(c) < 128 for c in v):
+
raise FormatError("NSID must contain only ASCII characters", "nsid", v)
+
+
return cls(v)
+263
src/atpasser/lexicon/ARCHITECTURE.md
···
···
+
# ATProto Lexicon 模块架构设计
+
+
## 概述
+
+
本模块负责解析、验证和管理 ATProto Lexicon 定义文件,将 JSON Schema 转换为可执行的 Pydantic 模型,并提供类型安全的接口。
+
+
## 核心架构设计
+
+
### 1. Lexicon 解析系统
+
+
#### 1.1 解析器层级结构
+
+
```
+
LexiconParser
+
├── DefinitionParser
+
│ ├── PrimaryDefinitionParser
+
│ │ ├── RecordParser
+
│ │ ├── QueryParser
+
│ │ ├── ProcedureParser
+
│ │ └── SubscriptionParser
+
│ └── FieldDefinitionParser
+
│ ├── SimpleTypeParser
+
│ ├── CompoundTypeParser
+
│ └── MetaTypeParser
+
└── Validator
+
├── SchemaValidator
+
└── CrossReferenceValidator
+
```
+
+
#### 1.2 解析流程
+
+
1. **加载 Lexicon JSON**: 读取并验证 Lexicon 文件结构
+
2. **解析定义**: 根据类型分发到相应的解析器
+
3. **构建模型**: 生成对应的 Pydantic 模型类
+
4. **验证引用**: 检查跨定义引用的有效性
+
5. **注册模型**: 将模型注册到全局注册表
+
+
### 2. 类型映射系统
+
+
#### 2.1 Lexicon 类型到 Python 类型映射
+
+
```python
+
LEXICON_TYPE_MAPPING = {
+
"null": None,
+
"boolean": bool,
+
"integer": int,
+
"string": str,
+
"bytes": bytes,
+
"cid-link": "CIDLink",
+
"blob": "BlobRef",
+
"array": list,
+
"object": dict,
+
"params": dict,
+
"token": "LexiconToken",
+
"ref": "LexiconRef",
+
"union": "LexiconUnion",
+
"unknown": Any,
+
"record": "RecordModel",
+
"query": "QueryModel",
+
"procedure": "ProcedureModel",
+
"subscription": "SubscriptionModel"
+
}
+
```
+
+
#### 2.2 自定义类型处理器
+
+
- **LexiconRef**: 处理跨定义引用解析
+
- **LexiconUnion**: 处理联合类型验证
+
- **LexiconToken**: 处理符号化值
+
- **RecordModel**: 记录类型基类
+
- **QueryModel**: 查询类型基类
+
+
### 3. 模型生成系统
+
+
#### 3.1 动态模型生成
+
+
```python
+
class ModelGenerator:
+
"""动态生成 Pydantic 模型"""
+
+
def generate_record_model(self, definition: dict) -> Type[BaseModel]:
+
"""生成记录模型"""
+
pass
+
+
def generate_query_model(self, definition: dict) -> Type[BaseModel]:
+
"""生成查询模型"""
+
pass
+
+
def generate_field_validator(self, field_def: dict) -> Callable:
+
"""生成字段验证器"""
+
pass
+
```
+
+
#### 3.2 约束处理
+
+
```python
+
class ConstraintProcessor:
+
"""处理字段约束"""
+
+
def process_integer_constraints(self, field_def: dict) -> dict:
+
"""处理整数约束 (min, max, enum)"""
+
pass
+
+
def process_string_constraints(self, field_def: dict) -> dict:
+
"""处理字符串约束 (format, length, enum)"""
+
pass
+
+
def process_array_constraints(self, field_def: dict) -> dict:
+
"""处理数组约束 (minLength, maxLength)"""
+
pass
+
```
+
+
### 4. 注册表和缓存机制
+
+
#### 4.1 模型注册表
+
+
```python
+
class LexiconRegistry:
+
"""Lexicon 模型注册表"""
+
+
def __init__(self):
+
self._models: Dict[str, Type[BaseModel]] = {}
+
self._definitions: Dict[str, dict] = {}
+
self._ref_cache: Dict[str, Type[BaseModel]] = {}
+
+
def register(self, nsid: str, model: Type[BaseModel], definition: dict):
+
"""注册 Lexicon 模型"""
+
pass
+
+
def get_model(self, nsid: str) -> Optional[Type[BaseModel]]:
+
"""获取已注册的模型"""
+
pass
+
+
def resolve_ref(self, ref: str) -> Optional[Type[BaseModel]]:
+
"""解析引用到具体模型"""
+
pass
+
+
def clear_cache(self):
+
"""清空缓存"""
+
pass
+
```
+
+
#### 4.2 缓存策略
+
+
- **内存缓存**: 缓存已解析的模型定义
+
- **文件缓存**: 缓存序列化结果以提高性能
+
- **LRU 策略**: 使用最近最少使用算法管理缓存
+
+
### 5. 验证系统
+
+
#### 5.1 验证层级
+
+
1. **语法验证**: JSON Schema 结构验证
+
2. **语义验证**: 类型约束和业务规则验证
+
3. **引用验证**: 跨定义引用有效性验证
+
4. **兼容性验证**: 前向和后向兼容性检查
+
+
#### 5.2 自定义验证器
+
+
```python
+
class LexiconValidator:
+
"""Lexicon 定义验证器"""
+
+
def validate_definition(self, definition: dict) -> bool:
+
"""验证 Lexicon 定义完整性"""
+
pass
+
+
def validate_refs(self, definition: dict) -> List[str]:
+
"""验证所有引用的有效性"""
+
pass
+
+
def validate_compatibility(self, old_def: dict, new_def: dict) -> bool:
+
"""验证版本兼容性"""
+
pass
+
```
+
+
### 6. 错误处理系统
+
+
#### 6.1 错误类型体系
+
+
```python
+
class LexiconError(Exception):
+
"""基础 Lexicon 错误"""
+
pass
+
+
class ParseError(LexiconError):
+
"""解析错误"""
+
pass
+
+
class ValidationError(LexiconError):
+
"""验证错误"""
+
pass
+
+
class ResolutionError(LexiconError):
+
"""引用解析错误"""
+
pass
+
+
class GenerationError(LexiconError):
+
"""模型生成错误"""
+
pass
+
```
+
+
#### 6.2 诊断信息
+
+
- **详细错误消息**: 包含具体的字段路径和期望值
+
- **上下文信息**: 提供验证时的上下文信息
+
- **建议修复**: 提供可能的修复建议
+
+
### 7. 模块文件结构
+
+
```
+
src/atpasser/lexicon/
+
├── __init__.py # 模块导出
+
├── ARCHITECTURE.md # 架构文档
+
├── parser.py # 主解析器
+
├── generator.py # 模型生成器
+
├── registry.py # 注册表实现
+
├── validator.py # 验证器实现
+
├── types.py # 类型定义
+
├── exceptions.py # 异常定义
+
├── constraints.py # 约束处理器
+
└── utils.py # 工具函数
+
```
+
+
### 8. 依赖关系
+
+
- **内部依赖**:
+
- `src/atpasser/data` (数据序列化和验证)
+
- `src/atpasser/uri` (NSID 验证和处理)
+
- **外部依赖**:
+
- `pydantic`: 模型生成和验证
+
- `jsonpath-ng`: JSONPath 支持
+
- `cbor2`: CBOR 序列化支持
+
+
## 实现策略
+
+
### 1. 渐进式实现
+
+
1. **阶段一**: 实现基础解析器和简单类型映射
+
2. **阶段二**: 添加复杂类型和引用解析
+
3. **阶段三**: 实现模型生成和注册表
+
4. **阶段四**: 添加高级验证和错误处理
+
+
### 2. 测试策略
+
+
- **单元测试**: 测试各个解析器组件
+
- **集成测试**: 测试端到端 Lexicon 解析流程
+
- **兼容性测试**: 确保与现有 Lexicon 文件兼容
+
- **性能测试**: 验证解析和模型生成性能
+
+
### 3. 扩展性考虑
+
+
- **插件系统**: 支持自定义类型解析器
+
- **中间件**: 支持预处理和后处理钩子
+
- **监控**: 集成性能监控和日志记录
+
+
## 优势
+
+
1. **类型安全**: 利用 Pydantic 的强类型系统
+
2. **性能**: 优化的解析和缓存机制
+
3. **可扩展**: 模块化设计支持未来扩展
+
4. **兼容性**: 保持与 ATProto Lexicon 规范完全兼容
+
5. **开发者友好**: 提供清晰的错误消息和文档
+71
src/atpasser/lexicon/__init__.py
···
···
+
"""ATProto Lexicon module for parsing and managing schema definitions."""
+
+
from .exceptions import (
+
LexiconError,
+
ParseError,
+
ValidationError,
+
ResolutionError,
+
GenerationError,
+
CompatibilityError,
+
)
+
+
from .types import (
+
LexiconType,
+
LexiconDefinition,
+
IntegerConstraints,
+
StringConstraints,
+
ArrayConstraints,
+
ObjectConstraints,
+
BlobConstraints,
+
ParamsConstraints,
+
RefDefinition,
+
UnionDefinition,
+
RecordDefinition,
+
QueryDefinition,
+
ProcedureDefinition,
+
SubscriptionDefinition,
+
LexiconDocument,
+
ErrorDefinition,
+
LexiconSchema,
+
PropertyMap,
+
DefinitionMap,
+
)
+
+
from .registry import LexiconRegistry, registry
+
from .parser import LexiconParser, parser
+
+
__all__ = [
+
# Exceptions
+
"LexiconError",
+
"ParseError",
+
"ValidationError",
+
"ResolutionError",
+
"GenerationError",
+
"CompatibilityError",
+
# Types
+
"LexiconType",
+
"LexiconDefinition",
+
"IntegerConstraints",
+
"StringConstraints",
+
"ArrayConstraints",
+
"ObjectConstraints",
+
"BlobConstraints",
+
"ParamsConstraints",
+
"RefDefinition",
+
"UnionDefinition",
+
"RecordDefinition",
+
"QueryDefinition",
+
"ProcedureDefinition",
+
"SubscriptionDefinition",
+
"LexiconDocument",
+
"ErrorDefinition",
+
"LexiconSchema",
+
"PropertyMap",
+
"DefinitionMap",
+
# Registry
+
"LexiconRegistry",
+
"registry",
+
# Parser
+
"LexiconParser",
+
"parser",
+
]
+125
src/atpasser/lexicon/exceptions.py
···
···
+
"""Exceptions for ATProto Lexicon module."""
+
+
from typing import Optional
+
+
+
class LexiconError(Exception):
+
"""Base exception for Lexicon errors."""
+
+
def __init__(self, message: str, details: Optional[str] = None):
+
self.message = message
+
self.details = details
+
super().__init__(message)
+
+
+
class ParseError(LexiconError):
+
"""Raised when Lexicon parsing fails."""
+
+
def __init__(
+
self, message: str, nsid: Optional[str] = None, definition: Optional[str] = None
+
):
+
self.nsid = nsid
+
self.definition = definition
+
+
details = []
+
if nsid:
+
details.append(f"NSID: {nsid}")
+
if definition:
+
details.append(f"Definition: {definition}")
+
+
super().__init__(
+
f"Parse error: {message}", "; ".join(details) if details else None
+
)
+
+
+
class ValidationError(LexiconError):
+
"""Raised when Lexicon validation fails."""
+
+
def __init__(
+
self,
+
message: str,
+
nsid: Optional[str] = None,
+
field: Optional[str] = None,
+
expected: Optional[str] = None,
+
):
+
self.nsid = nsid
+
self.field = field
+
self.expected = expected
+
+
details = []
+
if nsid:
+
details.append(f"NSID: {nsid}")
+
if field:
+
details.append(f"Field: {field}")
+
if expected:
+
details.append(f"Expected: {expected}")
+
+
super().__init__(
+
f"Validation error: {message}", "; ".join(details) if details else None
+
)
+
+
+
class ResolutionError(LexiconError):
+
"""Raised when reference resolution fails."""
+
+
def __init__(
+
self, message: str, ref: Optional[str] = None, context: Optional[str] = None
+
):
+
self.ref = ref
+
self.context = context
+
+
details = []
+
if ref:
+
details.append(f"Reference: {ref}")
+
if context:
+
details.append(f"Context: {context}")
+
+
super().__init__(
+
f"Resolution error: {message}", "; ".join(details) if details else None
+
)
+
+
+
class GenerationError(LexiconError):
+
"""Raised when model generation fails."""
+
+
def __init__(
+
self,
+
message: str,
+
nsid: Optional[str] = None,
+
definition_type: Optional[str] = None,
+
):
+
self.nsid = nsid
+
self.definitionType = definition_type
+
+
details = []
+
if nsid:
+
details.append(f"NSID: {nsid}")
+
if definition_type:
+
details.append(f"Type: {definition_type}")
+
+
super().__init__(
+
f"Generation error: {message}", "; ".join(details) if details else None
+
)
+
+
+
class CompatibilityError(LexiconError):
+
"""Raised when compatibility checks fail."""
+
+
def __init__(
+
self,
+
message: str,
+
old_nsid: Optional[str] = None,
+
new_nsid: Optional[str] = None,
+
):
+
self.oldNsid = old_nsid
+
self.newNsid = new_nsid
+
+
details = []
+
if old_nsid:
+
details.append(f"Old NSID: {old_nsid}")
+
if new_nsid:
+
details.append(f"New NSID: {new_nsid}")
+
+
super().__init__(
+
f"Compatibility error: {message}", "; ".join(details) if details else None
+
)
+208
src/atpasser/lexicon/parser.py
···
···
+
"""Parser for ATProto Lexicon definitions."""
+
+
import json
+
from typing import Dict, Any, Optional, Type, Union
+
from pydantic import BaseModel, create_model
+
from .exceptions import ParseError, ValidationError
+
from .types import LexiconDocument, LexiconType
+
from .registry import registry
+
+
+
class LexiconParser:
+
"""Parser for ATProto Lexicon JSON definitions."""
+
+
def __init__(self):
+
self.validators = LexiconValidator()
+
+
def parse_document(self, json_data: Union[str, dict]) -> LexiconDocument:
+
"""Parse a Lexicon JSON document."""
+
try:
+
if isinstance(json_data, str):
+
data = json.loads(json_data)
+
else:
+
data = json_data
+
+
# Validate basic document structure
+
self.validators.validate_document_structure(data)
+
+
# Parse into Pydantic model
+
document = LexiconDocument.model_validate(data)
+
+
# Validate semantic rules
+
self.validators.validate_document_semantics(document)
+
+
return document
+
+
except Exception as e:
+
if isinstance(e, (ParseError, ValidationError)):
+
raise
+
raise ParseError(f"Failed to parse Lexicon document: {str(e)}")
+
+
def parse_and_register(self, json_data: Union[str, dict]) -> None:
+
"""Parse a Lexicon document and register it."""
+
document = self.parse_document(json_data)
+
registry.register_lexicon(document)
+
+
# Generate and register models for all definitions
+
generator = ModelGenerator()
+
for def_name, def_data in document.defs.items():
+
try:
+
model = generator.generate_model(document.id, def_name, def_data)
+
registry.register_model(document.id, model, def_name)
+
except Exception as e:
+
raise ParseError(
+
f"Failed to generate model for {def_name}: {str(e)}",
+
document.id,
+
def_name,
+
)
+
+
+
class LexiconValidator:
+
"""Validator for Lexicon documents."""
+
+
def validate_document_structure(self, data: Dict[str, Any]) -> None:
+
"""Validate basic document structure."""
+
required_fields = ["lexicon", "id", "defs"]
+
for field in required_fields:
+
if field not in data:
+
raise ValidationError(f"Missing required field: {field}")
+
+
if not isinstance(data["defs"], dict) or not data["defs"]:
+
raise ValidationError("defs must be a non-empty dictionary")
+
+
if data["lexicon"] != 1:
+
raise ValidationError("lexicon version must be 1")
+
+
def validate_document_semantics(self, document: LexiconDocument) -> None:
+
"""Validate semantic rules for Lexicon document."""
+
# Check primary type constraints
+
primary_types = {
+
LexiconType.RECORD,
+
LexiconType.QUERY,
+
LexiconType.PROCEDURE,
+
LexiconType.SUBSCRIPTION,
+
}
+
+
primary_defs = []
+
for def_name, def_data in document.defs.items():
+
def_type = def_data.get("type")
+
if def_type in primary_types:
+
primary_defs.append((def_name, def_type))
+
+
# Primary types should usually be named 'main'
+
if def_name != "main":
+
# This is a warning, not an error
+
pass
+
+
# Only one primary type allowed per document
+
if len(primary_defs) > 1:
+
raise ValidationError(
+
f"Multiple primary types found: {[name for name, _ in primary_defs]}",
+
document.id,
+
)
+
+
+
class ModelGenerator:
+
"""Generates Pydantic models from Lexicon definitions."""
+
+
def generate_model(
+
self, nsid: str, def_name: str, definition: Dict[str, Any]
+
) -> Type[BaseModel]:
+
"""Generate a Pydantic model from a Lexicon definition."""
+
def_type = definition.get("type")
+
+
if def_type == LexiconType.RECORD:
+
return self._generate_record_model(nsid, def_name, definition)
+
elif def_type == LexiconType.OBJECT:
+
return self._generate_object_model(nsid, def_name, definition)
+
elif def_type in [
+
LexiconType.QUERY,
+
LexiconType.PROCEDURE,
+
LexiconType.SUBSCRIPTION,
+
]:
+
return self._generate_primary_model(nsid, def_name, definition)
+
else:
+
# For simple types, create a basic model
+
return self._generate_simple_model(nsid, def_name, definition)
+
+
def _generate_record_model(
+
self, nsid: str, def_name: str, definition: Dict[str, Any]
+
) -> Type[BaseModel]:
+
"""Generate a model for record type."""
+
record_schema = definition.get("record", {})
+
return self._generate_object_model(nsid, def_name, record_schema)
+
+
def _generate_object_model(
+
self, nsid: str, def_name: str, definition: Dict[str, Any]
+
) -> Type[BaseModel]:
+
"""Generate a model for object type."""
+
properties = definition.get("properties", {})
+
required = definition.get("required", [])
+
+
field_definitions = {}
+
for prop_name, prop_schema in properties.items():
+
field_type = self._get_field_type(prop_schema)
+
field_definitions[prop_name] = (
+
field_type,
+
... if prop_name in required else None,
+
)
+
+
model_name = self._get_model_name(nsid, def_name)
+
return create_model(model_name, **field_definitions)
+
+
def _generate_primary_model(
+
self, nsid: str, def_name: str, definition: Dict[str, Any]
+
) -> Type[BaseModel]:
+
"""Generate a model for primary types (query, procedure, subscription)."""
+
# For now, create a basic model - specific handling can be added later
+
return self._generate_simple_model(nsid, def_name, definition)
+
+
def _generate_simple_model(
+
self, nsid: str, def_name: str, definition: Dict[str, Any]
+
) -> Type[BaseModel]:
+
"""Generate a simple model for basic types."""
+
field_type = self._get_field_type(definition)
+
model_name = self._get_model_name(nsid, def_name)
+
return create_model(model_name, value=(field_type, ...))
+
+
def _get_field_type(self, schema: Dict[str, Any]) -> Any:
+
"""Get the Python type for a schema definition."""
+
schema_type = schema.get("type")
+
+
type_mapping = {
+
LexiconType.NULL: type(None),
+
LexiconType.BOOLEAN: bool,
+
LexiconType.INTEGER: int,
+
LexiconType.STRING: str,
+
LexiconType.BYTES: bytes,
+
LexiconType.ARRAY: list,
+
LexiconType.OBJECT: dict,
+
}
+
+
if schema_type and schema_type in type_mapping:
+
return type_mapping[schema_type]
+
+
if schema_type == LexiconType.REF:
+
ref = schema.get("ref")
+
if ref:
+
return registry.resolve_ref(ref)
+
+
# Default to Any for complex types
+
return Any
+
+
def _get_model_name(self, nsid: str, def_name: str) -> str:
+
"""Generate a valid Python class name from NSID and definition name."""
+
# Convert NSID to PascalCase
+
parts = nsid.split(".")
+
name_parts = [part.capitalize() for part in parts]
+
+
# Add definition name
+
if def_name != "main":
+
def_part = def_name.capitalize()
+
name_parts.append(def_part)
+
+
return "".join(name_parts)
+
+
+
# Global parser instance
+
parser = LexiconParser()
+114
src/atpasser/lexicon/registry.py
···
···
+
"""Registry for managing Lexicon definitions and generated models."""
+
+
from typing import Dict, Optional, Type, Any
+
from pydantic import BaseModel
+
from .exceptions import ResolutionError
+
from .types import LexiconDocument
+
+
+
class LexiconRegistry:
+
"""Registry for storing and resolving Lexicon definitions and models."""
+
+
def __init__(self):
+
self._definitions: Dict[str, LexiconDocument] = {}
+
self._models: Dict[str, Type[BaseModel]] = {}
+
self._ref_cache: Dict[str, Type[BaseModel]] = {}
+
+
def register_lexicon(self, document: LexiconDocument) -> None:
+
"""Register a Lexicon document."""
+
nsid = document.id
+
if nsid in self._definitions:
+
raise ValueError(f"Lexicon with NSID {nsid} is already registered")
+
+
self._definitions[nsid] = document
+
+
# Clear cache for this NSID
+
self._clear_cache_for_nsid(nsid)
+
+
def get_lexicon(self, nsid: str) -> Optional[LexiconDocument]:
+
"""Get a registered Lexicon document by NSID."""
+
return self._definitions.get(nsid)
+
+
def register_model(
+
self, nsid: str, model: Type[BaseModel], definition_name: Optional[str] = None
+
) -> None:
+
"""Register a generated model for a Lexicon definition."""
+
key = self._get_model_key(nsid, definition_name)
+
self._models[key] = model
+
+
# Also cache for quick reference resolution
+
if definition_name and definition_name != "main":
+
ref_key = f"{nsid}#{definition_name}"
+
self._ref_cache[ref_key] = model
+
+
def get_model(
+
self, nsid: str, definition_name: Optional[str] = None
+
) -> Optional[Type[BaseModel]]:
+
"""Get a registered model by NSID and optional definition name."""
+
key = self._get_model_key(nsid, definition_name)
+
return self._models.get(key)
+
+
def resolve_ref(self, ref: str) -> Type[BaseModel]:
+
"""Resolve a reference to a model."""
+
if ref in self._ref_cache:
+
return self._ref_cache[ref]
+
+
# Parse the reference
+
if "#" in ref:
+
nsid, definition_name = ref.split("#", 1)
+
else:
+
nsid, definition_name = ref, "main"
+
+
model = self.get_model(nsid, definition_name)
+
if model is None:
+
raise ResolutionError(f"Reference not found: {ref}", ref)
+
+
# Cache for future use
+
self._ref_cache[ref] = model
+
return model
+
+
def has_lexicon(self, nsid: str) -> bool:
+
"""Check if a Lexicon is registered."""
+
return nsid in self._definitions
+
+
def has_model(self, nsid: str, definition_name: Optional[str] = None) -> bool:
+
"""Check if a model is registered."""
+
key = self._get_model_key(nsid, definition_name)
+
return key in self._models
+
+
def clear_cache(self) -> None:
+
"""Clear all cached models and references."""
+
self._models.clear()
+
self._ref_cache.clear()
+
+
def _get_model_key(self, nsid: str, definition_name: Optional[str]) -> str:
+
"""Get the internal key for model storage."""
+
if definition_name:
+
return f"{nsid}#{definition_name}"
+
return f"{nsid}#main"
+
+
def _clear_cache_for_nsid(self, nsid: str) -> None:
+
"""Clear cache entries for a specific NSID."""
+
# Clear models
+
keys_to_remove = [
+
key for key in self._models.keys() if key.startswith(f"{nsid}#")
+
]
+
for key in keys_to_remove:
+
del self._models[key]
+
+
# Clear ref cache
+
keys_to_remove = [key for key in self._ref_cache.keys() if key.startswith(nsid)]
+
for key in keys_to_remove:
+
del self._ref_cache[key]
+
+
def list_lexicons(self) -> Dict[str, LexiconDocument]:
+
"""List all registered Lexicon documents."""
+
return self._definitions.copy()
+
+
def list_models(self) -> Dict[str, Type[BaseModel]]:
+
"""List all registered models."""
+
return self._models.copy()
+
+
+
# Global registry instance
+
registry = LexiconRegistry()
+155
src/atpasser/lexicon/types.py
···
···
+
"""Type definitions for ATProto Lexicon module."""
+
+
from typing import Dict, List, Optional, Union, Any, Type
+
from enum import Enum
+
from pydantic import BaseModel, Field
+
+
+
class LexiconType(str, Enum):
+
"""Enumeration of Lexicon definition types."""
+
+
NULL = "null"
+
BOOLEAN = "boolean"
+
INTEGER = "integer"
+
STRING = "string"
+
BYTES = "bytes"
+
CID_LINK = "cid-link"
+
BLOB = "blob"
+
ARRAY = "array"
+
OBJECT = "object"
+
PARAMS = "params"
+
TOKEN = "token"
+
REF = "ref"
+
UNION = "union"
+
UNKNOWN = "unknown"
+
RECORD = "record"
+
QUERY = "query"
+
PROCEDURE = "procedure"
+
SUBSCRIPTION = "subscription"
+
+
+
class LexiconDefinition(BaseModel):
+
"""Base class for Lexicon definitions."""
+
+
type: LexiconType
+
description: Optional[str] = None
+
+
+
class IntegerConstraints(BaseModel):
+
"""Constraints for integer fields."""
+
+
minimum: Optional[int] = None
+
maximum: Optional[int] = None
+
enum: Optional[List[int]] = None
+
default: Optional[int] = None
+
const: Optional[int] = None
+
+
+
class StringConstraints(BaseModel):
+
"""Constraints for string fields."""
+
+
format: Optional[str] = None
+
maxLength: Optional[int] = None
+
minLength: Optional[int] = None
+
maxGraphemes: Optional[int] = None
+
minGraphemes: Optional[int] = None
+
knownValues: Optional[List[str]] = None
+
enum: Optional[List[str]] = None
+
default: Optional[str] = None
+
const: Optional[str] = None
+
+
+
class ArrayConstraints(BaseModel):
+
"""Constraints for array fields."""
+
+
items: Dict[str, Any] # Schema definition for array items
+
minLength: Optional[int] = None
+
maxLength: Optional[int] = None
+
+
+
class ObjectConstraints(BaseModel):
+
"""Constraints for object fields."""
+
+
properties: Dict[str, Dict[str, Any]] # Map of property names to schemas
+
required: Optional[List[str]] = None
+
nullable: Optional[List[str]] = None
+
+
+
class BlobConstraints(BaseModel):
+
"""Constraints for blob fields."""
+
+
accept: Optional[List[str]] = None # MIME types
+
maxSize: Optional[int] = None # Maximum size in bytes
+
+
+
class ParamsConstraints(BaseModel):
+
"""Constraints for params fields."""
+
+
properties: Dict[str, Dict[str, Any]]
+
required: Optional[List[str]] = None
+
+
+
class RefDefinition(BaseModel):
+
"""Reference definition."""
+
+
ref: str # Reference to another schema
+
+
+
class UnionDefinition(BaseModel):
+
"""Union type definition."""
+
+
refs: List[str] # List of references
+
closed: Optional[bool] = False # Whether union is closed
+
+
+
class RecordDefinition(LexiconDefinition):
+
"""Record type definition."""
+
+
key: str # Record key type
+
record: Dict[str, Any] # Object schema
+
+
+
class QueryDefinition(LexiconDefinition):
+
"""Query type definition."""
+
+
parameters: Optional[Dict[str, Any]] = None # Params schema
+
output: Optional[Dict[str, Any]] = None # Output schema
+
+
+
class ProcedureDefinition(LexiconDefinition):
+
"""Procedure type definition."""
+
+
parameters: Optional[Dict[str, Any]] = None # Params schema
+
input: Optional[Dict[str, Any]] = None # Input schema
+
output: Optional[Dict[str, Any]] = None # Output schema
+
errors: Optional[List[Dict[str, Any]]] = None # Error definitions
+
+
+
class SubscriptionDefinition(LexiconDefinition):
+
"""Subscription type definition."""
+
+
parameters: Optional[Dict[str, Any]] = None # Params schema
+
message: Optional[Dict[str, Any]] = None # Message schema
+
errors: Optional[List[Dict[str, Any]]] = None # Error definitions
+
+
+
class LexiconDocument(BaseModel):
+
"""Complete Lexicon document."""
+
+
lexicon: int # Lexicon version (always 1)
+
id: str # NSID of the Lexicon
+
description: Optional[str] = None
+
defs: Dict[str, Dict[str, Any]] # Map of definition names to schemas
+
+
+
class ErrorDefinition(BaseModel):
+
"""Error definition for procedures and subscriptions."""
+
+
name: str # Error name
+
description: Optional[str] = None
+
+
+
# Type aliases for convenience
+
LexiconSchema = Dict[str, Any]
+
PropertyMap = Dict[str, LexiconSchema]
+
DefinitionMap = Dict[str, Union[LexiconDefinition, Dict[str, Any]]]