-
Notifications
You must be signed in to change notification settings - Fork 8
/
console.go
171 lines (141 loc) · 4.43 KB
/
console.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package console
import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"time"
"github.com/kr/text"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/types/known/timestamppb"
"namespacelabs.dev/foundation/internal/sync"
"namespacelabs.dev/foundation/schema/storage"
"namespacelabs.dev/foundation/std/tasks"
"namespacelabs.dev/foundation/std/tasks/idtypes"
"namespacelabs.dev/go-ids"
)
const (
CatOutputTool = idtypes.CatOutputTool
CatOutputUs = idtypes.CatOutputUs
)
var (
// Configured globally.
DebugToConsole = false
)
func Stdout(ctx context.Context) io.Writer {
return Output(ctx, idtypes.KnownStdout)
}
func Stderr(ctx context.Context) io.Writer {
return Output(ctx, idtypes.KnownStderr)
}
func Output(ctx context.Context, name string) io.Writer {
return TypedOutput(ctx, name, idtypes.CatOutputTool)
}
func Debug(ctx context.Context) io.Writer {
return NamedDebug(ctx, "debug")
}
func NamedDebug(ctx context.Context, name string) io.Writer {
return typedOutput(ctx, true, name, idtypes.CatOutputDebug)
}
func Warnings(ctx context.Context) io.Writer {
return typedOutput(ctx, true, "warning", idtypes.CatOutputWarnings)
}
func Errors(ctx context.Context) io.Writer {
return typedOutput(ctx, true, "error", idtypes.CatOutputErrors)
}
func ConsoleOutputName(name string) tasks.OutputName {
return tasks.Output("console:"+name, "application/json+ns-console-log")
}
func TypedOutput(ctx context.Context, name string, cat idtypes.CatOutputType) io.Writer {
return typedOutput(ctx, false, name, cat)
}
func typedOutput(ctx context.Context, stderr bool, name string, cat idtypes.CatOutputType) io.Writer {
if cat == idtypes.CatOutputDebug && !DebugToConsole {
return tasks.Attachments(ctx).Output(tasks.Output(name, "text/plain"), cat)
}
stored := tasks.Attachments(ctx).Output(ConsoleOutputName(name), cat)
return consoleOutputFromCtx(ctx, stderr, name, cat, writeStored{stored})
}
type writeStored struct {
stored io.Writer
}
func (w writeStored) WriteLines(id idtypes.IdAndHash, name string, cat idtypes.CatOutputType, actionID tasks.ActionID, ts time.Time, lines [][]byte) {
strLines := make([]string, len(lines))
for k, line := range lines {
strLines[k] = string(line)
}
if m, err := protojson.Marshal(&storage.LogLine{
BufferId: id.ID,
BufferName: name,
ActionCategory: string(cat),
ActionId: actionID.String(),
Line: strLines,
Timestamp: timestamppb.New(ts),
}); err == nil {
_, _ = w.stored.Write(append(m, []byte("\n")...))
} else {
_, _ = w.stored.Write([]byte(`{"failure":"serialization failure"}\n`))
}
}
func consoleOutputFromCtx(ctx context.Context, stderr bool, name string, cat idtypes.CatOutputType, extra ...writesLines) io.Writer {
unwrapped := UnwrapSink(tasks.SinkFrom(ctx))
if t, ok := unwrapped.(writesLines); ok {
actionID := tasks.Attachments(ctx).ActionID()
id := actionID.String()
if actionID == "" {
id = ids.NewRandomBase32ID(8)
}
if len(id) > 6 {
id = id[:6]
}
buf := &consoleBuffer{
actual: append([]writesLines{t}, extra...),
name: name,
cat: cat,
id: idtypes.IdAndHashFrom(id),
}
if actionID != "" {
buf.actionID = actionID
}
return buf
}
// If there's no console sink in context, pass along the original Stdout or Stderr.
if name == idtypes.KnownStdout {
return os.Stdout
} else if name == idtypes.KnownStderr {
return os.Stderr
}
out := os.Stdout
if stderr {
out = os.Stderr
}
// IndentWriter is not thread safe.
return sync.SyncWriter(text.NewIndentWriter(out, []byte(name+": ")))
}
// ConsoleOutput returns a writer, whose output will be managed by the specified ConsoleSink.
func ConsoleOutput(console writesLines, name string) io.Writer {
return &consoleBuffer{actual: []writesLines{console}, name: name}
}
func WriteJSON(w io.Writer, message string, data interface{}) {
fmt.Fprint(w, message, " ")
enc := json.NewEncoder(w)
if err := enc.Encode(data); err != nil {
fmt.Fprintf(w, "<failed to serialize: %v>", err)
}
}
func MakeConsoleName(logid string, key string, suffix string) string {
if key != "" {
if len(key) > 7 {
key = key[:7]
}
key = key + " "
}
if len(logid) > 32 {
logid = "..." + logid[len(logid)-29:]
}
return fmt.Sprintf("%s%s%s", key, logid, suffix)
}