github.com/authzed/spicedb@v1.32.1-0.20240520085336-ebda56537386/pkg/cmd/lsp.go (about)

     1  package cmd
     2  
     3  import (
     4  	"context"
     5  	"time"
     6  
     7  	"github.com/go-logr/zerologr"
     8  	"github.com/jzelinskie/cobrautil/v2"
     9  	"github.com/jzelinskie/cobrautil/v2/cobrazerolog"
    10  	"github.com/rs/zerolog"
    11  	"github.com/spf13/cobra"
    12  
    13  	"github.com/authzed/spicedb/internal/logging"
    14  	"github.com/authzed/spicedb/internal/lsp"
    15  	"github.com/authzed/spicedb/pkg/cmd/termination"
    16  	"github.com/authzed/spicedb/pkg/releases"
    17  )
    18  
    19  // LSPConfig is the configuration for the LSP command.
    20  type LSPConfig struct {
    21  	// Addr is the address to listen on to serve the language server protocol.
    22  	Addr string
    23  
    24  	Stdio bool
    25  }
    26  
    27  // Complete adapts the LSPConfig into a usable LSP server.
    28  func (c *LSPConfig) Complete(ctx context.Context) (*lsp.Server, error) {
    29  	return lsp.NewServer(), nil
    30  }
    31  
    32  func RegisterLSPFlags(cmd *cobra.Command, config *LSPConfig) error {
    33  	cmd.Flags().StringVar(&config.Addr, "addr", "-", "address to listen on to serve LSP")
    34  	cmd.Flags().BoolVar(&config.Stdio, "stdio", true, "enable stdio mode for LSP")
    35  	return nil
    36  }
    37  
    38  func NewLSPCommand(programName string, config *LSPConfig) *cobra.Command {
    39  	return &cobra.Command{
    40  		Use:   "lsp",
    41  		Short: "serve language server protocol",
    42  		PreRunE: cobrautil.CommandStack(
    43  			cobrautil.SyncViperDotEnvPreRunE(programName, "spicedb.env", zerologr.New(&logging.Logger)),
    44  			cobrazerolog.New(
    45  				cobrazerolog.WithTarget(func(logger zerolog.Logger) {
    46  					logging.SetGlobalLogger(logger)
    47  				}),
    48  			).RunE(),
    49  			releases.CheckAndLogRunE(),
    50  		),
    51  		RunE: termination.PublishError(func(cmd *cobra.Command, args []string) error {
    52  			srv, err := config.Complete(cmd.Context())
    53  			if err != nil {
    54  				return err
    55  			}
    56  
    57  			signalctx := SignalContextWithGracePeriod(
    58  				context.Background(),
    59  				time.Second*0, // No grace period
    60  			)
    61  
    62  			return srv.Run(signalctx, config.Addr, config.Stdio)
    63  		}),
    64  	}
    65  }