writer.go 4.11 KB
Newer Older
Jan Winkelmann's avatar
Jan Winkelmann committed
1 2 3
package cmds

import (
4
	"encoding/json"
Jan Winkelmann's avatar
Jan Winkelmann committed
5 6 7
	"fmt"
	"io"
	"reflect"
8
	"sync"
9

keks's avatar
keks committed
10
	"github.com/ipfs/go-ipfs-cmdkit"
Jan Winkelmann's avatar
Jan Winkelmann committed
11 12
)

Jan Winkelmann's avatar
Jan Winkelmann committed
13
func NewWriterResponseEmitter(w io.WriteCloser, req Request, enc func(Request) func(io.Writer) Encoder) *WriterResponseEmitter {
Jan Winkelmann's avatar
Jan Winkelmann committed
14
	re := &WriterResponseEmitter{
15 16
		w:   w,
		c:   w,
Jan Winkelmann's avatar
Jan Winkelmann committed
17
		req: req,
Jan Winkelmann's avatar
Jan Winkelmann committed
18
	}
Jan Winkelmann's avatar
Jan Winkelmann committed
19 20 21 22 23 24

	if enc != nil {
		re.enc = enc(req)(w)
	}

	return re
Jan Winkelmann's avatar
Jan Winkelmann committed
25 26 27
}

func NewReaderResponse(r io.Reader, encType EncodingType, req Request) Response {
28 29
	emitted := make(chan struct{})

Jan Winkelmann's avatar
Jan Winkelmann committed
30 31 32 33 34
	return &readerResponse{
		req:     req,
		r:       r,
		encType: encType,
		dec:     Decoders[encType](r),
35
		emitted: emitted,
Jan Winkelmann's avatar
Jan Winkelmann committed
36 37 38 39 40 41 42 43 44 45 46
	}
}

type readerResponse struct {
	r       io.Reader
	encType EncodingType
	dec     Decoder

	req Request

	length uint64
47
	err    *cmdkit.Error
Jan Winkelmann's avatar
Jan Winkelmann committed
48

49 50
	emitted chan struct{}
	once    sync.Once
Jan Winkelmann's avatar
Jan Winkelmann committed
51 52
}

Jan Winkelmann's avatar
Jan Winkelmann committed
53 54
func (r *readerResponse) Request() Request {
	return r.req
Jan Winkelmann's avatar
Jan Winkelmann committed
55 56
}

57
func (r *readerResponse) Error() *cmdkit.Error {
58 59
	<-r.emitted

Jan Winkelmann's avatar
Jan Winkelmann committed
60 61 62 63
	return r.err
}

func (r *readerResponse) Length() uint64 {
64 65
	<-r.emitted

Jan Winkelmann's avatar
Jan Winkelmann committed
66 67 68
	return r.length
}

69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
func (r *readerResponse) RawNext() (interface{}, error) {
	a := &Any{}
	a.Add(cmdkit.Error{})
	a.Add(r.req.Command().Type)

	err := r.dec.Decode(a)
	if err != nil {
		return nil, err
	}

	r.once.Do(func() { close(r.emitted) })

	v := a.Interface()
	return v, nil
}

Jan Winkelmann's avatar
Jan Winkelmann committed
85
func (r *readerResponse) Next() (interface{}, error) {
86
	a := &Any{}
87
	a.Add(cmdkit.Error{})
88
	a.Add(r.req.Command().Type)
Jan Winkelmann's avatar
Jan Winkelmann committed
89

90 91 92 93 94
	err := r.dec.Decode(a)
	if err != nil {
		return nil, err
	}

95 96
	r.once.Do(func() { close(r.emitted) })

97
	v := a.Interface()
98
	if err, ok := v.(cmdkit.Error); ok {
99
		v = &err
Jan Winkelmann's avatar
Jan Winkelmann committed
100
	}
101 102 103 104

	switch val := v.(type) {
	case *cmdkit.Error:
		r.err = val
Jan Winkelmann's avatar
Jan Winkelmann committed
105
		return nil, ErrRcvdError
106 107 108 109
	case Single:
		return val.Value, nil
	default:
		return v, nil
110
	}
Jan Winkelmann's avatar
Jan Winkelmann committed
111 112
}

113
type WriterResponseEmitter struct {
Jan Winkelmann's avatar
Jan Winkelmann committed
114
	// TODO maybe make those public?
115 116 117
	w   io.Writer
	c   io.Closer
	enc Encoder
Jan Winkelmann's avatar
Jan Winkelmann committed
118
	req Request
Jan Winkelmann's avatar
Jan Winkelmann committed
119 120

	length *uint64
121
	err    *cmdkit.Error
Jan Winkelmann's avatar
Jan Winkelmann committed
122 123 124 125

	emitted bool
}

