Skip to content

Commit c1b32d8

Browse files
authored
feat(store): add header for snapshot (#55)
1 parent 7d3c90f commit c1b32d8

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

pkg/store/fsm.go

+14-2
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,14 @@ package store
1919

2020
import (
2121
"bytes"
22+
"encoding/binary"
2223
"encoding/json"
2324
"errors"
2425
"fmt"
2526
"github.com/casbin/casbin-mesh/pkg/adapter"
2627
"github.com/casbin/casbin-mesh/pkg/auth"
2728
"io"
29+
"io/ioutil"
2830
"log"
2931
"sync"
3032
"time"
@@ -302,6 +304,15 @@ type persistData struct {
302304
CredentialStore []byte
303305
}
304306

307+
// SnapshotHdr is used to identify the snapshot protocol version.
308+
// length 8 bytes
309+
func SnapshotHdr() []byte {
310+
hdr := [8]byte{}
311+
// protocol version
312+
binary.LittleEndian.PutUint16(hdr[0:], uint16(1))
313+
return hdr[:]
314+
}
315+
305316
// Persist implements persistence of states
306317
func (f fsmSnapshot) Persist(sink raft.SnapshotSink) error {
307318
defer func() {
@@ -318,7 +329,7 @@ func (f fsmSnapshot) Persist(sink raft.SnapshotSink) error {
318329
return err
319330
}
320331
// JSON the cluster Enforcers.
321-
if _, err := sink.Write(data); err != nil {
332+
if _, err := sink.Write(append(SnapshotHdr(), data...)); err != nil {
322333
return err
323334
}
324335

@@ -383,7 +394,8 @@ func (s *Store) Snapshot() (raft.FSMSnapshot, error) {
383394
func (s *Store) Restore(closer io.ReadCloser) error {
384395
var err error
385396
var data persistData
386-
err = json.NewDecoder(closer).Decode(&data)
397+
snap, err := ioutil.ReadAll(closer)
398+
err = json.Unmarshal(snap[8:], &data)
387399
if err != nil {
388400
s.logger.Println("failed to decode restore data", err)
389401
return err

0 commit comments

Comments
 (0)