Files
boojack 619eb8d6b8 chore(mcp): expose spaces, forward the client address, re-pin evals
The MCP catalog survived the recent API changes because it is derived
from OpenAPI, but three things drifted around it, and fixing them
surfaced a fourth.

- mcp: the adapter built each in-process API request with httptest,
  whose fixed peer address (192.0.2.1) overrode the caller's resolved
  address on the client-address middleware's second pass. Every
  anonymous MCP caller shared one rate-limit bucket. The adapter now
  presents the address resolved for the /mcp request as the peer.
- mcp: the full SpaceService is curated as space_* tools. Space and
  member updates drop path-bound fields and rely on the gateway's
  update-mask inference; accepting and declining an invitation no
  longer require an empty body for a body: "*" binding whose only
  field comes from the path.
- mcp/evals: answers re-pinned to the current seed (four users,
  22 top-level memos, 35 reactions, four spaces) and extended with
  space questions.
- store/sqlite: transactions begin IMMEDIATE. Token authentication
  records the token's last-used time asynchronously on every request,
  and the space drivers read before they write in a deferred
  transaction; when the background commit landed in between, SQLite
  refused the upgrade with SQLITE_BUSY without consulting the busy
  timeout. Roughly half of space creates over MCP failed. Taking the
  write lock up front keeps the parent-delete serialization the design
  relies on, so the SQLite stale-snapshot test now asserts that a
  concurrent delete waits for the open transaction instead.
2026-09-18 07:21:38 +08:00

100 lines
3.7 KiB
Go

package sqlite
import (
"context"
"database/sql"
"github.com/pkg/errors"
// Note: modernc.org/sqlite driver is imported in functions.go where
// RegisterScalarFunction is used. No blank import needed here.
"github.com/usememos/memos/internal/profile"
"github.com/usememos/memos/store"
)
type DB struct {
db *sql.DB
profile *profile.Profile
}
// NewDB opens a database specified by its database driver name and a
// driver-specific data source name, usually consisting of at least a
// database name and connection information.
func NewDB(profile *profile.Profile) (store.Driver, error) {
// Ensure a DSN is set before attempting to open the database.
if profile.DSN == "" {
return nil, errors.New("dsn required")
}
if err := ensureUnicodeLowerRegistered(); err != nil {
return nil, errors.Wrap(err, "failed to register sqlite unicode lower function")
}
if err := ensureRegexpRegistered(); err != nil {
return nil, errors.Wrap(err, "failed to register sqlite regexp function")
}
// Connect to the database with some sane settings:
// - No shared-cache: it's obsolete; WAL journal mode is a better solution.
// - No foreign key constraints: it's currently disabled by default, but it's a
// good practice to be explicit and prevent future surprises on SQLite upgrades.
// - Journal mode set to WAL: it's the recommended journal mode for most applications
// as it prevents locking issues.
// - mmap size set to 0: it disables memory mapping, which can cause OOM errors on some systems.
// - Transactions begin IMMEDIATE: several drivers' transactions read before they
// write (a membership or lifecycle check, then an insert). With the default
// DEFERRED mode such a transaction holds a read snapshot when it tries to
// write, and if any other connection committed in between (for example the
// asynchronous personal-access-token last-used update that runs on every
// token-authenticated request) SQLite refuses the upgrade with SQLITE_BUSY
// at once, without consulting busy_timeout. Taking the write lock up front
// makes those transactions queue behind the busy handler instead.
//
// Notes:
// - When using the `modernc.org/sqlite` driver, each pragma must be prefixed with `_pragma=`.
//
// References:
// - https://pkg.go.dev/modernc.org/sqlite#Driver.Open
// - https://www.sqlite.org/sharedcache.html
// - https://www.sqlite.org/pragma.html
sqliteDB, err := sql.Open("sqlite", profile.DSN+"?_pragma=foreign_keys(0)&_pragma=busy_timeout(10000)&_pragma=journal_mode(WAL)&_pragma=mmap_size(0)&_txlock=immediate")
if err != nil {
return nil, errors.Wrapf(err, "failed to open db with dsn: %s", profile.DSN)
}
driver := DB{db: sqliteDB, profile: profile}
return &driver, nil
}
func (d *DB) GetDB() *sql.DB {
return d.db
}
func (d *DB) Close() error {
return d.db.Close()
}
func (d *DB) IsInitialized(ctx context.Context) (bool, error) {
// Check if the database is initialized by checking if the memo table exists.
var exists bool
err := d.db.QueryRowContext(ctx, "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name='memo')").Scan(&exists)
if err != nil {
return false, errors.Wrap(err, "failed to check if database is initialized")
}
return exists, nil
}
// GetDatabaseSize returns the database size in bytes, or -1 if unavailable.
func (d *DB) GetDatabaseSize(ctx context.Context) (int64, error) {
var pageCount, pageSize int64
if err := d.db.QueryRowContext(ctx, "PRAGMA page_count").Scan(&pageCount); err != nil {
return -1, errors.Wrap(err, "failed to read page_count")
}
if err := d.db.QueryRowContext(ctx, "PRAGMA page_size").Scan(&pageSize); err != nil {
return -1, errors.Wrap(err, "failed to read page_size")
}
return pageCount * pageSize, nil
}