Files
lincodex/backend/integration_test/practice_runner_fixture_test.go

319 lines
10 KiB
Go

//go:build integration
package integration_test
import (
"crypto/sha256"
"crypto/tls"
"encoding/pem"
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
coderunner "lincodex/backend/internal/adapter/secondary/code_runner"
"lincodex/backend/internal/adapter/secondary/code_runner/api"
)
const (
practiceRunnerToken = "fixture-token-0123456789abcdef0123456789abcdef"
practiceRunnerRunKey = "fixture-run-key-0123456789abcdef0123456789abcdef"
// practiceRunnerTimeout is the request timeout of the client under test.
// It is short so that a stalled answer ends a try quickly.
practiceRunnerTimeout = 750 * time.Millisecond
// practiceRunnerStall outlasts practiceRunnerTimeout.
practiceRunnerStall = 10 * time.Second
// practiceRunnerPrefix is the path of a run in the runner protocol.
practiceRunnerPrefix = "/v1/runs/"
)
// Sources of the two programs that the fixture recognizes. Each reads two
// integers and prints their sum.
const (
practicePythonSum = "print(sum(map(int, input().split())))\n"
practiceGoSum = "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tvar a, b int\n\tfmt.Scan(&a, &b)\n\tfmt.Println(a + b)\n}\n"
)
// runnerCall is what the fixture saw on the wire.
type runnerCall struct {
Method string
Path string
Header http.Header
Body []byte
}
// fixtureRun is one run that the fixture holds.
type fixtureRun struct {
ID string
Request api.RunRequest
Body []byte
Result api.RunResult
fingerprint [sha256.Size]byte
}
// practiceRunnerFixture is a local stand-in for the code runner. It speaks
// the protocol of api/runner over TLS 1.3 like the production runner: a
// bearer token, PUT and GET of /v1/runs/{id}, a run held once per run ID, and
// 422 for the same ID with another payload. It does not run code: it
// recognizes the two sum programs of this test file and compares their
// output with the expected output of each test, so the output of a program
// follows its source and its input.
type practiceRunnerFixture struct {
server *httptest.Server
mu sync.Mutex
runs map[string]*fixtureRun
order []string
calls []runnerCall
// holding keeps every run running until it is turned off.
holding bool
// afterAccept is applied once to the next newly accepted run: "cut"
// drops the connection without an answer, "stall" delays the answer past
// the client timeout. In both cases the run exists on the runner.
afterAccept string
}
func newPracticeRunnerFixture(t *testing.T) *practiceRunnerFixture {
t.Helper()
fixture := &practiceRunnerFixture{runs: map[string]*fixtureRun{}}
fixture.server = httptest.NewUnstartedServer(http.HandlerFunc(fixture.serve))
fixture.server.TLS = &tls.Config{MinVersion: tls.VersionTLS13}
fixture.server.StartTLS()
t.Cleanup(fixture.server.Close)
return fixture
}
// client builds a new client of the runner, as a restarted process would.
func (fixture *practiceRunnerFixture) client(t *testing.T) *coderunner.Client {
t.Helper()
client, err := coderunner.NewClient(coderunner.Settings{
BaseURL: fixture.server.URL, Token: practiceRunnerToken, RunKey: practiceRunnerRunKey,
CAPEM: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: fixture.server.Certificate().Raw}),
RequestTimeout: practiceRunnerTimeout,
})
if err != nil {
t.Fatalf("coderunner.NewClient() error = %v", err)
}
return client
}
// stop shuts the runner down; later connections are refused.
func (fixture *practiceRunnerFixture) stop() { fixture.server.Close() }
func (fixture *practiceRunnerFixture) hold(holding bool) {
fixture.mu.Lock()
defer fixture.mu.Unlock()
fixture.holding = holding
}
func (fixture *practiceRunnerFixture) failNextAccept(how string) {
fixture.mu.Lock()
defer fixture.mu.Unlock()
fixture.afterAccept = how
}
func (fixture *practiceRunnerFixture) runCount() int {
fixture.mu.Lock()
defer fixture.mu.Unlock()
return len(fixture.order)
}
// runIDsSince returns the run IDs that the fixture accepted after it held
// the first count runs.
func (fixture *practiceRunnerFixture) runIDsSince(count int) []string {
fixture.mu.Lock()
defer fixture.mu.Unlock()
return append([]string(nil), fixture.order[count:]...)
}
func (fixture *practiceRunnerFixture) run(id string) (fixtureRun, bool) {
fixture.mu.Lock()
defer fixture.mu.Unlock()
run, found := fixture.runs[id]
if !found {
return fixtureRun{}, false
}
return *run, true
}
// callsFor returns the requests that named the run.
func (fixture *practiceRunnerFixture) callsFor(id string) []runnerCall {
fixture.mu.Lock()
defer fixture.mu.Unlock()
var calls []runnerCall
for _, call := range fixture.calls {
if call.Path == practiceRunnerPrefix+id {
calls = append(calls, call)
}
}
return calls
}
func (fixture *practiceRunnerFixture) serve(writer http.ResponseWriter, request *http.Request) {
body, _ := io.ReadAll(request.Body)
fixture.mu.Lock()
fixture.calls = append(fixture.calls, runnerCall{
Method: request.Method, Path: request.URL.Path, Header: request.Header.Clone(), Body: body,
})
fixture.mu.Unlock()
if request.Header.Get("Authorization") != "Bearer "+practiceRunnerToken {
writeRunnerProblem(writer, http.StatusUnauthorized, api.ProblemCodeUnauthenticated)
return
}
id := strings.TrimPrefix(request.URL.Path, practiceRunnerPrefix)
switch request.Method {
case http.MethodPut:
fixture.put(writer, request, id, body)
case http.MethodGet:
fixture.get(writer, id)
default:
writeRunnerProblem(writer, http.StatusMethodNotAllowed, api.ProblemCodeMethodNotAllowed)
}
}
func (fixture *practiceRunnerFixture) put(writer http.ResponseWriter, request *http.Request, id string, body []byte) {
var payload api.RunRequest
if err := payload.UnmarshalJSON(body); err != nil {
writeRunnerProblem(writer, http.StatusBadRequest, api.ProblemCodeValidationFailed)
return
}
runID, err := uuid.Parse(id)
if err != nil {
writeRunnerProblem(writer, http.StatusBadRequest, api.ProblemCodeValidationFailed)
return
}
fingerprint := sha256.Sum256(body)
fixture.mu.Lock()
if existing, found := fixture.runs[id]; found {
defer fixture.mu.Unlock()
if existing.fingerprint != fingerprint {
writeRunnerProblem(writer, http.StatusUnprocessableEntity, api.ProblemCodeIdempotencyKeyReused)
return
}
writeRunnerStatus(writer, http.StatusOK, fixture.statusLocked(existing))
return
}
fixture.runs[id] = &fixtureRun{
ID: id, Request: payload, Body: body, Result: evaluateFixtureRun(payload), fingerprint: fingerprint,
}
fixture.order = append(fixture.order, id)
action := fixture.afterAccept
fixture.afterAccept = ""
fixture.mu.Unlock()
switch action {
case "cut":
// The run is accepted and the connection ends without an answer.
panic(http.ErrAbortHandler)
case "stall":
select {
case <-time.After(practiceRunnerStall):
case <-request.Context().Done():
return
}
}
writeRunnerStatus(writer, http.StatusAccepted, api.RunStatus{RunID: runID, State: api.RunStateRunning})
}
func (fixture *practiceRunnerFixture) get(writer http.ResponseWriter, id string) {
fixture.mu.Lock()
defer fixture.mu.Unlock()
run, found := fixture.runs[id]
if !found {
writeRunnerProblem(writer, http.StatusNotFound, api.ProblemCodeNotFound)
return
}
writeRunnerStatus(writer, http.StatusOK, fixture.statusLocked(run))
}
func (fixture *practiceRunnerFixture) statusLocked(run *fixtureRun) api.RunStatus {
status := api.RunStatus{RunID: uuid.MustParse(run.ID), State: api.RunStateRunning}
if !fixture.holding {
status.State = api.RunStateFinished
status.Result = api.NewOptRunResult(run.Result)
}
return status
}
// evaluateFixtureRun produces the result of a run: every test of a group runs
// until the first one that fails, and a failed public test carries the output
// of the program as its diagnostic, which the practice API shows.
func evaluateFixtureRun(request api.RunRequest) api.RunResult {
result := api.RunResult{Outcome: api.RunOutcomeAccepted, DurationMs: 25}
for _, group := range request.Groups {
groupResult := api.GroupResult{
ID: group.ID, Visibility: group.Visibility, Outcome: api.RunOutcomeAccepted, TotalTests: int32(len(group.Tests)),
}
for _, test := range group.Tests {
output := fixtureProgramOutput(request.Source, test.Input)
testResult := api.TestResult{ID: test.ID, Outcome: api.RunOutcomeAccepted, TimeMs: 3, WallTimeMs: 4, MemoryKB: 1024}
if output != strings.TrimSpace(test.ExpectedOutput) {
testResult.Outcome = api.RunOutcomeWrongAnswer
if group.Visibility == api.TestVisibilityPublic {
testResult.Diagnostic = api.NewOptString("got " + output)
}
groupResult.Outcome = api.RunOutcomeWrongAnswer
groupResult.Tests = append(groupResult.Tests, testResult)
break
}
groupResult.PassedTests++
groupResult.Tests = append(groupResult.Tests, testResult)
}
if result.Outcome == api.RunOutcomeAccepted {
result.Outcome = groupResult.Outcome
}
result.Groups = append(result.Groups, groupResult)
}
return result
}
// fixtureProgramOutput is the output of the sum programs for an input: the
// sum of its integer words. Another program prints nothing.
func fixtureProgramOutput(source, input string) string {
if !strings.Contains(source, "sum(map(int, input().split()))") && !strings.Contains(source, "fmt.Println(a + b)") {
return ""
}
total := 0
for _, word := range strings.Fields(input) {
if value, err := strconv.Atoi(word); err == nil {
total += value
}
}
return strconv.Itoa(total)
}
func writeRunnerStatus(writer http.ResponseWriter, code int, status api.RunStatus) {
// The generated types encode themselves; json.Marshal cannot encode an
// unset optional field.
body, err := status.MarshalJSON()
if err != nil {
panic(err)
}
writeRunnerJSON(writer, code, "application/json", body)
}
func writeRunnerProblem(writer http.ResponseWriter, code int, problem api.ProblemCode) {
body, err := (&api.Problem{
Type: "urn:lincodex:problem:" + string(problem), Title: "Problem", Status: int32(code), Code: problem,
}).MarshalJSON()
if err != nil {
panic(err)
}
writeRunnerJSON(writer, code, "application/problem+json", body)
}
func writeRunnerJSON(writer http.ResponseWriter, code int, contentType string, body []byte) {
writer.Header().Set("Content-Type", contentType)
writer.Header().Set("Content-Length", strconv.Itoa(len(body)))
writer.WriteHeader(code)
_, _ = writer.Write(body)
}