Compare changes

Choose any two refs to compare.

+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. **้”™่ฏฏๅ‹ๅฅฝ**: ่ฏฆ็ป†็š„้”™่ฏฏๆถˆๆฏๅ’Œ่ฏŠๆ–ญไฟกๆฏ
+47
src/atpasser/data/__init__.py
···
···
+
"""ATProto data model module for serialization and validation."""
+
+
from .exceptions import (
+
DataModelError,
+
SerializationError,
+
ValidationError,
+
FormatError,
+
CIDError,
+
BlobError,
+
)
+
+
from .types import (
+
CIDLink,
+
DateTimeString,
+
LanguageTag,
+
ATUri,
+
DIDString,
+
HandleString,
+
NSIDString,
+
)
+
+
from .formats import format_validator, FormatValidator
+
from .serializer import ATProtoSerializer, serializer
+
+
__all__ = [
+
# Exceptions
+
"DataModelError",
+
"SerializationError",
+
"ValidationError",
+
"FormatError",
+
"CIDError",
+
"BlobError",
+
# Types
+
"CIDLink",
+
"DateTimeString",
+
"LanguageTag",
+
"ATUri",
+
"DIDString",
+
"HandleString",
+
"NSIDString",
+
# Validators
+
"format_validator",
+
"FormatValidator",
+
# Serializers
+
"ATProtoSerializer",
+
"serializer",
+
]
+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]]]