Spaces:
Sleeping
Sleeping
File size: 9,836 Bytes
1e6a9db |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 |
"""HTTP API routes for note operations."""
from __future__ import annotations
from datetime import datetime
from typing import Optional
from urllib.parse import unquote
from fastapi import APIRouter, Depends, HTTPException, Query
from ...models.note import Note, NoteSummary, NoteUpdate, NoteCreate
from ...services.database import DatabaseService
from ...services.indexer import IndexerService
from ...services.vault import VaultService
from ..middleware import AuthContext, get_auth_context
router = APIRouter()
class ConflictError(Exception):
"""Raised when optimistic concurrency check fails."""
def __init__(self, message: str = "Version conflict detected"):
self.message = message
super().__init__(self.message)
@router.get("/api/notes", response_model=list[NoteSummary])
async def list_notes(
folder: Optional[str] = Query(None, description="Optional folder filter"),
auth: AuthContext = Depends(get_auth_context),
):
"""List all notes in the vault."""
user_id = auth.user_id
vault_service = VaultService()
try:
notes = vault_service.list_notes(user_id, folder=folder)
summaries = []
for note in notes:
# list_notes returns {path, title, last_modified}
updated = note.get("last_modified")
if not isinstance(updated, datetime):
updated = datetime.now()
summaries.append(
NoteSummary(
note_path=note["path"],
title=note["title"],
updated=updated,
)
)
return summaries
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to list notes: {str(e)}")
@router.post("/api/notes", response_model=Note, status_code=201)
async def create_note(create: NoteCreate, auth: AuthContext = Depends(get_auth_context)):
"""Create a new note."""
user_id = auth.user_id
vault_service = VaultService()
indexer_service = IndexerService()
db_service = DatabaseService()
try:
note_path = create.note_path
# Check if note already exists
try:
vault_service.read_note(user_id, note_path)
raise HTTPException(status_code=409, detail=f"Note already exists: {note_path}")
except FileNotFoundError:
pass # Good, note doesn't exist
# Prepare metadata
metadata = create.metadata.model_dump() if create.metadata else {}
if create.title:
metadata["title"] = create.title
# Write note to vault
written_note = vault_service.write_note(
user_id,
note_path,
body=create.body,
metadata=metadata,
title=create.title
)
# Index the note
new_version = indexer_service.index_note(user_id, written_note)
# Update index health
conn = db_service.connect()
try:
with conn:
indexer_service.update_index_health(conn, user_id)
finally:
conn.close()
# Return created note
created = written_note["metadata"].get("created")
updated_ts = written_note["metadata"].get("updated")
if isinstance(created, str):
created = datetime.fromisoformat(created.replace("Z", "+00:00"))
elif not isinstance(created, datetime):
created = datetime.now()
if isinstance(updated_ts, str):
updated_ts = datetime.fromisoformat(updated_ts.replace("Z", "+00:00"))
elif not isinstance(updated_ts, datetime):
updated_ts = created
return Note(
user_id=user_id,
note_path=note_path,
version=new_version,
title=written_note["title"],
metadata=written_note["metadata"],
body=written_note["body"],
created=created,
updated=updated_ts,
size_bytes=written_note.get("size_bytes", len(written_note["body"].encode("utf-8"))),
)
except HTTPException:
raise
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to create note: {str(e)}")
@router.get("/api/notes/{path:path}", response_model=Note)
async def get_note(path: str, auth: AuthContext = Depends(get_auth_context)):
"""Get a specific note by path."""
user_id = auth.user_id
vault_service = VaultService()
db_service = DatabaseService()
try:
# URL decode the path
note_path = unquote(path)
# Read note from vault
note_data = vault_service.read_note(user_id, note_path)
# Get version from index
conn = db_service.connect()
try:
cursor = conn.execute(
"SELECT version FROM note_metadata WHERE user_id = ? AND note_path = ?",
(user_id, note_path),
)
row = cursor.fetchone()
version = row["version"] if row else 1
finally:
conn.close()
# Parse metadata
metadata = note_data.get("metadata", {})
created = metadata.get("created")
updated = metadata.get("updated")
if isinstance(created, str):
created = datetime.fromisoformat(created.replace("Z", "+00:00"))
elif not isinstance(created, datetime):
created = datetime.now()
if isinstance(updated, str):
updated = datetime.fromisoformat(updated.replace("Z", "+00:00"))
elif not isinstance(updated, datetime):
updated = created
return Note(
user_id=user_id,
note_path=note_path,
version=version,
title=note_data["title"],
metadata=metadata,
body=note_data["body"],
created=created,
updated=updated,
size_bytes=note_data.get("size_bytes", len(note_data["body"].encode("utf-8"))),
)
except FileNotFoundError:
raise HTTPException(status_code=404, detail=f"Note not found: {path}")
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to read note: {str(e)}")
@router.put("/api/notes/{path:path}", response_model=Note)
async def update_note(
path: str,
update: NoteUpdate,
auth: AuthContext = Depends(get_auth_context),
):
"""Update a note with optimistic concurrency control."""
user_id = auth.user_id
vault_service = VaultService()
indexer_service = IndexerService()
db_service = DatabaseService()
try:
# URL decode the path
note_path = unquote(path)
# Check version if provided
if update.if_version is not None:
conn = db_service.connect()
try:
cursor = conn.execute(
"SELECT version FROM note_metadata WHERE user_id = ? AND note_path = ?",
(user_id, note_path),
)
row = cursor.fetchone()
current_version = row["version"] if row else 0
if current_version != update.if_version:
raise ConflictError(
f"Version conflict: expected {update.if_version}, got {current_version}"
)
finally:
conn.close()
# Prepare metadata
metadata = update.metadata.model_dump() if update.metadata else {}
if update.title:
metadata["title"] = update.title
# Write note to vault
written_note = vault_service.write_note(
user_id,
note_path,
body=update.body,
metadata=metadata,
title=update.title
)
# Index the note
new_version = indexer_service.index_note(user_id, written_note)
# Update index health
conn = db_service.connect()
try:
with conn:
indexer_service.update_index_health(conn, user_id)
finally:
conn.close()
# Return updated note
created = written_note["metadata"].get("created")
updated_ts = written_note["metadata"].get("updated")
if isinstance(created, str):
created = datetime.fromisoformat(created.replace("Z", "+00:00"))
elif not isinstance(created, datetime):
created = datetime.now()
if isinstance(updated_ts, str):
updated_ts = datetime.fromisoformat(updated_ts.replace("Z", "+00:00"))
elif not isinstance(updated_ts, datetime):
updated_ts = created
return Note(
user_id=user_id,
note_path=note_path,
version=new_version,
title=written_note["title"],
metadata=written_note["metadata"],
body=written_note["body"],
created=created,
updated=updated_ts,
size_bytes=written_note.get("size_bytes", len(written_note["body"].encode("utf-8"))),
)
except ConflictError as e:
raise HTTPException(status_code=409, detail=str(e))
except FileNotFoundError:
raise HTTPException(status_code=404, detail=f"Note not found: {path}")
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to update note: {str(e)}")
__all__ = ["router", "ConflictError"]
|