summaryrefslogtreecommitdiff
path: root/internal/vote
diff options
context:
space:
mode:
Diffstat (limited to 'internal/vote')
-rw-r--r--internal/vote/vote.go36
-rw-r--r--internal/vote/vote_test.go46
2 files changed, 82 insertions, 0 deletions
diff --git a/internal/vote/vote.go b/internal/vote/vote.go
new file mode 100644
index 0000000..079e021
--- /dev/null
+++ b/internal/vote/vote.go
@@ -0,0 +1,36 @@
+package vote
+
+import (
+ "log"
+ "strings"
+ "time"
+
+ "codeberg.org/snonux/gorum/internal/config"
+ "codeberg.org/snonux/gorum/internal/utils"
+)
+
+const Expiry = 20 * time.Second
+
+type Vote struct {
+ From string
+ IDs []string
+ ExpiresAt time.Time
+}
+
+func New(conf config.Config, from, message string) Vote {
+ var ids []string
+ for _, id := range strings.Split(strings.TrimSpace(message), " ") {
+ if !conf.IsParticipant(id) {
+ log.Printf("%s is not a participant, excluding from the vote", id)
+ continue
+ }
+ ids = append(ids, id)
+ }
+
+ return Vote{utils.StripPort(from), ids, time.Now().Add(Expiry)}
+}
+
+func (v Vote) Expired() bool {
+ now := time.Now()
+ return now.After(v.ExpiresAt) || now.Equal(v.ExpiresAt)
+}
diff --git a/internal/vote/vote_test.go b/internal/vote/vote_test.go
new file mode 100644
index 0000000..0986e00
--- /dev/null
+++ b/internal/vote/vote_test.go
@@ -0,0 +1,46 @@
+package vote
+
+import (
+ "testing"
+ "time"
+
+ "codeberg.org/snonux/gorum/internal/config"
+)
+
+func TestVote(t *testing.T) {
+ conf := config.Config{Participants: []string{"foo:1234", "bay:4321"}}
+ v := New(conf, "earth:334234", " foo bar baz bay\n")
+
+ if v.From != "earth" {
+ t.Errorf("Expected vote to come from earth but came from %s", v.From)
+ }
+
+ if len(v.IDs) != 2 {
+ t.Errorf("Expected vote length to be 2 but is %d", len(v.IDs))
+ }
+
+ if v.IDs[0] != "foo" {
+ t.Errorf("Expected vote 1 to be foo but is %s", v.IDs[0])
+ }
+
+ if v.IDs[1] != "bay" {
+ t.Errorf("Expected vote 2 to be bay but is %s", v.IDs[1])
+ }
+}
+
+func TestVoteExpiry(t *testing.T) {
+ conf := config.Config{Participants: []string{"foo:1234", "bay:4321"}}
+ v := New(conf, "earth:334234", " foo bar baz bay\n")
+
+ // Set expiry 1h into the future
+ v.ExpiresAt = time.Now().Add(1 * time.Hour)
+ if v.Expired() {
+ t.Errorf("Didn't expect vote to be expired")
+ }
+
+ // Set expiry to now
+ v.ExpiresAt = time.Now()
+ if !v.Expired() {
+ t.Errorf("Expected vote to be expired")
+ }
+}