Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def run_webdav(host, port, data_dir, username, password):

def run_api(host, port, data_dir):
import uvicorn
from nexanote.storage import FileNoteStore, run_migration
from nexanote.storage import create_store, run_migration
from nexanote.api.routes import create_app

data_dir = Path(data_dir)
Expand All @@ -50,7 +50,9 @@ def run_api(host, port, data_dir):
logger.info(report.summary())
if report.backup_path:
logger.info(f"Legacy SQLite backup kept at: {report.backup_path}")
db = FileNoteStore(data_dir)
# `create_store` reads the on-disk mode marker / NEXANOTE_STORAGE_MODE
# env var so users can opt into the plain-Markdown backend.
db = create_store(data_dir)
app = create_app(db)

logger.info(f"API REST démarrée sur http://{host}:{port}")
Expand Down
55 changes: 48 additions & 7 deletions nexanote/storage/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,68 @@
NexaNote — Storage package.

EN: Public entry points:
- FileNoteStore primary storage as of v1.0.0 (file-based)
- run_migration SQLite → file migration helper
- NexaNoteDB legacy SQLite store, kept for migration
- FileNoteStore YAML-frontmatter backend (default).
- PlainMarkdownNoteStore plain Markdown + JSON-sidecar backend.
- create_store factory that picks the backend from the
on-disk marker / env var.
- run_migration legacy SQLite → file-store migration.
- migrate_yaml_to_plain YAML store → plain Markdown migration.
- NexaNoteDB legacy SQLite store, kept for migration.
FR: Points d'entrée publics du package de stockage.
"""

from nexanote.storage.export import export_all, export_note, sanitize_filename
from nexanote.storage.backend import (
DEFAULT_MODE,
ENV_STORAGE_MODE,
MODE_MARKER,
MODE_PLAIN,
MODE_YAML,
BackendInfo,
NoteStore,
create_store,
detect_mode,
write_mode_marker,
)
from nexanote.storage.export import (
AutoExportConfig,
AutoExporter,
export_all,
export_note,
sanitize_filename,
)
from nexanote.storage.file_store import FileNoteStore
from nexanote.storage.legacy_db import NexaNoteDB
from nexanote.storage.migration import (
MigrationReport,
PlainMigrationReport,
migrate_yaml_to_plain,
needs_migration,
run_migration,
)
from nexanote.storage.plain_store import PlainMarkdownNoteStore

__all__ = [
"AutoExportConfig",
"AutoExporter",
"BackendInfo",
"DEFAULT_MODE",
"ENV_STORAGE_MODE",
"FileNoteStore",
"NexaNoteDB",
"MODE_MARKER",
"MODE_PLAIN",
"MODE_YAML",
"MigrationReport",
"needs_migration",
"run_migration",
"NexaNoteDB",
"NoteStore",
"PlainMarkdownNoteStore",
"PlainMigrationReport",
"create_store",
"detect_mode",
"export_all",
"export_note",
"migrate_yaml_to_plain",
"needs_migration",
"run_migration",
"sanitize_filename",
"write_mode_marker",
]
151 changes: 151 additions & 0 deletions nexanote/storage/backend.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
"""
NexaNote — Storage backend factory / Sélecteur de backend de stockage.

EN: Two backends ship side-by-side:
* ``FileNoteStore`` (default) — YAML frontmatter inside the
Markdown file itself, one
file per note keyed by id.
* ``PlainMarkdownNoteStore`` — Pure Markdown body in
``<Title>.md`` plus a
``<Title>.json`` sidecar for
metadata. Direct Obsidian
vault drop-in.

The active backend for a given data directory is recorded in a small
``.nexanote_storage_mode`` marker file. ``create_store`` reads the
marker, falls back to the ``NEXANOTE_STORAGE_MODE`` env var, and
finally to ``yaml`` when nothing is set. This keeps existing data
directories on the YAML backend unless the user explicitly switches.

