From 049998d5ec614a7ae1f3d5d36bbdec9eedfb8c3e Mon Sep 17 00:00:00 2001 From: Helmut Merz Date: Sun, 13 Aug 2023 22:24:43 +0200 Subject: [PATCH] server: Sync message processor (work in progress) --- core/message/message.go | 4 ++-- server/config.go | 3 ++- server/server.go | 16 ++++++++++++++-- tests/etc/etc.go | 2 +- 4 files changed, 19 insertions(+), 6 deletions(-) diff --git a/core/message/message.go b/core/message/message.go index 3673976..ecd45f4 100644 --- a/core/message/message.go +++ b/core/message/message.go @@ -116,11 +116,11 @@ func (pl *payload) FromJson(s string) lib.Payload { return pl } -func Payload(d interface{}) lib.Payload { +func Payload(d lib.Data) lib.Payload { return &payload{d} } -func PayloadFromJson[T any](s string) lib.Payload { +func PayloadFromJson[T lib.Data](s string) lib.Payload { pl := &payload{new(T)} return pl.FromJson(s) } diff --git a/server/config.go b/server/config.go index 8a34559..829d024 100644 --- a/server/config.go +++ b/server/config.go @@ -51,7 +51,8 @@ func MsgHandler(pattern string, proc msgProc, rcvs ...string) *mhSpec { if proc == nil { proc = Async } - cfg := mhSpec{config.Base("", nil), proc} + //cfg := mhSpec{config.Dummy(), proc} + cfg := mhSpec{config.Default(""), proc} cfg.AddAction(pattern, action.Base(action.Forward, rcvs...)) return &cfg } diff --git a/server/server.go b/server/server.go index cdf65a8..e34cfdd 100644 --- a/server/server.go +++ b/server/server.go @@ -3,6 +3,7 @@ package server import ( "net/http" "strings" + "time" lib "git.sr.ht/~cco/go-scopes" "git.sr.ht/~cco/go-scopes/config" @@ -78,10 +79,21 @@ func Async(ctx lib.Context, msg lib.Message) (int, lib.Data) { return http.StatusOK, lib.Map{"status": "OK"} } -func Sync(ctx lib.Context, msg lib.Message) (int, lib.Data) { +func Sync(timeout int) msgProc { + return func(ctx lib.Context, msg lib.Message) (int, lib.Data) { + return sync(ctx, msg, timeout) + } +} + +func sync(ctx lib.Context, msg lib.Message, to int) (int, lib.Data) { + timeout := time.Duration(to) * time.Second select { case msg := <-ctx.Mailbox(): return http.StatusOK, msg.Payload().Data() + case <-time.After(timeout): + return http.StatusNoContent, nil + case <-ctx.Done(): + return http.StatusGone, nil } - return http.StatusOK, lib.Map{"status": "OK"} + return http.StatusNoContent, nil } diff --git a/tests/etc/etc.go b/tests/etc/etc.go index 9addc00..b387fde 100644 --- a/tests/etc/etc.go +++ b/tests/etc/etc.go @@ -29,7 +29,7 @@ func Config() lib.Config { server_c := b("server", server.Start( (&server.Cfg{Port: ovr("8123", SERVER_PORT)}). AddRoute("/docs", server.FileServer("html")). - AddRoute("/api", server.MsgHandler("demo", nil, "test-receiver")), + AddRoute("/api", server.MsgHandler("demo", server.Async, "test-receiver")), )) test_client := &client.Cfg{