gitee.com/ks-custle/core-gm@v0.0.0-20230922171213-b83bdd97b62c/go-control-plane/pkg/server/rest/v3/server.go (about)

     1  // Copyright 2020 Envoyproxy Authors
     2  //
     3  //   Licensed under the Apache License, Version 2.0 (the "License");
     4  //   you may not use this file except in compliance with the License.
     5  //   You may obtain a copy of the License at
     6  //
     7  //       http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  //   Unless required by applicable law or agreed to in writing, software
    10  //   distributed under the License is distributed on an "AS IS" BASIS,
    11  //   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  //   See the License for the specific language governing permissions and
    13  //   limitations under the License.
    14  
    15  // Package rest provides an implementation of REST-JSON part of XDS server
    16  package rest
    17  
    18  import (
    19  	"context"
    20  	"errors"
    21  	"gitee.com/ks-custle/core-gm/go-control-plane/pkg/cache/v3"
    22  
    23  	discovery "gitee.com/ks-custle/core-gm/go-control-plane/envoy/service/discovery/v3"
    24  )
    25  
    26  type Server interface {
    27  	Fetch(context.Context, *discovery.DiscoveryRequest) (*discovery.DiscoveryResponse, error)
    28  }
    29  
    30  type Callbacks interface {
    31  	// OnFetchRequest is called for each Fetch request. Returning an error will end processing of the
    32  	// request and respond with an error.
    33  	OnFetchRequest(context.Context, *discovery.DiscoveryRequest) error
    34  	// OnFetchResponse is called immediately prior to sending a response.
    35  	OnFetchResponse(*discovery.DiscoveryRequest, *discovery.DiscoveryResponse)
    36  }
    37  
    38  func NewServer(config cache.ConfigFetcher, callbacks Callbacks) Server {
    39  	return &server{cache: config, callbacks: callbacks}
    40  }
    41  
    42  type server struct {
    43  	cache     cache.ConfigFetcher
    44  	callbacks Callbacks
    45  }
    46  
    47  func (s *server) Fetch(ctx context.Context, req *discovery.DiscoveryRequest) (*discovery.DiscoveryResponse, error) {
    48  	if s.callbacks != nil {
    49  		if err := s.callbacks.OnFetchRequest(ctx, req); err != nil {
    50  			return nil, err
    51  		}
    52  	}
    53  	resp, err := s.cache.Fetch(ctx, req)
    54  	if err != nil {
    55  		return nil, err
    56  	}
    57  	if resp == nil {
    58  		return nil, errors.New("missing response")
    59  	}
    60  	out, err := resp.GetDiscoveryResponse()
    61  	if s.callbacks != nil {
    62  		s.callbacks.OnFetchResponse(req, out)
    63  	}
    64  	return out, err
    65  }