FR: Deux backends cohabitent — frontmatter YAML ou Markdown propre +
sidecar JSON. Le mode actif est enregistré dans un marqueur, avec
repli sur la variable d'env ``NEXANOTE_STORAGE_MODE`` puis ``yaml``.
"""

from __future__ import annotations

import logging
import os
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Optional, Union

from nexanote.storage.file_store import FileNoteStore
from nexanote.storage.plain_store import PlainMarkdownNoteStore

if TYPE_CHECKING:
from nexanote.storage.export import AutoExportConfig

logger = logging.getLogger("nexanote.storage.backend")

# EN: Marker filename inside the data directory. Recording the mode on
# disk avoids accidental backend swaps when the env var is missing.
# FR: Marqueur dans le data dir — évite un changement de backend accidentel.
MODE_MARKER = ".nexanote_storage_mode"

ENV_STORAGE_MODE = "NEXANOTE_STORAGE_MODE"

MODE_YAML = "yaml"
MODE_PLAIN = "plain"
DEFAULT_MODE = MODE_YAML

NoteStore = Union[FileNoteStore, PlainMarkdownNoteStore]


@dataclass(frozen=True)
class BackendInfo:
"""Resolved backend selection for a data directory."""

mode: str
source: str # "marker", "env", or "default"


def detect_mode(
data_dir: Path,
env: Optional[dict] = None,
) -> BackendInfo:
"""
EN: Resolve which backend to open for `data_dir`. Marker file wins;
env var is the next choice; otherwise the default (`yaml`) is used.
FR: Détermine le backend à utiliser. Marqueur > env > défaut (`yaml`).
"""
data_dir = Path(data_dir)
marker = data_dir / MODE_MARKER
if marker.exists():
try:
mode = marker.read_text(encoding="utf-8").strip().lower()
except OSError as exc:
logger.warning(f"could not read storage mode marker {marker}: {exc}")
mode = ""
if mode in (MODE_YAML, MODE_PLAIN):
return BackendInfo(mode=mode, source="marker")
logger.warning(
f"storage mode marker contains unknown value {mode!r} — falling back"
)

source_env = env if env is not None else os.environ
env_mode = (source_env.get(ENV_STORAGE_MODE) or "").strip().lower()
if env_mode in (MODE_YAML, MODE_PLAIN):
return BackendInfo(mode=env_mode, source="env")

return BackendInfo(mode=DEFAULT_MODE, source="default")


def write_mode_marker(data_dir: Path, mode: str) -> None:
"""Pin `data_dir` to `mode` so future opens don't drift."""
if mode not in (MODE_YAML, MODE_PLAIN):
raise ValueError(f"unknown storage mode: {mode!r}")
data_dir = Path(data_dir)
data_dir.mkdir(parents=True, exist_ok=True)
marker = data_dir / MODE_MARKER
marker.write_text(mode + "\n", encoding="utf-8")


def create_store(
data_dir: Path,
mode: Optional[str] = None,
auto_export: Optional["AutoExportConfig"] = None,
) -> NoteStore:
"""
EN: Open the right backend for `data_dir`. Pass `mode` to force a
choice; otherwise `detect_mode` is used. The chosen mode is
persisted via a marker on first use so subsequent opens stay
consistent even if the env var disappears.
FR: Ouvre le bon backend pour `data_dir`. Persiste le choix dans un
marqueur pour rester stable d'un démarrage à l'autre.
"""
data_dir = Path(data_dir)
if mode is None:
info = detect_mode(data_dir)
mode = info.mode
logger.info(
f"Storage backend: {mode} (source={info.source}, dir={data_dir})"
)
else:
logger.info(f"Storage backend: {mode} (forced, dir={data_dir})")

# Record the choice so a later run without env vars stays consistent.
marker = data_dir / MODE_MARKER
if not marker.exists():
try:
write_mode_marker(data_dir, mode)
except OSError as exc:
logger.warning(f"could not write storage mode marker: {exc}")

if mode == MODE_PLAIN:
return PlainMarkdownNoteStore(data_dir, auto_export=auto_export)
Comment on lines +135 to +136
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Block plain mode on non-migrated YAML stores

create_store switches to PlainMarkdownNoteStore as soon as mode == plain, but it never verifies that the directory has already been converted from YAML-frontmatter files. In a data dir that still contains YAML notes, setting NEXANOTE_STORAGE_MODE=plain makes those files get interpreted as external plain Markdown, which changes note IDs (to synthetic md.* IDs) and makes previous IDs unreachable for API/sync clients. Add a migration precondition (or explicit refusal with guidance) before allowing the plain backend.

Useful? React with 👍 / 👎.

return FileNoteStore(data_dir, auto_export=auto_export)


__all__ = [
"BackendInfo",
"DEFAULT_MODE",
"ENV_STORAGE_MODE",
"MODE_MARKER",
"MODE_PLAIN",
"MODE_YAML",
"NoteStore",
"create_store",
"detect_mode",
"write_mode_marker",
]
Loading
Loading