openfaas / golang-http-template

Golang templates for OpenFaaS using HTTP extensions
https://www.openfaas.com/
MIT License
106 stars 57 forks source link

Read timeout values from env-vars #23

Closed alexellis closed 5 years ago

alexellis commented 5 years ago

Signed-off-by: Alex Ellis alexellis2@gmail.com

Description

Fixes: #20

Closes: #22

How Has This Been Tested?

Tested by creating Golang-http and Golang-middleware functions with a 5s wait inside. These were then deployed to Docker Swarm and invoked. Previously they choked at 3s.

package function

import (
    "fmt"
    "io/ioutil"
    "net/http"
    "time"
)

func Handle(w http.ResponseWriter, r *http.Request) {
    var input []byte

    if r.Body != nil {
        defer r.Body.Close()

        body, _ := ioutil.ReadAll(r.Body)

        input = body
    }

    time.Sleep(5 * time.Second)
    w.WriteHeader(http.StatusOK)
    w.Write([]byte(fmt.Sprintf("Nice sleep, input was: %s", string(input))))
}
package function

import (
    "fmt"
    "github.com/openfaas-incubator/go-function-sdk"
    "net/http"

    "time"
)

// Handle a function invocation
func Handle(req handler.Request) (handler.Response, error) {
    var err error

    message := fmt.Sprintf("Nice sleep, input was: %s", string(req.Body))

    time.Sleep(5 * time.Second)

    return handler.Response{
        Body:       []byte(message),
        StatusCode: http.StatusOK,
    }, err
}
space-mini:golang-http-template alex$ time curl -d test http://127.0.0.1:8080/function
/golang-middleware1
Nice sleep, input was: test
real    0m5.023s
user    0m0.005s
sys     0m0.004s
space-mini:golang-http-template alex$ 

space-mini:golang-http-template alex$ time curl -d "test" http://127.0.0.1:8080/functi
on/golang-http1
Nice sleep, input was: test
real    0m5.021s
user    0m0.004s
sys     0m0.004s
space-mini:golang-http-template alex$ 

Setting the timeout value to 2s then gave a premature failure, as expected:

version: 1.0
provider:
  name: openfaas
  gateway: http://127.0.0.1:8080
functions:
  golang-http1:
    lang: golang-http
    handler: ./golang-http1
    image: golang-http1:latest1
    environment:
      read_timeout: 2s
      write_timeout: 2s

The fail-back behaviour for legacy users / templates / docs of using an integer vs. Golang duration for timeouts is also now working as expected:

version: 1.0
provider:
  name: openfaas
  gateway: http://127.0.0.1:8080
functions:
  golang-http1:
    lang: golang-http
    handler: ./golang-http1
    image: golang-http1:latest1
    environment:
      read_timeout: 10
      write_timeout: 10

Result:

space-mini:golang-http-template alex$ time curl -d "test" http://127.0.0.1:8080/functi
on/golang-http1
Nice sleep, input was: test
real    0m5.021s
user    0m0.004s
sys     0m0.004s

How are existing users impacted? What migration steps/scripts do we need?

It should be a no-harm change. The default (10s) is larger than the previous 3s.

Checklist:

I have: