Bläddra i källkod

feat: hash calculation of runtime state

Yeuoly 1 år sedan
förälder
incheckning
e2c0c82d0b
2 ändrade filer med 71 tillägg och 0 borttagningar
  1. 19 0
      internal/types/entities/runtime.go
  2. 52 0
      internal/types/entities/runtime_test.go

+ 19 - 0
internal/types/entities/runtime.go

@@ -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"
@@ -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"`
@@ -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"

+ 52 - 0
internal/types/entities/runtime_test.go

@@ -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
+	}
+}