<commit_before>// Copyright 2020 The LUCI Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package cas provides remote-apis-sdks client with luci integration.
package casclient

import (
	"context"
	"fmt"
	"runtime"
	"strings"

	"github.com/bazelbuild/remote-apis-sdks/go/pkg/cas"
	"github.com/bazelbuild/remote-apis-sdks/go/pkg/client"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"

	"go.chromium.org/luci/auth"
	"go.chromium.org/luci/common/errors"
	"go.chromium.org/luci/common/logging"
	"go.chromium.org/luci/hardcoded/chromeinfra"
)

// New returns luci auth configured Client for RBE-CAS.
func New(ctx context.Context, instance string, opts auth.Options, readOnly bool) (*cas.Client, error) {
	creds, err := perRPCCreds(ctx, instance, opts, readOnly)
	if err != nil {
		return nil, err
	}

	dialParams := client.DialParams{
		Service:            "remotebuildexecution.googleapis.com:443",
		TransportCredsOnly: true,
		DialOpts:           []grpc.DialOption{grpc.WithPerRPCCredentials(creds)},
	}
	conn, err := client.Dial(ctx, dialParams.Service, dialParams)
	if err != nil {
		return nil, errors.Annotate(err, "failed to dial RBE").Err()
	}

	cl, err := cas.NewClientWithConfig(ctx, conn, instance, DefaultConfig())
	if err != nil {
		return nil, errors.Annotate(err, "failed to create client").Err()
	}
	return cl, nil
}

// DefaultConfig returns default CAS client configuration.
func DefaultConfig() cas.ClientConfig {
	cfg := cas.DefaultClientConfig()
	cfg.CompressedBytestreamThreshold = 0 // compress always
	return cfg
}

func perRPCCreds(ctx context.Context, instance string, opts auth.Options, readOnly bool) (credentials.PerRPCCredentials, error) {
	project := strings.Split(instance, "/")[1]
	var role string
	if readOnly {
		role = "cas-read-only"
	} else {
		role = "cas-read-write"
	}

	// Construct auth.Options.
	opts.ActAsServiceAccount = fmt.Sprintf("<EMAIL>", role, project)
	opts.ActViaLUCIRealm = fmt.Sprintf("@internal:%s/%s", project, role)
	opts.Scopes = []string{"https://www.googleapis.com/auth/cloud-platform"}

	if strings.HasSuffix(project, "-dev") || strings.HasSuffix(project, "-staging") {
		// use dev token server for dev/staging projects.
		opts.TokenServerHost = chromeinfra.TokenServerDevHost
	}

	creds, err := auth.NewAuthenticator(ctx, auth.SilentLogin, opts).PerRPCCredentials()
	if err != nil {
		return nil, errors.Annotate(err, "failed to get PerRPCCredentials").Err()
	}
	return creds, nil
}

// NewLegacy returns luci auth configured legacy Client for RBE.
// In general, NewClient is preferred.<commit_msg>isolate: use higher concurrency for large file reads<commit_after>// Copyright 2020 The LUCI Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package cas provides remote-apis-sdks client with luci integration.
package casclient

import (
	"context"
	"fmt"
	"runtime"
	"strings"

	"github.com/bazelbuild/remote-apis-sdks/go/pkg/cas"
	"github.com/bazelbuild/remote-apis-sdks/go/pkg/client"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"

	"go.chromium.org/luci/auth"
	"go.chromium.org/luci/common/errors"
	"go.chromium.org/luci/common/logging"
	"go.chromium.org/luci/hardcoded/chromeinfra"
)

// New returns luci auth configured Client for RBE-CAS.
func New(ctx context.Context, instance string, opts auth.Options, readOnly bool) (*cas.Client, error) {
	creds, err := perRPCCreds(ctx, instance, opts, readOnly)
	if err != nil {
		return nil, err
	}

	dialParams := client.DialParams{
		Service:            "remotebuildexecution.googleapis.com:443",
		TransportCredsOnly: true,
		DialOpts:           []grpc.DialOption{grpc.WithPerRPCCredentials(creds)},
	}
	conn, err := client.Dial(ctx, dialParams.Service, dialParams)
	if err != nil {
		return nil, errors.Annotate(err, "failed to dial RBE").Err()
	}

	cl, err := cas.NewClientWithConfig(ctx, conn, instance, DefaultConfig())
	if err != nil {
		return nil, errors.Annotate(err, "failed to create client").Err()
	}
	return cl, nil
}

// DefaultConfig returns default CAS client configuration.
func DefaultConfig() cas.ClientConfig {
	cfg := cas.DefaultClientConfig()
	cfg.CompressedBytestreamThreshold = 0 // compress always
	cfg.FSLargeConcurrency = runtime.NumCPU()
	return cfg
}

func perRPCCreds(ctx context.Context, instance string, opts auth.Options, readOnly bool) (credentials.PerRPCCredentials, error) {
	project := strings.Split(instance, "/")[1]
	var role string
	if readOnly {
		role = "cas-read-only"
	} else {
		role = "cas-read-write"
	}

	// Construct auth.Options.
	opts.ActAsServiceAccount = fmt.Sprintf("%s@%s.iam.gserviceaccount.com", role, project)
	opts.ActViaLUCIRealm = fmt.Sprintf("@internal:%s/%s", project, role)
	opts.Scopes = []string{"https://www.googleapis.com/auth/cloud-platform"}

	if strings.HasSuffix(project, "-dev") || strings.HasSuffix(project, "-staging") {
		// use dev token server for dev/staging projects.
		opts.TokenServerHost = chromeinfra.TokenServerDevHost
	}

	creds, err := auth.NewAuthenticator(ctx, auth.SilentLogin, opts).PerRPCCredentials()
	if err != nil {
		return nil, errors.Annotate(err, "failed to get PerRPCCredentials").Err()
	}
	return creds, nil
}

// NewLegacy returns luci auth configured legacy Client for RBE.
// In general, NewClient is preferred.
{'fraction_non_alphanumeric': 0.12527751347922614, 'fraction_numerical': 0.004123057405645417, 'mean_word_length': 4.15699100572363, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 4, 'https://': 2, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2613281', 'n_tokens_mistral': 2109, 'n_tokens_neox': 2023, 'n_words': 566}