aboutsummaryrefslogtreecommitdiffhomepage
path: root/backend/taskqueue/processor.go
blob: 8dadfdf9d05affde24340b347f2e5e649cf908a0 (plain)
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
package taskqueue

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"net/http"
)

type processor struct{}

func newProcessor() processor {
	return processor{}
}

type testrunRequestData struct {
	Code        string `json:"code"`
	Stdin       string `json:"stdin"`
	MaxDuration int    `json:"max_duration_ms"`
}

type testrunResponseData struct {
	Status string `json:"status"`
	Stdout string `json:"stdout"`
	Stderr string `json:"stderr"`
}

func (p *processor) doProcessTaskRunTestcase(
	_ context.Context,
	payload *TaskPayloadRunTestcase,
) (*TaskResultRunTestcase, error) {
	reqData := testrunRequestData{
		Code:        payload.Code,
		Stdin:       payload.Stdin,
		MaxDuration: 5000,
	}
	reqJSON, err := json.Marshal(reqData)
	if err != nil {
		return nil, fmt.Errorf("json.Marshal failed: %v", err)
	}
	req, err := http.NewRequest("POST", "http://worker-"+payload.Language+":80/exec", bytes.NewBuffer(reqJSON))
	if err != nil {
		return nil, fmt.Errorf("http.NewRequest failed: %v", err)
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Accept", "application/json")

	client := &http.Client{}
	res, err := client.Do(req)
	if err != nil {
		return nil, fmt.Errorf("client.Do failed: %v", err)
	}
	defer res.Body.Close()

	resData := testrunResponseData{}
	if err := json.NewDecoder(res.Body).Decode(&resData); err != nil {
		return nil, fmt.Errorf("json.Decode failed: %v", err)
	}
	return &TaskResultRunTestcase{
		TaskPayload: payload,
		Status:      resData.Status,
		Stdout:      resData.Stdout,
		Stderr:      resData.Stderr,
	}, nil
}