Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

http: use the request context #163

Merged
merged 2 commits into from
May 13, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 0 additions & 4 deletions cli/run_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,6 @@ type env struct {
ch chan struct{}
}

func (e env) Context() context.Context {
return context.Background()
}

func TestRunWaits(t *testing.T) {
flag := make(chan struct{}, 1)

Expand Down
5 changes: 0 additions & 5 deletions examples/adder/remote/server/main.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package main

import (
"context"
nethttp "net/http"

"github.com/ipfs/go-ipfs-cmds/examples/adder"
Expand All @@ -11,10 +10,6 @@ import (

type env struct{}

func (env) Context() context.Context {
return context.TODO()
}

func main() {
h := http.NewHandler(env{}, adder.RootCmd, http.NewServerConfig())

Expand Down
8 changes: 2 additions & 6 deletions executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,8 @@ type Executor interface {
Execute(req *Request, re ResponseEmitter, env Environment) error
}

// Environment is the environment passed to commands. The only required method
// is Context.
type Environment interface {
// Context returns the environment's context.
Context() context.Context
}
// Environment is the environment passed to commands.
type Environment interface{}
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(doesn't break anything in either go-filecoin or go-ipfs)

Copy link
Contributor

@djdv djdv Apr 30, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should MakeEnvironment be removed/altered with this?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We still need the environment (we type assert it to something more useful).

Really, we should consider stashing everything we'd usually put in the environment in the context (which is, IMO, where it should go) but we can handle that later.


// MakeEnvironment takes a context and the request to construct the environment
// that is passed to the command's Run function.
Expand Down
4 changes: 0 additions & 4 deletions executor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,6 @@ type wc struct {

type env int

func (e *env) Context() context.Context {
return context.Background()
}

func TestExecutor(t *testing.T) {
env := env(42)
req, err := NewRequest(context.Background(), []string{"test"}, nil, nil, nil, root)
Expand Down
31 changes: 1 addition & 30 deletions http/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ package http

import (
"context"
"crypto/rand"
"encoding/base32"
"errors"
"net/http"
"runtime/debug"
Expand Down Expand Up @@ -97,12 +95,6 @@ func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
}()

ctx := h.env.Context()
if ctx == nil {
log.Error("no root context found, using background")
ctx = context.Background()
}

if !allowOrigin(r, h.cfg) || !allowReferer(r, h.cfg) {
w.WriteHeader(http.StatusForbidden)
w.Write([]byte("403 - Forbidden"))
Expand All @@ -128,7 +120,7 @@ func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
r.Body = bw
}

req, err := parseRequest(ctx, r, h.root)
req, err := parseRequest(r, h.root)
if err != nil {
if err == ErrNotFound {
w.WriteHeader(http.StatusNotFound)
Expand All @@ -152,18 +144,6 @@ func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
defer cancel()

req.Context = logging.ContextWithLoggable(req.Context, uuidLoggable())
if cn, ok := w.(http.CloseNotifier); ok {
clientGone := cn.CloseNotify()
go func() {
select {
case <-clientGone:
case <-req.Context.Done():
}
cancel()
}()
}

re, err := NewResponseEmitter(w, r.Method, req, withRequestBodyEOFChan(bodyEOFChan))
if err != nil {
w.WriteHeader(http.StatusBadRequest)
Expand All @@ -186,15 +166,6 @@ func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.root.Call(req, re, h.env)
}

func uuidLoggable() logging.Loggable {
ids := make([]byte, 16)
rand.Read(ids)

return logging.Metadata{
"requestId": base32.HexEncoding.EncodeToString(ids),
}
}

func sanitizedErrStr(err error) string {
s := err.Error()
s = strings.Split(s, "\n")[0]
Expand Down
7 changes: 0 additions & 7 deletions http/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package http

import (
"bytes"
"context"
"errors"
"fmt"
"io"
Expand All @@ -26,15 +25,10 @@ type VersionOutput struct {

type testEnv struct {
version, commit, repoVersion string
rootCtx context.Context
t *testing.T
wait chan struct{}
}

func (env testEnv) Context() context.Context {
return env.rootCtx
}

func getCommit(env cmds.Environment) (string, bool) {
tEnv, ok := env.(testEnv)
return tEnv.commit, ok
Expand Down Expand Up @@ -307,7 +301,6 @@ func getTestServer(t *testing.T, origins []string) (cmds.Environment, *httptest.
version: "0.1.2",
commit: "c0mm17", // yes, I know there's no 'm' in hex.
repoVersion: "4",
rootCtx: context.Background(),
t: t,
wait: make(chan struct{}),
}
Expand Down
16 changes: 14 additions & 2 deletions http/parse.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
package http

import (
"context"
"encoding/base32"
"fmt"
"io/ioutil"
"math/rand"
"mime"
"net/http"
"strconv"
Expand All @@ -12,10 +13,11 @@ import (
"github.com/ipfs/go-ipfs-cmds"

"github.com/ipfs/go-ipfs-files"
logging "github.com/ipfs/go-log"
)

// parseRequest parses the data in a http.Request and returns a command Request object
func parseRequest(ctx context.Context, r *http.Request, root *cmds.Command) (*cmds.Request, error) {
func parseRequest(r *http.Request, root *cmds.Command) (*cmds.Request, error) {
if r.URL.Path[0] == '/' {
r.URL.Path = r.URL.Path[1:]
}
Expand Down Expand Up @@ -134,6 +136,7 @@ func parseRequest(ctx context.Context, r *http.Request, root *cmds.Command) (*cm
return nil, fmt.Errorf("File argument '%s' is required", requiredFile)
}

ctx := logging.ContextWithLoggable(r.Context(), uuidLoggable())
req, err := cmds.NewRequest(ctx, pth, opts, args, f, root)
if err != nil {
return nil, err
Expand Down Expand Up @@ -229,3 +232,12 @@ func parseResponse(httpRes *http.Response, req *cmds.Request) (cmds.Response, er

return res, nil
}

func uuidLoggable() logging.Loggable {
ids := make([]byte, 16)
rand.Read(ids)

return logging.Metadata{
"requestId": base32.HexEncoding.EncodeToString(ids),
}
}
6 changes: 3 additions & 3 deletions http/parse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func TestParse(t *testing.T) {
if err != nil {
t.Fatal(err)
}
req, err := parseRequest(nil, r, root)
req, err := parseRequest(r, root)
if err != nil {
t.Fatal(err)
}
Expand All @@ -47,7 +47,7 @@ func TestParse(t *testing.T) {
if err != nil {
t.Fatal(err)
}
req, err = parseRequest(nil, r, root)
req, err = parseRequest(r, root)
if err != ErrNotFound {
t.Errorf("expected ErrNotFound, got: %v", err)
}
Expand Down Expand Up @@ -78,7 +78,7 @@ func (tc parseReqTestCase) test(t *testing.T) {
}
httpReq.URL.RawQuery = vs.Encode()

req, err := parseRequest(nil, httpReq, cmdRoot)
req, err := parseRequest(httpReq, cmdRoot)
if !errEq(err, tc.err) {
t.Fatalf("expected error to be %v, but got %v", tc.err, err)
}
Expand Down