- TestMessageSavingNoListener: send, reply, ReplyTo and edit answer as before the seam, post-save events fire; event fields pinned - TestMessageSavingRejects: 422 under the Rejection field (content when empty), nothing stored or changed, no post-save event, no publication - TestMessageSavingOtherError: a plain listener error stays a 500
Chat
A compiled chat plugin for SummerCMS: conversations, messages and realtime delivery through lighthouse.
import _ "git.golem15.com/golem15/sm-chat-plugin"
Name: Talk on the shore; messages stay after the tide.
Module git.golem15.com/golem15/sm-chat-plugin, package chat, plugin ID golem15.chat, requires golem15.user. Display name Chat / Czat.
Overview
The plugin ports the WinterCMS Golem15.Chat plugin. Hosts register a chat context (a team, an organisation) at build time through *contracts.Registry. classes.Service is the ChatService successor: it persists messages, fires golem15.chat.message.created / .updated / .deleted inside the write transaction, and lighthouse Bind publishes created.chat.message to the context channel plus chat:conversation:{id} with an ids-only payload. Explicit Emit helpers cover typing, per-user chat:message / chat:read / chat:unread, deleted.chat.message, and the additive updated.chat.message and reacted.chat.message.
Tables (PHP v1.3.0 names, one idempotent baseline migration 202610160001_create_golem15_chat_baseline, every statement IF NOT EXISTS):
golem15_chat_conversations: the conversations (models.Conversation), keyed to a context bycontext_type(a morph alias) andcontext_id;golem15_chat_participants: membership and read/mute flags (models.Participant);golem15_chat_messages: messages (models.Message) withroot_idthreading,edited_atand soft deletes;metadatais JSONB;golem15_chat_thread_summaries: the reply sidecar (models.ThreadSummary);golem15_chat_thread_mutes: per-member mute of one thread root (models.ThreadMute);golem15_chat_reactions: one row per message, user and reaction key (models.Reaction), added by the additive migration202610260001_create_golem15_chat_reactions(alsoIF NOT EXISTS).
Message.MorphName stays the PHP class string Golem15\Chat\Models\Message so adopted system_files rows keep resolving.
Features
- Build-time context registry. A host plugin calls
Registry.Add(pluginID, Registration{Alias, Loader, LegacyPHPClass}).Resolver(alias)returnsErrUnknownContextTypeand is never skipped. Chat itself registers no host aliases. - CanActFor.
contracts.Context.CanActFor(ctx, actorID, memberID)is on the interface.contracts.DefaultCanActForreturns true only whenactorID == memberID. - SendMessage / EditMessage / DeleteMessage. Persist inside
lagoon.Transactionand Fire the matching festival event.SendMessagerequires the sender to be a conversation participant (PHPhasParticipant); a context member who is not a participant isErrNotParticipant. A reply also enqueuesgolem15.chat.maintain_thread_summaryon thebroadcastsqueue. - GetOrCreateDm. Same registered context only (not a friendship DM). Creates the two-person DM of the actor and the other user. Refusal is
ErrCannotCreateDMwhen the host is missing orChatEnabledis false. - GetGroupChat. Finds or creates the one group conversation of a context. On an existing group it still lazy-joins a context member via
addParticipant. - user.Deleting. Boot Listens
user.DeletingandReassignCreatedBymovescreated_byto another remaining participant (DMs and group rows) so the PHPON DELETE CASCADEconstraint ongolem15_chat_conversations.created_bycan stay. - MuteThread. Upserts
golem15_chat_thread_mutesfor(actor_id, root_id). Missing or unauthorized isErrNotFound. - Ids-only socket payload. Bind payload keys are
id,conversation_id,sender_id,root_id,type,action,created_at. Content, names, avatars and attachments never travel on the conversation channel. FullMessageAPI(PHPtoApiArrayplusroot_id/thread_summary) travels only onchat:messageand REST. Attachment URLs use/_chat/api/v1/attachments/{messageId}/{fileId}. - Reactions (additive). A participant who can see a message adds or removes a reaction key from the configured list (
golem15.chat.reactions). Adding is idempotent. Adding any other key isclasses.ErrUnknownReaction(HTTP 422errors.key); removing checks only the key's shape (1 to 32 bytes), so a reaction whose key left the config can still be taken off.MessageAPI.reactionsis[{key, count, user_ids}]in configured key order, omitted when empty, and a message page loads its reactions in one query. A change emitsreacted.chat.messageonchat:conversation:{id}with{id, conversation_id, user_id, key, action}(addedorremoved), inside the write. - Message metadata (additive).
SendMessageWith(ctx, SendInput{…, Metadata})stores an optional JSON object of at mostclasses.MaxMetadataBytes(4096) bytes serialized ingolem15_chat_messages.metadata; anything else isclasses.ErrMetadataInvalid(HTTP 422errors.metadata). The plugin does not interpret it (hosts keep, for example, embed references there).MessageAPI.metadatareturns it, omitted when empty, and an edit keeps it.SendMessagekeeps its signature as a wrapper without metadata. - Live edits (additive).
EditMessageemitsupdated.chat.messageonchat:conversation:{id}with{id, conversation_id, action: "updated", edited_at}inside the edit transaction, so other clients refetch the message. - Delete-only moderation (additive). A host
Contextmay also implementcontracts.MessageModerator.CanDeleteMessageis the sender while they still take part (Service.IsParticipant), elseCanModerateMessage(ctx, userID, conversationType), elseCanOverseeChats.CanEditMessageis the sender while they still take part, orCanOverseeChats, and never consults the moderator hook;CanViewis unchanged. Moderators and overseers need not be participants: the host decides, so a host that wants moderation to end when someone leaves checks membership inCanModerateMessage. Hosts that do not implement it behave as before. - Live membership (additive). A host
Contextmay also implementcontracts.LiveMembership. WhenRequireLiveMembership()is true, a participant row of that context's conversations counts only whileHasMemberis true: reading, sending, editing and deleting their own messages, marking read, typing, uploading, subscribing tochat:conversation:{id}and receivingchat:messageonuser:{id}stop as soon as someone leaves the context, before the host prunes their rows.Service.IsParticipantexposes the same check. Hosts that do not implement it keep the participant-row behaviour. - Pre-save seam (additive).
SendMessageWith(and soSendMessage, replies andReplyTo) andEditMessagefireevents.MessageSavingafter their access and empty-content checks and before the write transaction opens. A listener error aborts the write: no row is stored or changed,MessageCreated/MessageUpdateddo not fire and nothing is published. A listener that returnscontracts.Rejection{Field, Message}gets the 422 validation envelope{"error":"Validation failed","errors":{Field:[Message]}}(contentwhenFieldis empty); any other listener error stays a 500. Without a listener nothing changes. - Channel authorizer.
AuthorizeChatallows only participants onchat:conversation:{id}(the plugin registers it withService.IsParticipant, so live membership applies) with capabilities["prs"]. It splits the channel itself after stripping apresence:prefix and does not calllighthouse.ChannelID.
Usage
Register a context from an application plugin after looking the registry up (chat publishes it at Boot):
func (p *Plugin) Boot(app *backpack.App) error {
reg, _ := app.Lookup[*contracts.Registry]()
return reg.Add(p.ID(), contracts.Registration{
Alias: "teams",
LegacyPHPClass: `Acme\Teams\Models\Team`,
Loader: loadTeam, // returns contracts.Context
})
}
The service is published once the database is. Look it up at request time:
svc, _ := app.Lookup[*classes.Service]()
msg, err := svc.SendMessage(ctx, conversationID, senderID, "hello", nil, nil)
The generic JSON API is chat.APIPrefix (/_chat/api/v1). Routes sit behind jwt.auth and named buckets (chat-api 120/min, chat-dm 10/min). The app mounts that guard (and lighthouse.Mount); this plugin only names it (D-09). Published paths:
GET|POST /contexts/{type}/{id}/conversationGET|POST /conversations/{id}/messages(POST body{content, attachment_ids?, root_id?, metadata?}; attachments abovegolem15.chat.max_message_bytestogether, when set, are 422errors.attachment_ids)POST /conversations/{id}/read,/typing,/muteGET|PUT|DELETE /messages/{id}GET|POST /messages/{id}/repliesPUT /threads/{rootId}/mute(chat-ownedgolem15_chat_thread_mutes; bodymuted; responseroot_id,is_muted)POST /contexts/{type}/{id}/dm(chat-dm)GET /reactions({"data": [key, …]}, the configured list in order; additive)POST /messages/{id}/reactions(body{"key"}; idempotent) andDELETE /messages/{id}/reactions/{key}(URL-encoded key); both answer{"data": {"message_id", "reactions"}}, 404 for a message the caller cannot see or a deleted one, 422errors.keyfor an added key outside the list or a removed key over 32 bytes (additive)POST /attachments(pending,is_public=false, fieldchat-pending-{actorID}; request body limitgolem15.chat.upload_body_limit; ownchat-uploadbucket, 20/min; only for a user who takes part in at least one conversation, else 404; at mostgolem15.chat.pending_max_files(10) unsent uploads per user, andpending_max_byteswhen set, else 422errors.file)GET /attachments/{messageId}/{fileId}(private stream after participation; missing and unauthorized 404)
A host plugin can refuse content before it is stored by listening to the pre-save event (here a neutral acme plugin with its own allowed check):
app.Events.Listen[*events.MessageSaving]("acme.filter", func(ctx context.Context, ev *events.MessageSaving) error {
if !allowed(ev.Content) {
return contracts.Rejection{Field: "content", Message: "This message is not allowed."}
}
return nil
})
Downloads are never served from a public blob URL. Legacy /api/chat/* is not registered (D-10).
Uploads that are never sent with a message are deleted by chat:prune-pending (row and blob), which the plugin schedules every hour through pact.HasSchedule; the age is golem15.chat.pending_ttl_hours (24). The schedule runs where the app runs a queue worker (queue.work_in_serve or queue:work).
API reference
| Identifier | Description |
|---|---|
chat.PluginID |
golem15.chat |
chat.APIPrefix |
/_chat/api/v1 (D-06) |
chat.APIBucket |
Throttle bucket chat-api (120/min) |
chat.DMBucket |
Throttle bucket chat-dm (10/min) |
chat.ConfigUseUIAvatars |
Config key golem15.chat.use_ui_avatars |
chat.ConfigUploadBodyLimit |
Config key golem15.chat.upload_body_limit |
chat.DefaultUploadBodyLimit |
1048576 (1 MiB, the framework body limit; hosts opt in to more) |
chat.UploadBucket |
Throttle bucket chat-upload (20/min) on POST /attachments |
chat.ConfigPendingMaxFiles / chat.ConfigPendingMaxBytes / chat.ConfigMaxMessageBytes |
Config keys of the pending-upload quota and the per-message attachment total |
chat.UploadBodyLimit |
The upload route's body limit from the config |
contracts.MessageModerator |
Optional host hook CanModerateMessage(ctx, userID, conversationType), consulted only by CanDeleteMessage |
contracts.Context |
Host grouping: members, HasMember, CanOverseeChats, ChatEnabled, GroupName, CanActFor, BroadcastChannel |
contracts.DefaultCanActFor |
Self-action only |
contracts.Registry |
Add, Resolver, Registrations, optional SetProvider / ContextForUser |
contracts.ErrUnknownContextType |
Unknown morph alias; never skipped |
classes.Service |
ChatService successor (SendMessage, GetOrCreateDm, GetGroupChat, MuteThread, EditMessage, DeleteMessage, WithDB, ReassignCreatedBy, …) |
classes.New |
Builds the service; refuses a nil DB |
classes.Service.WithDB |
Shallow copy bound to a festival event transaction |
classes.Service.ReassignCreatedBy |
Moves created_by to another remaining participant on user.Deleting |
classes.APIPrefix |
/_chat/api/v1 |
classes.AttachmentLimits |
MaxBytes 102400*1024, PHP KNOWN_EXTS, banned SVG/HTML/XML |
classes.MaxAttachments |
5 files per message |
classes.PendingField |
chat-pending-{actorID} |
classes.Service.PrunePendingAttachments |
Deletes unsent uploads stored before a cutoff (row and blob); run by chat:prune-pending |
classes.Service.SetMaxMessageBytes / MaxMessageBytes |
Total size of one message's attachments (classes.ErrAttachmentsTooLarge) |
classes.Service.IsParticipant |
Participant check with the context's live membership |
classes.ErrPendingQuota |
Too many unsent uploads (HTTP 422 errors.file) |
contracts.LiveMembership |
Optional host hook RequireLiveMembership(): participant checks also require HasMember |
classes.MessageAPI |
PHP toApiArray plus root_id, thread_summary, and the additive reactions and metadata (both omitempty) |
classes.Service.MessagesAPI |
Serializes a page of messages with one reaction query |
classes.SendInput / classes.Service.SendMessageWith |
Send with optional metadata |
classes.MaxMetadataBytes / classes.ErrMetadataInvalid |
4096-byte metadata object limit |
classes.DefaultReactions / classes.AllowedReactions / classes.ConfigReactions |
Reaction key list (default 👍 ❤️ 😂 😮 😢 🙏) |
classes.Service.AddReaction / RemoveReaction / AllowedReactionKeys |
Reaction writes and the allowed list |
classes.ReactionAPI / classes.ErrUnknownReaction |
{key, count, user_ids}; key outside the list |
classes.Service.EmitReacted / EmitUpdated |
reacted.chat.message / updated.chat.message (ids-only) |
classes.AuthorizeChat |
lighthouse authorizer for namespace chat |
events.MessageCreated |
Festival event golem15.chat.message.created |
events.MessageUpdated |
Festival event golem15.chat.message.updated |
events.MessageDeleted |
Festival event golem15.chat.message.deleted |
events.MessageSaving |
Pre-save event: ConversationID, ActorID, MessageID (0 on create), RootID, Content (trimmed), Op; fired before the transaction, no Tx; a listener error aborts the write |
events.MessageSavingEventName |
golem15.chat.message.saving (Go-only, no PHP counterpart) |
events.OpCreate / events.OpUpdate |
MessageSaving.Op: create (send or reply) or update (edit) |
contracts.Rejection |
{Field, Message} error a MessageSaving listener returns to refuse content; the API answers 422 errors.{Field} (match with errors.As) |
jobs.MaintainThreadSummaryArgs |
River kind golem15.chat.maintain_thread_summary |
models.Message |
Row of golem15_chat_messages; MorphName is the PHP class string |
models.Conversation |
Row of golem15_chat_conversations |
models.Reaction |
Row of golem15_chat_reactions |
Configuration
| Key | Env | Default | Meaning |
|---|---|---|---|
golem15.chat.use_ui_avatars |
SUMMER_GOLEM15__CHAT__USE_UI_AVATARS (PHP: CHAT_USE_UI_AVATARS) |
true |
Fall back to ui-avatars.com when a member has no avatar |
golem15.chat.reactions |
SUMMER_GOLEM15__CHAT__REACTIONS (comma-separated, e.g. 👍,❤️) |
["👍", "❤️", "😂", "😮", "😢", "🙏"] |
Allowed reaction keys in display order; trimmed, deduplicated, at most 32 bytes each; an empty result means the default |
golem15.chat.upload_body_limit |
SUMMER_GOLEM15__CHAT__UPLOAD_BODY_LIMIT |
1048576 |
Request body limit of POST /attachments in bytes; 0 or negative means the default (1 MiB). Hosts that want larger files opt in; keep it at or below the proxy limit. The per-file, 5-file and banned-type rules still apply |
golem15.chat.pending_max_files |
SUMMER_GOLEM15__CHAT__PENDING_MAX_FILES |
10 |
Unsent uploads one user may have waiting; above it the upload is 422 errors.file |
golem15.chat.pending_max_bytes |
SUMMER_GOLEM15__CHAT__PENDING_MAX_BYTES |
0 |
Total size of one user's unsent uploads; 0 means no byte quota |
golem15.chat.pending_ttl_hours |
SUMMER_GOLEM15__CHAT__PENDING_TTL_HOURS |
24 |
Age after which chat:prune-pending deletes an unsent upload |
golem15.chat.max_message_bytes |
SUMMER_GOLEM15__CHAT__MAX_MESSAGE_BYTES |
0 |
Total size of one message's attachments; 0 means no total limit |
CLI commands
| Command | Meaning | Example |
|---|---|---|
chat:prune-pending |
Deletes chat uploads never sent with a message (field chat-pending-*, unattached) older than --hours (default golem15.chat.pending_ttl_hours), row and blob. Scheduled every hour by the plugin. Ends with Deleted N pending chat upload(s) older than H hour(s). |
bin/<app> chat:prune-pending --hours 2 |
chat:rewrite-context-types |
Idempotent UPDATE of golem15_chat_conversations.context_type from each registration's LegacyPHPClass to its alias. Hosts must Registry.Add before running it. Does not rewrite system_files.attachment_type. No flags; ends with Rewrote N conversation context_type row(s). |
bin/<app> chat:rewrite-context-types |
bin/<app> help chat:rewrite-context-types shows the long help and examples. The plugin logs through the component chat (log.components.chat in config/log.yaml).
chat:migrate-attachments is not ported.
Dependencies
golem15.user(required),git.golem15.com/golem15/sm-user-pluginv0.1.2 or later (classes.DeletingEvent)- SummerCMS v0.4.0 modules: backpack, party, pact, lagoon, festival, lighthouse, conga, bonfire, diary
Testing
go vet ./...
go test -short ./... # includes TestChatHTTPAuth (401 without jwt)
go test -run '^TestChatTracer$' -v . # needs Docker
go test -run '^TestChatHTTPTracer$' -v . # needs Docker; one authenticated send
TestCommandsDocumented (in -short) logs, without failing, each command whose help lacks a description, long help, examples or an option description (bonfire.CheckDocs).
The proof host is golem15.user + golem15.chat + a test-only teams fixture. TestFixtureAbsentFromProduction keeps the fixture id and the four retired tokens out of production sources.
Changelog
v0.1.5
- v0.1.5: pre-save
MessageSavingevent andcontracts.Rejection(additive; no listener means no change).SendMessageWith, replies andEditMessagefire it before the write transaction;writeChatErrormaps aRejectionto the 422 validation envelope. No route, payload, table, migration or config key changes.
v0.1.4
plugin.yamlmanifest for the SummerCMS marketplace. No code change.
v0.1.3
- Editing or deleting one's own message now requires the sender to still take part in the conversation (
Service.IsParticipant: a participant row and, for a context implementingcontracts.LiveMembership, current membership). - A removed user gets
ErrCannotEdit/ErrCannotDelete, which is HTTP 404 onPUT/DELETE /messages/{id}(the answer every other refusal gives);CanEditMessage/CanDeleteMessageanswer the same way. - The moderator (
contracts.MessageModerator) and overseer (CanOverseeChats) rules are unchanged and used as the host answers them. Moderators need not be participants (a host'sCanModerateMessagemay require membership). - Restrictive only: no route, payload or exported signature changes. Hosts without
LiveMembershipsee a change only for a sender whose participant row is gone. - On a
Servicewithout a database,CanEditMessageandCanDeleteMessagenow return an error instead of answering for the sender.
v0.1.2
- The service resolves the private uploads bucket lazily through
classes.Options.BucketLookup;bootServicepasses a lookup overapp.Lookup[*blob.Bucket](). - Why:
surf servepublishes*blob.Bucketafter it runs the database hooks, and the service is built insidelagoon.OnDatabase. The eager lookup alone stayed nil there, so everyPOST /_chat/api/v1/attachmentsand everychat:prune-pendingrun failed withgolem15.chat: uploads bucket is not published. The first non-nil lookup result is cached and shared byWithDBcopies. Options.Bucketstill wins when set, and the lookup is then never called. With neither,Bucket()is nil and the error is unchanged. Hosts that build their own Service can pass aBucketLookup.
v0.1.1
Several v0.1.1 changes apply to every host by default and can make existing upload flows fail after an upgrade.
- Deleted messages are tombstones (security fix): the API and realtime payloads carry no content, metadata, attachments or reactions for them, and an overseer can no longer read deleted content through
GET /messages/{id}. - Upload gate:
POST /attachmentsis 404 for a user with no participant row in any conversation. - Pending-upload quota:
golem15.chat.pending_max_files(default 10; 0 or negative also means 10) and optionalgolem15.chat.pending_max_bytes(0 = off). Above it the upload is 422errors.file(classes.ErrPendingQuota). - New
chat:prune-pending, scheduled hourly throughpact.HasSchedule, deletes unsent uploads older thangolem15.chat.pending_ttl_hours(24), row and blob. It runs where the app runs a queue worker. - New
chat-uploadthrottle bucket (20/min) onPOST /attachments, on top ofchat-api. - The default
golem15.chat.upload_body_limitis 1048576 (1 MiB, the framework body limit), down from v0.1.0's 105906176. Hosts that accept larger files must set it. - Opt-in
golem15.chat.max_message_bytes/Service.SetMaxMessageBytes(default 0 = off): attachments above the total are 422errors.attachment_ids. - Opt-in
contracts.LiveMembershipandService.IsParticipant. - Removing a reaction checks only the key shape (1-32 bytes); adding one still checks the configured list.