Connect shared configuration to CLI and server startup
This commit is contained in:
@@ -23,7 +23,7 @@ func newApp(identity commandkit.Identity) (*commandkit.App, error) {
|
||||
definitions := promptSuite()
|
||||
declarations := []commandkit.Declaration{
|
||||
commandkit.NewCommand(commandkit.CommandSpec[serveInput]{Name: "serve", Summary: "Serve the HTTP API.", Flags: serveFlags(), Run: serveHTTP}),
|
||||
configurationCommand(),
|
||||
commandkit.WithInvocationFeature(configurationCommand(), bootstrapFeature()),
|
||||
commandkit.Completion("scriptorium"),
|
||||
}
|
||||
declarations = append(declarations, runDeclarations()...)
|
||||
|
||||
43
internal/adapter/cli/bootstrap.go
Normal file
43
internal/adapter/cli/bootstrap.go
Normal file
@@ -0,0 +1,43 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
|
||||
"go.maximumdirect.net/ckconfig"
|
||||
"go.maximumdirect.net/commandkit"
|
||||
"go.maximumdirect.net/configkit"
|
||||
)
|
||||
|
||||
type bootstrapSinkKey struct{}
|
||||
type bootstrapSink func(*configkit.SecretsReport, error)
|
||||
|
||||
func bootstrapFeature() commandkit.InvocationFeature {
|
||||
return commandkit.NewInvocationFeature(commandkit.InvocationFeatureSpec[struct{}]{Start: func(inv commandkit.Invocation, _ struct{}) (context.Context, func() commandkit.Report) {
|
||||
sink := bootstrapSink(func(report *configkit.SecretsReport, err error) {
|
||||
var failure *configkit.SecretsError
|
||||
if errors.As(err, &failure) && failure != nil {
|
||||
diagnostics, explanation := ckconfig.AdaptDiagnostics("Secrets bootstrap:\n", nil, failure.Diagnostics())
|
||||
queueDiagnostics(inv.Reporter(), diagnostics)
|
||||
for _, detail := range explanation.Details {
|
||||
_ = inv.Reporter().AtEnd().Warn("", detail)
|
||||
}
|
||||
}
|
||||
if report == nil || len(report.Entries()) == 0 {
|
||||
return
|
||||
}
|
||||
write := func(w io.Writer) error { _, err := report.WriteTo(w); return err }
|
||||
failed := false
|
||||
for _, entry := range report.Entries() {
|
||||
failed = failed || entry.Status == configkit.SecretFileFailed || entry.Status == configkit.SecretFileNotApplied
|
||||
}
|
||||
if failed {
|
||||
_ = inv.Reporter().AtEnd().Warn("", write)
|
||||
} else {
|
||||
_ = inv.Reporter().AtEnd().Info("", write)
|
||||
}
|
||||
})
|
||||
return context.WithValue(inv.Context, bootstrapSinkKey{}, sink), nil
|
||||
}})
|
||||
}
|
||||
119
internal/adapter/cli/bootstrap_test.go
Normal file
119
internal/adapter/cli/bootstrap_test.go
Normal file
@@ -0,0 +1,119 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"go.maximumdirect.net/commandkit"
|
||||
)
|
||||
|
||||
func TestRunUsesConfiguredSecretsWithoutExposingValue(t *testing.T) {
|
||||
const name = "SCRIPTORIUM_TEST_RUN_CREDENTIAL"
|
||||
t.Setenv(name, "")
|
||||
root := t.TempDir()
|
||||
if err := os.Mkdir(filepath.Join(root, "secrets"), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(root, "secrets", name), []byte("synthetic-secret"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Authorization") != "Bearer synthetic-secret" {
|
||||
t.Errorf("credential not forwarded")
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
fmt.Fprint(w, `{"choices":[{"message":{"content":"artifact"}}]}`)
|
||||
}))
|
||||
defer provider.Close()
|
||||
path := filepath.Join(root, "app.yml")
|
||||
body := fmt.Sprintf("config: {secrets_dir: secrets, secrets_overwrite: true}\npromptkit:\n profiles:\n - id: local\n endpoint: %q\n model: controlled\n api_key_env: %s\n prompts:\n - id: selected\n default_profile: local\n messages:\n - {role: user, content: test}\n output: {format: text, validation_mode: none}\n", provider.URL+"/v1", name)
|
||||
if err := os.WriteFile(path, []byte(body), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out, diagnostics bytes.Buffer
|
||||
result := Execute(context.Background(), commandkit.Identity{Name: "scriptorium"}, []string{"run", "selected", "--config=" + path, "--verbose"}, &out, &diagnostics)
|
||||
if result.Status != 0 || out.String() != "artifact" || !strings.Contains(diagnostics.String(), name) || strings.Contains(out.String()+diagnostics.String(), "synthetic-secret") {
|
||||
t.Fatalf("outcome=%+v stdout=%q stderr=%q", result, out.String(), diagnostics.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestServerBootstrapsBeforeListening(t *testing.T) {
|
||||
const name = "SCRIPTORIUM_TEST_SERVER_CREDENTIAL"
|
||||
t.Setenv(name, "")
|
||||
root := t.TempDir()
|
||||
if err := os.Mkdir(filepath.Join(root, "secrets"), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
secret := filepath.Join(root, "secrets", name)
|
||||
if err := os.WriteFile(secret, []byte("initial"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := filepath.Join(root, "app.yml")
|
||||
if err := os.WriteFile(path, []byte("config: {secrets_dir: secrets, secrets_overwrite: true}\n"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ready := make(chan string, 1)
|
||||
listen := func(ctx context.Context, network, addr string) (net.Listener, error) {
|
||||
listener, err := (&net.ListenConfig{}).Listen(ctx, network, addr)
|
||||
if err == nil {
|
||||
ready <- listener.Addr().String()
|
||||
}
|
||||
return listener, err
|
||||
}
|
||||
cmd := commandkit.NewCommand(commandkit.CommandSpec[serveInput]{Name: "serve", Flags: serveFlags(), Run: func(inv commandkit.Invocation, input serveInput) commandkit.Outcome {
|
||||
return serveWithListener(inv, input, listen)
|
||||
}})
|
||||
app, err := commandkit.New(commandkit.Identity{Name: "scriptorium"}, commandkit.WithInvocationFeature(cmd, bootstrapFeature()))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
var out, diagnostics bytes.Buffer
|
||||
finished := make(chan commandkit.Outcome, 1)
|
||||
go func() {
|
||||
finished <- app.Execute(ctx, []string{"serve", "--config=" + path, "--addr=127.0.0.1:0", "--verbose"}, commandkit.Streams{Out: &out, Err: &diagnostics})
|
||||
}()
|
||||
var addr string
|
||||
select {
|
||||
case addr = <-ready:
|
||||
case result := <-finished:
|
||||
t.Fatalf("startup: %+v", result)
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("listen timeout")
|
||||
}
|
||||
if os.Getenv(name) != "initial" {
|
||||
t.Fatal("bootstrap did not precede listening")
|
||||
}
|
||||
if err := os.WriteFile(secret, []byte("replacement"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
response, err := (&http.Client{Timeout: 5 * time.Second}).Get("http://" + addr + "/not-found")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body, err := io.ReadAll(response.Body)
|
||||
response.Body.Close()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cancel()
|
||||
select {
|
||||
case <-finished:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("shutdown timeout")
|
||||
}
|
||||
if os.Getenv(name) != "initial" || strings.Contains(string(body)+out.String()+diagnostics.String(), "initial") || !strings.Contains(diagnostics.String(), name) {
|
||||
t.Fatalf("bootstrap repeated or leaked: response=%q stdout=%q stderr=%q", body, out.String(), diagnostics.String())
|
||||
}
|
||||
}
|
||||
@@ -8,15 +8,8 @@ import (
|
||||
"go.maximumdirect.net/promptkit"
|
||||
)
|
||||
|
||||
func newEngine(settings appconfig.AppSettings, options ...promptkit.Option) (*promptkit.Engine, error) {
|
||||
var main *configkit.Input
|
||||
if settings.PromptKitConfiguration != "" {
|
||||
main = &configkit.Input{Source: configkit.File(settings.PromptKitConfiguration), Imports: true}
|
||||
}
|
||||
engine, err := promptkit.NewEngine(promptkit.Config{
|
||||
Sources: promptkit.ConfigurationSources{Main: main},
|
||||
SchemaDir: settings.SchemaDir, TransientRetries: settings.TransientRetries,
|
||||
}, options...)
|
||||
func newEngine(result *configkit.Result[appconfig.Document], options ...promptkit.Option) (*promptkit.Engine, error) {
|
||||
engine, err := promptkit.NewFromConfig(result, promptkit.RuntimeConfig{TransientRetries: result.Config.TransientRetries}, options...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("engine initialization from application configuration: %w", err)
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"go.maximumdirect.net/ckconfig"
|
||||
"go.maximumdirect.net/ckprompt"
|
||||
"go.maximumdirect.net/commandkit"
|
||||
"go.maximumdirect.net/configkit"
|
||||
"go.maximumdirect.net/promptkit"
|
||||
)
|
||||
|
||||
@@ -73,30 +74,32 @@ func requestFromRunInput(input runInput) promptkit.RunRequest {
|
||||
}
|
||||
|
||||
func runPrompt(invocation commandkit.Invocation, input runInput) commandkit.Outcome {
|
||||
state := &acquisitionState{}
|
||||
engine, err := loadEngine(invocation.Context, input.Selection, applicationInput{}, state)
|
||||
applicationFailed := errors.Is(err, errApplicationAcquisition)
|
||||
acquired, err := attachApplicationEvidence(commandkit.Acquired[*promptkit.Engine]{Value: engine}, err, state, 0, false)
|
||||
queueDiagnostics(invocation.Reporter(), acquired.Diagnostics)
|
||||
if err != nil {
|
||||
if !applicationFailed {
|
||||
return frameworkFailure(invocation.Reporter(), err, acquired.Explanation)
|
||||
}
|
||||
return requestFailure(err, acquired.Explanation)
|
||||
result, err := loadApplication(invocation.Context, input.Selection, applicationInput{}, struct{}{})
|
||||
var sources []configkit.SourceInfo
|
||||
var records []configkit.Diagnostic
|
||||
if result != nil {
|
||||
sources, records = result.Sources(), result.Diagnostics()
|
||||
}
|
||||
inspection, err := engine.InspectConfiguration()
|
||||
if err != nil {
|
||||
return requestFailure(err, acquired.Explanation)
|
||||
var native *configkit.LoadError
|
||||
if errors.As(err, &native) && native != nil {
|
||||
sources, records = native.Sources(), native.Diagnostics()
|
||||
}
|
||||
diagnostics, explanation := ckconfig.AdaptDiagnostics("PromptKit configuration:\n", inspection.Sources(), inspection.Diagnostics())
|
||||
diagnostics, explanation := ckconfig.AdaptDiagnostics("Application configuration:\n", sources, records)
|
||||
queueDiagnostics(invocation.Reporter(), diagnostics)
|
||||
if err != nil {
|
||||
return requestFailure(err, explanation)
|
||||
}
|
||||
engine, err := newEngine(result)
|
||||
if err != nil {
|
||||
return requestFailure(err, explanation)
|
||||
}
|
||||
engine, err = engine.WithNamespaces(input.Namespaces)
|
||||
if err != nil {
|
||||
return requestFailure(err, explanation)
|
||||
}
|
||||
result, err := engine.Run(invocation.Context, requestFromRunInput(input))
|
||||
runResult, err := engine.Run(invocation.Context, requestFromRunInput(input))
|
||||
if err != nil {
|
||||
return requestFailure(err, explanation)
|
||||
}
|
||||
return deliverRunResult(invocation, input, result)
|
||||
return deliverRunResult(invocation, input, runResult)
|
||||
}
|
||||
|
||||
@@ -75,10 +75,13 @@ func loadApplication(ctx context.Context, selection ckconfig.Selection, input ap
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result, err := appconfig.Load(appconfig.LoadOptions{
|
||||
result, report, err := appconfig.Load(appconfig.LoadOptions{
|
||||
Path: selection.Config.Value, Explicit: selection.Config.Set, Overlay: selection.Overlay.Value,
|
||||
Overrides: append(namedApplicationOverrides(input), selection.Overrides...),
|
||||
})
|
||||
if sink, ok := ctx.Value(bootstrapSinkKey{}).(bootstrapSink); ok {
|
||||
sink(report, err)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -107,6 +110,5 @@ func loadEngine(ctx context.Context, selection ckconfig.Selection, input applica
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
settings := appconfig.Settings(result.Config)
|
||||
return newEngine(settings)
|
||||
return newEngine(result)
|
||||
}
|
||||
|
||||
@@ -8,7 +8,6 @@ import (
|
||||
"net/http"
|
||||
|
||||
httpadapter "gitea.maximumdirect.net/eric/scriptorium/internal/adapter/http"
|
||||
appconfig "gitea.maximumdirect.net/eric/scriptorium/internal/config"
|
||||
"gitea.maximumdirect.net/eric/scriptorium/internal/defaults"
|
||||
"go.maximumdirect.net/ckconfig"
|
||||
"go.maximumdirect.net/commandkit"
|
||||
@@ -36,27 +35,21 @@ func serveWithListener(invocation commandkit.Invocation, input serveInput, liste
|
||||
if err != nil {
|
||||
return requestFailure(err, explanation)
|
||||
}
|
||||
settings := appconfig.Settings(result.Config)
|
||||
settings := result.Config.Server
|
||||
reader, err := httpadapter.NewRestrictedArtifactReader(settings.ArtifactRoot, settings.MaxArtifactBytes)
|
||||
if err != nil {
|
||||
return commandkit.Failure("Could not initialize the HTTP artifact reader.").WithCause(err)
|
||||
}
|
||||
engine, err := newEngine(settings, promptkit.WithArtifactReader(reader))
|
||||
engine, err := newEngine(result, promptkit.WithArtifactReader(reader))
|
||||
if err != nil {
|
||||
return frameworkFailure(invocation.Reporter(), err, explanation)
|
||||
}
|
||||
inspection, err := engine.InspectConfiguration()
|
||||
if err != nil {
|
||||
return requestFailure(err, explanation)
|
||||
}
|
||||
diagnostics, explanation = ckconfig.AdaptDiagnostics("PromptKit configuration:\n", inspection.Sources(), inspection.Diagnostics())
|
||||
queueDiagnostics(invocation.Reporter(), diagnostics)
|
||||
server := &http.Server{
|
||||
Addr: settings.ServerAddr,
|
||||
Addr: settings.Addr,
|
||||
Handler: httpadapter.NewHandlerWithOptions(engine, httpadapter.HandlerOptions{MaxRequestBytes: settings.MaxRequestBytes, MaxResponseBytes: settings.MaxResponseBytes}),
|
||||
ReadHeaderTimeout: defaults.HTTPReadHeaderTimeoutDefault,
|
||||
}
|
||||
listener, err := listen(invocation.Context, "tcp", settings.ServerAddr)
|
||||
listener, err := listen(invocation.Context, "tcp", settings.Addr)
|
||||
if err != nil {
|
||||
return commandkit.Failure("Could not listen for HTTP requests.").WithCause(err)
|
||||
}
|
||||
|
||||
@@ -44,16 +44,3 @@ func Load(options LoadOptions) (*configkit.Result[Document], *configkit.SecretsR
|
||||
}
|
||||
return result, report, nil
|
||||
}
|
||||
|
||||
// Settings converts a validated document without another merge or normalization.
|
||||
func Settings(document Document) AppSettings {
|
||||
settings := AppSettings{
|
||||
ServerAddr: document.Server.Addr,
|
||||
ArtifactRoot: document.Server.ArtifactRoot,
|
||||
MaxRequestBytes: document.Server.MaxRequestBytes,
|
||||
MaxArtifactBytes: document.Server.MaxArtifactBytes,
|
||||
MaxResponseBytes: document.Server.MaxResponseBytes,
|
||||
TransientRetries: document.TransientRetries,
|
||||
}
|
||||
return settings
|
||||
}
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
package config
|
||||
|
||||
// AppSettings holds the validated application values used by executable adapters.
|
||||
type AppSettings struct {
|
||||
PromptKitConfiguration string
|
||||
SchemaDir string
|
||||
ServerAddr string
|
||||
ArtifactRoot string
|
||||
MaxRequestBytes int64
|
||||
MaxArtifactBytes int64
|
||||
MaxResponseBytes int64
|
||||
TransientRetries *int
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import "time"
|
||||
|
||||
const (
|
||||
HTTPAddrDefault = ":8080"
|
||||
SchemaDirDefault = "."
|
||||
HTTPMaxRequestBytesDefault = 16 * 1024 * 1024
|
||||
HTTPMaxArtifactBytesDefault = 16 * 1024 * 1024
|
||||
HTTPMaxResponseBytesDefault = 16 * 1024 * 1024
|
||||
|
||||
Reference in New Issue
Block a user