graphvent/group.go

88 lines
2.0 KiB
Go

2023-07-20 22:08:28 -06:00
package graphvent
import (
"slices"
2023-07-20 22:08:28 -06:00
)
type AddMemberSignal struct {
SignalHeader
MemberID NodeID `gv:"member_id"`
}
func (signal AddMemberSignal) Permission() Tree {
return Tree{
SerializedType(AddMemberSignalType): nil,
}
}
func NewAddMemberSignal(member_id NodeID) *AddMemberSignal {
return &AddMemberSignal{
NewSignalHeader(Direct),
member_id,
}
}
type RemoveMemberSignal struct {
SignalHeader
MemberID NodeID `gv:"member_id"`
}
func (signal RemoveMemberSignal) Permission() Tree {
return Tree{
SerializedType(RemoveMemberSignalType): nil,
}
}
func NewRemoveMemberSignal(member_id NodeID) *RemoveMemberSignal {
return &RemoveMemberSignal{
NewSignalHeader(Direct),
member_id,
}
}
2023-10-13 00:32:24 -06:00
var DefaultGroupPolicy = NewAllNodesPolicy(Tree{
2023-10-03 21:18:06 -06:00
SerializedType(ReadSignalType): {
SerializedType(GroupExtType): {
Hash(FieldNameBase, "members"): nil,
},
},
})
2023-07-25 09:51:55 -06:00
2023-10-03 21:18:06 -06:00
type GroupExt struct {
Members []NodeID `gv:"members"`
2023-07-25 09:51:55 -06:00
}
2023-10-03 21:18:06 -06:00
func NewGroupExt(members []NodeID) *GroupExt {
2023-07-26 11:56:10 -06:00
return &GroupExt{
Members: members,
}
}
2023-10-07 23:00:07 -06:00
func (ext *GroupExt) Process(ctx *Context, node *Node, source NodeID, signal Signal) (Messages, Changes) {
var messages Messages = nil
var changes Changes = nil
switch sig := signal.(type) {
case *AddMemberSignal:
if slices.Contains(ext.Members, sig.MemberID) == true {
messages = messages.Add(ctx, source, node, nil, NewErrorSignal(sig.Id, "already_member"))
} else {
ext.Members = append(ext.Members, sig.MemberID)
messages = messages.Add(ctx, source, node, nil, NewSuccessSignal(sig.Id))
changes = changes.Add("member_added")
}
case *RemoveMemberSignal:
idx := slices.Index(ext.Members, sig.MemberID)
if idx == -1 {
messages = messages.Add(ctx, source, node, nil, NewErrorSignal(sig.Id, "not_member"))
} else {
ext.Members = slices.Delete(ext.Members, idx, idx+1)
messages = messages.Add(ctx, source, node, nil, NewSuccessSignal(sig.Id))
changes = changes.Add("member_removed")
}
}
return messages, changes
2023-07-26 00:18:11 -06:00
}