refactor(demo): seed content after the configuration apply

Startup is now migrate, apply the configuration, then seed in demo mode,
the order in which comparable systems bootstrap identity before content.
Seed leaves store.Migrate and becomes a method the server calls after
applyConfigurationAtStartup.

The seed holds content only. The public demo access token and the
MEMO_RELATED row are gone; the reaction list belongs to the configuration.
Users are inserted without fixed ids and only when missing, their profile
fields are filled only where empty, and every memo, membership, reaction,
and attachment references its creator by username. A declared
administrator therefore keeps its row, credentials, and display name, and
the seeded content attaches to it. A bare --demo start without a
configuration seeds the same four users as before.

The seed test covers both starts and asserts the seed writes no instance
or user settings. Two stale lines of copy are fixed.
This commit is contained in:
boojack
2026-10-31 13:33:36 +08:00
parent e52a507924
commit f22b30f5c0
6 changed files with 165 additions and 119 deletions
+6
View File
@@ -165,6 +165,12 @@ func runServer() error {
if err := applyConfigurationAtStartup(ctx, storeInstance); err != nil {
return errors.Wrap(err, "failed to apply the declarative configuration")
}
if instanceProfile.Demo {
// After the apply, so the demo content attaches to the declared users.
if err := storeInstance.Seed(ctx); err != nil {
return errors.Wrap(err, "failed to seed the demo content")
}
}
accessSetting, err := storeInstance.GetInstanceAccessSetting(ctx)
if err != nil {
return errors.Wrap(err, "failed to get instance access setting")
+3 -2
View File
@@ -554,8 +554,9 @@ transaction, PostgreSQL from `SERIALIZABLE`, MySQL from `SERIALIZABLE` with `SEL
before rolling the replicas, the same place database migration runs. It migrates the database first, exactly as server startup does,
so it also bootstraps a fresh instance before its first start.
- Server startup, controlled by `--config-apply=startup|off` (`MEMOS_CONFIG_APPLY`), default `startup`, and `--config-dir`
(`MEMOS_CONFIG_DIR`). The sequence is migrate, seed (demo mode), apply, then construct services. A plan error or apply failure stops startup, as an invalid `nginx.conf` stops nginx; the
process never serves with a configuration it could not apply.
(`MEMOS_CONFIG_DIR`). The sequence is migrate, apply, seed (demo mode), then construct services. The demo seed runs after apply so its content attaches to
the users the configuration declares; it creates a user only when none exists. A plan error or apply failure stops startup, as an
invalid `nginx.conf` stops nginx; the process never serves with a configuration it could not apply.
`off` is for fleets that apply through the job and want replicas to never touch the files. Replicas started with `off` still read the
state record, so the API guard works everywhere.
+6 -2
View File
@@ -108,6 +108,10 @@ func bootInstance(ctx context.Context, t *testing.T, opts instanceOptions) *inst
plan, _, err := configuration.Apply(ctx, desired, storeInstance, configuration.ApplyMetadata{AppliedBy: "startup test", Now: time.Now()})
require.NoError(t, err, "should apply the configuration")
require.True(t, plan.Valid(), "the configuration should be applicable: %v", plan.Message.Errors)
if opts.demo {
// As the server does: after the apply, so content attaches to declared users.
require.NoError(t, storeInstance.Seed(ctx), "should seed the demo content")
}
s, err := server.NewServer(ctx, instanceProfile, storeInstance)
require.NoError(t, err, "should construct server")
@@ -535,8 +539,8 @@ func TestStartupGatewayOmitsNullMessageFields(t *testing.T) {
require.Equal(t, "image/gif", fetched["type"])
}
// TestStartupDemoMode verifies demo mode boots, which exercises the seed path
// in store.Migrate that prod-mode startups never touch.
// TestStartupDemoMode verifies demo mode boots, which exercises the seed step
// that prod-mode startups never run.
func TestStartupDemoMode(t *testing.T) {
ctx := context.Background()
inst := bootInstance(ctx, t, instanceOptions{
+46 -3
View File
@@ -14,8 +14,8 @@ import (
"github.com/usememos/memos/store/db/sqlite"
)
func TestDemoSeed(t *testing.T) {
ctx := context.Background()
func newDemoStore(t *testing.T) *store.Store {
t.Helper()
p := &profile.Profile{
Demo: true,
Data: t.TempDir(),
@@ -28,8 +28,14 @@ func TestDemoSeed(t *testing.T) {
t.Cleanup(func() {
require.NoError(t, stores.Close())
})
require.NoError(t, stores.Migrate(context.Background()))
return stores
}
require.NoError(t, stores.Migrate(ctx))
func TestDemoSeed(t *testing.T) {
ctx := context.Background()
stores := newDemoStore(t)
require.NoError(t, stores.Seed(ctx))
generalSetting, err := stores.GetInstanceGeneralSetting(ctx)
require.NoError(t, err)
require.False(t, generalSetting.DisallowPasswordAuth, "the demo seed does not set an authentication policy")
@@ -89,4 +95,41 @@ func TestDemoSeed(t *testing.T) {
attachments, err := stores.ListAttachments(ctx, &store.FindAttachment{HasRelatedMemo: true})
require.NoError(t, err)
require.NotEmpty(t, attachments, "demo should include a memo attachment")
// The seed holds content only: settings, including the reaction list, come
// from the demo's declarative configuration, and no account carries a
// seeded credential.
memoRelated, err := stores.GetUncachedInstanceSetting(ctx, &store.FindInstanceSetting{Name: "MEMO_RELATED"})
require.NoError(t, err)
require.Nil(t, memoRelated, "the seed does not set instance settings")
userSettings, err := stores.ListUserSettings(ctx, &store.FindUserSetting{})
require.NoError(t, err)
require.Empty(t, userSettings, "the seed does not set user settings or access tokens")
}
// The server seeds after the declarative configuration is applied, so the
// administrator may already exist: the seed keeps that row, fills only the
// profile fields left empty, and attaches its content to it.
func TestDemoSeedAttachesToDeclaredAdmin(t *testing.T) {
ctx := context.Background()
stores := newDemoStore(t)
declared, err := stores.CreateUser(ctx, &store.User{Username: "steven", Role: store.RoleAdmin, Nickname: "Declared", PasswordHash: "hash"})
require.NoError(t, err)
require.NoError(t, stores.Seed(ctx))
username := "steven"
users, err := stores.ListUsers(ctx, &store.FindUser{Username: &username})
require.NoError(t, err)
require.Len(t, users, 1, "the seed does not create a second steven")
require.Equal(t, declared.ID, users[0].ID)
require.Equal(t, "Declared", users[0].Nickname, "a declared display name is kept")
require.Equal(t, "hash", users[0].PasswordHash, "the declared credentials are kept")
require.NotEmpty(t, users[0].Description, "an empty bio is filled from the seed")
memos, err := stores.ListMemos(ctx, &store.FindMemo{CreatorID: &declared.ID})
require.NoError(t, err)
require.NotEmpty(t, memos, "the welcome memo and the rest of Steven's content belong to the declared user")
all, err := stores.ListMemos(ctx, &store.FindMemo{})
require.NoError(t, err)
require.GreaterOrEqual(t, len(all), 20)
}
+7 -13
View File
@@ -26,8 +26,8 @@ import (
// Migration Flow:
// 1. preMigrate: Check if DB is initialized. If not, apply LATEST.sql
// 2. checkMinimumUpgradeVersion: Verify the database meets the fixed v0.31.0 baseline
// 3. Migrate (prod mode): Apply incremental migrations from current to target version
// 4. Migrate (demo mode): Seed database with demo data
// 3. Migrate: Apply incremental migrations from current to target version
// 4. Seed (demo mode, called by the server after the configuration apply): load the demo content
//
// Version Tracking:
// - New installations: Schema version set in system_setting immediately
@@ -95,7 +95,6 @@ func validateMigrationFileName(filename string) error {
// Migrate migrates the database schema to the latest version.
// It checks the current schema version and applies any necessary migrations.
// It also seeds the database with initial data if in demo mode.
func (s *Store) Migrate(ctx context.Context) error {
if err := s.preMigrate(ctx); err != nil {
return errors.Wrap(err, "failed to pre-migrate")
@@ -127,12 +126,6 @@ func (s *Store) Migrate(ctx context.Context) error {
}
}
if s.profile.Demo {
// In demo mode, we should seed the database.
if err := s.seed(ctx); err != nil {
return errors.Wrap(err, "failed to seed")
}
}
if err := s.initializeInstanceAccessSetting(ctx); err != nil {
return errors.Wrap(err, "failed to initialize instance access setting")
}
@@ -289,10 +282,11 @@ func (s *Store) getSeedBasePath() string {
return fmt.Sprintf("seed/%s/", s.profile.Driver)
}
// seed seeds the database with initial data.
// It reads all seed files from the embedded filesystem and executes them in order.
// This is only supported for SQLite databases and is used in demo mode.
func (s *Store) seed(ctx context.Context) error {
// Seed loads the demo content: every seed file from the embedded filesystem,
// in name order, in one transaction. The server calls it in demo mode after
// the declarative configuration is applied, so content attaches to the users
// the configuration declares. Only SQLite has seed files.
func (s *Store) Seed(ctx context.Context) error {
// Only seed for SQLite - other databases should use production data
if s.profile.Driver != "sqlite" {
slog.Warn("seed is only supported for SQLite, skipping for other databases")
File diff suppressed because one or more lines are too long