Skip to content

Commit

Permalink
feat: hash calculation of runtime state
Browse files Browse the repository at this point in the history
  • Loading branch information
Yeuoly committed Jul 30, 2024
1 parent f1f67cb commit e2c0c82
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
19 changes: 19 additions & 0 deletions internal/types/entities/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import (
"bytes"
"crypto/sha256"
"encoding/binary"
"encoding/gob"
"encoding/hex"
"hash/fnv"
"time"

"github.com/langgenius/dify-plugin-daemon/internal/types/entities/plugin_entities"
Expand Down Expand Up @@ -91,6 +93,7 @@ const (
)

type PluginRuntimeState struct {
Identity string `json:"identity"`
Restarts int `json:"restarts"`
Status string `json:"status"`
RelativePath string `json:"relative_path"`
Expand All @@ -99,6 +102,22 @@ type PluginRuntimeState struct {
Verified bool `json:"verified"`
}

func (s *PluginRuntimeState) Hash() (uint64, error) {
buf := bytes.Buffer{}
enc := gob.NewEncoder(&buf)
err := enc.Encode(s)
if err != nil {
return 0, err
}
j := fnv.New64a()
_, err = j.Write(buf.Bytes())
if err != nil {
return 0, err
}

return j.Sum64(), nil
}

const (
PLUGIN_RUNTIME_STATUS_ACTIVE = "active"
PLUGIN_RUNTIME_STATUS_LAUNCHING = "launching"
Expand Down
52 changes: 52 additions & 0 deletions internal/types/entities/runtime_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package entities

import (
"testing"
"time"
)

func TestRuntimeStateHash(t *testing.T) {
state := PluginRuntimeState{
Identity: "test",
Restarts: 0,
Status: PLUGIN_RUNTIME_STATUS_PENDING,
RelativePath: "aaa",
ActiveAt: &[]time.Time{time.Now()}[0],
StoppedAt: &[]time.Time{time.Now()}[0],
Verified: true,
}

hash, err := state.Hash()
if err != nil {
t.Errorf("hash failed: %v", err)
return
}

if hash == 0 {
t.Errorf("hash is 0")
return
}

hash2, err := state.Hash()
if err != nil {
t.Errorf("hash failed: %v", err)
return
}

if hash != hash2 {
t.Errorf("hash is not the same: %d, %d", hash, hash2)
return
}

state.Restarts++
hash3, err := state.Hash()
if err != nil {
t.Errorf("hash failed: %v", err)
return
}

if hash == hash3 {
t.Errorf("hash is the same: %d, %d", hash, hash3)
return
}
}

0 comments on commit e2c0c82

Please sign in to comment.