From 5d8de80a181971a61bb8de3cef894fafc2700b86 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Wed, 11 Dec 2024 18:58:50 +0300 Subject: [PATCH 01/10] Write the error in the response --- internal/http/server.go | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/internal/http/server.go b/internal/http/server.go index 3ea0159..a6239c4 100644 --- a/internal/http/server.go +++ b/internal/http/server.go @@ -17,8 +17,7 @@ var ( type DefaultRequestParser struct { } - -func(rp *DefaultRequestParser) GetSessionId(rq any) (string, error) { +func (rp *DefaultRequestParser) GetSessionId(rq any) (string, error) { rqv, ok := rq.(*http.Request) if !ok { return "", handlers.ErrInvalidRequest @@ -30,7 +29,7 @@ func(rp *DefaultRequestParser) GetSessionId(rq any) (string, error) { return v, nil } -func(rp *DefaultRequestParser) GetInput(rq any) ([]byte, error) { +func (rp *DefaultRequestParser) GetInput(rq any) ([]byte, error) { rqv, ok := rq.(*http.Request) if !ok { return nil, handlers.ErrInvalidRequest @@ -53,25 +52,24 @@ func ToSessionHandler(h handlers.RequestHandler) *SessionHandler { } } -func(f *SessionHandler) writeError(w http.ResponseWriter, code int, err error) { +func (f *SessionHandler) writeError(w http.ResponseWriter, code int, err error) { s := err.Error() w.Header().Set("Content-Length", strconv.Itoa(len(s))) w.WriteHeader(code) - _, err = w.Write([]byte{}) + _, err = w.Write([]byte(s)) if err != nil { logg.Errorf("error writing error!!", "err", err, "olderr", s) w.WriteHeader(500) } - return } -func(f *SessionHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { +func (f *SessionHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { var code int var err error var perr error rqs := handlers.RequestSession{ - Ctx: req.Context(), + Ctx: req.Context(), Writer: w, } From f8ea2daa736887e97733e24470ca9b4c7bdfe796 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Thu, 12 Dec 2024 19:55:01 +0300 Subject: [PATCH 02/10] initialize the restart state devtool --- devtools/restart_state/main.go | 110 +++++++++++++++++++++++++++++++++ 1 file changed, 110 insertions(+) create mode 100644 devtools/restart_state/main.go diff --git a/devtools/restart_state/main.go b/devtools/restart_state/main.go new file mode 100644 index 0000000..136b38a --- /dev/null +++ b/devtools/restart_state/main.go @@ -0,0 +1,110 @@ +package main + +import ( + "context" + "flag" + "fmt" + "os" + "path" + + "git.defalsify.org/vise.git/engine" + "git.defalsify.org/vise.git/logging" + "git.defalsify.org/vise.git/resource" + + // "git.defalsify.org/vise.git/persist" + "git.grassecon.net/urdt/ussd/config" + "git.grassecon.net/urdt/ussd/initializers" + "git.grassecon.net/urdt/ussd/remote" + + "git.grassecon.net/urdt/ussd/internal/handlers" + "git.grassecon.net/urdt/ussd/internal/storage" +) + +var ( + logg = logging.NewVanilla() + scriptDir = path.Join("services", "registration") +) + +func init() { + initializers.LoadEnvVariables() +} + +func main() { + config.LoadConfig() + + var dbDir string + var sessionId string + var database string + var engineDebug bool + var size uint + + flag.StringVar(&sessionId, "session-id", "075xx2123", "session id") + flag.StringVar(&database, "db", "gdbm", "database to be used") + flag.StringVar(&dbDir, "dbdir", ".state", "database dir to read from") + flag.BoolVar(&engineDebug, "d", false, "use engine debug output") + flag.Parse() + + ctx := context.Background() + ctx = context.WithValue(ctx, "SessionId", sessionId) + ctx = context.WithValue(ctx, "Database", database) + + pfp := path.Join(scriptDir, "pp.csv") + + cfg := engine.Config{ + Root: "root", + SessionId: sessionId, + OutputSize: uint32(size), + FlagCount: uint32(128), + } + + resourceDir := scriptDir + menuStorageService := storage.NewMenuStorageService(dbDir, resourceDir) + + err := menuStorageService.EnsureDbDir() + if err != nil { + fmt.Fprintf(os.Stderr, err.Error()) + os.Exit(1) + } + + rs, err := menuStorageService.GetResource(ctx) + if err != nil { + fmt.Fprintf(os.Stderr, err.Error()) + os.Exit(1) + } + + pe, err := menuStorageService.GetPersister(ctx) + if err != nil { + fmt.Fprintf(os.Stderr, err.Error()) + os.Exit(1) + } + + userdatastore, err := menuStorageService.GetUserdataDb(ctx) + if err != nil { + fmt.Fprintf(os.Stderr, err.Error()) + os.Exit(1) + } + + + // initialize the persister + + // get the state + + // restart the state + + // persist the state + + // exit + + st := pe.GetState() + + if st == nil { + logg.ErrorCtxf(ctx, "state fail in devtool", "state", st) + fmt.Errorf("cannot get state") + os.Exit(1) + } + + st.Restart() + + + os.Exit(1) +} From 5428626c3f6cef24196be7d391b20b794ec284b1 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Tue, 17 Dec 2024 17:56:56 +0300 Subject: [PATCH 03/10] cleaned up the restart_state --- devtools/restart_state/main.go | 35 +--------------------------------- 1 file changed, 1 insertion(+), 34 deletions(-) diff --git a/devtools/restart_state/main.go b/devtools/restart_state/main.go index 136b38a..3068a38 100644 --- a/devtools/restart_state/main.go +++ b/devtools/restart_state/main.go @@ -7,16 +7,9 @@ import ( "os" "path" - "git.defalsify.org/vise.git/engine" "git.defalsify.org/vise.git/logging" - "git.defalsify.org/vise.git/resource" - - // "git.defalsify.org/vise.git/persist" "git.grassecon.net/urdt/ussd/config" "git.grassecon.net/urdt/ussd/initializers" - "git.grassecon.net/urdt/ussd/remote" - - "git.grassecon.net/urdt/ussd/internal/handlers" "git.grassecon.net/urdt/ussd/internal/storage" ) @@ -35,28 +28,16 @@ func main() { var dbDir string var sessionId string var database string - var engineDebug bool - var size uint - + flag.StringVar(&sessionId, "session-id", "075xx2123", "session id") flag.StringVar(&database, "db", "gdbm", "database to be used") flag.StringVar(&dbDir, "dbdir", ".state", "database dir to read from") - flag.BoolVar(&engineDebug, "d", false, "use engine debug output") flag.Parse() ctx := context.Background() ctx = context.WithValue(ctx, "SessionId", sessionId) ctx = context.WithValue(ctx, "Database", database) - pfp := path.Join(scriptDir, "pp.csv") - - cfg := engine.Config{ - Root: "root", - SessionId: sessionId, - OutputSize: uint32(size), - FlagCount: uint32(128), - } - resourceDir := scriptDir menuStorageService := storage.NewMenuStorageService(dbDir, resourceDir) @@ -66,25 +47,12 @@ func main() { os.Exit(1) } - rs, err := menuStorageService.GetResource(ctx) - if err != nil { - fmt.Fprintf(os.Stderr, err.Error()) - os.Exit(1) - } - pe, err := menuStorageService.GetPersister(ctx) if err != nil { fmt.Fprintf(os.Stderr, err.Error()) os.Exit(1) } - userdatastore, err := menuStorageService.GetUserdataDb(ctx) - if err != nil { - fmt.Fprintf(os.Stderr, err.Error()) - os.Exit(1) - } - - // initialize the persister // get the state @@ -105,6 +73,5 @@ func main() { st.Restart() - os.Exit(1) } From 553470618913fca61232761e3ffcfa8efe00cbab Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Tue, 17 Dec 2024 17:58:08 +0300 Subject: [PATCH 04/10] reset the state when input is nil --- internal/handlers/ussd/menuhandler.go | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index c5356d0..c2b41b2 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -124,6 +124,16 @@ func (h *Handlers) Init(ctx context.Context, sym string, input []byte) (resource h.st = h.pe.GetState() h.ca = h.pe.GetMemory() + + fmt.Println("Pre restart state:", h.st) + + if len(input) == 0 { + h.st.Restart() + h.st = h.pe.GetState() + } + + fmt.Println("New state:", h.st) + sessionId, _ := ctx.Value("SessionId").(string) flag_admin_privilege, _ := h.flagManager.GetFlag("flag_admin_privilege") From be215d3f75ed64a1794e87497a3682b5050842b7 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Fri, 20 Dec 2024 12:26:07 +0300 Subject: [PATCH 05/10] set the code to an empty byte for it to move to the top node --- internal/handlers/ussd/menuhandler.go | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index b3c6f1d..f509ff4 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -124,16 +124,11 @@ func (h *Handlers) Init(ctx context.Context, sym string, input []byte) (resource h.st = h.pe.GetState() h.ca = h.pe.GetMemory() - - fmt.Println("Pre restart state:", h.st) - if len(input) == 0 { - h.st.Restart() - h.st = h.pe.GetState() + // move to the top node + h.st.Code = []byte{} } - fmt.Println("New state:", h.st) - sessionId, _ := ctx.Value("SessionId").(string) flag_admin_privilege, _ := h.flagManager.GetFlag("flag_admin_privilege") From 50c006546cc88138416f88b6fa0b041cf792d24c Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Sat, 28 Dec 2024 13:21:03 +0300 Subject: [PATCH 06/10] added code to reset the state and persist it --- devtools/restart_state/main.go | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/devtools/restart_state/main.go b/devtools/restart_state/main.go index 3068a38..5df34fd 100644 --- a/devtools/restart_state/main.go +++ b/devtools/restart_state/main.go @@ -53,25 +53,24 @@ func main() { os.Exit(1) } - // initialize the persister - - // get the state - - // restart the state - - // persist the state - - // exit - st := pe.GetState() if st == nil { logg.ErrorCtxf(ctx, "state fail in devtool", "state", st) - fmt.Errorf("cannot get state") + fmt.Println("cannot get state") os.Exit(1) } - st.Restart() + fmt.Println("The state:", st) - os.Exit(1) + // set empty Code to allow the menu to run from the top + st.Code = []byte{} + + err = pe.Save(sessionId) + if err != nil { + logg.ErrorCtxf(ctx, "failed to persist the state and cache", "error", err) + os.Exit(1) + } + + os.Exit(0) } From 1311a0cab9980e32f3085a69da609596217ab0a5 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Tue, 31 Dec 2024 02:36:28 +0300 Subject: [PATCH 07/10] use the 'send_with_invite' test group in the menu traversal test --- menutraversal_test/menu_traversal_test.go | 5 +++-- menutraversal_test/test_setup.json | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/menutraversal_test/menu_traversal_test.go b/menutraversal_test/menu_traversal_test.go index 28d88db..6b6b3da 100644 --- a/menutraversal_test/menu_traversal_test.go +++ b/menutraversal_test/menu_traversal_test.go @@ -298,9 +298,10 @@ func TestMainMenuSend(t *testing.T) { ctx := context.Background() sessions := testData for _, session := range sessions { - groups := driver.FilterGroupsByName(session.Groups, "send_with_invalid_inputs") + groups := driver.FilterGroupsByName(session.Groups, "send_with_invite") for _, group := range groups { - for _, step := range group.Steps { + for index, step := range group.Steps { + t.Logf("step %v with input %v", index, step.Input) cont, err := en.Exec(ctx, []byte(step.Input)) if err != nil { t.Fatalf("Test case '%s' failed at input '%s': %v", group.Name, step.Input, err) diff --git a/menutraversal_test/test_setup.json b/menutraversal_test/test_setup.json index c5860b4..5115de9 100644 --- a/menutraversal_test/test_setup.json +++ b/menutraversal_test/test_setup.json @@ -64,8 +64,8 @@ "expectedContent": "Enter recipient's phone number/address/alias:\n0:Back" }, { - "input": "000", - "expectedContent": "000 is invalid, please try again:\n1:Retry\n9:Quit" + "input": "0@0", + "expectedContent": "0@0 is invalid, please try again:\n1:Retry\n9:Quit" }, { "input": "1", From 3c73fc718896a12f959a6496af287206bcf6deff Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Tue, 31 Dec 2024 05:05:39 +0300 Subject: [PATCH 08/10] added a test for the Init func with the different states --- internal/handlers/ussd/menuhandler_test.go | 101 +++++++++++++++++++++ 1 file changed, 101 insertions(+) diff --git a/internal/handlers/ussd/menuhandler_test.go b/internal/handlers/ussd/menuhandler_test.go index c01678d..54b1581 100644 --- a/internal/handlers/ussd/menuhandler_test.go +++ b/internal/handlers/ussd/menuhandler_test.go @@ -8,6 +8,7 @@ import ( "strings" "testing" + "git.defalsify.org/vise.git/cache" "git.defalsify.org/vise.git/lang" "git.defalsify.org/vise.git/persist" "git.defalsify.org/vise.git/resource" @@ -15,6 +16,7 @@ import ( "git.grassecon.net/urdt/ussd/internal/storage" "git.grassecon.net/urdt/ussd/internal/testutil/mocks" "git.grassecon.net/urdt/ussd/internal/testutil/testservice" + "git.grassecon.net/urdt/ussd/internal/utils" "git.grassecon.net/urdt/ussd/models" "git.grassecon.net/urdt/ussd/common" @@ -119,6 +121,105 @@ func TestNewHandlers(t *testing.T) { }) } +func TestInit(t *testing.T) { + sessionId := "session123" + ctx, store := InitializeTestStore(t) + ctx = context.WithValue(ctx, "SessionId", sessionId) + + fm, err := NewFlagManager(flagsPath) + if err != nil { + t.Fatal(err.Error()) + } + + adminstore, err := utils.NewAdminStore(ctx, "admin_numbers") + if err != nil { + t.Fatal(err.Error()) + } + + st := state.NewState(128) + ca := cache.NewCache() + + flag_admin_privilege, _ := fm.GetFlag("flag_admin_privilege") + + nonAdminExpectedResult := resource.Result{} + nonAdminExpectedResult.FlagReset = []uint32{flag_admin_privilege} + + tests := []struct { + name string + setup func() (*Handlers, context.Context) + input []byte + expectedResult resource.Result + }{ + { + name: "Handler not ready", + setup: func() (*Handlers, context.Context) { + return &Handlers{}, ctx + }, + input: []byte("1"), + expectedResult: resource.Result{}, + }, + { + name: "State and memory initialization", + setup: func() (*Handlers, context.Context) { + pe := persist.NewPersister(store).WithSession(sessionId).WithContent(st, ca) + h := &Handlers{ + flagManager: fm.parser, + adminstore: adminstore, + pe: pe, + } + return h, context.WithValue(ctx, "SessionId", sessionId) + }, + input: []byte("1"), + expectedResult: resource.Result{ + FlagReset: []uint32{flag_admin_privilege}, + }, + }, + { + name: "Non-admin session initialization", + setup: func() (*Handlers, context.Context) { + pe := persist.NewPersister(store).WithSession("0712345678").WithContent(st, ca) + h := &Handlers{ + flagManager: fm.parser, + adminstore: adminstore, + pe: pe, + } + return h, context.WithValue(context.Background(), "SessionId", "0712345678") + }, + input: []byte("1"), + expectedResult: resource.Result{ + FlagReset: []uint32{flag_admin_privilege}, + }, + }, + { + name: "Move to top node on empty input", + setup: func() (*Handlers, context.Context) { + pe := persist.NewPersister(store).WithSession(sessionId).WithContent(st, ca) + h := &Handlers{ + flagManager: fm.parser, + adminstore: adminstore, + pe: pe, + } + st.Code = []byte("some pending bytecode") + return h, context.WithValue(ctx, "SessionId", sessionId) + }, + input: []byte(""), + expectedResult: resource.Result{ + FlagReset: []uint32{flag_admin_privilege}, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + h, testCtx := tt.setup() + res, err := h.Init(testCtx, "", tt.input) + + assert.NoError(t, err, "Unexpected error occurred") + assert.Equal(t, res, tt.expectedResult, "Expected result should match actual result") + }) + } +} + func TestCreateAccount(t *testing.T) { sessionId := "session123" ctx, store := InitializeTestStore(t) From be2ea3a2f0fbdf79bfd9d28f2e2b4f09ca37ccb5 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Tue, 31 Dec 2024 10:51:29 +0300 Subject: [PATCH 09/10] removed the non-working restart_state devtool --- devtools/restart_state/main.go | 76 ---------------------------------- 1 file changed, 76 deletions(-) delete mode 100644 devtools/restart_state/main.go diff --git a/devtools/restart_state/main.go b/devtools/restart_state/main.go deleted file mode 100644 index 5df34fd..0000000 --- a/devtools/restart_state/main.go +++ /dev/null @@ -1,76 +0,0 @@ -package main - -import ( - "context" - "flag" - "fmt" - "os" - "path" - - "git.defalsify.org/vise.git/logging" - "git.grassecon.net/urdt/ussd/config" - "git.grassecon.net/urdt/ussd/initializers" - "git.grassecon.net/urdt/ussd/internal/storage" -) - -var ( - logg = logging.NewVanilla() - scriptDir = path.Join("services", "registration") -) - -func init() { - initializers.LoadEnvVariables() -} - -func main() { - config.LoadConfig() - - var dbDir string - var sessionId string - var database string - - flag.StringVar(&sessionId, "session-id", "075xx2123", "session id") - flag.StringVar(&database, "db", "gdbm", "database to be used") - flag.StringVar(&dbDir, "dbdir", ".state", "database dir to read from") - flag.Parse() - - ctx := context.Background() - ctx = context.WithValue(ctx, "SessionId", sessionId) - ctx = context.WithValue(ctx, "Database", database) - - resourceDir := scriptDir - menuStorageService := storage.NewMenuStorageService(dbDir, resourceDir) - - err := menuStorageService.EnsureDbDir() - if err != nil { - fmt.Fprintf(os.Stderr, err.Error()) - os.Exit(1) - } - - pe, err := menuStorageService.GetPersister(ctx) - if err != nil { - fmt.Fprintf(os.Stderr, err.Error()) - os.Exit(1) - } - - st := pe.GetState() - - if st == nil { - logg.ErrorCtxf(ctx, "state fail in devtool", "state", st) - fmt.Println("cannot get state") - os.Exit(1) - } - - fmt.Println("The state:", st) - - // set empty Code to allow the menu to run from the top - st.Code = []byte{} - - err = pe.Save(sessionId) - if err != nil { - logg.ErrorCtxf(ctx, "failed to persist the state and cache", "error", err) - os.Exit(1) - } - - os.Exit(0) -} From 4ea52bf3fbb0f605d1296c710fd6a823fa8c4bad Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Tue, 31 Dec 2024 11:16:43 +0300 Subject: [PATCH 10/10] removed unused code --- internal/handlers/ussd/menuhandler_test.go | 3 --- 1 file changed, 3 deletions(-) diff --git a/internal/handlers/ussd/menuhandler_test.go b/internal/handlers/ussd/menuhandler_test.go index 54b1581..34c8e76 100644 --- a/internal/handlers/ussd/menuhandler_test.go +++ b/internal/handlers/ussd/menuhandler_test.go @@ -141,9 +141,6 @@ func TestInit(t *testing.T) { flag_admin_privilege, _ := fm.GetFlag("flag_admin_privilege") - nonAdminExpectedResult := resource.Result{} - nonAdminExpectedResult.FlagReset = []uint32{flag_admin_privilege} - tests := []struct { name string setup func() (*Handlers, context.Context)