//go:build !debug
// +build !debug

package main

import (
	"context"

	"github.com/alibaba/sentinel-golang/api"
	"github.com/alibaba/sentinel-golang/ext/datasource"
	"gitlab.galaxy-immi.com/Backend-group/go-com/nacos"
	"gitlab.galaxy-immi.com/Backend-group/go-com/third/log"
	"gitlab.galaxy-immi.com/Backend-group/go-com/third/sentinel"
	"gitlab.galaxy-immi.com/Backend-group/go-com/yaml"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

func init() {
	conf := yaml.GetConf()

	var err = api.InitDefault()
	if err != nil {
		panic(err)
	}
	flowHandler := datasource.NewFlowRulesHandler(datasource.FlowRuleJsonArrayParser)
	circuitBreakerHandler := datasource.NewCircuitBreakerRulesHandler(datasource.CircuitBreakerRuleJsonArrayParser)
	hotspotHandler := datasource.NewHotSpotParamRulesHandler(datasource.HotSpotParamRuleJsonArrayParser)
	isolationHandler := datasource.NewIsolationRulesHandler(datasource.IsolationRuleJsonArrayParser)
	systemHandler := datasource.NewSystemRulesHandler(datasource.SystemRuleJsonArrayParser)

	nds, _ := sentinel.NewNacosDataSource(
		nacos.ConfigClient,
		conf.Nacos.Group,
		conf.Nacos.SentinelId,
		flowHandler,
		circuitBreakerHandler,
		hotspotHandler,
		isolationHandler,
		systemHandler,
	)
	err = nds.Initialize()
	if err != nil {
		panic(err)
	}
}

// sentinelEntry Sentinel处理
func sentinelEntry(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler)(
    resp any, err error) {
	entry, block := api.Entry(info.FullMethod)
	if block != nil {
		err = status.Error(codes.Unavailable, "服务器忙碌中")
		return
	}
	defer entry.Exit()

	resp, err = log.ServerInterceptor(ctx, req, info, handler)
	return
}
