blob: e95c020b2e9b465aab3f5aced2fd5ee2e9100d6d [file] [log] [blame]
Matteo Scandoloa4285862020-12-01 18:10:10 -08001/*
2Copyright 2014 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package versioned
18
19import (
20 "fmt"
21
22 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
23 "k8s.io/apimachinery/pkg/runtime"
24 "k8s.io/apimachinery/pkg/runtime/serializer/streaming"
25 "k8s.io/apimachinery/pkg/watch"
26)
27
28// Decoder implements the watch.Decoder interface for io.ReadClosers that
29// have contents which consist of a series of watchEvent objects encoded
30// with the given streaming decoder. The internal objects will be then
31// decoded by the embedded decoder.
32type Decoder struct {
33 decoder streaming.Decoder
34 embeddedDecoder runtime.Decoder
35}
36
37// NewDecoder creates an Decoder for the given writer and codec.
38func NewDecoder(decoder streaming.Decoder, embeddedDecoder runtime.Decoder) *Decoder {
39 return &Decoder{
40 decoder: decoder,
41 embeddedDecoder: embeddedDecoder,
42 }
43}
44
45// Decode blocks until it can return the next object in the reader. Returns an error
46// if the reader is closed or an object can't be decoded.
47func (d *Decoder) Decode() (watch.EventType, runtime.Object, error) {
48 var got metav1.WatchEvent
49 res, _, err := d.decoder.Decode(nil, &got)
50 if err != nil {
51 return "", nil, err
52 }
53 if res != &got {
54 return "", nil, fmt.Errorf("unable to decode to metav1.Event")
55 }
56 switch got.Type {
57 case string(watch.Added), string(watch.Modified), string(watch.Deleted), string(watch.Error), string(watch.Bookmark):
58 default:
59 return "", nil, fmt.Errorf("got invalid watch event type: %v", got.Type)
60 }
61
62 obj, err := runtime.Decode(d.embeddedDecoder, got.Object.Raw)
63 if err != nil {
64 return "", nil, fmt.Errorf("unable to decode watch event: %v", err)
65 }
66 return watch.EventType(got.Type), obj, nil
67}
68
69// Close closes the underlying r.
70func (d *Decoder) Close() {
71 d.decoder.Close()
72}