In the previous step one app kept several conversations. Now the members of a conversation agree on two lists: who is in it, and which rooms it has.
Messages need no agreed order. Each member writes its own log, and two messages written at the same moment can be shown in either order without anyone losing anything: they commute. The member list and the room list are different: they are shared state. Two admins can act at the same moment, one removing Carol while the other approves Dave, or both adding a room called "design", and every member must end with the same lists. kolo-braid gives that: it merges every member's entries into one order that every peer computes the same way, and an apply function you write turns that order into the lists. The chat keeps its messages, profiles and offline delivery as they were, moves only the two shared lists into a braid, and talks only to the people on the agreed member list.
What this list cannot do: an admin is chosen when a request is approved and stays one, the member who settles the order (the person who started the conversation) cannot be removed, and a removal takes effect in each member's app only once that app has learned of it. Removing someone does not change the conversation key, so it is not revocation: the removed person keeps the key and what they received. A removed member keeps everything it received and the key; any app that has not learned of the removal still gives it what it has. kolo-braid is beta: its settlement and membership are model-checked within bounds, which is not a proof, and it has been tested on one Mac, on 127.0.0.1 only, never over a real network.
You write the lesson: the apply function, in state.go, and the braid of a conversation, in braid.go: opening it, who the chat talks to, the one place that hands a connection to the braid, and the changes an admin makes. Everything else is plumbing that carries this through the app, and you bring it in from the tag step-7.
1Check what you need and bring in the given files
You need what step 6 needed: Go 1.26 or newer, Node.js, wails3, the bootstrap node and a local pin. Start from the project you finished in step 6. Fetch the tags:
git fetch origin --tagsBring in the window, the module files, the plumbing and the tests of this step. They replace your files of step 6 with the same names:
git checkout step-7 -- frontend go.mod go.sum mux.go braidstatus.go chatservice.go conversations.go invite.go pin.go profile.go '*_test.go'| File | What it does |
|---|---|
frontend/ | The window: Approve as member or as admin, Remove with its confirmation, marks for pending changes, and the sentences of chat:state. |
go.mod, go.sum | Add kolo-braid v0.1.0 and what it needs. |
mux.go | Splits one connection between the chat's messages, the chat's kolo-sync and the braid, by a tag byte at the start of each stream. |
braidstatus.go | What the window shows about the lists (chat:state), and the pause of a member whose braid breaks the protocol. |
chatservice.go | Opens the braid's store at start and the braid in enter, gives every connection a mux, puts our braid's ID in the hello, and asks the accepted set before it registers, answers, serves, pulls or shows anyone. |
invite.go | Every invite waits for an admin; the joiner sends a braid join request and completes its braid with the welcome the invite carries. |
profile.go | Profiles stay in each member's kolo-kv directory; the owner's room and member lists are gone. |
pin.go | The pull from the pin takes the authors on the member list only. |
conversations.go | Layout 3, the wrappers for the new calls, a join that fails removes its folder, and the start-up checks of the data folder. |
*_test.go | The tests of this step. |
The tag also holds the finished state.go and braid.go, in case you want to compare yours with them. Until you write them, the project does not build.
2One connection for the chat and the braid
kolo-swarm keeps one connection per peer key, and the chat's messages, the chat's kolo-sync server and the braid's ServeConn each must be the only one that accepts streams on that connection. So mux.go makes every stream start with a tag byte: m for the chat's messages, on uni streams; s for the chat's kolo-sync, on bidi streams; and b for the braid, on both. Each accepted stream gets a goroutine of its own, which reads the tag and hands the stream to its part; a wrong or late tag cancels that stream only. Each part looks like a whole connection to kolo-sync and kolo-braid, and its Close ends that part only. Every connection allows 64 incoming streams per direction, so a busy braid never takes the credit the chat needs:
const (
tagMsg = 'm'
tagSync = 's'
tagBraid = 'b'
// maxStreams is the incoming streams per direction a connection allows: 16 for the braid's pulls, 16 for the
// chat's kolo-sync streams and 32 for the uni messages of both.
maxStreams = 64
// maxWaiting is how many streams a braid part may hold waiting; one more is a fault, which closes the part and
// frees its streams at once. UNSOURCED: half of maxStreams, so a stuck braid never holds the credit the chat needs.
maxWaiting = maxStreams / 2
codeBadTag = 3
)A peer of step 6 sends untagged streams, so the two versions do not talk to each other.
3Write the apply function
The braid keeps the member list itself. Your apply function keeps the room list. A data entry of the chat is a fixed byte layout, not JSON: byte 0 the version, byte 1 the operation, byte 2 the length of the name in bytes, then the name. Version 1 has one operation, "add a room". The apply function must give the same result on every peer, so it reads only the view, the entry and the member list at the entry's position, never a clock or a map's order.
Create state.go with:
package main
// The shared state of a conversation: the room list, kept by kolo-braid.
//
// The braid keeps the member list itself (Snapshot.Members), so the view holds only the rooms. A data entry of the chat
// is a fixed byte layout: byte 0 the version, byte 1 the op, byte 2 the name's length in bytes, then the name. Version 1
// has one op, "add a room".
import (
"errors"
"fmt"
"slices"
kolobraid "github.com/ciranda-dev/kolo-braid"
)Add to state.go the name of the app's state and the key of the room list:
const (
stateApp = "kolochat/state/v1"
roomV1 = 1
opAddRoom = 1
)
var keyRooms = []byte("rooms")The checks run in a fixed order. Every kind of entry but data returns nil, since the library applies what membership entries do. A writer that is not an admin is refused before the version is read, so old and new apps agree on it and a member cannot halt anyone's view. A version above 1 is an error, which halts this app until it is updated: whatever a later version adds comes after byte 0, so an old app never refuses an entry it does not understand. Add to state.go:
// applyState keeps the view key "rooms", the sorted list of rooms admins added. It reads only the view, the entry and
// the roster at the entry's position, so every peer computes the same list.
func applyState(tx *kolobraid.Tx, e *kolobraid.Entry) error {
if e.Kind != kolobraid.KindData {
return nil // the library applied the membership effect
}
// Before the version: old and new apps agree on a non-admin's entry, so nobody can halt every view.
if m, ok := tx.Member(e.Writer); !ok || m.Roles&kolobraid.RoleAdmin == 0 {
return kolobraid.Reject("not an admin")
}
b := e.Body
switch {
case len(b) == 0 || b[0] == 0:
return kolobraid.Reject("no version")
case b[0] > roomV1: // a later version halts this app until it is updated, and is never rejected
return fmt.Errorf("room entry of version %d", b[0])
case len(b) < 3 || b[1] != opAddRoom || int(b[2]) != len(b)-3:
return kolobraid.Reject("not a version 1 room entry")
}
name := string(b[3:])
raw, err := tx.Get(keyRooms)
if err != nil && !errors.Is(err, kolobraid.ErrNotFound) {
return err
}
rooms, err := decodeRooms(raw)
if err != nil {
return err
}
switch {
case validRoomName(name) != nil, sameRoom(name, defaultRoom):
return kolobraid.Reject("bad room name")
case slices.ContainsFunc(rooms, func(r string) bool { return sameRoom(r, name) }):
return kolobraid.Reject("room exists")
case len(rooms) >= maxRooms:
return kolobraid.Reject("too many rooms")
}
rooms = append(rooms, name)
slices.Sort(rooms)
return tx.Put(keyRooms, encodeRooms(rooms))
}The room list in the view is a list of names, each with its length before it:
// encodeAddRoom is the body of an entry that adds the room name, which validRoomName accepts: at most 128 bytes.
func encodeAddRoom(name string) []byte {
return append([]byte{roomV1, opAddRoom, byte(len(name))}, name...)
}
// encodeRooms writes the room list as length-prefixed names.
func encodeRooms(rooms []string) []byte {
var out []byte
for _, r := range rooms {
out = append(append(out, byte(len(r))), r...)
}
return out
}
func decodeRooms(b []byte) ([]string, error) {
var rooms []string
for len(b) > 0 {
n := int(b[0])
if n == 0 || len(b) < 1+n {
return nil, errors.New("damaged room list")
}
rooms, b = append(rooms, string(b[1:1+n])), b[1+n:]
}
return rooms, nil
}
// roomsOf reads the rooms admins added from a snapshot of the braid's view.
func roomsOf(s *kolobraid.Snapshot) []string {
raw, err := s.Get(keyRooms)
if err != nil {
return nil
}
rooms, _ := decodeRooms(raw)
return rooms
}Two rooms are the same name when their ASCII letters match in any case, and every other byte matches as it is. Go's Unicode tables never decide what a peer applies:
// sameRoom compares two names with ASCII letters folded and every other byte as is: Go's Unicode tables never decide
// what a peer applies.
func sameRoom(a, b string) bool {
if len(a) != len(b) {
return false
}
for i := range len(a) {
if lowerASCII(a[i]) != lowerASCII(b[i]) {
return false
}
}
return true
}
func lowerASCII(c byte) byte {
if 'A' <= c && c <= 'Z' {
return c + 'a' - 'A'
}
return c
}4Open the braid
Each conversation has a braid in its own store, braid/, next to store/, with the conversation's kolo-id as its member key. Its genesis fixes the group: one settler, the person who starts the conversation; at most 64 members, kolo-braid's default; and bodies of at most 1 KiB, its least. The founder creates the braid; a joiner gets it from the welcome its invite carries.
Create braid.go with:
package main
//lint:file-ignore ST1005 these errors are sentences the window shows as they are
// The braid of a conversation: the member list and the room list, which every member must end with alike.
//
// Each member writes its own strand, and kolo-braid merges them into one order that every peer computes the same way;
// applyState (state.go) turns that order into the room list, and the braid keeps the roster. The chat talks only to
// the keys on that roster (the accepted set): a hello that proves the conversation key and names our group starts the
// braid's sync, and only an accepted key is registered, served, pulled and shown. Removing a member is not
// revocation: it keeps the conversation key.
import (
"cmp"
"context"
"encoding/hex"
"errors"
"log"
"path/filepath"
"slices"
"strings"
"time"
kolobraid "github.com/ciranda-dev/kolo-braid"
kolodht "github.com/ciranda-dev/kolo-dht"
invite "github.com/ciranda-dev/kolo-invite"
kolosecure "github.com/ciranda-dev/kolo-secure"
kolostore "github.com/ciranda-dev/kolo-store"
kolotransport "github.com/ciranda-dev/kolo-transport"
)Add the bounds, the group and the sentences the window shows:
const (
// braidWrite bounds every braid write: kolo-braid's ConfirmWait.
braidWrite = 10 * time.Second
stateTick = time.Second
codeRestart = 2 // closes a connection so both braids start fresh on the next one
)
// groupConfig is fixed in the genesis: one settler, the founder; 64 members, kolo-braid's default; 1 KiB bodies, its
// least.
var groupConfig = kolobraid.GroupConfig{
App: stateApp, Quorum: kolobraid.Majority, MaxMembers: maxMembers, MinSettlers: 1, MaxSettlers: 1, MaxBody: 1024,
}
var (
ErrNotAdmin = errors.New("Only an admin can do that.")
ErrFull = errors.New("This conversation has 64 members, the most it can have.")
ErrWaitingForMember = errors.New("Waiting for another member to come online.")
ErrCannotWrite = errors.New("This copy of the conversation can no longer write: ask an admin to invite you again.")
ErrSettler = errors.New("The member who settles changes to members and rooms cannot be removed.")
ErrUnknownMember = errors.New("That person is not on the member list.")
errNoBraid = errors.New("the shared member list of this conversation is missing")
)Open the braid. noBraidYet decides what a folder without conversation.json is: a join that did not finish, or a member's folder that lost the file, which is refused:
func braidOptions(db kolostore.Backend) kolobraid.Options {
// MaxPullAhead is twice the least, so a settler's next pulse is always in reach.
return kolobraid.Options{Backend: db, App: stateApp, Apply: applyState, Limits: &kolobraid.Limits{MaxPullAhead: 128}}
}
// dhtConfig gives every connection 64 incoming streams per direction: the chat and the braid share them (mux.go).
func dhtConfig() *kolodht.Config {
return &kolodht.Config{Secure: &kolosecure.Config{Transport: &kolotransport.Config{MaxIncomingStreams: maxStreams}}}
}
func openBraidStore(dir string) (kolostore.Backend, error) {
return kolostore.OpenPebble(filepath.Join(dir, "braid"))
}
// openBraid opens the conversation's braid, or creates it for the person who starts the conversation. A joiner has
// it from Complete already.
func (c *ChatService) openBraid(founder bool) (err error) {
if c.braid != nil {
return nil
}
c.braid, err = kolobraid.Open(c.ctx, c.id, braidOptions(c.braidDB))
if errors.Is(err, kolobraid.ErrNotFound) {
if !founder {
return errNoBraid
}
c.braid, err = kolobraid.Create(c.ctx, c.id, groupConfig, braidOptions(c.braidDB))
}
return err
}
// noBraidYet refuses a folder without conversation.json that holds anything of a member: a completed braid, a copy
// of another member's log, or entries in our own logs. Such a folder lost the file, and is never taken for a join
// that did not finish.
func (c *ChatService) noBraidYet() error {
b, err := kolobraid.Open(c.ctx, c.id, braidOptions(c.braidDB))
if err == nil {
b.Close()
return &DataDirError{Dir: c.set.DataDir}
}
if !errors.Is(err, kolobraid.ErrNotFound) {
return err
}
all, err := c.store.List()
if err != nil {
return err
}
if len(all) > 2 || c.log.Len() > 0 || c.dirLog.Len() > 0 {
return &DataDirError{Dir: c.set.DataDir}
}
return nil
}5Talk only to members
A hello has two results. It is proven when it proves the conversation key and names our braid. A peer is accepted when it is proven and on the member list of the braid's view. The accepted set lives in memory and is rebuilt from one snapshot on every braid event. When a peer becomes accepted, the chat registers it; when it leaves the list, the chat drops it. Add to braid.go:
// startBraid builds the accepted set before anything is pulled, and follows the braid's events.
func (c *ChatService) startBraid() {
c.mu.Lock()
c.group = c.braid.GroupID()
c.pauses = map[string]*pause{}
c.mu.Unlock()
c.rebuild()
c.wg.Go(c.stateLoop)
}
// stateLoop follows the braid's events and, at least every stateTick, tells the window the lists and the state. Every
// event rebuilds the accepted set from the whole roster, so an event dropped past MaxEvents changes nothing: the
// events after it rebuild.
func (c *ChatService) stateLoop() {
for {
ctx, cancel := context.WithTimeout(c.ctx, stateTick)
ev, err := c.braid.Next(ctx)
cancel()
if c.ctx.Err() != nil || errors.Is(err, kolobraid.ErrClosed) {
return
}
if err == nil {
c.rebuild()
switch ev.Kind {
case kolobraid.EventHalted, kolobraid.EventDiverged, kolobraid.EventSettlementHalted, kolobraid.EventStrandLost:
log.Printf("member list: event %d at %d", ev.Kind, ev.Position)
}
}
c.publishDirectory()
c.emitState(c.braid.Status())
}
}
// rebuild reads the roster from one snapshot of the view into the accepted set. Proven peers that are now accepted
// are registered, get a reply hello and a sync; registered peers that are not accepted any more are dropped.
func (c *ChatService) rebuild() {
snap := c.braid.View()
members := snap.Members()
snap.Close()
accepted := make(map[string]kolobraid.Member, len(members))
for _, m := range members {
accepted[hex.EncodeToString(m.Key)] = m
}
c.mu.Lock()
c.accepted = accepted
var join []*link
dropped := false
for key, l := range c.links {
_, ok := accepted[key]
switch {
case ok && !l.registered && l.hello != nil:
join = append(join, l)
case !ok && l.registered:
l.registered, dropped = false, true
log.Print("not on the member list: ", key[:8])
}
}
c.mu.Unlock()
for _, l := range join {
c.accept(l, *l.hello, true, true)
}
if dropped {
c.emitPeers()
}
}
// isAccepted says whether author, a hex key, is on the roster of the view.
func (c *ChatService) isAccepted(author string) bool {
c.mu.Lock()
defer c.mu.Unlock()
_, ok := c.accepted[author]
return ok
}
// IsAdmin says whether we are an admin: who may invite, approve, remove members and add rooms.
func (c *ChatService) IsAdmin() bool {
c.mu.Lock()
defer c.mu.Unlock()
m, ok := c.accepted[hex.EncodeToString(c.pub)]
return ok && m.Roles&kolobraid.RoleAdmin != 0
}The given chatservice.go checks the accepted set on every path of the chat: before it registers or answers a hello, shows a message, serves our logs, or pulls a member's log from the member or the pin. This is how it serves our logs:
if c.isAccepted(hex.EncodeToString(peer)) && owner.Equal(c.pub) && (logID == c.log.ID() || logID == c.dirLog.ID()) {6Hand a connection to the braid
A proven hello starts the bidi streams and the braid's sync, also for someone who is not on the member list yet, so a joiner can sync its own admission. A peer that sends no hello is someone who joins with an invite, and gets the invite protocol instead. This is the one place where a connection meets the braid. Add to braid.go:
// serveAfterHello serves our logs and the braid to the peer once its hello is proven: it knows the conversation key
// and names our braid. Who is not on the roster yet still gets the braid, so a joiner can sync its own admission. A
// peer that sends no hello in sendTimeout is someone who joins with an invite: one who left keeps its announcement of
// the topic for up to 20 minutes (kolo-dht's record lifetime), so the topic alone does not tell.
func (c *ChatService) serveAfterHello(l *link) {
timer := time.NewTimer(sendTimeout)
defer timer.Stop()
select {
case <-l.proven:
c.wg.Go(l.mx.acceptBidi)
c.wg.Go(func() { c.serveBraid(l) })
c.srv.Serve(c.ctx, l.mx.part(tagSync))
case <-timer.C:
c.mu.Lock()
if c.links[l.key] == l {
delete(c.links, l.key)
}
c.mu.Unlock()
c.inv.ServePeer(c.ctx, l.p)
case <-c.ctx.Done():
}
}The braid syncs on the connection's b part. Only ErrNotMember, a key the braid has not known for 60 seconds, closes the connection, so the swarm dials again and both braids start fresh: a joiner that met someone before its admission was ordered, or a removed member. A braid that breaks the protocol is paused with that member, and the chat goes on:
// serveBraid syncs the braid with one peer on the connection's 'b' part. Only ErrNotMember closes the connection; a
// braid fault pauses the braid with that member and the chat goes on.
func (c *ChatService) serveBraid(l *link) {
conn := l.p.Conn()
for {
if wait := c.pausedFor(l.key); wait > 0 {
t := time.NewTimer(wait)
select {
case <-t.C:
case <-conn.Context().Done():
t.Stop()
return
case <-c.ctx.Done():
t.Stop()
return
}
c.unpause(l.key)
conn.CloseWithError(codeRestart, "kolochat: braid starts fresh")
return
}
part := l.mx.part(tagBraid)
c.served(l.key)
err := c.braid.ServeConn(c.ctx, part)
part.Close()
switch {
case errors.Is(err, kolobraid.ErrNotMember): // unknown for 60 s: a joiner tries again, a removed member redials
conn.CloseWithError(codeRestart, "kolochat: not a member")
return
case errors.Is(err, kolobraid.ErrProtocol), part.overflowed.Load():
c.braidFault(l.key)
default:
return
}
}
}7Add rooms, remove and approve members
Every write to the braid runs under 10 seconds, kolo-braid's ConfirmWait. Only an admin writes. An admin adds a room by appending an entry, and removes a member with a braid call. The settler cannot be removed:
// writeCtx bounds a braid write.
func (c *ChatService) writeCtx() (context.Context, context.CancelFunc) {
return context.WithTimeout(c.ctx, braidWrite)
}
// writeError turns an error of a braid write into the sentence the window shows.
func (c *ChatService) writeError(err error) error {
switch {
case err == nil:
return nil
case errors.Is(err, kolobraid.ErrUnconfirmed):
c.mu.Lock()
c.unconfirmed = true
c.mu.Unlock()
return ErrWaitingForMember
case errors.Is(err, kolobraid.ErrStrandLost):
return ErrCannotWrite
case errors.Is(err, kolobraid.ErrNotAdmin), errors.Is(err, kolobraid.ErrRemoved), errors.Is(err, kolobraid.ErrNotMember):
return ErrNotAdmin
}
return err
}
// AddRoom adds a room to the room list, which admins write: anyone else gets ErrNotAdmin. A bad name is
// ErrInvalidRoom, and a room that exists (ASCII letters in any case) is ErrRoomExists. Two admins who add one name at
// once end with one room.
func (c *ChatService) AddRoom(name string) error {
name = strings.TrimSpace(name)
if !c.isActive() {
return ErrNotInConversation
}
if !c.IsAdmin() {
return ErrNotAdmin
}
if err := validRoomName(name); err != nil {
return err
}
rooms := c.Rooms()
if slices.ContainsFunc(rooms, func(r string) bool { return sameRoom(r, name) }) {
return ErrRoomExists
}
if len(rooms) > maxRooms {
return ErrTooManyRooms
}
ctx, cancel := c.writeCtx()
defer cancel()
_, err := c.braid.Append(ctx, encodeAddRoom(name))
return c.writeError(err)
}
// RemoveMember takes a member off the member list. Each member's app stops talking to it once it learns of this; the
// member keeps the conversation key, so this is not revocation. The settler cannot be removed.
func (c *ChatService) RemoveMember(key string) error {
if !c.isActive() {
return ErrNotInConversation
}
if !c.IsAdmin() {
return ErrNotAdmin
}
c.mu.Lock()
m, ok := c.accepted[key]
c.mu.Unlock()
switch {
case !ok:
return ErrUnknownMember
case m.Seat:
return ErrSettler
}
ctx, cancel := c.writeCtx()
defer cancel()
_, err := c.braid.RemoveMember(ctx, m.Key)
if err == nil {
log.Print("member removed: ", key[:8])
}
return c.writeError(err)
}Every invite now waits for an admin, because each joiner needs a welcome of its own from the braid. Approve checks the member bound first, then admits the joiner with its role, then answers the invite with the welcome. If the invite cannot carry it any more, the joiner is removed again. The role stays for good: kolo-braid has no public way to change it later:
// Approve lets in the person behind a request, as a member or as an admin; the role stays for good. The braid gets
// its AddMember entry, and the invite carries the conversation and the braid's welcome. If the invite cannot carry it,
// the joiner is removed again. Deny refuses it. Both need an admin.
func (c *ChatService) Approve(request uint64, admin bool) error {
if c.inv == nil {
return errors.New("not started")
}
if !c.IsAdmin() {
return ErrNotAdmin
}
c.mu.Lock()
r, ok := c.requests[invite.RequestID(request)]
full := len(c.accepted) >= maxMembers
c.mu.Unlock()
switch {
case !ok:
return ownerError(invite.ErrNotFound)
case full:
return ErrFull
}
var role kolobraid.Role
if admin {
role = kolobraid.RoleAdmin
}
ctx, cancel := c.writeCtx()
defer cancel()
welcome, err := c.braid.Admit(ctx, r.ev.Joiner, r.data.Request, &kolobraid.AdmitOptions{Roles: &role})
if err != nil {
c.answer(request, func(id invite.RequestID) error { return c.inv.Deny(id) })
if !admitRefused(err) {
c.braid.RemoveMember(ctx, r.ev.Joiner) // a write failed after the AddMember entry
}
return c.writeError(err)
}
payload, err := c.grantPayload(welcome)
if err == nil {
err = c.answer(request, func(id invite.RequestID) error { return c.inv.Approve(id, payload) })
}
if err != nil {
c.braid.RemoveMember(ctx, r.ev.Joiner) // the invite ended meanwhile
return ownerError(err)
}
log.Print("member admitted: ", hex.EncodeToString(r.ev.Joiner)[:8])
return nil
}
// admitRefused says that Admit wrote nothing, so there is nothing to remove.
func admitRefused(err error) bool {
return errors.Is(err, kolobraid.ErrActiveKey) || errors.Is(err, kolobraid.ErrKnownStrand) ||
errors.Is(err, kolobraid.ErrInvalidArgument) || errors.Is(err, kolobraid.ErrNotAdmin) ||
errors.Is(err, kolobraid.ErrRemoved) || errors.Is(err, kolobraid.ErrUnconfirmed)
}8Read the lists
The window reads both lists from the braid. Pending marks a member whose admission is not settled yet:
// Rooms lists the rooms of the conversation: the default room, then the ones admins added, by name.
func (c *ChatService) Rooms() []string {
rooms := []string{defaultRoom}
if c.braid == nil {
return rooms
}
snap := c.braid.View()
defer snap.Close()
return append(rooms, roomsOf(snap)...)
}
// Members lists the member list of the conversation with their profiles: the settler first, then the admins, then
// the others by key. Pending says the change that added it is not settled yet. A joiner whose braid has not synced
// yet lists itself.
func (c *ChatService) Members() []Member {
if c.braid == nil {
return []Member{} // "chat:profiles" sends it as is, and a nil slice would be null
}
view, settled := c.braid.View(), c.braid.Settled()
roster, done := view.Members(), settled.Members()
view.Close()
settled.Close()
me := hex.EncodeToString(c.pub)
out := make([]Member, 0, len(roster)+1)
for _, m := range roster {
key := hex.EncodeToString(m.Key)
p := c.profileOf(key)
out = append(out, Member{Key: key, Name: p.Name, Avatar: p.Avatar, Admin: m.Roles&kolobraid.RoleAdmin != 0, Seat: m.Seat,
Pending: !slices.ContainsFunc(done, func(d kolobraid.Member) bool { return d.Key.Equal(m.Key) })})
}
if !slices.ContainsFunc(out, func(m Member) bool { return m.Key == me }) {
p := c.profileOf(me)
out = append(out, Member{Key: me, Name: p.Name, Avatar: p.Avatar, Pending: true})
}
slices.SortStableFunc(out, func(a, b Member) int {
rank := func(m Member) int {
switch {
case m.Seat:
return 0
case m.Admin:
return 1
}
return 2
}
return cmp.Or(cmp.Compare(rank(a), rank(b)), strings.Compare(a.Key, b.Key))
})
return out
}9What the window does with it
The window shows the sentences of chat:state under the chat:
{joined ? stateBanners(conv.state).map((text) => <p key={text} className="note">{text}</p>) : null}A request has two approve buttons, one per role:
<button type="button" className="btn" onClick={() => answer((q) => Approve(conv, q, false), r.request)}>Approve as member</button>
<button type="button" className="btn btn--ghost" onClick={() => answer((q) => Approve(conv, q, true), r.request)}>Approve as admin</button>And Remove, after a confirmation that says what removal does not do, calls RemoveMember:
await RemoveMember(conv, who.key)10Run it
Start the bootstrap node, and keep it running:
go run ./cmd/bootstrapIn another terminal, start the local pin, and keep it running:
go run github.com/ciranda-dev/kolo-pin/cmd/kolo-pin run -data .data/pin -max-bytes 100MBBuild the app:
GOWORK=off wails3 buildThe data folders of step 6 are refused now, so use new ones. Alice needs the pin's public key, in her terminal only:
export KOLO_CHAT_PIN_KEY=$(go run github.com/ciranda-dev/kolo-pin/cmd/kolo-pin id -data .data/pin)./bin/kolo-chat -data .data/alice-7In Alice's window click New conversation, type "Team" and click Create. She founds it: she is an admin, and she settles the order of changes.
Start Bob, Carol and Dave, each in a terminal of their own, without the variable:
./bin/kolo-chat -data .data/bob-7./bin/kolo-chat -data .data/carol-7./bin/kolo-chat -data .data/dave-7In Alice's window click Invite and create an invite for Bob. In Bob's window click Join with an invite, paste the code and click Join. In Alice's window click "Approve as admin". Invite Carol the same way and click "Approve as member". Bob is an admin now: he has the Invite button and the box for a new room; Carol has neither.
Now two admins act at the same moment. In Alice's window and in Bob's window, type "design" in the box for a new room and press Enter in both as close together as you can. Every window ends with one room called "design". Then have Bob remove Carol while Alice approves Dave: create an invite in Alice's window and start Dave's join; in Bob's window click Remove next to Carol and confirm; in Alice's window click "Approve as member" for Dave. Every window that stays ends with the same member list: Alice, Bob and Dave.
Carol's window still holds the key and what she received. Nobody tells her. Within a few minutes, once her connections start again, nobody accepts her hello, and her window says that members are online but none answers, so she may have been removed.
11Run the tests
The tests you brought in cover the apply function on every delivery order, the tagged streams, two admins who act at once, a removed member who is not talked to and gets no entry key, a restart that keeps the lists, the member bound, a join that fails, special files in the data folder, and a folder of step 6:
GOWORK=off go test ./...12What the member list cannot do
- Removing is not revocation. Removing a member changes the agreed list but does not change the conversation key. The removed member keeps the key and everything it received, and can still read what it can fetch: the encrypted copies on the pin, with the keys of any app that has not learned of the removal. There is no key rotation yet.
- A removal reaches each app when it learns it. An app that was offline, or has not met an admin or the founder since, still talks to the removed member. The removed member is not told.
- Admins are chosen at approval. A role stays for good, and admins are fully trusted. The founder settles the order of changes and cannot be removed; while the founder is offline, changes show as pending.
- At most 64 members, approval always. Every request waits for an admin, and Approve at 64 members is refused.
- What a start deletes. As the example app's docs put it: "At start, a folder without
conversation.jsonis deleted only when it is provably a join that did not finish: nothing in it but a kolo-id with its stores, own logs with no entry, no completed braid and no copy of another member's log. Any other one, such as a member's folder that lost the file, is refused with the folder to move aside, and nothing in it is deleted." The starter does the same, and aconversation.jsonthat is a FIFO, a link or a file it cannot read gives a row with its folder, never a stuck start. - One device. A local list of conversations works because one kolo-id lives on one device: using one account on several devices is a different problem and is not solved here.
- Beta. kolo-braid's settlement and membership are model-checked within bounds, which is not a proof for any size, and this chat was tested on one Mac, on 127.0.0.1 only, never over a real network.
Next steps
- Start on the public network, and keep your own with
-bootstrap: Step 8: Use the public network. - Read kolo-braid's own guide on the kolo-braid page, and Build a shared document in two terminals, where a braid holds the whole state.
- The finished example, kolo-chat-wails3-example, adds the founder's hand over before Leave, marks for members whose entries were refused, and derived entry keys. Its
docs/shared-state.mdtells how. The finished example shows one list of rooms, one for each conversation, and its pin is optional: without one, messages reach people only while they are online. - To compare your files with the finished ones, check out the tag
step-7of the starter repository.