Skip to content

Commit

Permalink
WIP: signature fails
Browse files Browse the repository at this point in the history
  • Loading branch information
bahner committed Apr 6, 2024
1 parent c8a4dcd commit b9d8ba6
Show file tree
Hide file tree
Showing 23 changed files with 352 additions and 381 deletions.
34 changes: 2 additions & 32 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,24 +17,6 @@
"request": "launch",
"mode": "auto",
"program": "${workspaceFolder}/cmd/node",
},
{
"name": "Launch eggplant",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${workspaceFolder}/cmd/actor/",
"console": "integratedTerminal",
"args": [
"-p",
"aubergine"
],
"env": {
"GOLOG_FILE": "/tmp/debug.log",
"GOLOG_LOG_LEVEL": "debug",
"GOLOG_STDOUT": "false",
"GOLOG_OUTPUT": "file"
}
},
{
"name": "Launch actor as bahner",
Expand Down Expand Up @@ -68,20 +50,6 @@
"GOLOG_OUTPUT": "file"
}
},
{
"name": "Launch relay",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${workspaceFolder}/cmd/relay/",
"console": "integratedTerminal",
"env": {
"GOLOG_FILE": "/tmp/debug.log",
"GOLOG_LOG_LEVEL": "debug",
"GOLOG_STDOUT": "false",
"GOLOG_OUTPUT": "file"
}
},
{
"name": "go-ma-actor generate",
"type": "go",
Expand All @@ -99,6 +67,8 @@
"--generate",
"--nick",
"FUBAR",
"--publish",
"--force",
]
},
{
Expand Down
8 changes: 8 additions & 0 deletions cmd/actor/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@ import (
"os"

"github.com/bahner/go-ma-actor/config"
"github.com/bahner/go-ma-actor/entity"
"github.com/bahner/go-ma-actor/entity/actor"
"github.com/bahner/go-ma-actor/p2p/peer"

log "github.com/sirupsen/logrus"
)

func initConfig(defaultProfileName string) actor.ActorConfig {
Expand All @@ -24,5 +28,9 @@ func initConfig(defaultProfileName string) actor.ActorConfig {
os.Exit(0)
}

log.Info("Reading CSV files...")
go entity.WatchCSV()
go peer.WatchCSV()

return c
}
24 changes: 12 additions & 12 deletions cmd/node/entity.go → cmd/node/actors.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,23 +9,23 @@ import (
log "github.com/sirupsen/logrus"
)

var entities *entityCache
var actors *actorCache

type entityCache struct {
type actorCache struct {
store sync.Map
}

func init() {
entities = new(entityCache)
actors = new(actorCache)
}

// GetOrCreateEntity returns an entity from the cache or creates a new one
// The id is just the uniqgue name of the calling entity, not the full DID
func getOrCreateEntity(id string) (*actor.Actor, error) {
func getOrCreateActor(id string) (*actor.Actor, error) {

// Attempt to retrieve the entity from cache.
// This is runtime, so entities will be generated at least once.
if cachedEntity, ok := entities.Get(id); ok {
if cachedEntity, ok := actors.Get(id); ok {
if entity, ok := cachedEntity.(*actor.Actor); ok {
log.Debugf("found topic: %s in entities cache.", id)
return entity, nil // Successfully type-asserted and returned
Expand All @@ -40,31 +40,31 @@ func getOrCreateEntity(id string) (*actor.Actor, error) {
}

// Assuming entity.NewFromKeyset returns *actor.Actor
e, err := actor.NewFromKeyset(k)
a, err := actor.NewFromKeyset(k)
if err != nil {
return nil, fmt.Errorf("failed to create entity: %w", err)
}

e.Entity.Doc, err = e.CreateDocument(e.Entity.DID.Id)
a.Entity.Doc, err = a.CreateEntityDocument(a.Entity.DID.Id)
if err != nil {
return nil, fmt.Errorf("failed to create DID Document: %w", err)
}

// Force publication of document.
o := doc.DefaultPublishOptions()
o.Force = true
e.Entity.Doc.Publish(o)
a.Entity.Doc.Publish(o)

// Cache the newly created entity for future retrievals
entities.Set(id, e)
actors.Set(id, a)

return e, nil
return a, nil
}

func (e *entityCache) Set(key string, value interface{}) {
func (e *actorCache) Set(key string, value interface{}) {
e.store.Store(key, value)
}

func (e *entityCache) Get(key string) (interface{}, bool) {
func (e *actorCache) Get(key string) (interface{}, bool) {
return e.store.Load(key)
}
2 changes: 1 addition & 1 deletion cmd/node/subscription.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ func New(id string) gen.ServerBehavior {

log.Debugf("Creating new genServer: %s", id)

a, err := getOrCreateEntity(id)
a, err := getOrCreateActor(id)
if err != nil {
log.Errorf("Error getting or creating entity: %s", err)
return nil
Expand Down
6 changes: 6 additions & 0 deletions cmd/pong/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"

"github.com/bahner/go-ma-actor/entity/actor"
"github.com/bahner/go-ma-actor/ui/web"

"github.com/bahner/go-ma-actor/p2p"
)
Expand Down Expand Up @@ -48,6 +49,11 @@ func main() {
actor.HelloWorld(ctx, a)
fmt.Println("Sent hello world.")

// WEB
fmt.Println("Initialising web UI...")
wh := web.NewEntityHandler(p, a.Entity)
go web.Start(wh)

fmt.Printf("Running in pong mode as %s@%s\n", a.Entity.DID.Id, p.Host.ID())
fmt.Println("Press Ctrl-C to stop.")

Expand Down
6 changes: 3 additions & 3 deletions config/actor.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,8 @@ func initActor() {
// This function fails fatally, so no return value
initActorKeyset(keyset_string)

if PublishFlag() && keyset_string != "" {
// If publish then publish, unless we are to generate a new keyset.
if PublishFlag() && !GenerateFlag() {
fmt.Println("Publishing identity to IPFS...")
err := PublishIdentityFromKeyset(keyset)
if err != nil {
Expand Down Expand Up @@ -146,7 +147,6 @@ func initActorKeyset(keyset_string string) {
log.Errorf("config.initActor: %v", err)
os.Exit(70) // EX_SOFTWARE
}

}

func generateActorIdentity(nick string) (string, error) {
Expand All @@ -164,7 +164,7 @@ func generateActorIdentity(nick string) (string, error) {

if err != nil {
if errors.Is(err, doc.ErrAlreadyPublished) {
log.Warnf("Actor document already published: %v", err)
log.Debugf("Actor document already published: %v", err)
} else {
return "", fmt.Errorf("failed to publish actor identity: %w", err)
}
Expand Down
16 changes: 6 additions & 10 deletions config/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,19 @@ import (
"github.com/spf13/viper"
)

const (
EntitiesCSVMode = 0666
PeersCSVMode = 0666
)
const CSVMode = 0664

var (
defaultPeersPath = internal.NormalisePath(dataHome + "/peers.csv")
defaultEntitiesPath = internal.NormalisePath(dataHome + "/entities.csv")
)

func init() {
pflag.String("db-peers", defaultPeersPath, "Filename for CSV peers file.")
pflag.String("db-entities", defaultEntitiesPath, "Filename for CSV entities file.")
pflag.String("peers", defaultPeersPath, "Filename for CSV peers file.")
pflag.String("entities", defaultEntitiesPath, "Filename for CSV entities file.")

viper.BindPFlag("db.peers", pflag.Lookup("db-peers"))
viper.BindPFlag("db.entities", pflag.Lookup("db-entities"))
viper.BindPFlag("db.peers", pflag.Lookup("peers"))
viper.BindPFlag("db.entities", pflag.Lookup("entities"))

viper.SetDefault("db.peers", defaultPeersPath)
viper.SetDefault("db.entities", defaultEntitiesPath)
Expand All @@ -34,12 +31,11 @@ type DBConfig struct {

func DB() DBConfig {

viper.SetDefault("db.path", defaultPeersPath)

return DBConfig{
Peers: DBPeers(),
Entities: DBEntities(),
}

}

func DBPeers() string {
Expand Down
140 changes: 140 additions & 0 deletions db/csv.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
package db

import (
"encoding/csv"
"fmt"
"os"
"sync"

"github.com/bahner/go-ma-actor/config"
"github.com/fsnotify/fsnotify"
log "github.com/sirupsen/logrus"
)

// Save saves a sync.Map to a CSV file.
func Save(syncMap *sync.Map, filename string) error {

file, err := os.Create(filename)
if err != nil {
log.Error("db.Save: ", err)
return err
}
defer file.Close()

writer := csv.NewWriter(file)
syncMap.Range(func(key, value interface{}) bool {
writer.Write([]string{key.(string), value.(string)})
return true
})
writer.Flush()

return writer.Error()
}

// Watch monitors a CSV file for changes and reloads it
// and updates the sync.Map when changed.
func Watch(filename string, syncMap *sync.Map) error {
log.Debugf("db.Watch: watching %s", filename)

err := load(filename, syncMap) // Load the file initially
if err != nil {
log.Errorf("db.Watch: %v", err)
return fmt.Errorf("db.Watch: %w", err)
}

watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Errorf("db.Watch: %v", err)
return fmt.Errorf("db.Watch: %w", err)
}
defer watcher.Close()

// Function to re-add the file or directory to the watcher list
reAddWatcher := func(path string) error {
if err := watcher.Remove(path); err != nil {
log.Debugf("db.Watch: error removing watcher for %s: %v", path, err)
}
if err := watcher.Add(path); err != nil {
log.Errorf("db.Watch: error re-adding watcher for %s: %v", path, err)
return fmt.Errorf("db.Watch: %w", err)
}
return nil
}

done := make(chan bool)
go func() {
defer close(done)
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
log.Debugf("db.Watch: event: %v", event)
if event.Op&fsnotify.Write == fsnotify.Write || event.Op&fsnotify.Rename == fsnotify.Rename {
log.Infof("db.Watch: %s modified. Reloading.", filename)
load(filename, syncMap) // Reload the file when it changes
// Attempt to re-add the file to the watcher, to continue monitoring
if err := reAddWatcher(filename); err != nil {
log.Errorf("db.Watch: %v", err)
return
}
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
// Handle errors
log.Errorf("db.Watch: %v", err)
}
}
}()

if err := watcher.Add(filename); err != nil {
log.Errorf("db.Watch: %v", err)
return fmt.Errorf("db.Watch: %w", err)
}

// Block until the watcher is done to keep the watcher alive.
// You may need a mechanism to signal `done` based on your application's needs (not shown here).
<-done
return nil
}

// load reads peers from a CSV file and updates the sync.Map.
func load(filename string, nicks *sync.Map) error {

file, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, config.CSVMode)
if err != nil {
log.Errorf("db.load: %v", err)
return err
}
defer file.Close()

reader := csv.NewReader(file)
records, err := reader.ReadAll()
if err != nil {
log.Errorf("db.load: %v", err)
return err
}

tempMap := make(map[string]string)
for _, record := range records {
tempMap[record[0]] = record[1]
}

// Upsert entries from tempPeers into the global peers map
for key, value := range tempMap {
nicks.Store(key, value)
}

// Optionally, remove entries in peers that are not in tempPeers
nicks.Range(func(key, value interface{}) bool {
if _, exists := tempMap[key.(string)]; !exists {
nicks.Delete(key)
}
return true
})

return nil
}
2 changes: 1 addition & 1 deletion entity/actor/actor.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func New(d did.DID, k set.Keyset) (*Actor, error) {
Envelopes: make(chan *msg.Envelope, ENVELOPES_BUFFERSIZE),
}

a.CreateDocument(d.Id)
a.CreateEntityDocument(d.Id)

// Cache the entity
store(a)
Expand Down
Loading

0 comments on commit b9d8ba6

Please sign in to comment.