buildr/internal/rpc/v1/grpc_handler.go

74 lines
1.7 KiB
Go
Raw Normal View History

2023-04-11 20:30:48 +00:00
package v1
import (
"context"
"log/slog"
2023-06-22 16:06:56 +00:00
remotev1 "code.icb4dc0.de/buildr/api/generated/remote/v1"
2023-04-11 20:30:48 +00:00
)
var _ slog.Handler = (*GrpcExecutorHandler)(nil)
func NewGrpcExecutorHandler(sender StreamSender[*remotev1.ExecutionServerMessage]) *GrpcExecutorHandler {
return &GrpcExecutorHandler{
Level: slog.LevelDebug,
sender: sender,
}
}
2023-04-11 20:30:48 +00:00
type GrpcExecutorHandler struct {
sender StreamSender[*remotev1.ExecutionServerMessage]
2023-04-11 20:30:48 +00:00
group string
attributes []slog.Attr
2023-06-22 16:06:56 +00:00
Level slog.Level
2023-04-11 20:30:48 +00:00
}
func (g GrpcExecutorHandler) Enabled(_ context.Context, level slog.Level) bool {
return g.Level <= level
2023-04-11 20:30:48 +00:00
}
2023-06-22 16:06:56 +00:00
//nolint:gocritic // can't pass by reference due to interface constraints
func (g GrpcExecutorHandler) Handle(_ context.Context, record slog.Record) error {
taskLog := remotev1.TaskLog{
2023-05-24 20:10:01 +00:00
Time: record.Time.UnixMicro(),
Message: record.Message,
Level: int32(record.Level),
Attributes: make([]*remotev1.TaskLog_LogAttribute, 0, record.NumAttrs()),
2023-04-11 20:30:48 +00:00
}
record.Attrs(func(attr slog.Attr) bool {
taskLog.Attributes = append(taskLog.Attributes, &remotev1.TaskLog_LogAttribute{
Key: attr.Key,
Value: attr.Value.String(),
})
return true
2023-04-11 20:30:48 +00:00
})
resp := remotev1.ExecutionServerMessage{
Envelope: &remotev1.ExecutionServerMessage_TaskLog{
2023-04-11 20:30:48 +00:00
TaskLog: &taskLog,
},
}
return g.sender.Send(&resp)
2023-04-11 20:30:48 +00:00
}
func (g GrpcExecutorHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
all := make([]slog.Attr, len(g.attributes)+len(attrs))
copy(all, g.attributes)
copy(all[len(g.attributes):], attrs)
return GrpcExecutorHandler{
sender: g.sender,
Level: g.Level,
2023-04-11 20:30:48 +00:00
group: g.group,
attributes: all,
}
}
func (g GrpcExecutorHandler) WithGroup(name string) slog.Handler {
g.group = name
return g
}