Each message belongs to a room and has a sender. Add Message to
models.go, then generate its migration as you did for rooms.
Declare messages in migrations.go as Personal. Erasing the sender
deletes their messages.
messages.go holds the rules: 1 to 500 characters, in a room that
exists. The room page has the newest 100 messages, with the oldest at
the top.
Deleting a room now means deleting its messages too. deleteRoom
removes them in the same transaction as the room, so no message is left
pointing at a room that is gone.
Open the room in two windows and send a message from one. The other
window doesn't change until you reload it. The next step fixes that.
Check it worked
In a room, a message you send appears in the list, and an empty one is refused with a reason.
🤖 These pages were written by an LLM, on the ideas, instruction, and editing of humans. AI-written text here is always marked, visibly — that's factor X.
models.go Edit
internal/chat/models.go
package chat
import"time"// Models is every model rastrillo migration generate manages; migration// check fails the gate when it and migrations/ disagree.var Models = []any{
&Note{},
&Room{},
&Message{},
}
// Note is an example model: rename it, replace it, add more beside it.// Query it through owned (auth.go), and never bind a request// body onto a model; AGENTS.md says why.type Note struct {
ID int64 Owner string`gorm:"index"` Title string Body string CreatedAt time.Time
UpdatedAt time.Time
}
// Room is a place to talk. Admins make, rename and delete rooms.type Room struct {
ID int64 Name string`gorm:"uniqueIndex"` CreatedAt time.Time
UpdatedAt time.Time
}
// Message is one line somebody posted in a room.type Message struct {
ID int64 RoomID int64`gorm:"index"` Sender string Text string CreatedAt time.Time
}
migrations.go Edit
internal/chat/migrations.go
package chat
import (
"embed""amadan.net/rastrillo/rastrillo/apitoken""amadan.net/rastrillo/rastrillo/auth""amadan.net/rastrillo/rastrillo/migrate""amadan.net/rastrillo/rastrillo/passkey""amadan.net/rastrillo/rastrillo/pow""amadan.net/rastrillo/rastrillo/sessions""amadan.net/rastrillo/rastrillo/signin""amadan.net/rastrillo/rastrillo/totp")
//go:embed migrations/*.sqlvar migrationFS embed.FS
// Schema is this app's own migrations, which migration generate and// check diff against Models. Never edit one that has shipped.var Schema = migrate.MustFromFS(migrationFS, "chat").
Declare(migrate.Data{Name: "notes", Key: []string{"id"},
Kind: migrate.Personal, Owner: migrate.Subject("owner"),
Erase: migrate.EraseRow, Export: true}).
Declare(migrate.Data{Name: "rooms", Key: []string{"id"},
Kind: migrate.Shared}).
Declare(migrate.Data{Name: "messages", Key: []string{"id"},
Kind: migrate.Personal, Owner: migrate.Subject("sender"),
Erase: migrate.EraseRow, Export: true})
// BootSchema is what boot applies. A subsystem's schema goes here, in the// order it applies, and never in Schema: check would drop its tables.var BootSchema = migrate.Merge(sessions.Schema, auth.Schema,
pow.Schema, passkey.Schema, totp.Schema, signin.Schema,
apitoken.Schema, Schema)
messages.go New
internal/chat/messages.go
package chat
import (
"context""slices""strings""unicode/utf8""amadan.net/rastrillo/rastrillo/op")
// A message is one line of chat, not a letter.const messageLimit = 500
// The room page shows this many of the newest messages.const messagesShown = 100
func (app *App) recentMessages(
ctx context.Context, roomID int64,
) ([]Message, error) {
var messages []Message
err := app.database.G.WithContext(ctx).Where("room_id = ?", roomID).
Order("id desc").Limit(messagesShown).Find(&messages).Error
slices.Reverse(messages) // oldest first, as a chat readsreturn messages, err
}
func (app *App) postMessage(
ctx context.Context, roomID int64, sender, text string,
) error {
text = strings.TrimSpace(text)
if text == "" || utf8.RuneCountInString(text) > messageLimit {
return op.Invalid{Fields: map[string]string{
"Text": "Write a message of 1 to 500 characters.",
}}
}
if _, err := app.findRoom(ctx, roomID); err != nil {
return err
}
message := Message{RoomID: roomID, Sender: sender, Text: text}
return app.database.G.WithContext(ctx).Create(&message).Error
}
rooms.go Edit
internal/chat/rooms.go
package chat
import (
"context""errors""strings""unicode/utf8""gorm.io/gorm""amadan.net/rastrillo/rastrillo/op")
// A name longer than this would not fit the room list on a phone.const roomNameLimit = 40
func (app *App) listRooms(ctx context.Context) ([]Room, error) {
var rooms []Room
err := app.database.G.WithContext(ctx).Order("name").Find(&rooms).Error
return rooms, err
}
func (app *App) findRoom(ctx context.Context, id int64) (Room, error) {
var room Room
err := app.database.G.WithContext(ctx).First(&room, id).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return room, op.NotFound{}
}
return room, err
}
func (app *App) createRoom(ctx context.Context, name string) (Room, error) {
room := Room{Name: strings.TrimSpace(name)}
if err := checkRoomName(room.Name); err != nil {
return room, err
}
err := app.database.G.WithContext(ctx).Create(&room).Error
return room, nameTaken(err)
}
func (app *App) renameRoom(ctx context.Context, id int64, name string) error {
name = strings.TrimSpace(name)
if err := checkRoomName(name); err != nil {
return err
}
renamed := app.database.G.WithContext(ctx).Model(&Room{}).
Where("id = ?", id).Update("name", name)
if renamed.Error == nil && renamed.RowsAffected == 0 {
return op.NotFound{}
}
return nameTaken(renamed.Error)
}
// deleteRoom takes the room's messages with it, in one transaction, so// no message is left pointing at a room that is gone.func (app *App) deleteRoom(ctx context.Context, id int64) error {
return app.database.G.WithContext(ctx).Transaction(
func(transaction *gorm.DB) error {
err := transaction.Where("room_id = ?", id).
Delete(&Message{}).Error
if err != nil {
return err
}
deleted := transaction.Delete(&Room{}, id)
if deleted.Error == nil && deleted.RowsAffected == 0 {
return op.NotFound{}
}
return deleted.Error
})
}
func checkRoomName(name string) error {
if name == "" || utf8.RuneCountInString(name) > roomNameLimit {
return op.Invalid{Fields: map[string]string{
"Name": "Give the room a name of 1 to 40 characters.",
}}
}
returnnil}
// nameTaken turns the unique index's refusal into a message the form// can show beside the name.func nameTaken(err error) error {
if err != nil && strings.Contains(err.Error(), "UNIQUE") {
return op.Invalid{Fields: map[string]string{
"Name": "There is already a room with that name.",
}}
}
return err
}
package chat
import (
"net/http""amadan.net/rastrillo/rastrillo/action""amadan.net/rastrillo/rastrillo/csrf")
const homePage action.Path = "/"const accountPage action.Path = "/account"const livePage action.Path = "/live"// Routes registers everything the app serves. The API and MCP are outside// the page group: a bearer token is their only credential, so they get no// CSRF check and no page middleware.func Routes(routes *action.Routes, app *App) {
routes.Mount("/static", assets.Handler(), "static")
routes.Mount("/api/v1/mcp", app.mcp, "mcp")
routes.Mount("/api/v1", app.api, "api")
// Every page and form goes in this group: it is what checks CSRF. routes.Group(func(guarded *action.Routes) {
guarded.Guard("csrf", csrf.Protect(app.origin))
guarded.Guard("pages", pages.Middleware)
guarded.Guard("signedIn", app.signedIn)
// After a first link, the offer of a faster way in, once. guarded.Guard("signinGate", app.signins.Gate)
app.mountAuth(guarded)
guarded.Get(homePage, app.home)
// Owned pages and the stream: a visitor signs in first. guarded.Group(func(owned *action.Routes) {
owned.Guard("session", app.auth.RequireSession)
owned.Get(accountPage, app.account)
owned.Get(roomPage, app.room)
owned.Post(messagesPage, app.postMessageAt)
owned.Group(func(admin *action.Routes) {
admin.Guard("admin", app.requireAdmin)
admin.Get(adminRoomsPage, app.adminRooms)
admin.Post(adminRoomsPage, app.addRoom)
admin.Get(adminRoomPage, app.adminRoom)
admin.Post(adminRoomPage, app.renameRoomAt)
admin.Get(adminRoomDeletePage, app.confirmDeleteRoom)
admin.Post(adminRoomDeletePage, app.deleteRoomAt)
})
owned.Handle(http.MethodGet, livePage, app.live.Handler(),
"live")
})
})
}