Nexus/pkg/internal/http/api/command.go

68 lines
1.7 KiB
Go
Raw Normal View History

2024-10-20 09:42:51 +00:00
package api
import (
"context"
2024-10-20 10:13:07 +00:00
"fmt"
2024-10-20 16:05:40 +00:00
"git.solsynth.dev/hypernet/nexus/pkg/internal/directory"
2024-10-20 09:42:51 +00:00
"git.solsynth.dev/hypernet/nexus/pkg/proto"
"github.com/gofiber/fiber/v2"
"github.com/rs/zerolog/log"
"google.golang.org/grpc/metadata"
"strings"
"time"
)
func invokeCommand(c *fiber.Ctx) error {
command := c.Params("command")
method := strings.ToLower(c.Method())
handler := directory.GetCommandHandler(command, method)
if handler == nil {
return fiber.NewError(fiber.StatusNotFound, "command not found")
}
conn, err := handler.GetGrpcConn()
if err != nil {
return fiber.NewError(fiber.StatusServiceUnavailable, "service unavailable")
}
log.Debug().Str("id", command).Str("method", method).Msg("Invoking command from HTTP Gateway...")
2024-10-20 10:13:07 +00:00
var meta []string
meta = append(meta, "client_id", "http-gateway")
meta = append(meta, "net.ip", c.IP())
meta = append(meta, "http.user_agent", c.Get(fiber.HeaderUserAgent))
for k, v := range c.GetReqHeaders() {
meta = append(
meta,
strings.ToLower(fmt.Sprintf("header.%s", strings.ReplaceAll(k, "-", "_"))),
strings.Join(v, "\n"),
)
}
2024-10-20 11:55:52 +00:00
for k, v := range c.Queries() {
meta = append(
meta,
strings.ToLower(fmt.Sprintf("query.%s", strings.ReplaceAll(k, "-", "_"))),
v,
)
}
2024-10-20 10:13:07 +00:00
ctx := metadata.AppendToOutgoingContext(c.Context(), meta...)
2024-10-20 09:42:51 +00:00
ctx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
2024-10-21 14:07:36 +00:00
out, err := proto.NewCommandProviderClient(conn).SendCommand(ctx, &proto.CommandArgument{
2024-10-20 09:42:51 +00:00
Command: command,
Method: method,
Payload: c.Body(),
})
if err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
} else {
2024-10-20 10:13:07 +00:00
c.Set(fiber.HeaderContentType, out.ContentType)
2024-10-20 09:42:51 +00:00
return c.Status(int(out.Status)).Send(out.Payload)
}
}