dubbo.apache.org/dubbo-go/v3@v3.1.1/filter/seata/filter.go (about)

     1  /*
     2   * Licensed to the Apache Software Foundation (ASF) under one or more
     3   * contributor license agreements.  See the NOTICE file distributed with
     4   * this work for additional information regarding copyright ownership.
     5   * The ASF licenses this file to You under the Apache License, Version 2.0
     6   * (the "License"); you may not use this file except in compliance with
     7   * the License.  You may obtain a copy of the License at
     8   *
     9   *     http://www.apache.org/licenses/LICENSE-2.0
    10   *
    11   * Unless required by applicable law or agreed to in writing, software
    12   * distributed under the License is distributed on an "AS IS" BASIS,
    13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14   * See the License for the specific language governing permissions and
    15   * limitations under the License.
    16   */
    17  
    18  // Package seata provides a filter when use seata-golang, use this filter to transfer xid.
    19  package seata
    20  
    21  import (
    22  	"context"
    23  	"strings"
    24  	"sync"
    25  )
    26  
    27  import (
    28  	"github.com/dubbogo/gost/log/logger"
    29  )
    30  
    31  import (
    32  	"dubbo.apache.org/dubbo-go/v3/common/constant"
    33  	"dubbo.apache.org/dubbo-go/v3/common/extension"
    34  	"dubbo.apache.org/dubbo-go/v3/filter"
    35  	"dubbo.apache.org/dubbo-go/v3/protocol"
    36  )
    37  
    38  const (
    39  	SEATA_XID = constant.DubboCtxKey("SEATA_XID")
    40  )
    41  
    42  var (
    43  	once  sync.Once
    44  	seata *seataFilter
    45  )
    46  
    47  func init() {
    48  	extension.SetFilter(constant.SeataFilterKey, newSeataFilter)
    49  }
    50  
    51  type seataFilter struct{}
    52  
    53  func newSeataFilter() filter.Filter {
    54  	if seata == nil {
    55  		once.Do(func() {
    56  			seata = &seataFilter{}
    57  		})
    58  	}
    59  	return seata
    60  }
    61  
    62  // Invoke Get Xid by attachment key `SEATA_XID`. When use Seata, transfer xid by attachments
    63  func (f *seataFilter) Invoke(ctx context.Context, invoker protocol.Invoker, invocation protocol.Invocation) protocol.Result {
    64  	xid := invocation.GetAttachmentWithDefaultValue(string(SEATA_XID), "")
    65  	if len(strings.TrimSpace(xid)) > 0 {
    66  		logger.Debugf("Method: %v,Xid: %v", invocation.MethodName(), xid)
    67  		return invoker.Invoke(context.WithValue(ctx, SEATA_XID, xid), invocation)
    68  	}
    69  	return invoker.Invoke(ctx, invocation)
    70  }
    71  
    72  // OnResponse dummy process, returns the result directly
    73  func (f *seataFilter) OnResponse(ctx context.Context, result protocol.Result, invoker protocol.Invoker, invocation protocol.Invocation) protocol.Result {
    74  	return result
    75  }