github.com/authzed/spicedb@v1.32.1-0.20240520085336-ebda56537386/internal/middleware/readonly/readonly.go (about)

     1  package readonly
     2  
     3  import (
     4  	"context"
     5  
     6  	middleware "github.com/grpc-ecosystem/go-grpc-middleware/v2"
     7  	"google.golang.org/grpc"
     8  
     9  	"github.com/authzed/spicedb/internal/datastore/proxy"
    10  	datastoremw "github.com/authzed/spicedb/internal/middleware/datastore"
    11  )
    12  
    13  // UnaryServerInterceptor returns a new unary server interceptor that sets the datastore to readonly
    14  func UnaryServerInterceptor() grpc.UnaryServerInterceptor {
    15  	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
    16  		if err := datastoremw.SetInContext(ctx, proxy.NewReadonlyDatastore(datastoremw.MustFromContext(ctx))); err != nil {
    17  			return nil, err
    18  		}
    19  
    20  		return handler(ctx, req)
    21  	}
    22  }
    23  
    24  // StreamServerInterceptor returns a new stream server interceptor  that sets the datastore to readonly
    25  func StreamServerInterceptor() grpc.StreamServerInterceptor {
    26  	return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
    27  		wrapped := middleware.WrapServerStream(stream)
    28  		if err := datastoremw.SetInContext(wrapped.WrappedContext, proxy.NewReadonlyDatastore(datastoremw.MustFromContext(stream.Context()))); err != nil {
    29  			return err
    30  		}
    31  		return handler(srv, wrapped)
    32  	}
    33  }