Use cobra command line

This commit is contained in:
mcrakhman 2022-12-05 12:43:36 +01:00 committed by Mikhail Iudin
parent 2b3ae0fb94
commit 4eca88b0bc
No known key found for this signature in database
GPG Key ID: FAAAA8BAABDFF1C0
3 changed files with 509 additions and 513 deletions

View File

@ -2,7 +2,6 @@ package api
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
clientproto "github.com/anytypeio/go-anytype-infrastructure-experiments/client/api/apiproto" clientproto "github.com/anytypeio/go-anytype-infrastructure-experiments/client/api/apiproto"
"github.com/anytypeio/go-anytype-infrastructure-experiments/common/app" "github.com/anytypeio/go-anytype-infrastructure-experiments/common/app"
@ -11,51 +10,55 @@ import (
"github.com/anytypeio/go-anytype-infrastructure-experiments/util/cmd/debug/api/client" "github.com/anytypeio/go-anytype-infrastructure-experiments/util/cmd/debug/api/client"
"github.com/anytypeio/go-anytype-infrastructure-experiments/util/cmd/debug/api/node" "github.com/anytypeio/go-anytype-infrastructure-experiments/util/cmd/debug/api/node"
"github.com/anytypeio/go-anytype-infrastructure-experiments/util/cmd/debug/peers" "github.com/anytypeio/go-anytype-infrastructure-experiments/util/cmd/debug/peers"
"github.com/zeebo/errs" "github.com/spf13/cobra"
"math/rand" _ "github.com/spf13/cobra"
"strconv"
"sync"
) )
const CName = "debug.api" const CName = "debug.api"
var log = logger.NewNamed(CName) var log = logger.NewNamed(CName)
var (
ErrNoSuchCommand = errors.New("no such command")
ErrIncorrectPeerType = errors.New("incorrect peer type")
ErrIncorrectParamsCount = errors.New("incorrect params count")
)
type Command struct {
Cmd func(server peers.Peer, params []string) (string, error)
}
type Script struct {
Cmd func(params []string) (string, error)
}
type Service interface { type Service interface {
app.Component app.ComponentRunnable
Call(server peers.Peer, cmdName string, params []string) (string, error)
Script(scriptName string, params []string) (res string, err error)
} }
type service struct { type service struct {
clientCommands map[string]Command
nodeCommands map[string]Command
scripts map[string]Script
client client.Service client client.Service
node node.Service node node.Service
peers peers.Service peers peers.Service
clientCommands []*cobra.Command
nodeCommands []*cobra.Command
scripts []*cobra.Command
} }
func New() Service { func New() Service {
return &service{ return &service{}
clientCommands: map[string]Command{}, }
nodeCommands: map[string]Command{},
scripts: map[string]Script{}, func (s *service) Run(ctx context.Context) (err error) {
rootCmd := &cobra.Command{Use: "debug"}
clientCmd := &cobra.Command{Use: "client commands"}
clientCmd.PersistentFlags().StringP("client", "c", "", "the alias of the client")
clientCmd.MarkFlagRequired("client")
for _, cmd := range s.clientCommands {
clientCmd.AddCommand(cmd)
} }
rootCmd.AddCommand(clientCmd)
nodeCmd := &cobra.Command{Use: "node commands"}
nodeCmd.PersistentFlags().StringP("node", "n", "", "the alias of the node")
nodeCmd.MarkFlagRequired("node")
for _, cmd := range s.nodeCommands {
nodeCmd.AddCommand(cmd)
}
rootCmd.AddCommand(nodeCmd)
return rootCmd.Execute()
}
func (s *service) Close(ctx context.Context) (err error) {
return nil
} }
func (s *service) Init(a *app.App) (err error) { func (s *service) Init(a *app.App) (err error) {
@ -64,7 +67,7 @@ func (s *service) Init(a *app.App) (err error) {
s.peers = a.MustComponent(peers.CName).(peers.Service) s.peers = a.MustComponent(peers.CName).(peers.Service)
s.registerClientCommands() s.registerClientCommands()
s.registerNodeCommands() s.registerNodeCommands()
s.registerScripts() //s.registerScripts()
return nil return nil
} }
@ -73,130 +76,172 @@ func (s *service) Name() (name string) {
return CName return CName
} }
func (s *service) Script(scriptName string, params []string) (res string, err error) {
script, ok := s.scripts[scriptName]
if !ok {
err = ErrNoSuchCommand
return
}
return script.Cmd(params)
}
func (s *service) Call(server peers.Peer, cmdName string, params []string) (res string, err error) {
var (
cmd Command
commands map[string]Command
)
switch server.PeerType {
case peers.PeerTypeClient:
commands = s.clientCommands
case peers.PeerTypeNode:
commands = s.nodeCommands
}
cmd, ok := commands[cmdName]
if !ok {
err = ErrNoSuchCommand
return
}
return cmd.Cmd(server, params)
}
func (s *service) registerClientCommands() { func (s *service) registerClientCommands() {
s.clientCommands["create-space"] = Command{Cmd: func(server peers.Peer, params []string) (res string, err error) { cmdCreateSpace := &cobra.Command{
if len(params) != 0 { Use: "create-space [params]",
err = ErrIncorrectParamsCount Short: "create the space",
Args: cobra.RangeArgs(0, 0),
Run: func(cmd *cobra.Command, args []string) {
cli, _ := cmd.Flags().GetString("client")
server, err := s.peers.Get(cli)
if err != nil {
fmt.Println("no such client")
return return
} }
resp, err := s.client.CreateSpace(context.Background(), server.Address, &clientproto.CreateSpaceRequest{}) resp, err := s.client.CreateSpace(context.Background(), server.Address, &clientproto.CreateSpaceRequest{})
if err != nil { if err != nil {
fmt.Println("couldn't create a space", err)
return return
} }
res = resp.Id fmt.Println(resp.Id)
},
}
s.clientCommands = append(s.clientCommands, cmdCreateSpace)
cmdLoadSpace := &cobra.Command{
Use: "load-space [params]",
Short: "load the space",
Args: cobra.RangeArgs(1, 1),
Run: func(cmd *cobra.Command, args []string) {
cli, _ := cmd.Flags().GetString("client")
server, err := s.peers.Get(cli)
if err != nil {
fmt.Println("no such client")
return return
}} }
s.clientCommands["derive-space"] = Command{Cmd: func(server peers.Peer, params []string) (res string, err error) { _, err = s.client.LoadSpace(context.Background(), server.Address, &clientproto.LoadSpaceRequest{
if len(params) != 0 { SpaceId: args[0],
err = ErrIncorrectParamsCount })
if err != nil {
fmt.Println("couldn't load the space", err)
return
}
fmt.Println("space loaded", args[0])
},
}
s.clientCommands = append(s.clientCommands, cmdLoadSpace)
cmdDeriveSpace := &cobra.Command{
Use: "derive-space [params]",
Short: "derive the space from account data",
Args: cobra.RangeArgs(0, 0),
Run: func(cmd *cobra.Command, args []string) {
cli, _ := cmd.Flags().GetString("client")
server, err := s.peers.Get(cli)
if err != nil {
fmt.Println("no such client")
return return
} }
resp, err := s.client.DeriveSpace(context.Background(), server.Address, &clientproto.DeriveSpaceRequest{}) resp, err := s.client.DeriveSpace(context.Background(), server.Address, &clientproto.DeriveSpaceRequest{})
if err != nil { if err != nil {
fmt.Println("couldn't derive a space", err)
return return
} }
res = resp.Id fmt.Println(resp.Id)
return },
}} }
s.clientCommands["create-document"] = Command{Cmd: func(server peers.Peer, params []string) (res string, err error) { s.clientCommands = append(s.clientCommands, cmdDeriveSpace)
if len(params) != 1 {
err = ErrIncorrectParamsCount cmdCreateDocument := &cobra.Command{
Use: "create-document [params]",
Short: "create the document in a particular space",
Args: cobra.RangeArgs(1, 1),
Run: func(cmd *cobra.Command, args []string) {
cli, _ := cmd.Flags().GetString("client")
server, err := s.peers.Get(cli)
if err != nil {
fmt.Println("no such client")
return return
} }
resp, err := s.client.CreateDocument(context.Background(), server.Address, &clientproto.CreateDocumentRequest{ resp, err := s.client.CreateDocument(context.Background(), server.Address, &clientproto.CreateDocumentRequest{
SpaceId: params[0], SpaceId: args[0],
}) })
if err != nil { if err != nil {
fmt.Println("couldn't create a document", err)
return return
} }
res = resp.Id fmt.Println(resp.Id)
return },
}} }
s.clientCommands["delete-document"] = Command{Cmd: func(server peers.Peer, params []string) (res string, err error) { s.clientCommands = append(s.clientCommands, cmdCreateDocument)
if len(params) != 2 {
err = ErrIncorrectParamsCount cmdDeleteDocument := &cobra.Command{
Use: "delete-document [params]",
Short: "delete the document in a particular space",
Args: cobra.RangeArgs(1, 1),
Run: func(cmd *cobra.Command, args []string) {
cli, _ := cmd.Flags().GetString("client")
space, _ := cmd.Flags().GetString("space")
server, err := s.peers.Get(cli)
if err != nil {
fmt.Println("no such client")
return return
} }
_, err = s.client.DeleteDocument(context.Background(), server.Address, &clientproto.DeleteDocumentRequest{ _, err = s.client.DeleteDocument(context.Background(), server.Address, &clientproto.DeleteDocumentRequest{
SpaceId: params[0], SpaceId: space,
DocumentId: params[1], DocumentId: args[0],
}) })
if err != nil { if err != nil {
fmt.Println("couldn't delete the document", err)
return return
} }
res = "deleted" fmt.Println("deleted", args[1])
return },
}} }
s.clientCommands["add-text"] = Command{Cmd: func(server peers.Peer, params []string) (res string, err error) { cmdDeleteDocument.Flags().String("space", "", "the space where something is happening :-)")
if len(params) != 3 && len(params) != 4 { cmdDeleteDocument.MarkFlagRequired("space")
err = ErrIncorrectParamsCount s.clientCommands = append(s.clientCommands, cmdDeleteDocument)
cmdAddText := &cobra.Command{
Use: "add-text [params]",
Short: "add text to the document in the particular space",
Args: cobra.RangeArgs(1, 1),
Run: func(cmd *cobra.Command, args []string) {
cli, _ := cmd.Flags().GetString("client")
space, _ := cmd.Flags().GetString("space")
document, _ := cmd.Flags().GetString("document")
server, err := s.peers.Get(cli)
if err != nil {
fmt.Println("no such client")
return return
} }
resp, err := s.client.AddText(context.Background(), server.Address, &clientproto.AddTextRequest{ resp, err := s.client.AddText(context.Background(), server.Address, &clientproto.AddTextRequest{
SpaceId: params[0], SpaceId: space,
DocumentId: params[1], DocumentId: document,
Text: params[2], Text: args[0],
IsSnapshot: len(params) == 4,
}) })
if err != nil { if err != nil {
fmt.Println("couldn't add text to the document", err)
return return
} }
res = resp.DocumentId + "->" + resp.RootId + "->" + resp.HeadId fmt.Println("added text", resp.DocumentId, "root:", resp.RootId, "head:", resp.HeadId)
return },
}}
s.clientCommands["load-space"] = Command{Cmd: func(server peers.Peer, params []string) (res string, err error) {
if len(params) != 1 {
err = ErrIncorrectParamsCount
return
} }
_, err = s.client.LoadSpace(context.Background(), server.Address, &clientproto.LoadSpaceRequest{ cmdAddText.Flags().String("space", "", "the space where something is happening :-)")
SpaceId: params[0], cmdAddText.Flags().String("document", "", "the document where something is happening :-)")
}) cmdAddText.MarkFlagRequired("space")
cmdAddText.MarkFlagRequired("document")
s.clientCommands = append(s.clientCommands, cmdAddText)
cmdAllTrees := &cobra.Command{
Use: "all-trees [params]",
Short: "print all trees in space and their heads",
Args: cobra.RangeArgs(1, 1),
Run: func(cmd *cobra.Command, args []string) {
cli, _ := cmd.Flags().GetString("client")
server, err := s.peers.Get(cli)
if err != nil { if err != nil {
return fmt.Println("no such client")
}
res = params[0]
return
}}
s.clientCommands["all-trees"] = Command{Cmd: func(server peers.Peer, params []string) (res string, err error) {
if len(params) != 1 {
err = ErrIncorrectParamsCount
return return
} }
resp, err := s.client.AllTrees(context.Background(), server.Address, &clientproto.AllTreesRequest{ resp, err := s.client.AllTrees(context.Background(), server.Address, &clientproto.AllTreesRequest{
SpaceId: params[0], SpaceId: args[0],
}) })
if err != nil { if err != nil {
fmt.Println("couldn't print all the trees", err)
return return
} }
var res string
for treeIdx, tree := range resp.Trees { for treeIdx, tree := range resp.Trees {
treeStr := tree.Id + ":[" treeStr := tree.Id + ":["
for headIdx, head := range tree.Heads { for headIdx, head := range tree.Heads {
@ -211,75 +256,123 @@ func (s *service) registerClientCommands() {
res += "\n" res += "\n"
} }
} }
return fmt.Println(res)
}} },
s.clientCommands["dump-tree"] = Command{Cmd: func(server peers.Peer, params []string) (res string, err error) { }
if len(params) != 2 { s.clientCommands = append(s.clientCommands, cmdAllTrees)
err = ErrIncorrectParamsCount
cmdDumpTree := &cobra.Command{
Use: "dump-tree [params]",
Short: "get graphviz description of the tree",
Args: cobra.RangeArgs(1, 1),
Run: func(cmd *cobra.Command, args []string) {
cli, _ := cmd.Flags().GetString("client")
space, _ := cmd.Flags().GetString("space")
server, err := s.peers.Get(cli)
if err != nil {
fmt.Println("no such client")
return return
} }
resp, err := s.client.DumpTree(context.Background(), server.Address, &clientproto.DumpTreeRequest{ resp, err := s.client.DumpTree(context.Background(), server.Address, &clientproto.DumpTreeRequest{
SpaceId: params[0], SpaceId: space,
DocumentId: params[1], DocumentId: args[0],
}) })
if err != nil { if err != nil {
fmt.Println("couldn't dump the tree", err)
return return
} }
res = resp.Dump fmt.Println(resp.Dump)
return },
}} }
s.clientCommands["tree-params"] = Command{Cmd: func(server peers.Peer, params []string) (res string, err error) { cmdDumpTree.Flags().String("space", "", "the space where something is happening :-)")
if len(params) != 2 { cmdDumpTree.MarkFlagRequired("space")
err = ErrIncorrectParamsCount s.clientCommands = append(s.clientCommands, cmdDumpTree)
cmdTreeParams := &cobra.Command{
Use: "tree-params [params]",
Short: "print heads and root of the tree",
Args: cobra.RangeArgs(1, 1),
Run: func(cmd *cobra.Command, args []string) {
cli, _ := cmd.Flags().GetString("client")
space, _ := cmd.Flags().GetString("space")
server, err := s.peers.Get(cli)
if err != nil {
fmt.Println("no such client")
return return
} }
resp, err := s.client.TreeParams(context.Background(), server.Address, &clientproto.TreeParamsRequest{ resp, err := s.client.TreeParams(context.Background(), server.Address, &clientproto.TreeParamsRequest{
SpaceId: params[0], SpaceId: space,
DocumentId: params[1], DocumentId: args[0],
}) })
if err != nil { if err != nil {
fmt.Println("couldn't print params of the tree", err)
return return
} }
res = resp.RootId + "->" res := resp.RootId + "->"
for headIdx, head := range resp.HeadIds { for headIdx, head := range resp.HeadIds {
res += head res += head
if headIdx != len(resp.HeadIds)-1 { if headIdx != len(resp.HeadIds)-1 {
res += "," res += ","
} }
} }
return fmt.Println(res)
}} },
s.clientCommands["all-spaces"] = Command{Cmd: func(server peers.Peer, params []string) (res string, err error) { }
if len(params) != 0 { cmdTreeParams.Flags().String("space", "", "the space where something is happening :-)")
err = ErrIncorrectParamsCount cmdTreeParams.MarkFlagRequired("space")
s.clientCommands = append(s.clientCommands, cmdTreeParams)
cmdAllSpaces := &cobra.Command{
Use: "all-spaces [params]",
Short: "print all spaces",
Args: cobra.RangeArgs(0, 0),
Run: func(cmd *cobra.Command, args []string) {
cli, _ := cmd.Flags().GetString("client")
server, err := s.peers.Get(cli)
if err != nil {
fmt.Println("no such client")
return return
} }
resp, err := s.client.AllSpaces(context.Background(), server.Address, &clientproto.AllSpacesRequest{}) resp, err := s.client.AllSpaces(context.Background(), server.Address, &clientproto.AllSpacesRequest{})
if err != nil { if err != nil {
fmt.Println("couldn't print all the spaces", err)
return return
} }
var res string
for treeIdx, spaceId := range resp.SpaceIds { for treeIdx, spaceId := range resp.SpaceIds {
res += spaceId res += spaceId
if treeIdx != len(resp.SpaceIds)-1 { if treeIdx != len(resp.SpaceIds)-1 {
res += "\n" res += "\n"
} }
} }
return fmt.Println(res)
}} },
}
s.clientCommands = append(s.clientCommands, cmdAllSpaces)
} }
func (s *service) registerNodeCommands() { func (s *service) registerNodeCommands() {
s.nodeCommands["all-trees"] = Command{Cmd: func(server peers.Peer, params []string) (res string, err error) { cmdAllTrees := &cobra.Command{
if len(params) != 1 { Use: "all-trees [params]",
err = ErrIncorrectParamsCount Short: "print all trees in space and their heads",
Args: cobra.RangeArgs(1, 1),
Run: func(cmd *cobra.Command, args []string) {
nd, _ := cmd.Flags().GetString("node")
server, err := s.peers.Get(nd)
if err != nil {
fmt.Println("no such node")
return return
} }
resp, err := s.node.AllTrees(context.Background(), server.Address, &nodeproto.AllTreesRequest{ resp, err := s.node.AllTrees(context.Background(), server.Address, &nodeproto.AllTreesRequest{
SpaceId: params[0], SpaceId: args[0],
}) })
if err != nil { if err != nil {
fmt.Println("couldn't print all the trees", err)
return return
} }
var res string
for treeIdx, tree := range resp.Trees { for treeIdx, tree := range resp.Trees {
treeStr := tree.Id + ":[" treeStr := tree.Id + ":["
for headIdx, head := range tree.Heads { for headIdx, head := range tree.Heads {
@ -294,141 +387,182 @@ func (s *service) registerNodeCommands() {
res += "\n" res += "\n"
} }
} }
return fmt.Println(res)
}} },
s.nodeCommands["dump-tree"] = Command{Cmd: func(server peers.Peer, params []string) (res string, err error) { }
if len(params) != 2 { s.nodeCommands = append(s.nodeCommands, cmdAllTrees)
err = ErrIncorrectParamsCount
cmdDumpTree := &cobra.Command{
Use: "dump-tree [params]",
Short: "get graphviz description of the tree",
Args: cobra.RangeArgs(1, 1),
Run: func(cmd *cobra.Command, args []string) {
nd, _ := cmd.Flags().GetString("node")
space, _ := cmd.Flags().GetString("space")
server, err := s.peers.Get(nd)
if err != nil {
fmt.Println("no such node")
return return
} }
resp, err := s.node.DumpTree(context.Background(), server.Address, &nodeproto.DumpTreeRequest{ resp, err := s.node.DumpTree(context.Background(), server.Address, &nodeproto.DumpTreeRequest{
SpaceId: params[0], SpaceId: space,
DocumentId: params[1], DocumentId: args[0],
}) })
if err != nil { if err != nil {
fmt.Println("couldn't dump the tree", err)
return return
} }
res = resp.Dump fmt.Println(resp.Dump)
return },
}} }
s.nodeCommands["tree-params"] = Command{Cmd: func(server peers.Peer, params []string) (res string, err error) { cmdDumpTree.Flags().String("space", "", "the space where something is happening :-)")
if len(params) != 2 { cmdDumpTree.MarkFlagRequired("space")
err = ErrIncorrectParamsCount s.nodeCommands = append(s.nodeCommands, cmdDumpTree)
cmdTreeParams := &cobra.Command{
Use: "tree-params [params]",
Short: "print heads and root of the tree",
Args: cobra.RangeArgs(1, 1),
Run: func(cmd *cobra.Command, args []string) {
nd, _ := cmd.Flags().GetString("node")
space, _ := cmd.Flags().GetString("space")
server, err := s.peers.Get(nd)
if err != nil {
fmt.Println("no such node")
return return
} }
resp, err := s.node.TreeParams(context.Background(), server.Address, &nodeproto.TreeParamsRequest{ resp, err := s.node.TreeParams(context.Background(), server.Address, &nodeproto.TreeParamsRequest{
SpaceId: params[0], SpaceId: space,
DocumentId: params[1], DocumentId: args[0],
}) })
if err != nil { if err != nil {
fmt.Println("couldn't print params of the tree", err)
return return
} }
res = resp.RootId + "->" res := resp.RootId + "->"
for headIdx, head := range resp.HeadIds { for headIdx, head := range resp.HeadIds {
res += head res += head
if headIdx != len(resp.HeadIds)-1 { if headIdx != len(resp.HeadIds)-1 {
res += "," res += ","
} }
} }
return fmt.Println(res)
}} },
s.nodeCommands["all-spaces"] = Command{Cmd: func(server peers.Peer, params []string) (res string, err error) { }
if len(params) != 0 { cmdTreeParams.Flags().String("space", "", "the space where something is happening :-)")
err = ErrIncorrectParamsCount cmdTreeParams.MarkFlagRequired("space")
s.nodeCommands = append(s.nodeCommands, cmdTreeParams)
cmdAllSpaces := &cobra.Command{
Use: "all-spaces [params]",
Short: "print all spaces",
Args: cobra.RangeArgs(0, 0),
Run: func(cmd *cobra.Command, args []string) {
nd, _ := cmd.Flags().GetString("node")
server, err := s.peers.Get(nd)
if err != nil {
fmt.Println("no such node")
return return
} }
resp, err := s.node.AllSpaces(context.Background(), server.Address, &nodeproto.AllSpacesRequest{}) resp, err := s.node.AllSpaces(context.Background(), server.Address, &nodeproto.AllSpacesRequest{})
if err != nil { if err != nil {
fmt.Println("couldn't print all the spaces", err)
return return
} }
var res string
for treeIdx, spaceId := range resp.SpaceIds { for treeIdx, spaceId := range resp.SpaceIds {
res += spaceId res += spaceId
if treeIdx != len(resp.SpaceIds)-1 { if treeIdx != len(resp.SpaceIds)-1 {
res += "\n" res += "\n"
} }
} }
return fmt.Println(res)
}} },
}
s.nodeCommands = append(s.nodeCommands, cmdAllSpaces)
} }
func (s *service) registerScripts() { //
s.scripts["create-many"] = Script{Cmd: func(params []string) (res string, err error) { //func (s *service) registerScripts() {
if len(params) != 5 { // s.scripts["create-many"] = Script{Cmd: func(params []string) (res string, err error) {
err = ErrIncorrectParamsCount // if len(params) != 5 {
return // err = ErrIncorrectParamsCount
} // return
peer, err := s.peers.Get(params[0]) // }
if err != nil { // peer, err := s.peers.Get(params[0])
return // if err != nil {
} // return
last, err := strconv.Atoi(params[4]) // }
if err != nil { // last, err := strconv.Atoi(params[4])
return // if err != nil {
} // return
if last <= 0 { // }
err = fmt.Errorf("incorrect number of steps") // if last <= 0 {
return // err = fmt.Errorf("incorrect number of steps")
} // return
// }
for i := 0; i < last; i++ { //
_, err := s.client.AddText(context.Background(), peer.Address, &clientproto.AddTextRequest{ // for i := 0; i < last; i++ {
SpaceId: params[1], // _, err := s.client.AddText(context.Background(), peer.Address, &clientproto.AddTextRequest{
DocumentId: params[2], // SpaceId: params[1],
Text: params[3], // DocumentId: params[2],
}) // Text: params[3],
if err != nil { // })
return "", err // if err != nil {
} // return "", err
} // }
return // }
}} // return
s.scripts["create-many-two-clients"] = Script{Cmd: func(params []string) (res string, err error) { // }}
if len(params) != 6 { // s.scripts["create-many-two-clients"] = Script{Cmd: func(params []string) (res string, err error) {
err = ErrIncorrectParamsCount // if len(params) != 6 {
return // err = ErrIncorrectParamsCount
} // return
peer1, err := s.peers.Get(params[0]) // }
if err != nil { // peer1, err := s.peers.Get(params[0])
return // if err != nil {
} // return
peer2, err := s.peers.Get(params[1]) // }
if err != nil { // peer2, err := s.peers.Get(params[1])
return // if err != nil {
} // return
last, err := strconv.Atoi(params[5]) // }
if err != nil { // last, err := strconv.Atoi(params[5])
return // if err != nil {
} // return
if last <= 0 { // }
err = fmt.Errorf("incorrect number of steps") // if last <= 0 {
return // err = fmt.Errorf("incorrect number of steps")
} // return
wg := &sync.WaitGroup{} // }
var mError errs.Group // wg := &sync.WaitGroup{}
createMany := func(peer peers.Peer) { // var mError errs.Group
defer wg.Done() // createMany := func(peer peers.Peer) {
for i := 0; i < last; i++ { // defer wg.Done()
_, err := s.client.AddText(context.Background(), peer.Address, &clientproto.AddTextRequest{ // for i := 0; i < last; i++ {
SpaceId: params[2], // _, err := s.client.AddText(context.Background(), peer.Address, &clientproto.AddTextRequest{
DocumentId: params[3], // SpaceId: params[2],
Text: params[4], // DocumentId: params[3],
IsSnapshot: rand.Int()%2 == 0, // Text: params[4],
}) // IsSnapshot: rand.Int()%2 == 0,
if err != nil { // })
mError.Add(err) // if err != nil {
return // mError.Add(err)
} // return
} // }
} // }
for _, p := range []peers.Peer{peer1, peer2} { // }
wg.Add(1) // for _, p := range []peers.Peer{peer1, peer2} {
createMany(p) // wg.Add(1)
} // createMany(p)
wg.Wait() // }
if mError.Err() != nil { // wg.Wait()
err = mError.Err() // if mError.Err() != nil {
return // err = mError.Err()
} // return
return // }
}} // return
} // }}
//}

View File

@ -2,8 +2,6 @@ package main
import ( import (
"context" "context"
"flag"
"fmt"
"github.com/anytypeio/go-anytype-infrastructure-experiments/common/app" "github.com/anytypeio/go-anytype-infrastructure-experiments/common/app"
"github.com/anytypeio/go-anytype-infrastructure-experiments/common/app/logger" "github.com/anytypeio/go-anytype-infrastructure-experiments/common/app/logger"
"github.com/anytypeio/go-anytype-infrastructure-experiments/util/cmd/debug/api" "github.com/anytypeio/go-anytype-infrastructure-experiments/util/cmd/debug/api"
@ -11,24 +9,14 @@ import (
"github.com/anytypeio/go-anytype-infrastructure-experiments/util/cmd/debug/api/node" "github.com/anytypeio/go-anytype-infrastructure-experiments/util/cmd/debug/api/node"
"github.com/anytypeio/go-anytype-infrastructure-experiments/util/cmd/debug/drpcclient" "github.com/anytypeio/go-anytype-infrastructure-experiments/util/cmd/debug/drpcclient"
"github.com/anytypeio/go-anytype-infrastructure-experiments/util/cmd/debug/peers" "github.com/anytypeio/go-anytype-infrastructure-experiments/util/cmd/debug/peers"
"github.com/anytypeio/go-anytype-infrastructure-experiments/util/cmd/debug/stdin"
"go.uber.org/zap" "go.uber.org/zap"
"go.uber.org/zap/zapcore" "go.uber.org/zap/zapcore"
"net/http" "net/http"
"os" "os"
"os/signal"
"syscall"
"time"
) )
var log = logger.NewNamed("main") var log = logger.NewNamed("main")
var (
// we can't use "v" here because of glog init (through badger) setting flag.Bool with "v"
flagVersion = flag.Bool("ver", false, "show version and exit")
flagHelp = flag.Bool("h", false, "show help and exit")
)
func init() { func init() {
config := zap.NewProductionEncoderConfig() config := zap.NewProductionEncoderConfig()
config.EncodeTime = zapcore.ISO8601TimeEncoder config.EncodeTime = zapcore.ISO8601TimeEncoder
@ -43,17 +31,6 @@ func init() {
} }
func main() { func main() {
flag.Parse()
if *flagVersion {
fmt.Println(app.VersionDescription())
return
}
if *flagHelp {
flag.PrintDefaults()
return
}
if debug, ok := os.LookupEnv("ANYPROF"); ok && debug != "" { if debug, ok := os.LookupEnv("ANYPROF"); ok && debug != "" {
go func() { go func() {
http.ListenAndServe(debug, nil) http.ListenAndServe(debug, nil)
@ -64,27 +41,11 @@ func main() {
ctx := context.Background() ctx := context.Background()
a := new(app.App) a := new(app.App)
Bootstrap(a) Bootstrap(a)
// start app // start app
if err := a.Start(ctx); err != nil { if err := a.Start(ctx); err != nil {
log.Fatal("can't start app", zap.Error(err)) log.Fatal("can't start app", zap.Error(err))
} }
log.Info("app started", zap.String("version", a.Version()))
// wait exit signal
exit := make(chan os.Signal, 1)
signal.Notify(exit, os.Interrupt, syscall.SIGKILL, syscall.SIGTERM, syscall.SIGQUIT)
sig := <-exit
log.Info("received exit signal, stop app...", zap.String("signal", fmt.Sprint(sig)))
// close app
ctx, cancel := context.WithTimeout(ctx, time.Minute)
defer cancel()
if err := a.Close(ctx); err != nil {
log.Fatal("close error", zap.Error(err))
} else {
log.Info("goodbye!")
}
time.Sleep(time.Second / 3)
} }
func Bootstrap(a *app.App) { func Bootstrap(a *app.App) {
@ -92,6 +53,5 @@ func Bootstrap(a *app.App) {
Register(peers.New()). Register(peers.New()).
Register(client.New()). Register(client.New()).
Register(node.New()). Register(node.New()).
Register(api.New()). Register(api.New())
Register(stdin.New())
} }

View File

@ -1,98 +0,0 @@
package stdin
import (
"bufio"
"context"
"fmt"
"github.com/anytypeio/go-anytype-infrastructure-experiments/common/app"
"github.com/anytypeio/go-anytype-infrastructure-experiments/common/app/logger"
"github.com/anytypeio/go-anytype-infrastructure-experiments/util/cmd/debug/api"
"github.com/anytypeio/go-anytype-infrastructure-experiments/util/cmd/debug/peers"
"os"
"strings"
)
const CName = "debug.stdin"
var log = logger.NewNamed(CName)
type Service interface {
app.ComponentRunnable
}
type service struct {
api api.Service
peers peers.Service
}
func New() Service {
return &service{}
}
func (s *service) Init(a *app.App) (err error) {
s.api = a.MustComponent(api.CName).(api.Service)
s.peers = a.MustComponent(peers.CName).(peers.Service)
return
}
func (s *service) Name() (name string) {
return CName
}
func (s *service) Run(ctx context.Context) (err error) {
go s.readStdin()
return nil
}
func (s *service) Close(ctx context.Context) (err error) {
return nil
}
func (s *service) readStdin() {
reader := bufio.NewReader(os.Stdin)
Loop:
for {
fmt.Print("> ")
str, err := reader.ReadString('\n')
if err != nil {
fmt.Println("error in read string:", err)
return
}
// trimming newline
str = str[:len(str)-1]
split := strings.Split(str, " ")
if len(split) < 2 {
fmt.Println("incorrect number of arguments")
continue
}
switch split[0] {
case "script":
res, err := s.api.Script(split[1], split[2:])
if err != nil {
fmt.Println("error in performing script:", err)
continue Loop
}
fmt.Println(res)
continue Loop
case "cmd":
break
default:
fmt.Println("incorrect input")
continue Loop
}
peer, err := s.peers.Get(split[1])
if err != nil {
fmt.Println("no such peer", err)
continue
}
res, err := s.api.Call(peer, split[2], split[3:])
if err != nil {
fmt.Println("error in performing command:", err)
continue
}
fmt.Println(res)
}
}