Jan Winkelmann's avatar
Jan Winkelmann committed
126 127 128 129
func (re *WriterResponseEmitter) SetEncoder(mkEnc func(io.Writer) Encoder) {
	re.enc = mkEnc(re.w)
}

130 131
func (re *WriterResponseEmitter) SetError(v interface{}, errType cmdkit.ErrorType) {
	err := re.Emit(&cmdkit.Error{Message: fmt.Sprint(v), Code: errType})
132
	if err != nil {
133
		panic(err)
134
	}
Jan Winkelmann's avatar
Jan Winkelmann committed
135 136
}

137
func (re *WriterResponseEmitter) SetLength(length uint64) {
Jan Winkelmann's avatar
Jan Winkelmann committed
138 139 140 141 142 143 144
	if re.emitted {
		return
	}

	*re.length = length
}

145 146 147 148 149 150 151 152 153 154 155 156
func (re *WriterResponseEmitter) Close() error {
	return re.c.Close()
}

func (re *WriterResponseEmitter) Head() Head {
	return Head{
		Len: *re.length,
		Err: re.err,
	}
}

func (re *WriterResponseEmitter) Emit(v interface{}) error {
157 158 159
	if ch, ok := v.(chan interface{}); ok {
		v = (<-chan interface{})(ch)
	}
Jan Winkelmann's avatar
Jan Winkelmann committed
160

161 162 163 164 165 166 167 168
	if ch, isChan := v.(<-chan interface{}); isChan {
		for v = range ch {
			err := re.Emit(v)
			if err != nil {
				return err
			}
		}
		return nil
Jan Winkelmann's avatar
Jan Winkelmann committed
169 170
	}

171 172
	re.emitted = true

173 174 175 176
	if _, ok := v.(Single); ok {
		defer re.Close()
	}

177
	return re.enc.Encode(v)
Jan Winkelmann's avatar
Jan Winkelmann committed
178 179
}

180
type Any struct {
Jan Winkelmann's avatar
Jan Winkelmann committed
181 182
	types map[reflect.Type]bool
	order []reflect.Type
183 184 185 186 187 188 189 190 191 192

	v interface{}
}

func (a *Any) UnmarshalJSON(data []byte) error {
	var (
		iv  interface{}
		err error
	)

Jan Winkelmann's avatar
Jan Winkelmann committed
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
	for _, t := range a.order {
		v := reflect.New(t).Elem().Addr()

		isNil := func(v reflect.Value) (yup, ok bool) {
			ok = true
			defer func() {
				r := recover()
				if r != nil {
					ok = false
				}
			}()
			yup = v.IsNil()
			return
		}

		isZero := func(v reflect.Value, t reflect.Type) (yup, ok bool) {
			ok = true
			defer func() {
				r := recover()
				if r != nil {
					ok = false
				}
			}()
			yup = v.Elem().Interface() == reflect.Zero(t).Interface()
			return
		}
219 220

		err = json.Unmarshal(data, v.Interface())
Jan Winkelmann's avatar
Jan Winkelmann committed
221 222 223 224 225 226 227

		vIsNil, isNilOk := isNil(v)
		vIsZero, isZeroOk := isZero(v, t)

		nilish := (isNilOk && vIsNil) || (isZeroOk && vIsZero)
		if err == nil && !nilish {
			a.v = v.Interface()
228 229 230 231 232 233 234 235 236 237 238
			return nil
		}
	}

	err = json.Unmarshal(data, &iv)
	a.v = iv

	return err
}

func (a *Any) Add(v interface{}) {
Jan Winkelmann's avatar
Jan Winkelmann committed
239 240 241 242 243 244
	if v == nil {
		return
	}
	if a.types == nil {
		a.types = map[reflect.Type]bool{}
	}
245
	t := reflect.TypeOf(v)
Jan Winkelmann's avatar
Jan Winkelmann committed
246 247
	isPtr := t.Kind() == reflect.Ptr
	if isPtr || t.Kind() == reflect.Interface {
248 249 250
		t = t.Elem()
	}

Jan Winkelmann's avatar
Jan Winkelmann committed
251 252
	a.types[t] = isPtr
	a.order = append(a.order, t)
253 254 255 256 257
}

func (a *Any) Interface() interface{} {
	return a.v
}