code
stringlengths
0
56.1M
repo_name
stringclasses
515 values
path
stringlengths
2
147
language
stringclasses
447 values
license
stringclasses
7 values
size
int64
0
56.8M
//go:build subtlecrypto // +build subtlecrypto /* Copyright 2023 The Dapr 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. */ //nolint:protogetter package universal import ( "context" "crypto/sha256" "encoding/hex" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/dapr/dapr/pkg/messages" runtimev1pb "github.com/dapr/dapr/pkg/proto/runtime/v1" "github.com/dapr/dapr/pkg/resiliency" "github.com/dapr/dapr/pkg/runtime/compstore" daprt "github.com/dapr/dapr/pkg/testing" ) var oneHundredTwentyEightBits = []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16} func TestSubtleGetKeyAlpha1(t *testing.T) { fakeCryptoProvider := &daprt.FakeSubtleCrypto{} compStore := compstore.New() compStore.AddCryptoProvider("myvault", fakeCryptoProvider) fakeAPI := &Universal{ logger: testLogger, resiliency: resiliency.New(nil), compStore: compStore, } t.Run("return key in PEM format", func(t *testing.T) { res, err := fakeAPI.SubtleGetKeyAlpha1(context.Background(), &runtimev1pb.SubtleGetKeyRequest{ ComponentName: "myvault", Name: "good-key", Format: runtimev1pb.SubtleGetKeyRequest_PEM, }) require.NoError(t, err) require.NotNil(t, res) assert.Equal(t, "good-key", res.Name) compareSHA256Hash(t, []byte(res.PublicKey), "d8e7975660f2a44223afddbe0d8fd05305758f69227494d23de4458b7a0e5b0b") }) t.Run("return key in JSON format", func(t *testing.T) { res, err := fakeAPI.SubtleGetKeyAlpha1(context.Background(), &runtimev1pb.SubtleGetKeyRequest{ ComponentName: "myvault", Name: "good-key", Format: runtimev1pb.SubtleGetKeyRequest_JSON, }) require.NoError(t, err) require.NotNil(t, res) assert.Equal(t, "good-key", res.Name) compareSHA256Hash(t, []byte(res.PublicKey), "2643402c63512dbc20b041c920b5828389a2ff1437f1bd7b406df95e693db2b4") }) t.Run("default to PEM format", func(t *testing.T) { res, err := fakeAPI.SubtleGetKeyAlpha1(context.Background(), &runtimev1pb.SubtleGetKeyRequest{ ComponentName: "myvault", Name: "good-key", }) require.NoError(t, err) require.NotNil(t, res) assert.Equal(t, "good-key", res.Name) compareSHA256Hash(t, []byte(res.PublicKey), "d8e7975660f2a44223afddbe0d8fd05305758f69227494d23de4458b7a0e5b0b") }) t.Run("key not found", func(t *testing.T) { res, err := fakeAPI.SubtleGetKeyAlpha1(context.Background(), &runtimev1pb.SubtleGetKeyRequest{ ComponentName: "myvault", Name: "not-found", }) require.NoError(t, err) require.NotNil(t, res) assert.Empty(t, res.Name) assert.Empty(t, res.PublicKey) }) t.Run("key has key ID", func(t *testing.T) { res, err := fakeAPI.SubtleGetKeyAlpha1(context.Background(), &runtimev1pb.SubtleGetKeyRequest{ ComponentName: "myvault", Name: "with-name", }) require.NoError(t, err) require.NotNil(t, res) assert.Equal(t, "my-name-is-giovanni-giorgio", res.Name) compareSHA256Hash(t, []byte(res.PublicKey), "d8e7975660f2a44223afddbe0d8fd05305758f69227494d23de4458b7a0e5b0b") }) t.Run("no provider configured", func(t *testing.T) { fakeAPI.compStore.DeleteCryptoProvider("myvault") defer func() { compStore.AddCryptoProvider("myvault", fakeCryptoProvider) }() _, err := fakeAPI.SubtleGetKeyAlpha1(context.Background(), &runtimev1pb.SubtleGetKeyRequest{}) require.Error(t, err) require.ErrorIs(t, err, messages.ErrCryptoProvidersNotConfigured) }) t.Run("provider not found", func(t *testing.T) { _, err := fakeAPI.SubtleGetKeyAlpha1(context.Background(), &runtimev1pb.SubtleGetKeyRequest{ ComponentName: "notfound", }) require.Error(t, err) require.ErrorIs(t, err, messages.ErrCryptoProviderNotFound) }) t.Run("invalid format", func(t *testing.T) { _, err := fakeAPI.SubtleGetKeyAlpha1(context.Background(), &runtimev1pb.SubtleGetKeyRequest{ ComponentName: "myvault", Format: runtimev1pb.SubtleGetKeyRequest_KeyFormat(-9000), }) require.Error(t, err) require.ErrorIs(t, err, messages.ErrBadRequest) require.ErrorContains(t, err, "invalid key format") }) t.Run("failed to get key", func(t *testing.T) { _, err := fakeAPI.SubtleGetKeyAlpha1(context.Background(), &runtimev1pb.SubtleGetKeyRequest{ ComponentName: "myvault", Name: "error-key", }) require.Error(t, err) require.ErrorIs(t, err, messages.ErrCryptoGetKey) require.ErrorContains(t, err, "error occurs with error-key") }) } func TestSubtleEncryptAlpha1(t *testing.T) { fakeCryptoProvider := &daprt.FakeSubtleCrypto{} compStore := compstore.New() compStore.AddCryptoProvider("myvault", fakeCryptoProvider) fakeAPI := &Universal{ logger: testLogger, resiliency: resiliency.New(nil), compStore: compStore, } t.Run("encrypt message", func(t *testing.T) { res, err := fakeAPI.SubtleEncryptAlpha1(context.Background(), &runtimev1pb.SubtleEncryptRequest{ ComponentName: "myvault", Plaintext: []byte("hello world"), KeyName: "good-tag", }) require.NoError(t, err) require.NotNil(t, res) // Message isn't actually encrypted assert.Equal(t, "hello world", string(res.Ciphertext)) assert.Len(t, res.Tag, 16) }) t.Run("no provider configured", func(t *testing.T) { fakeAPI.compStore.DeleteCryptoProvider("myvault") defer func() { compStore.AddCryptoProvider("myvault", fakeCryptoProvider) }() _, err := fakeAPI.SubtleEncryptAlpha1(context.Background(), &runtimev1pb.SubtleEncryptRequest{}) require.Error(t, err) require.ErrorIs(t, err, messages.ErrCryptoProvidersNotConfigured) }) t.Run("provider not found", func(t *testing.T) { _, err := fakeAPI.SubtleEncryptAlpha1(context.Background(), &runtimev1pb.SubtleEncryptRequest{ ComponentName: "notfound", }) require.Error(t, err) require.ErrorIs(t, err, messages.ErrCryptoProviderNotFound) }) t.Run("failed to encrypt", func(t *testing.T) { _, err := fakeAPI.SubtleEncryptAlpha1(context.Background(), &runtimev1pb.SubtleEncryptRequest{ ComponentName: "myvault", KeyName: "error", }) require.Error(t, err) require.ErrorIs(t, err, messages.ErrCryptoOperation) // The actual error is not returned to the user for security reasons require.ErrorContains(t, err, "failed to encrypt") }) } func TestSubtleDecryptAlpha1(t *testing.T) { fakeCryptoProvider := &daprt.FakeSubtleCrypto{} compStore := compstore.New() compStore.AddCryptoProvider("myvault", fakeCryptoProvider) fakeAPI := &Universal{ logger: testLogger, resiliency: resiliency.New(nil), compStore: compStore, } t.Run("decrypt message", func(t *testing.T) { res, err := fakeAPI.SubtleDecryptAlpha1(context.Background(), &runtimev1pb.SubtleDecryptRequest{ ComponentName: "myvault", Ciphertext: []byte("hello world"), KeyName: "good", }) require.NoError(t, err) require.NotNil(t, res) // Message isn't actually encrypted assert.Equal(t, "hello world", string(res.Plaintext)) }) t.Run("no provider configured", func(t *testing.T) { fakeAPI.compStore.DeleteCryptoProvider("myvault") defer func() { compStore.AddCryptoProvider("myvault", fakeCryptoProvider) }() _, err := fakeAPI.SubtleDecryptAlpha1(context.Background(), &runtimev1pb.SubtleDecryptRequest{}) require.Error(t, err) require.ErrorIs(t, err, messages.ErrCryptoProvidersNotConfigured) }) t.Run("provider not found", func(t *testing.T) { _, err := fakeAPI.SubtleDecryptAlpha1(context.Background(), &runtimev1pb.SubtleDecryptRequest{ ComponentName: "notfound", }) require.Error(t, err) require.ErrorIs(t, err, messages.ErrCryptoProviderNotFound) }) t.Run("failed to decrypt", func(t *testing.T) { _, err := fakeAPI.SubtleDecryptAlpha1(context.Background(), &runtimev1pb.SubtleDecryptRequest{ ComponentName: "myvault", KeyName: "error", }) require.Error(t, err) require.ErrorIs(t, err, messages.ErrCryptoOperation) // The actual error is not returned to the user for security reasons require.ErrorContains(t, err, "failed to decrypt") }) } func TestSubtleWrapKeyAlpha1(t *testing.T) { fakeCryptoProvider := &daprt.FakeSubtleCrypto{} compStore := compstore.New() compStore.AddCryptoProvider("myvault", fakeCryptoProvider) fakeAPI := &Universal{ logger: testLogger, resiliency: resiliency.New(nil), compStore: compStore, } t.Run("wrap key", func(t *testing.T) { res, err := fakeAPI.SubtleWrapKeyAlpha1(context.Background(), &runtimev1pb.SubtleWrapKeyRequest{ ComponentName: "myvault", PlaintextKey: []byte("hello world"), KeyName: "good-tag", }) require.NoError(t, err) require.NotNil(t, res) assert.Equal(t, oneHundredTwentyEightBits, res.WrappedKey) assert.Len(t, res.Tag, 16) }) t.Run("no provider configured", func(t *testing.T) { fakeAPI.compStore.DeleteCryptoProvider("myvault") defer func() { compStore.AddCryptoProvider("myvault", fakeCryptoProvider) }() _, err := fakeAPI.SubtleWrapKeyAlpha1(context.Background(), &runtimev1pb.SubtleWrapKeyRequest{}) require.Error(t, err) require.ErrorIs(t, err, messages.ErrCryptoProvidersNotConfigured) }) t.Run("provider not found", func(t *testing.T) { _, err := fakeAPI.SubtleWrapKeyAlpha1(context.Background(), &runtimev1pb.SubtleWrapKeyRequest{ ComponentName: "notfound", }) require.Error(t, err) require.ErrorIs(t, err, messages.ErrCryptoProviderNotFound) }) t.Run("key is empty", func(t *testing.T) { _, err := fakeAPI.SubtleWrapKeyAlpha1(context.Background(), &runtimev1pb.SubtleWrapKeyRequest{ ComponentName: "myvault", KeyName: "error", }) require.Error(t, err) require.ErrorIs(t, err, messages.ErrCryptoOperation) require.ErrorContains(t, err, "key is empty") }) t.Run("failed to wrap key", func(t *testing.T) { _, err := fakeAPI.SubtleWrapKeyAlpha1(context.Background(), &runtimev1pb.SubtleWrapKeyRequest{ ComponentName: "myvault", KeyName: "error", PlaintextKey: oneHundredTwentyEightBits, }) require.Error(t, err) require.ErrorIs(t, err, messages.ErrCryptoOperation) // The actual error is not returned to the user for security reasons require.ErrorContains(t, err, "failed to wrap key") }) } func TestSubtleUnwrapKeyAlpha1(t *testing.T) { fakeCryptoProvider := &daprt.FakeSubtleCrypto{} compStore := compstore.New() compStore.AddCryptoProvider("myvault", fakeCryptoProvider) fakeAPI := &Universal{ logger: testLogger, resiliency: resiliency.New(nil), compStore: compStore, } t.Run("unwrap key", func(t *testing.T) { res, err := fakeAPI.SubtleUnwrapKeyAlpha1(context.Background(), &runtimev1pb.SubtleUnwrapKeyRequest{ ComponentName: "myvault", WrappedKey: []byte("hello world"), KeyName: "good", }) require.NoError(t, err) require.NotNil(t, res) // Message isn't actually encrypted assert.Equal(t, oneHundredTwentyEightBits, res.PlaintextKey) }) t.Run("no provider configured", func(t *testing.T) { fakeAPI.compStore.DeleteCryptoProvider("myvault") defer func() { compStore.AddCryptoProvider("myvault", fakeCryptoProvider) }() _, err := fakeAPI.SubtleUnwrapKeyAlpha1(context.Background(), &runtimev1pb.SubtleUnwrapKeyRequest{}) require.Error(t, err) require.ErrorIs(t, err, messages.ErrCryptoProvidersNotConfigured) }) t.Run("provider not found", func(t *testing.T) { _, err := fakeAPI.SubtleUnwrapKeyAlpha1(context.Background(), &runtimev1pb.SubtleUnwrapKeyRequest{ ComponentName: "notfound", }) require.Error(t, err) require.ErrorIs(t, err, messages.ErrCryptoProviderNotFound) }) t.Run("failed to unwrap key", func(t *testing.T) { _, err := fakeAPI.SubtleUnwrapKeyAlpha1(context.Background(), &runtimev1pb.SubtleUnwrapKeyRequest{ ComponentName: "myvault", KeyName: "error", WrappedKey: oneHundredTwentyEightBits, }) require.Error(t, err) require.ErrorIs(t, err, messages.ErrCryptoOperation) // The actual error is not returned to the user for security reasons require.ErrorContains(t, err, "failed to unwrap key") }) } func TestSubtleSignAlpha1(t *testing.T) { fakeCryptoProvider := &daprt.FakeSubtleCrypto{} compStore := compstore.New() compStore.AddCryptoProvider("myvault", fakeCryptoProvider) fakeAPI := &Universal{ logger: testLogger, resiliency: resiliency.New(nil), compStore: compStore, } t.Run("sign message", func(t *testing.T) { res, err := fakeAPI.SubtleSignAlpha1(context.Background(), &runtimev1pb.SubtleSignRequest{ ComponentName: "myvault", Digest: []byte("hello world"), KeyName: "good", }) require.NoError(t, err) require.NotNil(t, res) // Message isn't actually signed assert.Equal(t, oneHundredTwentyEightBits, res.Signature) }) t.Run("no provider configured", func(t *testing.T) { fakeAPI.compStore.DeleteCryptoProvider("myvault") defer func() { compStore.AddCryptoProvider("myvault", fakeCryptoProvider) }() _, err := fakeAPI.SubtleSignAlpha1(context.Background(), &runtimev1pb.SubtleSignRequest{}) require.Error(t, err) require.ErrorIs(t, err, messages.ErrCryptoProvidersNotConfigured) }) t.Run("provider not found", func(t *testing.T) { _, err := fakeAPI.SubtleSignAlpha1(context.Background(), &runtimev1pb.SubtleSignRequest{ ComponentName: "notfound", }) require.Error(t, err) require.ErrorIs(t, err, messages.ErrCryptoProviderNotFound) }) t.Run("failed to sign", func(t *testing.T) { _, err := fakeAPI.SubtleSignAlpha1(context.Background(), &runtimev1pb.SubtleSignRequest{ ComponentName: "myvault", KeyName: "error", Digest: oneHundredTwentyEightBits, }) require.Error(t, err) require.ErrorIs(t, err, messages.ErrCryptoOperation) // The actual error is not returned to the user for security reasons require.ErrorContains(t, err, "failed to sign") }) } func TestSubtleVerifyAlpha1(t *testing.T) { fakeCryptoProvider := &daprt.FakeSubtleCrypto{} compStore := compstore.New() compStore.AddCryptoProvider("myvault", fakeCryptoProvider) fakeAPI := &Universal{ logger: testLogger, resiliency: resiliency.New(nil), compStore: compStore, } t.Run("signature is valid", func(t *testing.T) { res, err := fakeAPI.SubtleVerifyAlpha1(context.Background(), &runtimev1pb.SubtleVerifyRequest{ ComponentName: "myvault", Digest: oneHundredTwentyEightBits, Signature: oneHundredTwentyEightBits, KeyName: "good", }) require.NoError(t, err) require.NotNil(t, res) assert.True(t, res.Valid) }) t.Run("signature is invalid", func(t *testing.T) { res, err := fakeAPI.SubtleVerifyAlpha1(context.Background(), &runtimev1pb.SubtleVerifyRequest{ ComponentName: "myvault", Digest: oneHundredTwentyEightBits, Signature: oneHundredTwentyEightBits, KeyName: "bad", }) require.NoError(t, err) require.NotNil(t, res) assert.False(t, res.Valid) }) t.Run("no provider configured", func(t *testing.T) { fakeAPI.compStore.DeleteCryptoProvider("myvault") defer func() { compStore.AddCryptoProvider("myvault", fakeCryptoProvider) }() _, err := fakeAPI.SubtleVerifyAlpha1(context.Background(), &runtimev1pb.SubtleVerifyRequest{}) require.Error(t, err) require.ErrorIs(t, err, messages.ErrCryptoProvidersNotConfigured) }) t.Run("provider not found", func(t *testing.T) { _, err := fakeAPI.SubtleVerifyAlpha1(context.Background(), &runtimev1pb.SubtleVerifyRequest{ ComponentName: "notfound", }) require.Error(t, err) require.ErrorIs(t, err, messages.ErrCryptoProviderNotFound) }) t.Run("failed to verify", func(t *testing.T) { _, err := fakeAPI.SubtleVerifyAlpha1(context.Background(), &runtimev1pb.SubtleVerifyRequest{ ComponentName: "myvault", KeyName: "error", }) require.Error(t, err) require.ErrorIs(t, err, messages.ErrCryptoOperation) // The actual error is not returned to the user for security reasons require.ErrorContains(t, err, "failed to verify") }) } func compareSHA256Hash(t *testing.T, data []byte, expect string) { t.Helper() h := sha256.Sum256(data) actual := hex.EncodeToString(h[:]) if actual != expect { t.Errorf("expected data to have hash %s, but got %s", expect, actual) } }
mikeee/dapr
pkg/api/universal/subtlecrypto_subtlecrypto_test.go
GO
mit
16,674
/* Copyright 2022 The Dapr 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 universal contains the implementation of APIs that are shared between gRPC and HTTP servers. // On HTTP servers, they use protojson to convert data to/from JSON. package universal import ( "sync" "sync/atomic" "github.com/dapr/dapr/pkg/actors" "github.com/dapr/dapr/pkg/config" "github.com/dapr/dapr/pkg/resiliency" "github.com/dapr/dapr/pkg/runtime/compstore" "github.com/dapr/dapr/pkg/runtime/wfengine" "github.com/dapr/kit/logger" ) type Options struct { AppID string Logger logger.Logger Resiliency resiliency.Provider Actors actors.ActorRuntime CompStore *compstore.ComponentStore ShutdownFn func() GetComponentsCapabilitiesFn func() map[string][]string ExtendedMetadata map[string]string AppConnectionConfig config.AppConnectionConfig GlobalConfig *config.Configuration WorkflowEngine *wfengine.WorkflowEngine } // Universal contains the implementation of gRPC APIs that are also used by the HTTP server. type Universal struct { appID string logger logger.Logger resiliency resiliency.Provider actors actors.ActorRuntime compStore *compstore.ComponentStore shutdownFn func() getComponentsCapabilitiesFn func() map[string][]string extendedMetadata map[string]string appConnectionConfig config.AppConnectionConfig globalConfig *config.Configuration workflowEngine *wfengine.WorkflowEngine extendedMetadataLock sync.RWMutex actorsLock sync.RWMutex actorsReady atomic.Bool actorsReadyCh chan struct{} } func New(opts Options) *Universal { return &Universal{ appID: opts.AppID, logger: opts.Logger, resiliency: opts.Resiliency, actors: opts.Actors, compStore: opts.CompStore, shutdownFn: opts.ShutdownFn, getComponentsCapabilitiesFn: opts.GetComponentsCapabilitiesFn, extendedMetadata: opts.ExtendedMetadata, appConnectionConfig: opts.AppConnectionConfig, globalConfig: opts.GlobalConfig, workflowEngine: opts.WorkflowEngine, actorsReadyCh: make(chan struct{}), } } func (a *Universal) AppID() string { return a.appID } func (a *Universal) Resiliency() resiliency.Provider { return a.resiliency } func (a *Universal) Actors() actors.ActorRuntime { a.actorsLock.RLock() defer a.actorsLock.RUnlock() return a.actors } func (a *Universal) SetActorRuntime(actor actors.ActorRuntime) { a.actorsLock.Lock() defer a.actorsLock.Unlock() a.actors = actor } func (a *Universal) CompStore() *compstore.ComponentStore { return a.compStore } func (a *Universal) AppConnectionConfig() config.AppConnectionConfig { return a.appConnectionConfig }
mikeee/dapr
pkg/api/universal/universal.go
GO
mit
3,615
/* Copyright 2023 The Dapr 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 universal import ( "github.com/dapr/dapr/pkg/apis/resiliency/v1alpha1" "github.com/dapr/kit/logger" "github.com/dapr/kit/ptr" ) var testLogger = logger.NewLogger("testlogger") var testResiliency = &v1alpha1.Resiliency{ Spec: v1alpha1.ResiliencySpec{ Policies: v1alpha1.Policies{ Retries: map[string]v1alpha1.Retry{ "singleRetry": { MaxRetries: ptr.Of(1), MaxInterval: "100ms", Policy: "constant", Duration: "10ms", }, "tenRetries": { MaxRetries: ptr.Of(10), MaxInterval: "100ms", Policy: "constant", Duration: "10ms", }, }, Timeouts: map[string]string{ "fast": "100ms", }, CircuitBreakers: map[string]v1alpha1.CircuitBreaker{ "simpleCB": { MaxRequests: 1, Timeout: "1s", Trip: "consecutiveFailures > 4", }, }, }, Targets: v1alpha1.Targets{ Components: map[string]v1alpha1.ComponentPolicyNames{ "failSecret": { Outbound: v1alpha1.PolicyNames{ Retry: "singleRetry", Timeout: "fast", }, }, }, }, }, }
mikeee/dapr
pkg/api/universal/universal_test.go
GO
mit
1,651
/* Copyright 2023 The Dapr 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 universal import ( "context" "errors" "unicode" "github.com/google/uuid" "github.com/microsoft/durabletask-go/api" "google.golang.org/protobuf/types/known/emptypb" "google.golang.org/protobuf/types/known/timestamppb" "github.com/dapr/components-contrib/workflows" "github.com/dapr/dapr/pkg/messages" runtimev1pb "github.com/dapr/dapr/pkg/proto/runtime/v1" ) // GetWorkflowBeta1 is the API handler for getting workflow details func (a *Universal) GetWorkflowBeta1(ctx context.Context, in *runtimev1pb.GetWorkflowRequest) (*runtimev1pb.GetWorkflowResponse, error) { if err := a.validateInstanceID(in.GetInstanceId(), false /* isCreate */); err != nil { a.logger.Debug(err) return &runtimev1pb.GetWorkflowResponse{}, err } a.workflowEngine.WaitForWorkflowEngineReady(ctx) workflowComponent, err := a.getWorkflowComponent(in.GetWorkflowComponent()) if err != nil { a.logger.Debug(err) return &runtimev1pb.GetWorkflowResponse{}, err } req := workflows.GetRequest{ InstanceID: in.GetInstanceId(), } response, err := workflowComponent.Get(ctx, &req) if err != nil { if errors.Is(err, api.ErrInstanceNotFound) { err = messages.ErrWorkflowInstanceNotFound.WithFormat(in.GetInstanceId(), err) } else { err = messages.ErrWorkflowGetResponse.WithFormat(in.GetInstanceId(), err) } a.logger.Debug(err) return &runtimev1pb.GetWorkflowResponse{}, err } res := &runtimev1pb.GetWorkflowResponse{ InstanceId: response.Workflow.InstanceID, WorkflowName: response.Workflow.WorkflowName, CreatedAt: timestamppb.New(response.Workflow.CreatedAt), LastUpdatedAt: timestamppb.New(response.Workflow.LastUpdatedAt), RuntimeStatus: response.Workflow.RuntimeStatus, Properties: response.Workflow.Properties, } return res, nil } // StartWorkflowBeta1 is the API handler for starting a workflow func (a *Universal) StartWorkflowBeta1(ctx context.Context, in *runtimev1pb.StartWorkflowRequest) (*runtimev1pb.StartWorkflowResponse, error) { // The instance ID is optional. If not specified, we generate a random one. if in.GetInstanceId() == "" { randomID, err := uuid.NewRandom() if err != nil { return nil, err } in.InstanceId = randomID.String() } if err := a.validateInstanceID(in.GetInstanceId(), true /* isCreate */); err != nil { a.logger.Debug(err) return &runtimev1pb.StartWorkflowResponse{}, err } if in.GetWorkflowName() == "" { err := messages.ErrWorkflowNameMissing a.logger.Debug(err) return &runtimev1pb.StartWorkflowResponse{}, err } a.workflowEngine.WaitForWorkflowEngineReady(ctx) workflowComponent, err := a.getWorkflowComponent(in.GetWorkflowComponent()) if err != nil { a.logger.Debug(err) return &runtimev1pb.StartWorkflowResponse{}, err } req := workflows.StartRequest{ InstanceID: in.GetInstanceId(), Options: in.GetOptions(), WorkflowName: in.GetWorkflowName(), WorkflowInput: in.GetInput(), } resp, err := workflowComponent.Start(ctx, &req) if err != nil { err := messages.ErrStartWorkflow.WithFormat(in.GetWorkflowName(), err) a.logger.Debug(err) return &runtimev1pb.StartWorkflowResponse{}, err } ret := &runtimev1pb.StartWorkflowResponse{ InstanceId: resp.InstanceID, } return ret, nil } // TerminateWorkflowBeta1 is the API handler for terminating a workflow func (a *Universal) TerminateWorkflowBeta1(ctx context.Context, in *runtimev1pb.TerminateWorkflowRequest) (*emptypb.Empty, error) { emptyResponse := &emptypb.Empty{} if err := a.validateInstanceID(in.GetInstanceId(), false /* isCreate */); err != nil { a.logger.Debug(err) return emptyResponse, err } a.workflowEngine.WaitForWorkflowEngineReady(ctx) workflowComponent, err := a.getWorkflowComponent(in.GetWorkflowComponent()) if err != nil { a.logger.Debug(err) return emptyResponse, err } req := &workflows.TerminateRequest{ InstanceID: in.GetInstanceId(), Recursive: true, } if err := workflowComponent.Terminate(ctx, req); err != nil { if errors.Is(err, api.ErrInstanceNotFound) { err = messages.ErrWorkflowInstanceNotFound.WithFormat(in.GetInstanceId(), err) } else { err = messages.ErrTerminateWorkflow.WithFormat(in.GetInstanceId(), err) } a.logger.Debug(err) return emptyResponse, err } return emptyResponse, nil } // RaiseEventWorkflowBeta1 is the API handler for raising an event to a workflow func (a *Universal) RaiseEventWorkflowBeta1(ctx context.Context, in *runtimev1pb.RaiseEventWorkflowRequest) (*emptypb.Empty, error) { emptyResponse := &emptypb.Empty{} if err := a.validateInstanceID(in.GetInstanceId(), false /* isCreate */); err != nil { a.logger.Debug(err) return emptyResponse, err } if in.GetEventName() == "" { err := messages.ErrMissingWorkflowEventName a.logger.Debug(err) return emptyResponse, err } a.workflowEngine.WaitForWorkflowEngineReady(ctx) workflowComponent, err := a.getWorkflowComponent(in.GetWorkflowComponent()) if err != nil { a.logger.Debug(err) return emptyResponse, err } req := workflows.RaiseEventRequest{ InstanceID: in.GetInstanceId(), EventName: in.GetEventName(), EventData: in.GetEventData(), } err = workflowComponent.RaiseEvent(ctx, &req) if err != nil { err = messages.ErrRaiseEventWorkflow.WithFormat(in.GetInstanceId(), err) a.logger.Debug(err) return emptyResponse, err } return emptyResponse, nil } // PauseWorkflowBeta1 is the API handler for pausing a workflow func (a *Universal) PauseWorkflowBeta1(ctx context.Context, in *runtimev1pb.PauseWorkflowRequest) (*emptypb.Empty, error) { emptyResponse := &emptypb.Empty{} if err := a.validateInstanceID(in.GetInstanceId(), false /* isCreate */); err != nil { a.logger.Debug(err) return emptyResponse, err } a.workflowEngine.WaitForWorkflowEngineReady(ctx) workflowComponent, err := a.getWorkflowComponent(in.GetWorkflowComponent()) if err != nil { a.logger.Debug(err) return emptyResponse, err } req := &workflows.PauseRequest{ InstanceID: in.GetInstanceId(), } if err := workflowComponent.Pause(ctx, req); err != nil { err = messages.ErrPauseWorkflow.WithFormat(in.GetInstanceId(), err) a.logger.Debug(err) return emptyResponse, err } return emptyResponse, nil } // ResumeWorkflowBeta1 is the API handler for resuming a workflow func (a *Universal) ResumeWorkflowBeta1(ctx context.Context, in *runtimev1pb.ResumeWorkflowRequest) (*emptypb.Empty, error) { emptyResponse := &emptypb.Empty{} if err := a.validateInstanceID(in.GetInstanceId(), false /* isCreate */); err != nil { a.logger.Debug(err) return emptyResponse, err } a.workflowEngine.WaitForWorkflowEngineReady(ctx) workflowComponent, err := a.getWorkflowComponent(in.GetWorkflowComponent()) if err != nil { a.logger.Debug(err) return emptyResponse, err } req := &workflows.ResumeRequest{ InstanceID: in.GetInstanceId(), } if err := workflowComponent.Resume(ctx, req); err != nil { err = messages.ErrResumeWorkflow.WithFormat(in.GetInstanceId(), err) a.logger.Debug(err) return emptyResponse, err } return emptyResponse, nil } // PurgeWorkflowBeta1 is the API handler for purging a workflow func (a *Universal) PurgeWorkflowBeta1(ctx context.Context, in *runtimev1pb.PurgeWorkflowRequest) (*emptypb.Empty, error) { emptyResponse := &emptypb.Empty{} if err := a.validateInstanceID(in.GetInstanceId(), false /* isCreate */); err != nil { a.logger.Debug(err) return emptyResponse, err } a.workflowEngine.WaitForWorkflowEngineReady(ctx) workflowComponent, err := a.getWorkflowComponent(in.GetWorkflowComponent()) if err != nil { a.logger.Debug(err) return emptyResponse, err } req := workflows.PurgeRequest{ InstanceID: in.GetInstanceId(), Recursive: true, } err = workflowComponent.Purge(ctx, &req) if err != nil { if errors.Is(err, api.ErrInstanceNotFound) { err = messages.ErrWorkflowInstanceNotFound.WithFormat(in.GetInstanceId(), err) } else { err = messages.ErrPurgeWorkflow.WithFormat(in.GetInstanceId(), err) } a.logger.Debug(err) return emptyResponse, err } return emptyResponse, nil } // GetWorkflowAlpha1 is the API handler for getting workflow details func (a *Universal) GetWorkflowAlpha1(ctx context.Context, in *runtimev1pb.GetWorkflowRequest) (*runtimev1pb.GetWorkflowResponse, error) { return a.GetWorkflowBeta1(ctx, in) } // StartWorkflowAlpha1 is the API handler for starting a workflow func (a *Universal) StartWorkflowAlpha1(ctx context.Context, in *runtimev1pb.StartWorkflowRequest) (*runtimev1pb.StartWorkflowResponse, error) { return a.StartWorkflowBeta1(ctx, in) } // TerminateWorkflowAlpha1 is the API handler for terminating a workflow func (a *Universal) TerminateWorkflowAlpha1(ctx context.Context, in *runtimev1pb.TerminateWorkflowRequest) (*emptypb.Empty, error) { return a.TerminateWorkflowBeta1(ctx, in) } // RaiseEventWorkflowAlpha1 is the API handler for raising an event to a workflow func (a *Universal) RaiseEventWorkflowAlpha1(ctx context.Context, in *runtimev1pb.RaiseEventWorkflowRequest) (*emptypb.Empty, error) { return a.RaiseEventWorkflowBeta1(ctx, in) } // PauseWorkflowAlpha1 is the API handler for pausing a workflow func (a *Universal) PauseWorkflowAlpha1(ctx context.Context, in *runtimev1pb.PauseWorkflowRequest) (*emptypb.Empty, error) { return a.PauseWorkflowBeta1(ctx, in) } // ResumeWorkflowAlpha1 is the API handler for resuming a workflow func (a *Universal) ResumeWorkflowAlpha1(ctx context.Context, in *runtimev1pb.ResumeWorkflowRequest) (*emptypb.Empty, error) { return a.ResumeWorkflowBeta1(ctx, in) } // PurgeWorkflowAlpha1 is the API handler for purging a workflow func (a *Universal) PurgeWorkflowAlpha1(ctx context.Context, in *runtimev1pb.PurgeWorkflowRequest) (*emptypb.Empty, error) { return a.PurgeWorkflowBeta1(ctx, in) } func (a *Universal) validateInstanceID(instanceID string, isCreate bool) error { if instanceID == "" { return messages.ErrMissingOrEmptyInstance } if isCreate { // Limit the length of the instance ID to avoid potential conflicts with state stores that have restrictive key limits. const maxInstanceIDLength = 64 if len(instanceID) > maxInstanceIDLength { return messages.ErrInstanceIDTooLong.WithFormat(maxInstanceIDLength) } // Check to see if the instance ID contains invalid characters. Valid characters are letters, digits, dashes, and underscores. // See https://github.com/dapr/dapr/issues/6156 for more context on why we check this. for _, c := range instanceID { if !unicode.IsLetter(c) && c != '_' && c != '-' && !unicode.IsDigit(c) { return messages.ErrInvalidInstanceID.WithFormat(instanceID) } } } return nil } func (a *Universal) getWorkflowComponent(componentName string) (workflows.Workflow, error) { if componentName == "" { return nil, messages.ErrNoOrMissingWorkflowComponent } workflowComponent, ok := a.compStore.GetWorkflow(componentName) if !ok { err := messages.ErrWorkflowComponentDoesNotExist.WithFormat(componentName) a.logger.Debug(err) return nil, err } return workflowComponent, nil }
mikeee/dapr
pkg/api/universal/workflow.go
GO
mit
11,622
/* Copyright 2023 The Dapr 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 universal import ( "context" "testing" "github.com/stretchr/testify/require" "github.com/dapr/components-contrib/workflows" "github.com/dapr/dapr/pkg/config" "github.com/dapr/dapr/pkg/messages" runtimev1pb "github.com/dapr/dapr/pkg/proto/runtime/v1" "github.com/dapr/dapr/pkg/resiliency" "github.com/dapr/dapr/pkg/runtime/compstore" "github.com/dapr/dapr/pkg/runtime/wfengine" daprt "github.com/dapr/dapr/pkg/testing" "github.com/dapr/kit/logger" ) const ( fakeComponentName = "fakeWorkflowComponent" fakeInstanceID = "fake-instance-ID__123" ) func TestStartWorkflowBeta1API(t *testing.T) { fakeWorkflowName := "fakeWorkflow" fakeWorkflows := map[string]workflows.Workflow{ fakeComponentName: &daprt.MockWorkflow{}, } testCases := []struct { testName string workflowComponent string workflowName string instanceID string expectedError error }{ { testName: "No workflow component provided in start request", workflowComponent: "", workflowName: fakeWorkflowName, instanceID: fakeInstanceID, expectedError: messages.ErrNoOrMissingWorkflowComponent, }, { testName: "workflow component does not exist in start request", workflowComponent: "fakeWorkflowNotExist", workflowName: fakeWorkflowName, instanceID: fakeInstanceID, expectedError: messages.ErrWorkflowComponentDoesNotExist.WithFormat("fakeWorkflowNotExist"), }, { testName: "No workflow name provided in start request", workflowComponent: fakeComponentName, workflowName: "", instanceID: fakeInstanceID, expectedError: messages.ErrWorkflowNameMissing, }, { testName: "Invalid instance ID provided in start request", workflowComponent: fakeComponentName, workflowName: fakeWorkflowName, instanceID: "invalid#12", expectedError: messages.ErrInvalidInstanceID.WithFormat("invalid#12"), }, { testName: "Too long instance ID provided in start request", workflowComponent: fakeComponentName, workflowName: fakeWorkflowName, instanceID: "this_is_a_very_long_instance_id_that_is_longer_than_64_characters_and_therefore_should_not_be_allowed", expectedError: messages.ErrInstanceIDTooLong.WithFormat(64), }, { testName: "Start for this instance throws error", workflowComponent: fakeComponentName, workflowName: fakeWorkflowName, instanceID: daprt.ErrorInstanceID, expectedError: messages.ErrStartWorkflow.WithFormat(fakeWorkflowName, daprt.ErrFakeWorkflowComponentError), }, { testName: "No instance ID provided in start request", workflowComponent: fakeComponentName, workflowName: fakeWorkflowName, instanceID: "", }, { testName: "All is well in start request", workflowComponent: fakeComponentName, workflowName: fakeWorkflowName, instanceID: fakeInstanceID, }, } compStore := compstore.New() for name, wf := range fakeWorkflows { compStore.AddWorkflow(name, wf) } // Setup universal dapr API fakeAPI := &Universal{ logger: logger.NewLogger("test"), resiliency: resiliency.New(nil), compStore: compStore, actorsReadyCh: make(chan struct{}), workflowEngine: getWorkflowEngine(), } fakeAPI.SetActorsInitDone() for _, tt := range testCases { t.Run(tt.testName, func(t *testing.T) { req := &runtimev1pb.StartWorkflowRequest{ WorkflowComponent: tt.workflowComponent, InstanceId: tt.instanceID, WorkflowName: tt.workflowName, } _, err := fakeAPI.StartWorkflowBeta1(context.Background(), req) if tt.expectedError == nil { require.NoError(t, err) } else { require.ErrorIs(t, err, tt.expectedError) } }) } } func TestGetWorkflowBeta1API(t *testing.T) { fakeWorkflows := map[string]workflows.Workflow{ fakeComponentName: &daprt.MockWorkflow{}, } testCases := []struct { testName string workflowComponent string instanceID string expectedError error }{ { testName: "No workflow component provided in get request", workflowComponent: "", instanceID: fakeInstanceID, expectedError: messages.ErrNoOrMissingWorkflowComponent, }, { testName: "workflow component does not exist in get request", workflowComponent: "fakeWorkflowNotExist", instanceID: fakeInstanceID, expectedError: messages.ErrWorkflowComponentDoesNotExist.WithFormat("fakeWorkflowNotExist"), }, { testName: "No instance ID provided in get request", workflowComponent: fakeComponentName, instanceID: "", expectedError: messages.ErrMissingOrEmptyInstance, }, { testName: "Get for this instance throws error", workflowComponent: fakeComponentName, instanceID: daprt.ErrorInstanceID, expectedError: messages.ErrWorkflowGetResponse.WithFormat(daprt.ErrorInstanceID, daprt.ErrFakeWorkflowComponentError), }, { testName: "All is well in get request", workflowComponent: fakeComponentName, instanceID: fakeInstanceID, }, } compStore := compstore.New() for name, wf := range fakeWorkflows { compStore.AddWorkflow(name, wf) } // Setup universal dapr API fakeAPI := &Universal{ logger: logger.NewLogger("test"), resiliency: resiliency.New(nil), compStore: compStore, actorsReadyCh: make(chan struct{}), workflowEngine: getWorkflowEngine(), } fakeAPI.SetActorsInitDone() for _, tt := range testCases { t.Run(tt.testName, func(t *testing.T) { req := &runtimev1pb.GetWorkflowRequest{ WorkflowComponent: tt.workflowComponent, InstanceId: tt.instanceID, } _, err := fakeAPI.GetWorkflowBeta1(context.Background(), req) if tt.expectedError == nil { require.NoError(t, err) } else { require.ErrorIs(t, err, tt.expectedError) } }) } } func TestTerminateWorkflowBeta1API(t *testing.T) { fakeWorkflows := map[string]workflows.Workflow{ fakeComponentName: &daprt.MockWorkflow{}, } testCases := []struct { testName string workflowComponent string instanceID string expectedError error }{ { testName: "No workflow component provided in terminate request", workflowComponent: "", instanceID: fakeInstanceID, expectedError: messages.ErrNoOrMissingWorkflowComponent, }, { testName: "workflow component does not exist in terminate request", workflowComponent: "fakeWorkflowNotExist", instanceID: fakeInstanceID, expectedError: messages.ErrWorkflowComponentDoesNotExist.WithFormat("fakeWorkflowNotExist"), }, { testName: "No instance ID provided in terminate request", workflowComponent: fakeComponentName, instanceID: "", expectedError: messages.ErrMissingOrEmptyInstance, }, { testName: "Terminate for this instance throws error", workflowComponent: fakeComponentName, instanceID: daprt.ErrorInstanceID, expectedError: messages.ErrTerminateWorkflow.WithFormat(daprt.ErrorInstanceID, daprt.ErrFakeWorkflowComponentError), }, { testName: "All is well in terminate request", workflowComponent: fakeComponentName, instanceID: fakeInstanceID, }, } compStore := compstore.New() for name, wf := range fakeWorkflows { compStore.AddWorkflow(name, wf) } // Setup universal dapr API fakeAPI := &Universal{ logger: logger.NewLogger("test"), resiliency: resiliency.New(nil), compStore: compStore, actorsReadyCh: make(chan struct{}), workflowEngine: getWorkflowEngine(), } fakeAPI.SetActorsInitDone() for _, tt := range testCases { t.Run(tt.testName, func(t *testing.T) { req := &runtimev1pb.TerminateWorkflowRequest{ WorkflowComponent: tt.workflowComponent, InstanceId: tt.instanceID, } _, err := fakeAPI.TerminateWorkflowBeta1(context.Background(), req) if tt.expectedError == nil { require.NoError(t, err) } else { require.ErrorIs(t, err, tt.expectedError) } }) } } func TestRaiseEventWorkflowBeta1Api(t *testing.T) { fakeEventName := "fake_event_name" fakeWorkflows := map[string]workflows.Workflow{ fakeComponentName: &daprt.MockWorkflow{}, } testCases := []struct { testName string workflowComponent string instanceID string eventName string expectedError error }{ { testName: "No workflow component provided in raise event request", workflowComponent: "", instanceID: fakeInstanceID, eventName: fakeEventName, expectedError: messages.ErrNoOrMissingWorkflowComponent, }, { testName: "workflow component does not exist in raise event request", workflowComponent: "fakeWorkflowNotExist", instanceID: fakeInstanceID, eventName: fakeEventName, expectedError: messages.ErrWorkflowComponentDoesNotExist.WithFormat("fakeWorkflowNotExist"), }, { testName: "No instance ID provided in raise event request", workflowComponent: fakeComponentName, instanceID: "", eventName: fakeEventName, expectedError: messages.ErrMissingOrEmptyInstance, }, { testName: "No event name provided in raise event request", workflowComponent: fakeComponentName, instanceID: fakeInstanceID, eventName: "", expectedError: messages.ErrMissingWorkflowEventName, }, { testName: "Raise event for this instance throws error", workflowComponent: fakeComponentName, instanceID: daprt.ErrorInstanceID, eventName: fakeEventName, expectedError: messages.ErrRaiseEventWorkflow.WithFormat(daprt.ErrorInstanceID, daprt.ErrFakeWorkflowComponentError), }, { testName: "All is well in raise event request", workflowComponent: fakeComponentName, instanceID: fakeInstanceID, eventName: fakeEventName, }, } compStore := compstore.New() for name, wf := range fakeWorkflows { compStore.AddWorkflow(name, wf) } // Setup universal dapr API fakeAPI := &Universal{ logger: logger.NewLogger("test"), resiliency: resiliency.New(nil), compStore: compStore, actorsReadyCh: make(chan struct{}), workflowEngine: getWorkflowEngine(), } fakeAPI.SetActorsInitDone() for _, tt := range testCases { t.Run(tt.testName, func(t *testing.T) { req := &runtimev1pb.RaiseEventWorkflowRequest{ WorkflowComponent: tt.workflowComponent, InstanceId: tt.instanceID, EventName: tt.eventName, EventData: []byte("fake_input"), } _, err := fakeAPI.RaiseEventWorkflowBeta1(context.Background(), req) if tt.expectedError == nil { require.NoError(t, err) } else { require.ErrorIs(t, err, tt.expectedError) } }) } } func TestPauseWorkflowBeta1Api(t *testing.T) { fakeWorkflows := map[string]workflows.Workflow{ fakeComponentName: &daprt.MockWorkflow{}, } testCases := []struct { testName string workflowComponent string instanceID string expectedError error }{ { testName: "No workflow component provided in pause request", workflowComponent: "", instanceID: fakeInstanceID, expectedError: messages.ErrNoOrMissingWorkflowComponent, }, { testName: "workflow component does not exist in pause request", workflowComponent: "fakeWorkflowNotExist", instanceID: fakeInstanceID, expectedError: messages.ErrWorkflowComponentDoesNotExist.WithFormat("fakeWorkflowNotExist"), }, { testName: "No instance ID provided in pause request", workflowComponent: fakeComponentName, instanceID: "", expectedError: messages.ErrMissingOrEmptyInstance, }, { testName: "Pause for this instance throws error", workflowComponent: fakeComponentName, instanceID: daprt.ErrorInstanceID, expectedError: messages.ErrPauseWorkflow.WithFormat(daprt.ErrorInstanceID, daprt.ErrFakeWorkflowComponentError), }, { testName: "All is well in pause request", workflowComponent: fakeComponentName, instanceID: fakeInstanceID, }, } compStore := compstore.New() for name, wf := range fakeWorkflows { compStore.AddWorkflow(name, wf) } // Setup universal dapr API fakeAPI := &Universal{ logger: logger.NewLogger("test"), resiliency: resiliency.New(nil), compStore: compStore, actorsReadyCh: make(chan struct{}), workflowEngine: getWorkflowEngine(), } fakeAPI.SetActorsInitDone() for _, tt := range testCases { t.Run(tt.testName, func(t *testing.T) { req := &runtimev1pb.PauseWorkflowRequest{ WorkflowComponent: tt.workflowComponent, InstanceId: tt.instanceID, } _, err := fakeAPI.PauseWorkflowBeta1(context.Background(), req) if tt.expectedError == nil { require.NoError(t, err) } else { require.ErrorIs(t, err, tt.expectedError) } }) } } func TestResumeWorkflowBeta1Api(t *testing.T) { fakeWorkflows := map[string]workflows.Workflow{ fakeComponentName: &daprt.MockWorkflow{}, } testCases := []struct { testName string workflowComponent string instanceID string expectedError error }{ { testName: "No workflow component provided in resume request", workflowComponent: "", instanceID: fakeInstanceID, expectedError: messages.ErrNoOrMissingWorkflowComponent, }, { testName: "workflow component does not exist in resume request", workflowComponent: "fakeWorkflowNotExist", instanceID: fakeInstanceID, expectedError: messages.ErrWorkflowComponentDoesNotExist.WithFormat("fakeWorkflowNotExist"), }, { testName: "No instance ID provided in resume request", workflowComponent: fakeComponentName, instanceID: "", expectedError: messages.ErrMissingOrEmptyInstance, }, { testName: "Resume for this instance throws error", workflowComponent: fakeComponentName, instanceID: daprt.ErrorInstanceID, expectedError: messages.ErrResumeWorkflow.WithFormat(daprt.ErrorInstanceID, daprt.ErrFakeWorkflowComponentError), }, { testName: "All is well in resume request", workflowComponent: fakeComponentName, instanceID: fakeInstanceID, }, } compStore := compstore.New() for name, wf := range fakeWorkflows { compStore.AddWorkflow(name, wf) } // Setup universal dapr API fakeAPI := &Universal{ logger: logger.NewLogger("test"), resiliency: resiliency.New(nil), compStore: compStore, actorsReadyCh: make(chan struct{}), workflowEngine: getWorkflowEngine(), } fakeAPI.SetActorsInitDone() for _, tt := range testCases { t.Run(tt.testName, func(t *testing.T) { req := &runtimev1pb.ResumeWorkflowRequest{ WorkflowComponent: tt.workflowComponent, InstanceId: tt.instanceID, } _, err := fakeAPI.ResumeWorkflowBeta1(context.Background(), req) if tt.expectedError == nil { require.NoError(t, err) } else { require.ErrorIs(t, err, tt.expectedError) } }) } } func getWorkflowEngine() *wfengine.WorkflowEngine { spec := config.WorkflowSpec{MaxConcurrentWorkflowInvocations: 100, MaxConcurrentActivityInvocations: 100} wfengine := wfengine.NewWorkflowEngine("testAppID", spec, nil) wfengine.SetWorkflowEngineReadyDone() return wfengine }
mikeee/dapr
pkg/api/universal/workflow_test.go
GO
mit
16,231
/* Copyright 2023 The Dapr 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 common // +kubebuilder:object:generate=true import ( "strconv" apiextensionsV1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" ) // NameValuePair is a name/value pair. type NameValuePair struct { // Name of the property. Name string `json:"name"` // Value of the property, in plaintext. //+optional Value DynamicValue `json:"value,omitempty"` // SecretKeyRef is the reference of a value in a secret store component. //+optional SecretKeyRef SecretKeyRef `json:"secretKeyRef,omitempty"` // EnvRef is the name of an environmental variable to read the value from. //+optional EnvRef string `json:"envRef,omitempty"` } // HasValue returns true if the NameValuePair has a non-empty value. func (nvp NameValuePair) HasValue() bool { return len(nvp.Value.JSON.Raw) > 0 } // SetValue sets the value. func (nvp *NameValuePair) SetValue(val []byte) { nvp.Value = DynamicValue{ JSON: apiextensionsV1.JSON{ Raw: val, }, } } // SecretKeyRef is a reference to a secret holding the value for the name/value item. type SecretKeyRef struct { // Secret name. Name string `json:"name"` // Field in the secret. //+optional Key string `json:"key"` } // DynamicValue is a dynamic value struct for the component.metadata pair value. // +kubebuilder:validation:Type="" // +kubebuilder:validation:Schemaless type DynamicValue struct { apiextensionsV1.JSON `json:",inline"` } // String returns the string representation of the raw value. // If the value is a string, it will be unquoted as the string is guaranteed to be a JSON serialized string. func (d *DynamicValue) String() string { s := string(d.Raw) c, err := strconv.Unquote(s) if err == nil { s = c } return s }
mikeee/dapr
pkg/apis/common/namevalue.go
GO
mit
2,270
/* Copyright 2023 The Dapr 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 common // +kubebuilder:object:generate=true // Scoped is a base struct for components and other resources that can be scoped to apps. type Scoped struct { //+optional Scopes []string `json:"scopes,omitempty"` } // IsAppScoped returns true if the appID is allowed in the scopes for the resource. func (s Scoped) IsAppScoped(appID string) bool { if len(s.Scopes) == 0 { // If there are no scopes, then every app is allowed return true } for _, s := range s.Scopes { if s == appID { return true } } return false }
mikeee/dapr
pkg/apis/common/scoped.go
GO
mit
1,103
/* Copyright 2023 The Dapr 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 common // +kubebuilder:object:generate=true // TLSDocument describes and in-line or pointer to a document to build a TLS configuration. type TLSDocument struct { // Value of the property, in plaintext. //+optional Value *DynamicValue `json:"value,omitempty"` // SecretKeyRef is the reference of a value in a secret store component. //+optional SecretKeyRef *SecretKeyRef `json:"secretKeyRef,omitempty"` } // TLS describes how to build client or server TLS configurations. type TLS struct { //+optional RootCA *TLSDocument `json:"rootCA"` //+optional Certificate *TLSDocument `json:"certificate"` //+optional PrivateKey *TLSDocument `json:"privateKey"` //+optional //+kubebuilder:validation:Enum={"Never", "OnceAsClient", "FreelyAsClient"} //+kubebuilder:default=Never Renegotiation *Renegotiation `json:"renegotiation"` } // Renegotiation sets the underlying tls negotiation strategy for an http channel. type Renegotiation string const ( NegotiateNever Renegotiation = "Never" NegotiateOnceAsClient Renegotiation = "OnceAsClient" NegotiateFreelyAsClient Renegotiation = "FreelyAsClient" )
mikeee/dapr
pkg/apis/common/tls.go
GO
mit
1,694
//go:build !ignore_autogenerated /* Copyright The Dapr 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. */ // Code generated by controller-gen. DO NOT EDIT. package common import () // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *DynamicValue) DeepCopyInto(out *DynamicValue) { *out = *in in.JSON.DeepCopyInto(&out.JSON) } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DynamicValue. func (in *DynamicValue) DeepCopy() *DynamicValue { if in == nil { return nil } out := new(DynamicValue) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *NameValuePair) DeepCopyInto(out *NameValuePair) { *out = *in in.Value.DeepCopyInto(&out.Value) out.SecretKeyRef = in.SecretKeyRef } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NameValuePair. func (in *NameValuePair) DeepCopy() *NameValuePair { if in == nil { return nil } out := new(NameValuePair) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Scoped) DeepCopyInto(out *Scoped) { *out = *in if in.Scopes != nil { in, out := &in.Scopes, &out.Scopes *out = make([]string, len(*in)) copy(*out, *in) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Scoped. func (in *Scoped) DeepCopy() *Scoped { if in == nil { return nil } out := new(Scoped) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SecretKeyRef) DeepCopyInto(out *SecretKeyRef) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SecretKeyRef. func (in *SecretKeyRef) DeepCopy() *SecretKeyRef { if in == nil { return nil } out := new(SecretKeyRef) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *TLS) DeepCopyInto(out *TLS) { *out = *in if in.RootCA != nil { in, out := &in.RootCA, &out.RootCA *out = new(TLSDocument) (*in).DeepCopyInto(*out) } if in.Certificate != nil { in, out := &in.Certificate, &out.Certificate *out = new(TLSDocument) (*in).DeepCopyInto(*out) } if in.PrivateKey != nil { in, out := &in.PrivateKey, &out.PrivateKey *out = new(TLSDocument) (*in).DeepCopyInto(*out) } if in.Renegotiation != nil { in, out := &in.Renegotiation, &out.Renegotiation *out = new(Renegotiation) **out = **in } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TLS. func (in *TLS) DeepCopy() *TLS { if in == nil { return nil } out := new(TLS) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *TLSDocument) DeepCopyInto(out *TLSDocument) { *out = *in if in.Value != nil { in, out := &in.Value, &out.Value *out = new(DynamicValue) (*in).DeepCopyInto(*out) } if in.SecretKeyRef != nil { in, out := &in.SecretKeyRef, &out.SecretKeyRef *out = new(SecretKeyRef) **out = **in } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TLSDocument. func (in *TLSDocument) DeepCopy() *TLSDocument { if in == nil { return nil } out := new(TLSDocument) in.DeepCopyInto(out) return out }
mikeee/dapr
pkg/apis/common/zz_generated.deepcopy.go
GO
mit
4,155
/* Copyright 2021 The Dapr 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 components const ( GroupName = "dapr.io" )
mikeee/dapr
pkg/apis/components/register.go
GO
mit
614
/* Copyright 2021 The Dapr 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. */ // +kubebuilder:object:generate=true // +groupName=dapr.io package v1alpha1
mikeee/dapr
pkg/apis/components/v1alpha1/doc.go
GO
mit
637
/* Copyright 2021 The Dapr 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 v1alpha1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "github.com/dapr/dapr/pkg/apis/components" ) // SchemeGroupVersion is group version used to register these objects. var SchemeGroupVersion = schema.GroupVersion{Group: components.GroupName, Version: "v1alpha1"} // GroupKindFromKind takes an unqualified kind and returns back a Group qualified GroupKind. func GroupKindFromKind(kind string) schema.GroupKind { return SchemeGroupVersion.WithKind(kind).GroupKind() } // Resource takes an unqualified resource and returns a Group qualified GroupResource. func Resource(resource string) schema.GroupResource { return SchemeGroupVersion.WithResource(resource).GroupResource() } var ( SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) AddToScheme = SchemeBuilder.AddToScheme ) // Adds the list of known types to Scheme. func addKnownTypes(scheme *runtime.Scheme) error { scheme.AddKnownTypes( SchemeGroupVersion, &Component{}, &ComponentList{}, ) metav1.AddToGroupVersion(scheme, SchemeGroupVersion) return nil }
mikeee/dapr
pkg/apis/components/v1alpha1/register.go
GO
mit
1,697
/* Copyright 2021 The Dapr 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 v1alpha1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/client" "github.com/dapr/dapr/pkg/apis/common" "github.com/dapr/dapr/pkg/apis/components" "github.com/dapr/dapr/utils" ) const ( Kind = "Component" Version = "v1alpha1" ) //+genclient //+genclient:noStatus //+kubebuilder:object:root=true // Component describes an Dapr component type. type Component struct { metav1.TypeMeta `json:",inline"` //+optional metav1.ObjectMeta `json:"metadata,omitempty"` //+optional Spec ComponentSpec `json:"spec,omitempty"` //+optional Auth `json:"auth,omitempty"` common.Scoped `json:",inline"` } // Kind returns the component kind. func (Component) Kind() string { return "Component" } func (Component) APIVersion() string { return components.GroupName + "/" + Version } // GetName returns the component name. func (c Component) GetName() string { return c.Name } // GetNamespace returns the component namespace. func (c Component) GetNamespace() string { return c.Namespace } // LogName returns the name of the component that can be used in logging. func (c Component) LogName() string { return utils.ComponentLogName(c.ObjectMeta.Name, c.Spec.Type, c.Spec.Version) } // GetSecretStore returns the name of the secret store. func (c Component) GetSecretStore() string { return c.Auth.SecretStore } // NameValuePairs returns the component's metadata as name/value pairs func (c Component) NameValuePairs() []common.NameValuePair { return c.Spec.Metadata } func (c Component) ClientObject() client.Object { return &c } func (c Component) GetScopes() []string { return c.Scopes } // EmptyMetaDeepCopy returns a new instance of the component type with the // TypeMeta's Kind and APIVersion fields set. func (c Component) EmptyMetaDeepCopy() metav1.Object { n := c.DeepCopy() n.TypeMeta = metav1.TypeMeta{ Kind: Kind, APIVersion: components.GroupName + "/" + Version, } n.ObjectMeta = metav1.ObjectMeta{Name: c.Name} return n } // ComponentSpec is the spec for a component. type ComponentSpec struct { Type string `json:"type"` Version string `json:"version"` //+optional IgnoreErrors bool `json:"ignoreErrors"` Metadata []common.NameValuePair `json:"metadata"` //+optional InitTimeout string `json:"initTimeout"` } // Auth represents authentication details for the component. type Auth struct { SecretStore string `json:"secretStore"` } //+kubebuilder:object:root=true // ComponentList is a list of Dapr components. type ComponentList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata"` Items []Component `json:"items"` }
mikeee/dapr
pkg/apis/components/v1alpha1/types.go
GO
mit
3,251
//go:build !ignore_autogenerated /* Copyright The Dapr 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. */ // Code generated by controller-gen. DO NOT EDIT. package v1alpha1 import ( "github.com/dapr/dapr/pkg/apis/common" "k8s.io/apimachinery/pkg/runtime" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Auth) DeepCopyInto(out *Auth) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Auth. func (in *Auth) DeepCopy() *Auth { if in == nil { return nil } out := new(Auth) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Component) DeepCopyInto(out *Component) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) out.Auth = in.Auth in.Scoped.DeepCopyInto(&out.Scoped) } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Component. func (in *Component) DeepCopy() *Component { if in == nil { return nil } out := new(Component) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *Component) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ComponentList) DeepCopyInto(out *ComponentList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]Component, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ComponentList. func (in *ComponentList) DeepCopy() *ComponentList { if in == nil { return nil } out := new(ComponentList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *ComponentList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ComponentSpec) DeepCopyInto(out *ComponentSpec) { *out = *in if in.Metadata != nil { in, out := &in.Metadata, &out.Metadata *out = make([]common.NameValuePair, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ComponentSpec. func (in *ComponentSpec) DeepCopy() *ComponentSpec { if in == nil { return nil } out := new(ComponentSpec) in.DeepCopyInto(out) return out }
mikeee/dapr
pkg/apis/components/v1alpha1/zz_generated.deepcopy.go
GO
mit
3,475
/* Copyright 2021 The Dapr 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 configuration const ( GroupName = "dapr.io" )
mikeee/dapr
pkg/apis/configuration/register.go
GO
mit
617
/* Copyright 2021 The Dapr 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. */ // +kubebuilder:object:generate=true // +groupName=dapr.io package v1alpha1
mikeee/dapr
pkg/apis/configuration/v1alpha1/doc.go
GO
mit
637
/* Copyright 2021 The Dapr 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 v1alpha1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "github.com/dapr/dapr/pkg/apis/configuration" ) // SchemeGroupVersion is group version used to register these objects. var SchemeGroupVersion = schema.GroupVersion{Group: configuration.GroupName, Version: "v1alpha1"} // Kind takes an unqualified kind and returns back a Group qualified GroupKind. func Kind(kind string) schema.GroupKind { return SchemeGroupVersion.WithKind(kind).GroupKind() } // Resource takes an unqualified resource and returns a Group qualified GroupResource. func Resource(resource string) schema.GroupResource { return SchemeGroupVersion.WithResource(resource).GroupResource() } var ( SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) AddToScheme = SchemeBuilder.AddToScheme ) // Adds the list of known types to Scheme. func addKnownTypes(scheme *runtime.Scheme) error { scheme.AddKnownTypes( SchemeGroupVersion, &Configuration{}, &ConfigurationList{}, ) metav1.AddToGroupVersion(scheme, SchemeGroupVersion) return nil }
mikeee/dapr
pkg/apis/configuration/v1alpha1/register.go
GO
mit
1,685
/* Copyright 2021 The Dapr 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 v1alpha1 import ( "strconv" v1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // +genclient // +genclient:noStatus // +kubebuilder:object:root=true // Configuration describes an Dapr configuration setting. type Configuration struct { metav1.TypeMeta `json:",inline"` // +optional metav1.ObjectMeta `json:"metadata,omitempty"` // +optional Spec ConfigurationSpec `json:"spec,omitempty"` } // ConfigurationSpec is the spec for a configuration. type ConfigurationSpec struct { // +optional AppHTTPPipelineSpec *PipelineSpec `json:"appHttpPipeline,omitempty"` // +optional HTTPPipelineSpec *PipelineSpec `json:"httpPipeline,omitempty"` // +optional TracingSpec *TracingSpec `json:"tracing,omitempty"` // +kubebuilder:default={enabled:true} MetricSpec *MetricSpec `json:"metric,omitempty"` // +kubebuilder:default={enabled:true} MetricsSpec *MetricSpec `json:"metrics,omitempty"` // +optional MTLSSpec *MTLSSpec `json:"mtls,omitempty"` // +optional Secrets *SecretsSpec `json:"secrets,omitempty"` // +optional AccessControlSpec *AccessControlSpec `json:"accessControl,omitempty"` // +optional NameResolutionSpec *NameResolutionSpec `json:"nameResolution,omitempty"` // +optional Features []FeatureSpec `json:"features,omitempty"` // +optional APISpec *APISpec `json:"api,omitempty"` // +optional ComponentsSpec *ComponentsSpec `json:"components,omitempty"` // +optional LoggingSpec *LoggingSpec `json:"logging,omitempty"` // +optional WasmSpec *WasmSpec `json:"wasm,omitempty"` // +optional WorkflowSpec *WorkflowSpec `json:"workflow,omitempty"` } // WorkflowSpec defines the configuration for Dapr workflows. type WorkflowSpec struct { // maxConcurrentWorkflowInvocations is the maximum number of concurrent workflow invocations that can be scheduled by a single Dapr instance. // Attempted invocations beyond this will be queued until the number of concurrent invocations drops below this value. // If omitted, the default value of 100 will be used. // +optional MaxConcurrentWorkflowInvocations int32 `json:"maxConcurrentWorkflowInvocations,omitempty"` // maxConcurrentActivityInvocations is the maximum number of concurrent activities that can be processed by a single Dapr instance. // Attempted invocations beyond this will be queued until the number of concurrent invocations drops below this value. // If omitted, the default value of 100 will be used. // +optional MaxConcurrentActivityInvocations int32 `json:"maxConcurrentActivityInvocations,omitempty"` } // APISpec describes the configuration for Dapr APIs. type APISpec struct { // List of allowed APIs. Can be used in conjunction with denied. // +optional Allowed []APIAccessRule `json:"allowed,omitempty"` // List of denied APIs. Can be used in conjunction with allowed. // +optional Denied []APIAccessRule `json:"denied,omitempty"` } // WasmSpec describes the security profile for all Dapr Wasm components. type WasmSpec struct { // Force enabling strict sandbox mode for all WASM components. // When this is enabled, WASM components always run in strict mode regardless of their configuration. // Strict mode enhances security of the WASM sandbox by limiting access to certain capabilities such as real-time clocks and random number generators. StrictSandbox bool `json:"strictSandbox,omitempty"` } // APIAccessRule describes an access rule for allowing or denying a Dapr API. type APIAccessRule struct { Name string `json:"name"` Version string `json:"version"` // +optional Protocol string `json:"protocol,omitempty"` } // NameResolutionSpec is the spec for name resolution configuration. type NameResolutionSpec struct { Component string `json:"component"` Version string `json:"version"` Configuration *DynamicValue `json:"configuration"` } // SecretsSpec is the spec for secrets configuration. type SecretsSpec struct { Scopes []SecretsScope `json:"scopes"` } // SecretsScope defines the scope for secrets. type SecretsScope struct { StoreName string `json:"storeName"` // +optional DefaultAccess string `json:"defaultAccess,omitempty"` // +optional AllowedSecrets []string `json:"allowedSecrets,omitempty"` // +optional DeniedSecrets []string `json:"deniedSecrets,omitempty"` } // PipelineSpec defines the middleware pipeline. type PipelineSpec struct { Handlers []HandlerSpec `json:"handlers"` } // HandlerSpec defines a request handlers. type HandlerSpec struct { Name string `json:"name"` Type string `json:"type"` // +optional SelectorSpec *SelectorSpec `json:"selector,omitempty"` } // MTLSSpec defines mTLS configuration. type MTLSSpec struct { Enabled *bool `json:"enabled"` // +optional WorkloadCertTTL *string `json:"workloadCertTTL,omitempty"` // +optional AllowedClockSkew *string `json:"allowedClockSkew,omitempty"` SentryAddress string `json:"sentryAddress"` ControlPlaneTrustDomain string `json:"controlPlaneTrustDomain"` // Additional token validators to use. // When Dapr is running in Kubernetes mode, this is in addition to the built-in "kubernetes" validator. // In self-hosted mode, enabling a custom validator will disable the built-in "insecure" validator. // +optional TokenValidators []ValidatorSpec `json:"tokenValidators,omitempty"` } // GetEnabled returns true if mTLS is enabled. func (m *MTLSSpec) GetEnabled() bool { // Defaults to true if unset return m == nil || m.Enabled == nil || *m.Enabled } // ValidatorSpec contains additional token validators to use. type ValidatorSpec struct { // Name of the validator // +kubebuilder:validation:Enum={"jwks"} Name string `json:"name"` // Options for the validator, if any Options *DynamicValue `json:"options,omitempty"` } // SelectorSpec selects target services to which the handler is to be applied. type SelectorSpec struct { Fields []SelectorField `json:"fields"` } // SelectorField defines a selector fields. type SelectorField struct { Field string `json:"field"` Value string `json:"value"` } // TracingSpec defines distributed tracing configuration. type TracingSpec struct { SamplingRate string `json:"samplingRate"` // +optional Stdout *bool `json:"stdout,omitempty"` // +optional Zipkin *ZipkinSpec `json:"zipkin,omitempty"` // +optional Otel *OtelSpec `json:"otel,omitempty"` } // OtelSpec defines Otel exporter configurations. type OtelSpec struct { Protocol string `json:"protocol" yaml:"protocol"` EndpointAddress string `json:"endpointAddress" yaml:"endpointAddress"` IsSecure *bool `json:"isSecure" yaml:"isSecure"` } // ZipkinSpec defines Zipkin trace configurations. type ZipkinSpec struct { EndpointAddresss string `json:"endpointAddress"` } // MetricSpec defines metrics configuration. type MetricSpec struct { Enabled *bool `json:"enabled"` // +optional HTTP *MetricHTTP `json:"http,omitempty"` // +optional Rules []MetricsRule `json:"rules,omitempty"` } // MetricHTTP defines configuration for metrics for the HTTP server type MetricHTTP struct { // If false, metrics for the HTTP server are collected with increased cardinality. // The default is true in Dapr 1.13, but will be changed to false in 1.15+ // TODO: [MetricsCardinality] Change default in 1.15+ // +optional IncreasedCardinality *bool `json:"increasedCardinality,omitempty"` // +optional PathMatching *PathMatching `json:"pathMatching,omitempty"` } // PathMatching defines configuration options for path matching. type PathMatching struct { // IngressPaths is a list of paths to match for ingress metrics. IngressPaths []string `json:"ingress,omitempty"` // EgressPaths is a list of paths to match for egress metrics. EgressPaths []string `json:"egress,omitempty"` } // MetricsRule defines configuration options for a metric. type MetricsRule struct { Name string `json:"name"` Labels []MetricLabel `json:"labels"` } // MetricsLabel defines an object that allows to set regex expressions for a label. type MetricLabel struct { Name string `json:"name"` Regex map[string]string `json:"regex"` } // AppPolicySpec defines the policy data structure for each app. type AppPolicySpec struct { AppName string `json:"appId" yaml:"appId"` // +optional DefaultAction string `json:"defaultAction,omitempty" yaml:"defaultAction,omitempty"` // +optional TrustDomain string `json:"trustDomain,omitempty" yaml:"trustDomain,omitempty"` // +optional Namespace string `json:"namespace,omitempty" yaml:"namespace,omitempty"` // +optional AppOperationActions []AppOperationAction `json:"operations,omitempty" yaml:"operations,omitempty"` } // AppOperationAction defines the data structure for each app operation. type AppOperationAction struct { Operation string `json:"name" yaml:"name"` Action string `json:"action" yaml:"action"` // +optional HTTPVerb []string `json:"httpVerb,omitempty" yaml:"httpVerb,omitempty"` } // AccessControlSpec is the spec object in ConfigurationSpec. type AccessControlSpec struct { // +optional DefaultAction string `json:"defaultAction,omitempty" yaml:"defaultAction,omitempty"` // +optional TrustDomain string `json:"trustDomain,omitempty" yaml:"trustDomain,omitempty"` // +optional AppPolicies []AppPolicySpec `json:"policies,omitempty" yaml:"policies,omitempty"` } // FeatureSpec defines the features that are enabled/disabled. type FeatureSpec struct { Name string `json:"name" yaml:"name"` Enabled *bool `json:"enabled" yaml:"enabled"` } // ComponentsSpec describes the configuration for Dapr components type ComponentsSpec struct { // Denylist of component types that cannot be instantiated // +optional Deny []string `json:"deny,omitempty" yaml:"deny,omitempty"` } // LoggingSpec defines the configuration for logging. type LoggingSpec struct { // Configure API logging. // +optional APILogging *APILoggingSpec `json:"apiLogging,omitempty" yaml:"apiLogging,omitempty"` } // APILoggingSpec defines the configuration for API logging. type APILoggingSpec struct { // Default value for enabling API logging. Sidecars can always override this by setting `--enable-api-logging` to true or false explicitly. // The default value is false. // +optional Enabled *bool `json:"enabled,omitempty" yaml:"enabled,omitempty"` // When enabled, obfuscates the values of URLs in HTTP API logs, logging the route name rather than the full path being invoked, which could contain PII. // Default: false. // This option has no effect if API logging is disabled. // +optional ObfuscateURLs *bool `json:"obfuscateURLs,omitempty" yaml:"obfuscateURLs,omitempty"` // If true, health checks are not reported in API logs. Default: false. // This option has no effect if API logging is disabled. // +optional OmitHealthChecks *bool `json:"omitHealthChecks,omitempty" yaml:"omitHealthChecks,omitempty"` } // +kubebuilder:object:root=true // ConfigurationList is a list of Dapr event sources. type ConfigurationList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata"` Items []Configuration `json:"items"` } // DynamicValue is a dynamic value struct for the component.metadata pair value. type DynamicValue struct { v1.JSON `json:",inline"` } // String returns the string representation of the raw value. // If the value is a string, it will be unquoted as the string is guaranteed to be a JSON serialized string. func (d *DynamicValue) String() string { s := string(d.Raw) c, err := strconv.Unquote(s) if err == nil { s = c } return s }
mikeee/dapr
pkg/apis/configuration/v1alpha1/types.go
GO
mit
12,120
//go:build !ignore_autogenerated /* Copyright The Dapr 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. */ // Code generated by controller-gen. DO NOT EDIT. package v1alpha1 import ( "k8s.io/apimachinery/pkg/runtime" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *APIAccessRule) DeepCopyInto(out *APIAccessRule) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIAccessRule. func (in *APIAccessRule) DeepCopy() *APIAccessRule { if in == nil { return nil } out := new(APIAccessRule) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *APILoggingSpec) DeepCopyInto(out *APILoggingSpec) { *out = *in if in.Enabled != nil { in, out := &in.Enabled, &out.Enabled *out = new(bool) **out = **in } if in.ObfuscateURLs != nil { in, out := &in.ObfuscateURLs, &out.ObfuscateURLs *out = new(bool) **out = **in } if in.OmitHealthChecks != nil { in, out := &in.OmitHealthChecks, &out.OmitHealthChecks *out = new(bool) **out = **in } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APILoggingSpec. func (in *APILoggingSpec) DeepCopy() *APILoggingSpec { if in == nil { return nil } out := new(APILoggingSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *APISpec) DeepCopyInto(out *APISpec) { *out = *in if in.Allowed != nil { in, out := &in.Allowed, &out.Allowed *out = make([]APIAccessRule, len(*in)) copy(*out, *in) } if in.Denied != nil { in, out := &in.Denied, &out.Denied *out = make([]APIAccessRule, len(*in)) copy(*out, *in) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APISpec. func (in *APISpec) DeepCopy() *APISpec { if in == nil { return nil } out := new(APISpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *AccessControlSpec) DeepCopyInto(out *AccessControlSpec) { *out = *in if in.AppPolicies != nil { in, out := &in.AppPolicies, &out.AppPolicies *out = make([]AppPolicySpec, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AccessControlSpec. func (in *AccessControlSpec) DeepCopy() *AccessControlSpec { if in == nil { return nil } out := new(AccessControlSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *AppOperationAction) DeepCopyInto(out *AppOperationAction) { *out = *in if in.HTTPVerb != nil { in, out := &in.HTTPVerb, &out.HTTPVerb *out = make([]string, len(*in)) copy(*out, *in) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AppOperationAction. func (in *AppOperationAction) DeepCopy() *AppOperationAction { if in == nil { return nil } out := new(AppOperationAction) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *AppPolicySpec) DeepCopyInto(out *AppPolicySpec) { *out = *in if in.AppOperationActions != nil { in, out := &in.AppOperationActions, &out.AppOperationActions *out = make([]AppOperationAction, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AppPolicySpec. func (in *AppPolicySpec) DeepCopy() *AppPolicySpec { if in == nil { return nil } out := new(AppPolicySpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ComponentsSpec) DeepCopyInto(out *ComponentsSpec) { *out = *in if in.Deny != nil { in, out := &in.Deny, &out.Deny *out = make([]string, len(*in)) copy(*out, *in) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ComponentsSpec. func (in *ComponentsSpec) DeepCopy() *ComponentsSpec { if in == nil { return nil } out := new(ComponentsSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Configuration) DeepCopyInto(out *Configuration) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Configuration. func (in *Configuration) DeepCopy() *Configuration { if in == nil { return nil } out := new(Configuration) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *Configuration) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ConfigurationList) DeepCopyInto(out *ConfigurationList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]Configuration, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConfigurationList. func (in *ConfigurationList) DeepCopy() *ConfigurationList { if in == nil { return nil } out := new(ConfigurationList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *ConfigurationList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ConfigurationSpec) DeepCopyInto(out *ConfigurationSpec) { *out = *in if in.AppHTTPPipelineSpec != nil { in, out := &in.AppHTTPPipelineSpec, &out.AppHTTPPipelineSpec *out = new(PipelineSpec) (*in).DeepCopyInto(*out) } if in.HTTPPipelineSpec != nil { in, out := &in.HTTPPipelineSpec, &out.HTTPPipelineSpec *out = new(PipelineSpec) (*in).DeepCopyInto(*out) } if in.TracingSpec != nil { in, out := &in.TracingSpec, &out.TracingSpec *out = new(TracingSpec) (*in).DeepCopyInto(*out) } if in.MetricSpec != nil { in, out := &in.MetricSpec, &out.MetricSpec *out = new(MetricSpec) (*in).DeepCopyInto(*out) } if in.MetricsSpec != nil { in, out := &in.MetricsSpec, &out.MetricsSpec *out = new(MetricSpec) (*in).DeepCopyInto(*out) } if in.MTLSSpec != nil { in, out := &in.MTLSSpec, &out.MTLSSpec *out = new(MTLSSpec) (*in).DeepCopyInto(*out) } if in.Secrets != nil { in, out := &in.Secrets, &out.Secrets *out = new(SecretsSpec) (*in).DeepCopyInto(*out) } if in.AccessControlSpec != nil { in, out := &in.AccessControlSpec, &out.AccessControlSpec *out = new(AccessControlSpec) (*in).DeepCopyInto(*out) } if in.NameResolutionSpec != nil { in, out := &in.NameResolutionSpec, &out.NameResolutionSpec *out = new(NameResolutionSpec) (*in).DeepCopyInto(*out) } if in.Features != nil { in, out := &in.Features, &out.Features *out = make([]FeatureSpec, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } if in.APISpec != nil { in, out := &in.APISpec, &out.APISpec *out = new(APISpec) (*in).DeepCopyInto(*out) } if in.ComponentsSpec != nil { in, out := &in.ComponentsSpec, &out.ComponentsSpec *out = new(ComponentsSpec) (*in).DeepCopyInto(*out) } if in.LoggingSpec != nil { in, out := &in.LoggingSpec, &out.LoggingSpec *out = new(LoggingSpec) (*in).DeepCopyInto(*out) } if in.WasmSpec != nil { in, out := &in.WasmSpec, &out.WasmSpec *out = new(WasmSpec) **out = **in } if in.WorkflowSpec != nil { in, out := &in.WorkflowSpec, &out.WorkflowSpec *out = new(WorkflowSpec) **out = **in } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConfigurationSpec. func (in *ConfigurationSpec) DeepCopy() *ConfigurationSpec { if in == nil { return nil } out := new(ConfigurationSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *DynamicValue) DeepCopyInto(out *DynamicValue) { *out = *in in.JSON.DeepCopyInto(&out.JSON) } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DynamicValue. func (in *DynamicValue) DeepCopy() *DynamicValue { if in == nil { return nil } out := new(DynamicValue) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *FeatureSpec) DeepCopyInto(out *FeatureSpec) { *out = *in if in.Enabled != nil { in, out := &in.Enabled, &out.Enabled *out = new(bool) **out = **in } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new FeatureSpec. func (in *FeatureSpec) DeepCopy() *FeatureSpec { if in == nil { return nil } out := new(FeatureSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *HandlerSpec) DeepCopyInto(out *HandlerSpec) { *out = *in if in.SelectorSpec != nil { in, out := &in.SelectorSpec, &out.SelectorSpec *out = new(SelectorSpec) (*in).DeepCopyInto(*out) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HandlerSpec. func (in *HandlerSpec) DeepCopy() *HandlerSpec { if in == nil { return nil } out := new(HandlerSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *LoggingSpec) DeepCopyInto(out *LoggingSpec) { *out = *in if in.APILogging != nil { in, out := &in.APILogging, &out.APILogging *out = new(APILoggingSpec) (*in).DeepCopyInto(*out) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LoggingSpec. func (in *LoggingSpec) DeepCopy() *LoggingSpec { if in == nil { return nil } out := new(LoggingSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MTLSSpec) DeepCopyInto(out *MTLSSpec) { *out = *in if in.Enabled != nil { in, out := &in.Enabled, &out.Enabled *out = new(bool) **out = **in } if in.WorkloadCertTTL != nil { in, out := &in.WorkloadCertTTL, &out.WorkloadCertTTL *out = new(string) **out = **in } if in.AllowedClockSkew != nil { in, out := &in.AllowedClockSkew, &out.AllowedClockSkew *out = new(string) **out = **in } if in.TokenValidators != nil { in, out := &in.TokenValidators, &out.TokenValidators *out = make([]ValidatorSpec, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MTLSSpec. func (in *MTLSSpec) DeepCopy() *MTLSSpec { if in == nil { return nil } out := new(MTLSSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MetricHTTP) DeepCopyInto(out *MetricHTTP) { *out = *in if in.IncreasedCardinality != nil { in, out := &in.IncreasedCardinality, &out.IncreasedCardinality *out = new(bool) **out = **in } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MetricHTTP. func (in *MetricHTTP) DeepCopy() *MetricHTTP { if in == nil { return nil } out := new(MetricHTTP) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MetricLabel) DeepCopyInto(out *MetricLabel) { *out = *in if in.Regex != nil { in, out := &in.Regex, &out.Regex *out = make(map[string]string, len(*in)) for key, val := range *in { (*out)[key] = val } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MetricLabel. func (in *MetricLabel) DeepCopy() *MetricLabel { if in == nil { return nil } out := new(MetricLabel) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MetricSpec) DeepCopyInto(out *MetricSpec) { *out = *in if in.Enabled != nil { in, out := &in.Enabled, &out.Enabled *out = new(bool) **out = **in } if in.HTTP != nil { in, out := &in.HTTP, &out.HTTP *out = new(MetricHTTP) (*in).DeepCopyInto(*out) } if in.Rules != nil { in, out := &in.Rules, &out.Rules *out = make([]MetricsRule, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MetricSpec. func (in *MetricSpec) DeepCopy() *MetricSpec { if in == nil { return nil } out := new(MetricSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MetricsRule) DeepCopyInto(out *MetricsRule) { *out = *in if in.Labels != nil { in, out := &in.Labels, &out.Labels *out = make([]MetricLabel, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MetricsRule. func (in *MetricsRule) DeepCopy() *MetricsRule { if in == nil { return nil } out := new(MetricsRule) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *NameResolutionSpec) DeepCopyInto(out *NameResolutionSpec) { *out = *in if in.Configuration != nil { in, out := &in.Configuration, &out.Configuration *out = new(DynamicValue) (*in).DeepCopyInto(*out) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NameResolutionSpec. func (in *NameResolutionSpec) DeepCopy() *NameResolutionSpec { if in == nil { return nil } out := new(NameResolutionSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *OtelSpec) DeepCopyInto(out *OtelSpec) { *out = *in if in.IsSecure != nil { in, out := &in.IsSecure, &out.IsSecure *out = new(bool) **out = **in } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new OtelSpec. func (in *OtelSpec) DeepCopy() *OtelSpec { if in == nil { return nil } out := new(OtelSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PipelineSpec) DeepCopyInto(out *PipelineSpec) { *out = *in if in.Handlers != nil { in, out := &in.Handlers, &out.Handlers *out = make([]HandlerSpec, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PipelineSpec. func (in *PipelineSpec) DeepCopy() *PipelineSpec { if in == nil { return nil } out := new(PipelineSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SecretsScope) DeepCopyInto(out *SecretsScope) { *out = *in if in.AllowedSecrets != nil { in, out := &in.AllowedSecrets, &out.AllowedSecrets *out = make([]string, len(*in)) copy(*out, *in) } if in.DeniedSecrets != nil { in, out := &in.DeniedSecrets, &out.DeniedSecrets *out = make([]string, len(*in)) copy(*out, *in) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SecretsScope. func (in *SecretsScope) DeepCopy() *SecretsScope { if in == nil { return nil } out := new(SecretsScope) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SecretsSpec) DeepCopyInto(out *SecretsSpec) { *out = *in if in.Scopes != nil { in, out := &in.Scopes, &out.Scopes *out = make([]SecretsScope, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SecretsSpec. func (in *SecretsSpec) DeepCopy() *SecretsSpec { if in == nil { return nil } out := new(SecretsSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SelectorField) DeepCopyInto(out *SelectorField) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SelectorField. func (in *SelectorField) DeepCopy() *SelectorField { if in == nil { return nil } out := new(SelectorField) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SelectorSpec) DeepCopyInto(out *SelectorSpec) { *out = *in if in.Fields != nil { in, out := &in.Fields, &out.Fields *out = make([]SelectorField, len(*in)) copy(*out, *in) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SelectorSpec. func (in *SelectorSpec) DeepCopy() *SelectorSpec { if in == nil { return nil } out := new(SelectorSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *TracingSpec) DeepCopyInto(out *TracingSpec) { *out = *in if in.Stdout != nil { in, out := &in.Stdout, &out.Stdout *out = new(bool) **out = **in } if in.Zipkin != nil { in, out := &in.Zipkin, &out.Zipkin *out = new(ZipkinSpec) **out = **in } if in.Otel != nil { in, out := &in.Otel, &out.Otel *out = new(OtelSpec) (*in).DeepCopyInto(*out) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TracingSpec. func (in *TracingSpec) DeepCopy() *TracingSpec { if in == nil { return nil } out := new(TracingSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ValidatorSpec) DeepCopyInto(out *ValidatorSpec) { *out = *in if in.Options != nil { in, out := &in.Options, &out.Options *out = new(DynamicValue) (*in).DeepCopyInto(*out) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ValidatorSpec. func (in *ValidatorSpec) DeepCopy() *ValidatorSpec { if in == nil { return nil } out := new(ValidatorSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *WasmSpec) DeepCopyInto(out *WasmSpec) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WasmSpec. func (in *WasmSpec) DeepCopy() *WasmSpec { if in == nil { return nil } out := new(WasmSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *WorkflowSpec) DeepCopyInto(out *WorkflowSpec) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkflowSpec. func (in *WorkflowSpec) DeepCopy() *WorkflowSpec { if in == nil { return nil } out := new(WorkflowSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ZipkinSpec) DeepCopyInto(out *ZipkinSpec) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ZipkinSpec. func (in *ZipkinSpec) DeepCopy() *ZipkinSpec { if in == nil { return nil } out := new(ZipkinSpec) in.DeepCopyInto(out) return out }
mikeee/dapr
pkg/apis/configuration/v1alpha1/zz_generated.deepcopy.go
GO
mit
21,510
/* Copyright 2023 The Dapr 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 httpendpoint const ( GroupName = "dapr.io" )
mikeee/dapr
pkg/apis/httpEndpoint/register.go
GO
mit
616
/* Copyright 2023 The Dapr 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. */ // +kubebuilder:object:generate=true // +groupName=dapr.io package v1alpha1
mikeee/dapr
pkg/apis/httpEndpoint/v1alpha1/doc.go
GO
mit
637
/* Copyright 2023 The Dapr 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 v1alpha1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" httpendpoint "github.com/dapr/dapr/pkg/apis/httpEndpoint" ) // SchemeGroupVersion is group version used to register these objects. var SchemeGroupVersion = schema.GroupVersion{Group: httpendpoint.GroupName, Version: "v1alpha1"} // GroupKindFromKind takes an unqualified kind and returns back a Group // qualified GroupKind. func GroupKindFromKind(kind string) schema.GroupKind { return SchemeGroupVersion.WithKind(kind).GroupKind() } // Resource takes an unqualified resource and returns a Group qualified GroupResource. func Resource(resource string) schema.GroupResource { return SchemeGroupVersion.WithResource(resource).GroupResource() } var ( SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) AddToScheme = SchemeBuilder.AddToScheme ) // Adds the list of known types to Scheme. func addKnownTypes(scheme *runtime.Scheme) error { scheme.AddKnownTypes( SchemeGroupVersion, &HTTPEndpoint{}, &HTTPEndpointList{}, ) metav1.AddToGroupVersion(scheme, SchemeGroupVersion) return nil }
mikeee/dapr
pkg/apis/httpEndpoint/v1alpha1/register.go
GO
mit
1,723
/* Copyright 2023 The Dapr 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 v1alpha1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/client" "github.com/dapr/dapr/pkg/apis/common" httpendpoint "github.com/dapr/dapr/pkg/apis/httpEndpoint" ) const ( Kind = "HTTPEndpoint" Version = "v1alpha1" ) //+genclient //+genclient:noStatus //+kubebuilder:object:root=true // HTTPEndpoint describes a Dapr HTTPEndpoint type for external service invocation. // This endpoint can be external to Dapr, or external to the environment. type HTTPEndpoint struct { metav1.TypeMeta `json:",inline"` //+optional metav1.ObjectMeta `json:"metadata,omitempty"` //+optional Spec HTTPEndpointSpec `json:"spec,omitempty"` //+optional Auth `json:"auth,omitempty"` common.Scoped `json:",inline"` } const kind = "HTTPEndpoint" // Kind returns the component kind. func (HTTPEndpoint) Kind() string { return kind } func (HTTPEndpoint) APIVersion() string { return httpendpoint.GroupName + "/" + Version } // GetName returns the component name. func (h HTTPEndpoint) GetName() string { return h.Name } // GetNamespace returns the component namespace. func (h HTTPEndpoint) GetNamespace() string { return h.Namespace } // GetSecretStore returns the name of the secret store. func (h HTTPEndpoint) GetSecretStore() string { return h.Auth.SecretStore } // LogName returns the name of the component that can be used in logging. func (h HTTPEndpoint) LogName() string { return h.Name + " (" + h.Spec.BaseURL + ")" } // NameValuePairs returns the component's headers as name/value pairs func (h HTTPEndpoint) NameValuePairs() []common.NameValuePair { return h.Spec.Headers } // nil returns a bool indicating if a tls private key has a secret reference func (h HTTPEndpoint) HasTLSPrivateKeySecret() bool { return h.Spec.ClientTLS != nil && h.Spec.ClientTLS.PrivateKey != nil && h.Spec.ClientTLS.PrivateKey.SecretKeyRef != nil && h.Spec.ClientTLS.PrivateKey.SecretKeyRef.Name != "" } // HasTLSClientCertSecret returns a bool indicating if a tls client cert has a secret reference func (h HTTPEndpoint) HasTLSClientCertSecret() bool { return h.Spec.ClientTLS != nil && h.Spec.ClientTLS.Certificate != nil && h.Spec.ClientTLS.Certificate.SecretKeyRef != nil && h.Spec.ClientTLS.Certificate.SecretKeyRef.Name != "" } // HasTLSRootCASecret returns a bool indicating if a tls root cert has a secret reference func (h HTTPEndpoint) HasTLSRootCASecret() bool { return h.Spec.ClientTLS != nil && h.Spec.ClientTLS.RootCA != nil && h.Spec.ClientTLS.RootCA.SecretKeyRef != nil && h.Spec.ClientTLS.RootCA.SecretKeyRef.Name != "" } // HasTLSRootCA returns a bool indicating if the HTTP endpoint contains a tls root ca func (h HTTPEndpoint) HasTLSRootCA() bool { return h.Spec.ClientTLS != nil && h.Spec.ClientTLS.RootCA != nil && h.Spec.ClientTLS.RootCA.Value != nil } // HasTLSClientCert returns a bool indicating if the HTTP endpoint contains a tls client cert func (h HTTPEndpoint) HasTLSClientCert() bool { return h.Spec.ClientTLS != nil && h.Spec.ClientTLS.Certificate != nil && h.Spec.ClientTLS.Certificate.Value != nil } // HasTLSPrivateKey returns a bool indicating if the HTTP endpoint contains a tls client key func (h HTTPEndpoint) HasTLSPrivateKey() bool { return h.Spec.ClientTLS != nil && h.Spec.ClientTLS.PrivateKey != nil && h.Spec.ClientTLS.PrivateKey.Value != nil } func (h HTTPEndpoint) ClientObject() client.Object { return &h } func (h HTTPEndpoint) GetScopes() []string { return h.Scopes } // EmptyMetaDeepCopy returns a new instance of the component type with the // TypeMeta's Kind and APIVersion fields set. func (h HTTPEndpoint) EmptyMetaDeepCopy() metav1.Object { n := h.DeepCopy() n.TypeMeta = metav1.TypeMeta{ Kind: Kind, APIVersion: httpendpoint.GroupName + "/" + Version, } n.ObjectMeta = metav1.ObjectMeta{Name: h.Name} return n } // HTTPEndpointSpec describes an access specification for allowing external service invocations. type HTTPEndpointSpec struct { BaseURL string `json:"baseUrl" validate:"required"` //+optional Headers []common.NameValuePair `json:"headers"` //+optional ClientTLS *common.TLS `json:"clientTLS,omitempty"` } // Auth represents authentication details for the component. type Auth struct { SecretStore string `json:"secretStore"` } //+kubebuilder:object:root=true // HTTPEndpointList is a list of Dapr HTTPEndpoints. type HTTPEndpointList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata"` Items []HTTPEndpoint `json:"items"` }
mikeee/dapr
pkg/apis/httpEndpoint/v1alpha1/types.go
GO
mit
5,085
//go:build !ignore_autogenerated /* Copyright The Dapr 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. */ // Code generated by controller-gen. DO NOT EDIT. package v1alpha1 import ( "github.com/dapr/dapr/pkg/apis/common" "k8s.io/apimachinery/pkg/runtime" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Auth) DeepCopyInto(out *Auth) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Auth. func (in *Auth) DeepCopy() *Auth { if in == nil { return nil } out := new(Auth) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *HTTPEndpoint) DeepCopyInto(out *HTTPEndpoint) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) out.Auth = in.Auth in.Scoped.DeepCopyInto(&out.Scoped) } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HTTPEndpoint. func (in *HTTPEndpoint) DeepCopy() *HTTPEndpoint { if in == nil { return nil } out := new(HTTPEndpoint) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *HTTPEndpoint) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *HTTPEndpointList) DeepCopyInto(out *HTTPEndpointList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]HTTPEndpoint, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HTTPEndpointList. func (in *HTTPEndpointList) DeepCopy() *HTTPEndpointList { if in == nil { return nil } out := new(HTTPEndpointList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *HTTPEndpointList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *HTTPEndpointSpec) DeepCopyInto(out *HTTPEndpointSpec) { *out = *in if in.Headers != nil { in, out := &in.Headers, &out.Headers *out = make([]common.NameValuePair, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } if in.ClientTLS != nil { in, out := &in.ClientTLS, &out.ClientTLS *out = new(common.TLS) (*in).DeepCopyInto(*out) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HTTPEndpointSpec. func (in *HTTPEndpointSpec) DeepCopy() *HTTPEndpointSpec { if in == nil { return nil } out := new(HTTPEndpointSpec) in.DeepCopyInto(out) return out }
mikeee/dapr
pkg/apis/httpEndpoint/v1alpha1/zz_generated.deepcopy.go
GO
mit
3,659
/* Copyright 2021 The Dapr 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 resiliency const ( // GroupName is the API group name. GroupName = "dapr.io" )
mikeee/dapr
pkg/apis/resiliency/register.go
GO
mit
651
/* Copyright 2021 The Dapr 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. */ // +kubebuilder:object:generate=true // +groupName=dapr.io package v1alpha1
mikeee/dapr
pkg/apis/resiliency/v1alpha1/doc.go
GO
mit
637
/* Copyright 2021 The Dapr 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 v1alpha1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "github.com/dapr/dapr/pkg/apis/resiliency" ) // SchemeGroupVersion is group version used to register these objects. var SchemeGroupVersion = schema.GroupVersion{Group: resiliency.GroupName, Version: "v1alpha1"} // Kind takes an unqualified kind and returns back a Group qualified GroupKind. func Kind(kind string) schema.GroupKind { return SchemeGroupVersion.WithKind(kind).GroupKind() } // Resource takes an unqualified resource and returns a Group qualified GroupResource. func Resource(resource string) schema.GroupResource { return SchemeGroupVersion.WithResource(resource).GroupResource() } var ( // SchemeBuilder is the scheme builder for resiliency. SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) // AddToScheme is the func to add the resiliency scheme to the operator API. AddToScheme = SchemeBuilder.AddToScheme ) // Adds the list of known types to Scheme. func addKnownTypes(scheme *runtime.Scheme) error { scheme.AddKnownTypes( SchemeGroupVersion, &Resiliency{}, //nolint:exhaustivestruct &ResiliencyList{}, //nolint:exhaustivestruct ) metav1.AddToGroupVersion(scheme, SchemeGroupVersion) return nil }
mikeee/dapr
pkg/apis/resiliency/v1alpha1/register.go
GO
mit
1,861
/* Copyright 2021 The Dapr 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 v1alpha1 import ( "encoding/json" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // +genclient // +genclient:noStatus // +kubebuilder:object:root=true type Resiliency struct { metav1.TypeMeta `json:",inline"` // +optional metav1.ObjectMeta `json:"metadata,omitempty"` // +optional Spec ResiliencySpec `json:"spec,omitempty"` // +optional Scopes []string `json:"scopes,omitempty"` } // String implements fmt.Stringer and is used for debugging. It returns the policy object encoded as JSON. func (r Resiliency) String() string { b, _ := json.Marshal(r) return string(b) } type ResiliencySpec struct { Policies Policies `json:"policies"` Targets Targets `json:"targets" yaml:"targets"` } type Policies struct { Timeouts map[string]string `json:"timeouts,omitempty" yaml:"timeouts,omitempty"` Retries map[string]Retry `json:"retries,omitempty" yaml:"retries,omitempty"` CircuitBreakers map[string]CircuitBreaker `json:"circuitBreakers,omitempty" yaml:"circuitBreakers,omitempty"` } type Retry struct { Policy string `json:"policy,omitempty" yaml:"policy,omitempty"` Duration string `json:"duration,omitempty" yaml:"duration,omitempty"` MaxInterval string `json:"maxInterval,omitempty" yaml:"maxInterval,omitempty"` MaxRetries *int `json:"maxRetries,omitempty" yaml:"maxRetries,omitempty"` } type CircuitBreaker struct { MaxRequests int `json:"maxRequests,omitempty" yaml:"maxRequests,omitempty"` Interval string `json:"interval,omitempty" yaml:"interval,omitempty"` Timeout string `json:"timeout,omitempty" yaml:"timeout,omitempty"` Trip string `json:"trip,omitempty" yaml:"trip,omitempty"` } type Targets struct { Apps map[string]EndpointPolicyNames `json:"apps,omitempty" yaml:"apps,omitempty"` Actors map[string]ActorPolicyNames `json:"actors,omitempty" yaml:"actors,omitempty"` Components map[string]ComponentPolicyNames `json:"components,omitempty" yaml:"components,omitempty"` } type ComponentPolicyNames struct { Inbound PolicyNames `json:"inbound,omitempty" yaml:"inbound,omitempty"` Outbound PolicyNames `json:"outbound,omitempty" yaml:"outbound,omitempty"` } type PolicyNames struct { Timeout string `json:"timeout,omitempty" yaml:"timeout,omitempty"` Retry string `json:"retry,omitempty" yaml:"retry,omitempty"` CircuitBreaker string `json:"circuitBreaker,omitempty" yaml:"circuitBreaker,omitempty"` } type EndpointPolicyNames struct { Timeout string `json:"timeout,omitempty" yaml:"timeout,omitempty"` Retry string `json:"retry,omitempty" yaml:"retry,omitempty"` CircuitBreaker string `json:"circuitBreaker,omitempty" yaml:"circuitBreaker,omitempty"` CircuitBreakerCacheSize int `json:"circuitBreakerCacheSize,omitempty" yaml:"circuitBreakerCacheSize,omitempty"` } type ActorPolicyNames struct { Timeout string `json:"timeout,omitempty" yaml:"timeout,omitempty"` Retry string `json:"retry,omitempty" yaml:"retry,omitempty"` CircuitBreaker string `json:"circuitBreaker,omitempty" yaml:"circuitBreaker,omitempty"` CircuitBreakerScope string `json:"circuitBreakerScope,omitempty" yaml:"circuitBreakerScope,omitempty"` CircuitBreakerCacheSize int `json:"circuitBreakerCacheSize,omitempty" yaml:"circuitBreakerCacheSize,omitempty"` } // ResiliencyList represents a list of `Resiliency` items. // +kubebuilder:object:root=true type ResiliencyList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata"` Items []Resiliency `json:"items"` }
mikeee/dapr
pkg/apis/resiliency/v1alpha1/types.go
GO
mit
4,181
//go:build !ignore_autogenerated /* Copyright The Dapr 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. */ // Code generated by controller-gen. DO NOT EDIT. package v1alpha1 import ( "k8s.io/apimachinery/pkg/runtime" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ActorPolicyNames) DeepCopyInto(out *ActorPolicyNames) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ActorPolicyNames. func (in *ActorPolicyNames) DeepCopy() *ActorPolicyNames { if in == nil { return nil } out := new(ActorPolicyNames) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CircuitBreaker) DeepCopyInto(out *CircuitBreaker) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CircuitBreaker. func (in *CircuitBreaker) DeepCopy() *CircuitBreaker { if in == nil { return nil } out := new(CircuitBreaker) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ComponentPolicyNames) DeepCopyInto(out *ComponentPolicyNames) { *out = *in out.Inbound = in.Inbound out.Outbound = in.Outbound } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ComponentPolicyNames. func (in *ComponentPolicyNames) DeepCopy() *ComponentPolicyNames { if in == nil { return nil } out := new(ComponentPolicyNames) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *EndpointPolicyNames) DeepCopyInto(out *EndpointPolicyNames) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EndpointPolicyNames. func (in *EndpointPolicyNames) DeepCopy() *EndpointPolicyNames { if in == nil { return nil } out := new(EndpointPolicyNames) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Policies) DeepCopyInto(out *Policies) { *out = *in if in.Timeouts != nil { in, out := &in.Timeouts, &out.Timeouts *out = make(map[string]string, len(*in)) for key, val := range *in { (*out)[key] = val } } if in.Retries != nil { in, out := &in.Retries, &out.Retries *out = make(map[string]Retry, len(*in)) for key, val := range *in { (*out)[key] = *val.DeepCopy() } } if in.CircuitBreakers != nil { in, out := &in.CircuitBreakers, &out.CircuitBreakers *out = make(map[string]CircuitBreaker, len(*in)) for key, val := range *in { (*out)[key] = val } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Policies. func (in *Policies) DeepCopy() *Policies { if in == nil { return nil } out := new(Policies) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PolicyNames) DeepCopyInto(out *PolicyNames) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PolicyNames. func (in *PolicyNames) DeepCopy() *PolicyNames { if in == nil { return nil } out := new(PolicyNames) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Resiliency) DeepCopyInto(out *Resiliency) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) if in.Scopes != nil { in, out := &in.Scopes, &out.Scopes *out = make([]string, len(*in)) copy(*out, *in) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Resiliency. func (in *Resiliency) DeepCopy() *Resiliency { if in == nil { return nil } out := new(Resiliency) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *Resiliency) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ResiliencyList) DeepCopyInto(out *ResiliencyList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]Resiliency, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ResiliencyList. func (in *ResiliencyList) DeepCopy() *ResiliencyList { if in == nil { return nil } out := new(ResiliencyList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *ResiliencyList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ResiliencySpec) DeepCopyInto(out *ResiliencySpec) { *out = *in in.Policies.DeepCopyInto(&out.Policies) in.Targets.DeepCopyInto(&out.Targets) } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ResiliencySpec. func (in *ResiliencySpec) DeepCopy() *ResiliencySpec { if in == nil { return nil } out := new(ResiliencySpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Retry) DeepCopyInto(out *Retry) { *out = *in if in.MaxRetries != nil { in, out := &in.MaxRetries, &out.MaxRetries *out = new(int) **out = **in } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Retry. func (in *Retry) DeepCopy() *Retry { if in == nil { return nil } out := new(Retry) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Targets) DeepCopyInto(out *Targets) { *out = *in if in.Apps != nil { in, out := &in.Apps, &out.Apps *out = make(map[string]EndpointPolicyNames, len(*in)) for key, val := range *in { (*out)[key] = val } } if in.Actors != nil { in, out := &in.Actors, &out.Actors *out = make(map[string]ActorPolicyNames, len(*in)) for key, val := range *in { (*out)[key] = val } } if in.Components != nil { in, out := &in.Components, &out.Components *out = make(map[string]ComponentPolicyNames, len(*in)) for key, val := range *in { (*out)[key] = val } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Targets. func (in *Targets) DeepCopy() *Targets { if in == nil { return nil } out := new(Targets) in.DeepCopyInto(out) return out }
mikeee/dapr
pkg/apis/resiliency/v1alpha1/zz_generated.deepcopy.go
GO
mit
7,763
/* Copyright 2021 The Dapr 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 subscriptions const ( GroupName = "dapr.io" )
mikeee/dapr
pkg/apis/subscriptions/register.go
GO
mit
617
package v1alpha1 // Hub marks this type as a conversion hub. func (*Subscription) Hub() {}
mikeee/dapr
pkg/apis/subscriptions/v1alpha1/conversion.go
GO
mit
92
/* Copyright 2021 The Dapr 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. */ // +kubebuilder:object:generate=true // +groupName=dapr.io package v1alpha1
mikeee/dapr
pkg/apis/subscriptions/v1alpha1/doc.go
GO
mit
637
/* Copyright 2021 The Dapr 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 v1alpha1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "github.com/dapr/dapr/pkg/apis/subscriptions" ) // SchemeGroupVersion is group version used to register these objects. var SchemeGroupVersion = schema.GroupVersion{Group: subscriptions.GroupName, Version: "v1alpha1"} // GroupKindFromKind takes an unqualified kind and returns back a Group qualified GroupKind. func GroupKindFromKind(kind string) schema.GroupKind { return SchemeGroupVersion.WithKind(kind).GroupKind() } // Resource takes an unqualified resource and returns a Group qualified GroupResource. func Resource(resource string) schema.GroupResource { return SchemeGroupVersion.WithResource(resource).GroupResource() } var ( SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) AddToScheme = SchemeBuilder.AddToScheme ) // Adds the list of known types to Scheme. func addKnownTypes(scheme *runtime.Scheme) error { scheme.AddKnownTypes( SchemeGroupVersion, &Subscription{}, &SubscriptionList{}, ) metav1.AddToGroupVersion(scheme, SchemeGroupVersion) return nil }
mikeee/dapr
pkg/apis/subscriptions/v1alpha1/register.go
GO
mit
1,709
/* Copyright 2021 The Dapr 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 v1alpha1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/client" "github.com/dapr/dapr/pkg/apis/common" "github.com/dapr/dapr/pkg/apis/subscriptions" ) const ( Kind = "Subscription" Version = "v1alpha1" ) // +genclient // +genclient:noStatus // +kubebuilder:object:root=true // Subscription describes an pub/sub event subscription. type Subscription struct { metav1.TypeMeta `json:",inline"` // +optional metav1.ObjectMeta `json:"metadata,omitempty"` Spec SubscriptionSpec `json:"spec,omitempty"` // +optional Scopes []string `json:"scopes,omitempty"` } // SubscriptionSpec is the spec for an event subscription. type SubscriptionSpec struct { Topic string `json:"topic"` Pubsubname string `json:"pubsubname"` // +optional Metadata map[string]string `json:"metadata,omitempty"` Route string `json:"route"` BulkSubscribe BulkSubscribe `json:"bulkSubscribe,omitempty"` DeadLetterTopic string `json:"deadLetterTopic,omitempty"` } // BulkSubscribe encapsulates the bulk subscription configuration for a topic. type BulkSubscribe struct { Enabled bool `json:"enabled"` // +optional MaxMessagesCount int32 `json:"maxMessagesCount,omitempty"` MaxAwaitDurationMs int32 `json:"maxAwaitDurationMs,omitempty"` } // +kubebuilder:object:root=true // SubscriptionList is a list of Dapr event sources. type SubscriptionList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata"` Items []Subscription `json:"items"` } func (Subscription) Kind() string { return Kind } func (Subscription) APIVersion() string { return subscriptions.GroupName + "/" + Version } // EmptyMetaDeepCopy returns a new instance of the subscription type with the // TypeMeta's Kind and APIVersion fields set. func (s Subscription) EmptyMetaDeepCopy() metav1.Object { n := s.DeepCopy() n.TypeMeta = metav1.TypeMeta{ Kind: Kind, APIVersion: subscriptions.GroupName + "/" + Version, } n.ObjectMeta = metav1.ObjectMeta{Name: s.Name} return n } func (s Subscription) GetName() string { return s.Name } func (s Subscription) GetNamespace() string { return s.Namespace } func (s Subscription) GetSecretStore() string { return "" } func (s Subscription) LogName() string { return s.GetName() } func (s Subscription) NameValuePairs() []common.NameValuePair { return nil } func (s Subscription) ClientObject() client.Object { return &s } func (s Subscription) GetScopes() []string { return s.Scopes }
mikeee/dapr
pkg/apis/subscriptions/v1alpha1/types.go
GO
mit
3,120
//go:build !ignore_autogenerated /* Copyright The Dapr 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. */ // Code generated by controller-gen. DO NOT EDIT. package v1alpha1 import ( "k8s.io/apimachinery/pkg/runtime" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *BulkSubscribe) DeepCopyInto(out *BulkSubscribe) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BulkSubscribe. func (in *BulkSubscribe) DeepCopy() *BulkSubscribe { if in == nil { return nil } out := new(BulkSubscribe) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Subscription) DeepCopyInto(out *Subscription) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) if in.Scopes != nil { in, out := &in.Scopes, &out.Scopes *out = make([]string, len(*in)) copy(*out, *in) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Subscription. func (in *Subscription) DeepCopy() *Subscription { if in == nil { return nil } out := new(Subscription) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *Subscription) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SubscriptionList) DeepCopyInto(out *SubscriptionList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]Subscription, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SubscriptionList. func (in *SubscriptionList) DeepCopy() *SubscriptionList { if in == nil { return nil } out := new(SubscriptionList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *SubscriptionList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SubscriptionSpec) DeepCopyInto(out *SubscriptionSpec) { *out = *in if in.Metadata != nil { in, out := &in.Metadata, &out.Metadata *out = make(map[string]string, len(*in)) for key, val := range *in { (*out)[key] = val } } out.BulkSubscribe = in.BulkSubscribe } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SubscriptionSpec. func (in *SubscriptionSpec) DeepCopy() *SubscriptionSpec { if in == nil { return nil } out := new(SubscriptionSpec) in.DeepCopyInto(out) return out }
mikeee/dapr
pkg/apis/subscriptions/v1alpha1/zz_generated.deepcopy.go
GO
mit
3,634
package v2alpha1 import ( "errors" "sigs.k8s.io/controller-runtime/pkg/conversion" "github.com/dapr/dapr/pkg/apis/subscriptions/v1alpha1" ) // +kubebuilder:docs-gen:collapse=Imports /* Our "spoke" versions need to implement the [`Convertible`](https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/conversion?tab=doc#Convertible) interface. Namely, they'll need `ConvertTo` and `ConvertFrom` methods to convert to/from the hub version. */ /* ConvertTo is expected to modify its argument to contain the converted object. Most of the conversion is straightforward copying, except for converting our changed field. */ // ConvertTo converts this Subscription to the Hub version (v1). func (s *Subscription) ConvertTo(dstRaw conversion.Hub) error { dst, ok := dstRaw.(*v1alpha1.Subscription) if !ok { return errors.New("expected to convert to *v1alpha1.Subscription") } // Copy scopes dst.Scopes = s.Scopes // ObjectMeta dst.ObjectMeta = s.ObjectMeta // Spec dst.Spec.Pubsubname = s.Spec.Pubsubname dst.Spec.Topic = s.Spec.Topic dst.Spec.Metadata = s.Spec.Metadata dst.Spec.Route = s.Spec.Routes.Default dst.Spec.DeadLetterTopic = s.Spec.DeadLetterTopic dst.Spec.BulkSubscribe = *convertBulkSubscriptionV2alpha1ToV1alpha1(&s.Spec.BulkSubscribe) // +kubebuilder:docs-gen:collapse=rote conversion return nil } func convertBulkSubscriptionV2alpha1ToV1alpha1(in *BulkSubscribe) *v1alpha1.BulkSubscribe { out := v1alpha1.BulkSubscribe{ Enabled: in.Enabled, MaxMessagesCount: in.MaxMessagesCount, MaxAwaitDurationMs: in.MaxAwaitDurationMs, } return &out } /* ConvertFrom is expected to modify its receiver to contain the converted object. Most of the conversion is straightforward copying, except for converting our changed field. */ // ConvertFrom converts from the Hub version (v1) to this version. func (s *Subscription) ConvertFrom(srcRaw conversion.Hub) error { src, ok := srcRaw.(*v1alpha1.Subscription) if !ok { return errors.New("expected to convert from *v1alpha1.Subscription") } // Copy scopes s.Scopes = src.Scopes // ObjectMeta s.ObjectMeta = src.ObjectMeta // Spec s.Spec.Pubsubname = src.Spec.Pubsubname s.Spec.Topic = src.Spec.Topic s.Spec.Metadata = src.Spec.Metadata s.Spec.Routes.Default = src.Spec.Route s.Spec.DeadLetterTopic = src.Spec.DeadLetterTopic s.Spec.BulkSubscribe = *convertBulkSubscriptionV1alpha1ToV2alpha1(&src.Spec.BulkSubscribe) // +kubebuilder:docs-gen:collapse=rote conversion return nil } func convertBulkSubscriptionV1alpha1ToV2alpha1(in *v1alpha1.BulkSubscribe) *BulkSubscribe { out := BulkSubscribe{ Enabled: in.Enabled, MaxMessagesCount: in.MaxMessagesCount, MaxAwaitDurationMs: in.MaxAwaitDurationMs, } return &out }
mikeee/dapr
pkg/apis/subscriptions/v2alpha1/conversion.go
GO
mit
2,751
package v2alpha1_test import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/dapr/dapr/pkg/apis/subscriptions/v1alpha1" "github.com/dapr/dapr/pkg/apis/subscriptions/v2alpha1" ) func TestConversion(t *testing.T) { // Test converting to and from v1alpha1 subscriptionV2 := v2alpha1.Subscription{ Scopes: []string{"app1", "app2"}, Spec: v2alpha1.SubscriptionSpec{ Pubsubname: "testPubSub", Topic: "topicName", Metadata: map[string]string{ "testName": "testValue", }, Routes: v2alpha1.Routes{ Default: "testPath", }, DeadLetterTopic: "testDeadLetterTopic", BulkSubscribe: v2alpha1.BulkSubscribe{ Enabled: true, MaxMessagesCount: 10, MaxAwaitDurationMs: 1000, }, }, } var subscriptionV1 v1alpha1.Subscription err := subscriptionV2.ConvertTo(&subscriptionV1) require.NoError(t, err) var actual v2alpha1.Subscription err = actual.ConvertFrom(&subscriptionV1) require.NoError(t, err) assert.Equal(t, &subscriptionV2, &actual) }
mikeee/dapr
pkg/apis/subscriptions/v2alpha1/conversion_test.go
GO
mit
1,064
/* Copyright 2021 The Dapr 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. */ // +kubebuilder:object:generate=true // +groupName=dapr.io package v2alpha1
mikeee/dapr
pkg/apis/subscriptions/v2alpha1/doc.go
GO
mit
637
/* Copyright 2021 The Dapr 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 v2alpha1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "github.com/dapr/dapr/pkg/apis/subscriptions" ) // SchemeGroupVersion is group version used to register these objects. var SchemeGroupVersion = schema.GroupVersion{Group: subscriptions.GroupName, Version: "v2alpha1"} // GroupKindFromKind takes an unqualified kind and returns back a Group qualified GroupKind. func GroupKindFromKind(kind string) schema.GroupKind { return SchemeGroupVersion.WithKind(kind).GroupKind() } // Resource takes an unqualified resource and returns a Group qualified GroupResource. func Resource(resource string) schema.GroupResource { return SchemeGroupVersion.WithResource(resource).GroupResource() } var ( SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) AddToScheme = SchemeBuilder.AddToScheme ) // Adds the list of known types to Scheme. func addKnownTypes(scheme *runtime.Scheme) error { scheme.AddKnownTypes( SchemeGroupVersion, &Subscription{}, &SubscriptionList{}, ) metav1.AddToGroupVersion(scheme, SchemeGroupVersion) return nil }
mikeee/dapr
pkg/apis/subscriptions/v2alpha1/register.go
GO
mit
1,709
/* Copyright 2021 The Dapr 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 v2alpha1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/client" "github.com/dapr/dapr/pkg/apis/common" "github.com/dapr/dapr/pkg/apis/subscriptions" ) const ( Kind = "Subscription" Version = "v2alpha1" ) // +genclient // +genclient:noStatus // +kubebuilder:object:root=true // +kubebuilder:storageversion // Subscription describes an pub/sub event subscription. type Subscription struct { metav1.TypeMeta `json:",inline"` // +optional metav1.ObjectMeta `json:"metadata,omitempty"` Spec SubscriptionSpec `json:"spec,omitempty"` // +optional Scopes []string `json:"scopes,omitempty"` } // SubscriptionSpec is the spec for an event subscription. type SubscriptionSpec struct { // The PubSub component name. Pubsubname string `json:"pubsubname"` // The topic name to subscribe to. Topic string `json:"topic"` // The optional metadata to provide the subscription. // +optional Metadata map[string]string `json:"metadata,omitempty"` // The Routes configuration for this topic. Routes Routes `json:"routes"` // The optional dead letter queue for this topic to send events to. DeadLetterTopic string `json:"deadLetterTopic,omitempty"` // The option to enable bulk subscription for this topic. BulkSubscribe BulkSubscribe `json:"bulkSubscribe,omitempty"` } // BulkSubscribe encapsulates the bulk subscription configuration for a topic. type BulkSubscribe struct { Enabled bool `json:"enabled"` // +optional MaxMessagesCount int32 `json:"maxMessagesCount,omitempty"` MaxAwaitDurationMs int32 `json:"maxAwaitDurationMs,omitempty"` } // Routes encapsulates the rules and optional default path for a topic. type Routes struct { // The list of rules for this topic. // +optional Rules []Rule `json:"rules,omitempty"` // The default path for this topic. // +optional Default string `json:"default,omitempty"` } // Rule is used to specify the condition for sending // a message to a specific path. type Rule struct { // The optional CEL expression used to match the event. // If the match is not specified, then the route is considered // the default. The rules are tested in the order specified, // so they should be define from most-to-least specific. // The default route should appear last in the list. Match string `json:"match"` // The path for events that match this rule. Path string `json:"path"` } // +kubebuilder:object:root=true // SubscriptionList is a list of Dapr event sources. type SubscriptionList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata"` Items []Subscription `json:"items"` } func (Subscription) Kind() string { return Kind } func (Subscription) APIVersion() string { return subscriptions.GroupName + "/" + Version } // EmptyMetaDeepCopy returns a new instance of the subscription type with the // TypeMeta's Kind and APIVersion fields set. func (s Subscription) EmptyMetaDeepCopy() metav1.Object { n := s.DeepCopy() n.TypeMeta = metav1.TypeMeta{ Kind: Kind, APIVersion: subscriptions.GroupName + "/" + Version, } n.ObjectMeta = metav1.ObjectMeta{Name: s.Name} return n } func (s Subscription) GetName() string { return s.Name } func (s Subscription) GetNamespace() string { return s.Namespace } func (s Subscription) GetSecretStore() string { return "" } func (s Subscription) LogName() string { return s.GetName() } func (s Subscription) NameValuePairs() []common.NameValuePair { return nil } func (s Subscription) ClientObject() client.Object { return &s } func (s Subscription) GetScopes() []string { return s.Scopes }
mikeee/dapr
pkg/apis/subscriptions/v2alpha1/types.go
GO
mit
4,185
//go:build !ignore_autogenerated /* Copyright The Dapr 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. */ // Code generated by controller-gen. DO NOT EDIT. package v2alpha1 import ( "k8s.io/apimachinery/pkg/runtime" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *BulkSubscribe) DeepCopyInto(out *BulkSubscribe) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BulkSubscribe. func (in *BulkSubscribe) DeepCopy() *BulkSubscribe { if in == nil { return nil } out := new(BulkSubscribe) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Routes) DeepCopyInto(out *Routes) { *out = *in if in.Rules != nil { in, out := &in.Rules, &out.Rules *out = make([]Rule, len(*in)) copy(*out, *in) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Routes. func (in *Routes) DeepCopy() *Routes { if in == nil { return nil } out := new(Routes) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Rule) DeepCopyInto(out *Rule) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Rule. func (in *Rule) DeepCopy() *Rule { if in == nil { return nil } out := new(Rule) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Subscription) DeepCopyInto(out *Subscription) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) if in.Scopes != nil { in, out := &in.Scopes, &out.Scopes *out = make([]string, len(*in)) copy(*out, *in) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Subscription. func (in *Subscription) DeepCopy() *Subscription { if in == nil { return nil } out := new(Subscription) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *Subscription) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SubscriptionList) DeepCopyInto(out *SubscriptionList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]Subscription, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SubscriptionList. func (in *SubscriptionList) DeepCopy() *SubscriptionList { if in == nil { return nil } out := new(SubscriptionList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *SubscriptionList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SubscriptionSpec) DeepCopyInto(out *SubscriptionSpec) { *out = *in if in.Metadata != nil { in, out := &in.Metadata, &out.Metadata *out = make(map[string]string, len(*in)) for key, val := range *in { (*out)[key] = val } } in.Routes.DeepCopyInto(&out.Routes) out.BulkSubscribe = in.BulkSubscribe } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SubscriptionSpec. func (in *SubscriptionSpec) DeepCopy() *SubscriptionSpec { if in == nil { return nil } out := new(SubscriptionSpec) in.DeepCopyInto(out) return out }
mikeee/dapr
pkg/apis/subscriptions/v2alpha1/zz_generated.deepcopy.go
GO
mit
4,569
/* Copyright 2022 The Dapr 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 apphealth import ( "context" "errors" "strconv" "sync" "sync/atomic" "time" "k8s.io/utils/clock" "github.com/dapr/dapr/pkg/config" "github.com/dapr/kit/logger" ) const ( AppStatusUnhealthy uint8 = 0 AppStatusHealthy uint8 = 1 // reportMinInterval is the minimum interval between health reports. reportMinInterval = time.Second ) var log = logger.NewLogger("dapr.apphealth") // AppHealth manages the health checks for the app. type AppHealth struct { config config.AppHealthConfig probeFn ProbeFunction changeCb ChangeCallback report chan uint8 failureCount atomic.Int32 queue chan struct{} // lastReport is the last report as UNIX microseconds time. lastReport atomic.Int64 clock clock.WithTicker wg sync.WaitGroup closed atomic.Bool closeCh chan struct{} } // ProbeFunction is the signature of the function that performs health probes. // Health probe functions return errors only in case of internal errors. // Network errors are considered probe failures, and should return nil as errors. type ProbeFunction func(context.Context) (bool, error) // ChangeCallback is the signature of the callback that is invoked when the app's health status changes. type ChangeCallback func(ctx context.Context, status uint8) // New creates a new AppHealth object. func New(config config.AppHealthConfig, probeFn ProbeFunction) *AppHealth { a := &AppHealth{ config: config, probeFn: probeFn, report: make(chan uint8, 1), queue: make(chan struct{}, 1), clock: &clock.RealClock{}, closeCh: make(chan struct{}), } // Initial state is unhealthy until we validate it a.failureCount.Store(config.Threshold) return a } // OnHealthChange sets the callback that is invoked when the health of the app changes (app becomes either healthy or unhealthy). func (h *AppHealth) OnHealthChange(cb ChangeCallback) { h.changeCb = cb } // StartProbes starts polling the app on the interval. func (h *AppHealth) StartProbes(ctx context.Context) error { if h.closed.Load() { return errors.New("app health is closed") } if h.probeFn == nil { return errors.New("cannot start probes with nil probe function") } if h.config.ProbeInterval <= 0 { return errors.New("probe interval must be larger than 0") } if h.config.ProbeTimeout > h.config.ProbeInterval { return errors.New("app health checks probe timeouts must be smaller than probe intervals") } log.Info("App health probes starting") ctx, cancel := context.WithCancel(ctx) h.wg.Add(2) go func() { defer h.wg.Done() defer cancel() select { case <-h.closeCh: case <-ctx.Done(): } }() go func() { defer h.wg.Done() ticker := h.clock.NewTicker(h.config.ProbeInterval) ch := ticker.C() defer ticker.Stop() for { select { case <-ctx.Done(): ticker.Stop() log.Info("App health probes stopping") return case status := <-h.report: log.Debug("Received health status report") h.setResult(ctx, status == AppStatusHealthy) case <-ch: log.Debug("Probing app health") h.Enqueue() case <-h.queue: // Run synchronously so the loop is blocked h.doProbe(ctx) } } }() return nil } // Enqueue adds a new probe request to the queue func (h *AppHealth) Enqueue() { // The queue has a capacity of 1, so no more than one iteration can be queued up select { case h.queue <- struct{}{}: // Do nothing default: // Do nothing } return } // ReportHealth is used by the runtime to report a health signal from the app. func (h *AppHealth) ReportHealth(status uint8) { // If the user wants health probes only, short-circuit here if h.config.ProbeOnly { return } // Limit health reports to 1 per second if !h.ratelimitReports() { return } // Channel is buffered, so make sure that this doesn't block // Just in case another report is being worked on! select { case h.report <- status: // No action default: // No action } } // GetStatus returns the status of the app's health func (h *AppHealth) GetStatus() uint8 { fc := h.failureCount.Load() if fc >= h.config.Threshold { return AppStatusUnhealthy } return AppStatusHealthy } // Performs a health probe. // Should be invoked in a background goroutine. func (h *AppHealth) doProbe(parentCtx context.Context) { ctx, cancel := context.WithTimeout(parentCtx, h.config.ProbeTimeout) defer cancel() successful, err := h.probeFn(ctx) if err != nil { h.setResult(parentCtx, false) log.Errorf("App health probe could not complete with error: %v", err) return } log.Debug("App health probe successful: " + strconv.FormatBool(successful)) h.setResult(parentCtx, successful) } // Returns true if the health report can be saved. Only 1 report per second at most is allowed. func (h *AppHealth) ratelimitReports() bool { var ( swapped bool attempts uint8 ) now := h.clock.Now().UnixMicro() // Attempts at most 2 times before giving up, as the report may be stale at that point for !swapped && attempts < 2 { attempts++ // If the last report was less than `reportMinInterval` ago, nothing to do here prev := h.lastReport.Load() if prev > now-reportMinInterval.Microseconds() { return false } swapped = h.lastReport.CompareAndSwap(prev, now) } // If we couldn't do the swap after 2 attempts, just return false return swapped } func (h *AppHealth) setResult(ctx context.Context, successful bool) { h.lastReport.Store(h.clock.Now().UnixMicro()) if successful { // Reset the failure count // If the previous value was >= threshold, we need to report a health change prev := h.failureCount.Swap(0) if prev >= h.config.Threshold { log.Info("App entered healthy status") if h.changeCb != nil { h.wg.Add(1) go func() { defer h.wg.Done() h.changeCb(ctx, AppStatusHealthy) }() } } return } // Count the failure failures := h.failureCount.Add(1) // First, check if we've overflown if failures < 0 { // Reset to the threshold + 1 h.failureCount.Store(h.config.Threshold + 1) } else if failures == h.config.Threshold { // If we're here, we just passed the threshold right now log.Warn("App entered un-healthy status") if h.changeCb != nil { h.wg.Add(1) go func() { defer h.wg.Done() h.changeCb(ctx, AppStatusUnhealthy) }() } } } func (h *AppHealth) Close() error { defer h.wg.Wait() if h.closed.CompareAndSwap(false, true) { close(h.closeCh) } return nil }
mikeee/dapr
pkg/apphealth/health.go
GO
mit
7,029
/* Copyright 2022 The Dapr 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 apphealth import ( "context" "math" "sync" "sync/atomic" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" clocktesting "k8s.io/utils/clock/testing" "github.com/dapr/dapr/pkg/config" ) func TestAppHealth_setResult(t *testing.T) { var threshold int32 = 3 h := New(config.AppHealthConfig{ Threshold: threshold, }, nil) // Set the initial state to healthy h.setResult(context.Background(), true) statusChange := make(chan uint8, 1) unexpectedStatusChanges := atomic.Int32{} h.OnHealthChange(func(ctx context.Context, status uint8) { select { case statusChange <- status: // Do nothing default: // If the channel is full, it means we were not expecting a status change unexpectedStatusChanges.Add(1) } }) simulateFailures := func(n int32) { statusChange <- 255 // Fill the channel for i := int32(0); i < n; i++ { if i == threshold-1 { <-statusChange // Allow the channel to be written into } h.setResult(context.Background(), false) if i == threshold-1 { select { case v := <-statusChange: assert.Equal(t, AppStatusUnhealthy, v) case <-time.After(100 * time.Millisecond): t.Error("did not get a status change before deadline") } statusChange <- 255 // Fill the channel again } else { time.Sleep(time.Millisecond) } } } // Trigger threshold+10 failures and detect the invocation after the threshold simulateFailures(threshold + 10) assert.Empty(t, unexpectedStatusChanges.Load()) assert.Equal(t, threshold+10, h.failureCount.Load()) // First success should bring the app back to healthy <-statusChange // Allow the channel to be written into h.setResult(context.Background(), true) select { case v := <-statusChange: assert.Equal(t, AppStatusHealthy, v) case <-time.After(100 * time.Millisecond): t.Error("did not get a status change before deadline") } assert.Equal(t, int32(0), h.failureCount.Load()) // Multiple invocations in parallel // Only one failure should be sent wg := sync.WaitGroup{} for i := 0; i < 5; i++ { wg.Add(1) go func() { for i := int32(0); i < (threshold + 5); i++ { h.setResult(context.Background(), false) } wg.Done() }() } wg.Wait() select { case v := <-statusChange: assert.Equal(t, AppStatusUnhealthy, v) case <-time.After(50 * time.Millisecond): t.Error("did not get a status change before deadline") } assert.Empty(t, unexpectedStatusChanges.Load()) assert.Equal(t, (threshold+5)*5, h.failureCount.Load()) // Test overflows h.failureCount.Store(int32(math.MaxInt32 - 2)) statusChange <- 255 // Fill the channel again for i := int32(0); i < 5; i++ { h.setResult(context.Background(), false) } assert.Empty(t, unexpectedStatusChanges.Load()) assert.Equal(t, threshold+3, h.failureCount.Load()) } func TestAppHealth_ratelimitReports(t *testing.T) { clock := clocktesting.NewFakeClock(time.Now()) h := New(config.AppHealthConfig{}, nil) h.clock = clock // First run should always succeed require.True(t, h.ratelimitReports()) // Run again without waiting require.False(t, h.ratelimitReports()) require.False(t, h.ratelimitReports()) // Step and test clock.Step(reportMinInterval) require.True(t, h.ratelimitReports()) require.False(t, h.ratelimitReports()) // Run tests for 1 second, constantly // Should succeed only 10 times. clock.Step(reportMinInterval) firehose := func(start time.Time, step time.Duration) (passed int64) { for clock.Now().Sub(start) < time.Second*10 { if h.ratelimitReports() { passed++ } clock.Step(step) } return passed } passed := firehose(clock.Now(), 10*time.Millisecond) assert.Equal(t, int64(10), passed) // Repeat, but run with 3 parallel goroutines wg := sync.WaitGroup{} totalPassed := atomic.Int64{} start := clock.Now() wg.Add(3) for i := 0; i < 3; i++ { go func() { totalPassed.Add(firehose(start, 3*time.Millisecond)) wg.Done() }() } wg.Wait() passed = totalPassed.Load() assert.GreaterOrEqual(t, passed, int64(8)) assert.LessOrEqual(t, passed, int64(12)) } func Test_StartProbes(t *testing.T) { t.Run("closing context should return", func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) t.Cleanup(cancel) done := make(chan struct{}) h := New(config.AppHealthConfig{ ProbeInterval: time.Second, }, func(context.Context) (bool, error) { assert.Fail(t, "unexpected probe call") return false, nil }) clock := clocktesting.NewFakeClock(time.Now()) h.clock = clock go func() { defer close(done) require.NoError(t, h.StartProbes(ctx)) }() // Wait for ticker to start, assert.Eventually(t, clock.HasWaiters, time.Second, time.Microsecond) cancel() select { case <-done: case <-time.After(time.Millisecond * 100): assert.Fail(t, "StartProbes didn't return in time") } }) t.Run("calling StartProbes after it has already closed should error", func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) t.Cleanup(cancel) h := New(config.AppHealthConfig{ ProbeInterval: time.Second, }, func(context.Context) (bool, error) { assert.Fail(t, "unexpected probe call") return false, nil }) h.Close() done := make(chan struct{}) go func() { defer close(done) require.Error(t, h.StartProbes(ctx)) }() select { case <-done: case <-time.After(time.Millisecond * 100): require.Fail(t, "StartProbes didn't return in time") } }) t.Run("should return after closed", func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) t.Cleanup(cancel) h := New(config.AppHealthConfig{ ProbeInterval: time.Second, }, func(context.Context) (bool, error) { assert.Fail(t, "unexpected probe call") return false, nil }) clock := clocktesting.NewFakeClock(time.Now()) h.clock = clock done := make(chan struct{}) go func() { defer close(done) require.NoError(t, h.StartProbes(ctx)) }() // Wait for ticker to start, assert.Eventually(t, clock.HasWaiters, time.Second, time.Microsecond) h.Close() select { case <-done: case <-time.After(time.Millisecond * 100): require.Fail(t, "StartProbes didn't return in time") } }) t.Run("should call app probe function after interval", func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) t.Cleanup(cancel) var probeCalls atomic.Int64 var currentStatus atomic.Uint32 h := New(config.AppHealthConfig{ ProbeInterval: time.Second, Threshold: 1, }, func(context.Context) (bool, error) { defer probeCalls.Add(1) return probeCalls.Load() == 0, nil }) clock := clocktesting.NewFakeClock(time.Now()) h.clock = clock done := make(chan struct{}) go func() { defer close(done) require.NoError(t, h.StartProbes(ctx)) }() h.OnHealthChange(func(ctx context.Context, status uint8) { currentStatus.Store(uint32(status)) }) // Wait for ticker to start, assert.Eventually(t, clock.HasWaiters, time.Second, time.Microsecond) assert.Equal(t, int64(0), probeCalls.Load()) clock.Step(time.Second) assert.Eventually(t, func() bool { return currentStatus.Load() == uint32(AppStatusHealthy) }, time.Second, time.Microsecond) assert.Equal(t, int64(1), probeCalls.Load()) clock.Step(time.Second) assert.Eventually(t, func() bool { return currentStatus.Load() == uint32(AppStatusUnhealthy) }, time.Second, time.Microsecond) assert.Equal(t, int64(2), probeCalls.Load()) h.Close() select { case <-done: case <-time.After(time.Millisecond * 100): require.Fail(t, "StartProbes didn't return in time") } }) }
mikeee/dapr
pkg/apphealth/health_test.go
GO
mit
8,244
/* Copyright 2023 The Dapr 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 buildinfo import ( "strings" ) // Values for these are injected by the build. var ( version = "edge" gitcommit, gitversion string features string ) // PtrSize returns the size of the pointer type for this system // This will be 64 on 64-bit environments, and 32 on 32-bit ones // See: https://stackoverflow.com/a/25741986/192024 const PtrSize = 32 << uintptr(^uintptr(0)>>63) //nolint:unconvert // Set by the init function var featuresSlice []string func init() { if featuresSlice != nil { // Return if another init method (e.g. for a build tag) already initialized return } // At initialization, parse the value of "features" into a slice if features == "" { featuresSlice = []string{} } else { featuresSlice = strings.Split(features, ",") } features = "" } // Version returns the Dapr version. This is either a semantic version // number or else, in the case of unreleased code, the string "edge". func Version() string { return version } // Commit returns the git commit SHA for the code that Dapr was built from. func Commit() string { return gitcommit } // GitVersion returns the git version for the code that Dapr was built from. func GitVersion() string { return gitversion } // Features returns the list of features enabled for this build. func Features() []string { return featuresSlice } // AddFeature adds a new feature to the featuresSlice. It's primarily meant for testing purposes. // This should only be called as part of an init() method. func AddFeature(feature string) { if featuresSlice == nil { // If featuresSlice is nil, it means the caller's init() was executed before this package's features += "," + feature } else { featuresSlice = append(featuresSlice, feature) } }
mikeee/dapr
pkg/buildinfo/buildinfo.go
GO
mit
2,319
//go:build unit // +build unit /* Copyright 2023 The Dapr 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 buildinfo import ( "strings" ) // Comma-separated list of features to enable in unit tests const unitTestFeatures = "Resiliency,ServiceInvocationStreaming" // Set values for feature flags used in unit tests func init() { if unitTestFeatures == "" { featuresSlice = []string{} } else { featuresSlice = strings.Split(unitTestFeatures, ",") } }
mikeee/dapr
pkg/buildinfo/buildinfo_unit.go
GO
mit
954
/* Copyright 2021 The Dapr 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 channel import ( "context" "crypto/tls" "github.com/dapr/dapr/pkg/apphealth" "github.com/dapr/dapr/pkg/config" invokev1 "github.com/dapr/dapr/pkg/messaging/v1" ) const ( // AppChannelMinTLSVersion is the minimum TLS version that the app channel will use. AppChannelMinTLSVersion = tls.VersionTLS12 ) // AppChannel is an abstraction over communications with user code. type AppChannel interface { GetAppConfig(ctx context.Context, appID string) (*config.ApplicationConfig, error) InvokeMethod(ctx context.Context, req *invokev1.InvokeMethodRequest, appID string) (*invokev1.InvokeMethodResponse, error) HealthProbe(ctx context.Context) (bool, error) SetAppHealth(ah *apphealth.AppHealth) } // HTTPEndpointAppChannel is an abstraction over communications with http endpoint resources. type HTTPEndpointAppChannel interface { InvokeMethod(ctx context.Context, req *invokev1.InvokeMethodRequest, appID string) (*invokev1.InvokeMethodResponse, error) }
mikeee/dapr
pkg/channel/channel.go
GO
mit
1,534
/* Copyright 2021 The Dapr 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 grpc import ( "context" "fmt" "net" "strconv" "sync" "google.golang.org/grpc" "google.golang.org/grpc/codes" grpcMetadata "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" "google.golang.org/protobuf/types/known/emptypb" "github.com/dapr/dapr/pkg/apphealth" "github.com/dapr/dapr/pkg/config" "github.com/dapr/dapr/pkg/messages" invokev1 "github.com/dapr/dapr/pkg/messaging/v1" internalv1pb "github.com/dapr/dapr/pkg/proto/internals/v1" runtimev1pb "github.com/dapr/dapr/pkg/proto/runtime/v1" "github.com/dapr/dapr/pkg/security" securityConsts "github.com/dapr/dapr/pkg/security/consts" ) // Channel is a concrete AppChannel implementation for interacting with gRPC based user code. type Channel struct { appCallbackClient runtimev1pb.AppCallbackClient conn *grpc.ClientConn baseAddress string ch chan struct{} tracingSpec config.TracingSpec appMetadataToken string maxRequestBodySize int appHealth *apphealth.AppHealth } // CreateLocalChannel creates a gRPC connection with user code. func CreateLocalChannel(port, maxConcurrency int, conn *grpc.ClientConn, spec config.TracingSpec, maxRequestBodySize int, readBufferSize int, baseAddress string) *Channel { // readBufferSize is unused c := &Channel{ appCallbackClient: runtimev1pb.NewAppCallbackClient(conn), conn: conn, baseAddress: net.JoinHostPort(baseAddress, strconv.Itoa(port)), tracingSpec: spec, appMetadataToken: security.GetAppToken(), maxRequestBodySize: maxRequestBodySize, } if maxConcurrency > 0 { c.ch = make(chan struct{}, maxConcurrency) } return c } // GetAppConfig gets application config from user application. func (g *Channel) GetAppConfig(_ context.Context, appID string) (*config.ApplicationConfig, error) { return nil, nil } // InvokeMethod invokes user code via gRPC. func (g *Channel) InvokeMethod(ctx context.Context, req *invokev1.InvokeMethodRequest, _ string) (*invokev1.InvokeMethodResponse, error) { if g.appHealth != nil && g.appHealth.GetStatus() != apphealth.AppStatusHealthy { return nil, status.Error(codes.Internal, messages.ErrAppUnhealthy) } switch req.APIVersion() { case internalv1pb.APIVersion_V1: //nolint:nosnakecase return g.invokeMethodV1(ctx, req) default: // Reject unsupported version return nil, status.Error(codes.Unimplemented, fmt.Sprintf("Unsupported spec version: %d", req.APIVersion())) } } // invokeMethodV1 calls user applications using daprclient v1. func (g *Channel) invokeMethodV1(ctx context.Context, req *invokev1.InvokeMethodRequest) (*invokev1.InvokeMethodResponse, error) { if g.ch != nil { g.ch <- struct{}{} } // Read the request, including the data pd, err := req.ProtoWithData() if err != nil { return nil, err } md := invokev1.InternalMetadataToGrpcMetadata(ctx, pd.GetMetadata(), true) if g.appMetadataToken != "" { md.Set(securityConsts.APITokenHeader, g.appMetadataToken) } // Prepare gRPC Metadata ctx = grpcMetadata.NewOutgoingContext(context.Background(), md) var header, trailer grpcMetadata.MD opts := []grpc.CallOption{ grpc.Header(&header), grpc.Trailer(&trailer), grpc.MaxCallSendMsgSize(g.maxRequestBodySize), grpc.MaxCallRecvMsgSize(g.maxRequestBodySize), } resp, err := g.appCallbackClient.OnInvoke(ctx, pd.GetMessage(), opts...) if g.ch != nil { <-g.ch } var rsp *invokev1.InvokeMethodResponse if err != nil { // Convert status code respStatus := status.Convert(err) // Prepare response rsp = invokev1.NewInvokeMethodResponse(int32(respStatus.Code()), respStatus.Message(), respStatus.Proto().GetDetails()) } else { rsp = invokev1.NewInvokeMethodResponse(int32(codes.OK), "", nil) } rsp.WithHeaders(header). WithTrailers(trailer). WithMessage(resp) // If the data has a type_url, set that in the object too // This is necessary to support the HTTP->gRPC and gRPC->gRPC service invocation (legacy, non-proxy) paths correctly // (Note that GetTypeUrl could return an empty value, so this call becomes a no-op) rsp.WithDataTypeURL(resp.GetData().GetTypeUrl()) return rsp, nil } var emptyPbPool = sync.Pool{ New: func() any { return &emptypb.Empty{} }, } // HealthProbe performs a health probe. func (g *Channel) HealthProbe(ctx context.Context) (bool, error) { // We use the low-level method here so we can avoid allocating multiple &emptypb.Empty and use the pool in := emptyPbPool.Get() defer emptyPbPool.Put(in) out := emptyPbPool.Get() defer emptyPbPool.Put(out) err := g.conn.Invoke(ctx, "/dapr.proto.runtime.v1.AppCallbackHealthCheck/HealthCheck", in, out) return err == nil, err } // SetAppHealth sets the apphealth.AppHealth object. func (g *Channel) SetAppHealth(ah *apphealth.AppHealth) { g.appHealth = ah }
mikeee/dapr
pkg/channel/grpc/grpc_channel.go
GO
mit
5,383
/* Copyright 2021 The Dapr 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 grpc import ( "context" "encoding/json" "errors" "io" "log" "net" "net/http" "os" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" "github.com/dapr/dapr/pkg/api/grpc/metadata" channelt "github.com/dapr/dapr/pkg/channel/testing" "github.com/dapr/dapr/pkg/config" invokev1 "github.com/dapr/dapr/pkg/messaging/v1" runtimev1pb "github.com/dapr/dapr/pkg/proto/runtime/v1" securityConsts "github.com/dapr/dapr/pkg/security/consts" daprt "github.com/dapr/dapr/pkg/testing" ) // TODO: Add APIVersion testing var mockServer *channelt.MockServer func TestMain(m *testing.M) { // Setup lis, err := net.Listen("tcp", "127.0.0.1:9998") if err != nil { log.Fatalf("failed to create listener: %v", err) } grpcServer := grpc.NewServer( grpc.UnaryInterceptor(metadata.SetMetadataInContextUnary), grpc.InTapHandle(metadata.SetMetadataInTapHandle), ) mockServer = &channelt.MockServer{} go func() { runtimev1pb.RegisterAppCallbackServer(grpcServer, mockServer) runtimev1pb.RegisterAppCallbackHealthCheckServer(grpcServer, mockServer) grpcServer.Serve(lis) if err != nil { log.Fatalf("failed to start gRPC server: %v", err) } }() // Run tests code := m.Run() // Teardown grpcServer.Stop() os.Exit(code) } func createConnection(t *testing.T) *grpc.ClientConn { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) conn, err := grpc.DialContext(ctx, "localhost:9998", grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock(), ) cancel() require.NoError(t, err, "failed to connect to gRPC server") return conn } func closeConnection(t *testing.T, conn *grpc.ClientConn) { err := conn.Close() require.NoError(t, err, "failed to close client connection") } func TestInvokeMethod(t *testing.T) { conn := createConnection(t) defer closeConnection(t, conn) c := Channel{ baseAddress: "localhost:9998", appCallbackClient: runtimev1pb.NewAppCallbackClient(conn), conn: conn, appMetadataToken: "token1", maxRequestBodySize: 4 << 20, } ctx := context.Background() t.Run("successful request", func(t *testing.T) { req := invokev1.NewInvokeMethodRequest("method"). WithHTTPExtension(http.MethodPost, "param1=val1&param2=val2") defer req.Close() response, err := c.InvokeMethod(ctx, req, "") require.NoError(t, err) defer response.Close() assert.Equal(t, "application/json", response.ContentType()) actual := map[string]string{} err = json.NewDecoder(response.RawData()).Decode(&actual) require.NoError(t, err) assert.Equal(t, "POST", actual["httpverb"]) assert.Equal(t, "method", actual["method"]) assert.Equal(t, "token1", actual[securityConsts.APITokenHeader]) assert.Equal(t, "param1=val1&param2=val2", actual["querystring"]) }) t.Run("request body stream errors", func(t *testing.T) { req := invokev1.NewInvokeMethodRequest("method"). WithHTTPExtension(http.MethodPost, "param1=val1&param2=val2"). WithRawData(&daprt.ErrorReader{}) defer req.Close() response, err := c.InvokeMethod(ctx, req, "") require.Error(t, err) require.ErrorIs(t, err, io.ErrClosedPipe) if response != nil { defer response.Close() } }) } func TestHealthProbe(t *testing.T) { conn := createConnection(t) c := Channel{ baseAddress: "localhost:9998", appCallbackClient: runtimev1pb.NewAppCallbackClient(conn), conn: conn, appMetadataToken: "token1", maxRequestBodySize: 4 << 20, } ctx := context.Background() var ( success bool err error ) // OK response success, err = c.HealthProbe(ctx) require.NoError(t, err) assert.True(t, success) // Non-2xx status code mockServer.Error = errors.New("test failure") success, err = c.HealthProbe(ctx) require.Error(t, err) assert.False(t, success) // Closed connection closeConnection(t, conn) success, err = c.HealthProbe(ctx) require.Error(t, err) assert.False(t, success) } func TestCreateLocalChannelWithBaseAddress(t *testing.T) { ch := CreateLocalChannel(8080, 1, nil, config.TracingSpec{}, 1024, 1, "my.app") assert.Equal(t, "my.app:8080", ch.baseAddress) }
mikeee/dapr
pkg/channel/grpc/grpc_channel_test.go
GO
mit
4,814
/* Copyright 2021 The Dapr 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 http import ( "bytes" "context" "encoding/json" "fmt" "io" "net/http" "strconv" "strings" "time" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" commonapi "github.com/dapr/dapr/pkg/apis/common" "github.com/dapr/dapr/pkg/apphealth" "github.com/dapr/dapr/pkg/channel" "github.com/dapr/dapr/pkg/config" diag "github.com/dapr/dapr/pkg/diagnostics" diagUtils "github.com/dapr/dapr/pkg/diagnostics/utils" "github.com/dapr/dapr/pkg/messages" invokev1 "github.com/dapr/dapr/pkg/messaging/v1" "github.com/dapr/dapr/pkg/middleware" commonv1pb "github.com/dapr/dapr/pkg/proto/common/v1" internalv1pb "github.com/dapr/dapr/pkg/proto/internals/v1" "github.com/dapr/dapr/pkg/runtime/compstore" "github.com/dapr/dapr/pkg/security" securityConsts "github.com/dapr/dapr/pkg/security/consts" streamutils "github.com/dapr/kit/streams" ) const ( // HTTPStatusCode is an dapr http channel status code. HTTPStatusCode = "http.status_code" httpScheme = "http" httpsScheme = "https" appConfigEndpoint = "/dapr/config" ) // Channel is an HTTP implementation of an AppChannel. type Channel struct { client *http.Client baseAddress string ch chan struct{} compStore *compstore.ComponentStore tracingSpec *config.TracingSpec appHeaderToken string maxResponseBodySize int appHealthCheckPath string appHealth *apphealth.AppHealth middleware middleware.HTTP } // ChannelConfiguration is the configuration used to create an HTTP AppChannel. type ChannelConfiguration struct { Client *http.Client CompStore *compstore.ComponentStore Endpoint string MaxConcurrency int Middleware middleware.HTTP TracingSpec *config.TracingSpec MaxRequestBodySize int TLSClientCert string TLSClientKey string TLSRootCA string TLSRenegotiation string } // CreateHTTPChannel creates an HTTP AppChannel. func CreateHTTPChannel(config ChannelConfiguration) (channel.AppChannel, error) { c := &Channel{ middleware: config.Middleware, client: config.Client, compStore: config.CompStore, baseAddress: config.Endpoint, tracingSpec: config.TracingSpec, appHeaderToken: security.GetAppToken(), maxResponseBodySize: config.MaxRequestBodySize, } if config.MaxConcurrency > 0 { c.ch = make(chan struct{}, config.MaxConcurrency) } return c, nil } // GetAppConfig gets application config from user application // GET http://localhost:<app_port>/dapr/config func (h *Channel) GetAppConfig(ctx context.Context, appID string) (*config.ApplicationConfig, error) { req := invokev1.NewInvokeMethodRequest(appConfigEndpoint). WithHTTPExtension(http.MethodGet, ""). WithContentType(invokev1.JSONContentType). WithMetadata(map[string][]string{ "dapr-app-id": {appID}, }) defer req.Close() resp, err := h.InvokeMethod(ctx, req, "") if err != nil { return nil, err } defer resp.Close() var config config.ApplicationConfig if resp.Status().GetCode() != http.StatusOK { return &config, nil } // Get versioning info, currently only v1 is supported. headers := resp.Headers() var version string if val, ok := headers["dapr-app-config-version"]; ok && len(val.GetValues()) > 0 { version = val.GetValues()[0] } switch version { case "v1": fallthrough default: err = json.NewDecoder(resp.RawData()).Decode(&config) if err != nil { return nil, err } } return &config, nil } // InvokeMethod invokes user code via HTTP. func (h *Channel) InvokeMethod(ctx context.Context, req *invokev1.InvokeMethodRequest, appID string) (*invokev1.InvokeMethodResponse, error) { // Check if HTTP Extension is given. Otherwise, it will return error. httpExt := req.Message().GetHttpExtension() if httpExt == nil { return nil, status.Error(codes.InvalidArgument, "missing HTTP extension field") } // Go's net/http library does not support sending requests with the CONNECT method if httpExt.GetVerb() == commonv1pb.HTTPExtension_NONE || httpExt.GetVerb() == commonv1pb.HTTPExtension_CONNECT { //nolint:nosnakecase return nil, status.Error(codes.InvalidArgument, "invalid HTTP verb") } // If the request is for an internal endpoint, do not allow it if the app health status is not successful if h.baseAddress != "" && appID == "" && h.appHealth != nil && h.appHealth.GetStatus() != apphealth.AppStatusHealthy { return nil, status.Error(codes.Internal, messages.ErrAppUnhealthy) } switch req.APIVersion() { case internalv1pb.APIVersion_V1: //nolint:nosnakecase return h.invokeMethodV1(ctx, req, appID) } // Reject unsupported version return nil, status.Error(codes.Unimplemented, fmt.Sprintf("Unsupported spec version: %d", req.APIVersion())) } // SetAppHealthCheckPath sets the path where to send requests for health probes. func (h *Channel) SetAppHealthCheckPath(path string) { h.appHealthCheckPath = "/" + strings.TrimPrefix(path, "/") } // SetAppHealth sets the apphealth.AppHealth object. func (h *Channel) SetAppHealth(ah *apphealth.AppHealth) { h.appHealth = ah } // HealthProbe performs a health probe. func (h *Channel) HealthProbe(ctx context.Context) (bool, error) { channelReq, err := http.NewRequestWithContext(ctx, http.MethodGet, h.baseAddress+h.appHealthCheckPath, nil) if err != nil { return false, err } diag.DefaultHTTPMonitoring.AppHealthProbeStarted(ctx) startRequest := time.Now() channelResp, err := h.client.Do(channelReq) elapsedMs := float64(time.Since(startRequest) / time.Millisecond) if err != nil { // Errors here are network-level errors, so we are not returning them as errors // Instead, we just return a failed probe diag.DefaultHTTPMonitoring.AppHealthProbeCompleted(ctx, strconv.Itoa(http.StatusInternalServerError), elapsedMs) //nolint:nilerr return false, nil } // Drain before closing _, _ = io.Copy(io.Discard, channelResp.Body) channelResp.Body.Close() status := channelResp.StatusCode >= 200 && channelResp.StatusCode < 300 diag.DefaultHTTPMonitoring.AppHealthProbeCompleted(ctx, strconv.Itoa(channelResp.StatusCode), elapsedMs) return status, nil } func (h *Channel) invokeMethodV1(ctx context.Context, req *invokev1.InvokeMethodRequest, appID string) (*invokev1.InvokeMethodResponse, error) { channelReq, err := h.constructRequest(ctx, req, appID) if err != nil { return nil, err } if h.ch != nil { h.ch <- struct{}{} } defer func() { if h.ch != nil { <-h.ch } }() // Emit metric when request is sent diag.DefaultHTTPMonitoring.ClientRequestStarted(ctx, channelReq.Method, req.Message().GetMethod(), int64(len(req.Message().GetData().GetValue()))) startRequest := time.Now() rw := &RWRecorder{ W: &bytes.Buffer{}, } execPipeline := h.middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Send request to user application // (Body is closed below, but linter isn't detecting that) //nolint:bodyclose clientResp, clientErr := h.client.Do(r) if clientResp != nil { copyHeader(w.Header(), clientResp.Header) w.WriteHeader(clientResp.StatusCode) _, _ = io.Copy(w, clientResp.Body) } if clientErr != nil { err = clientErr } })) execPipeline.ServeHTTP(rw, channelReq) resp := rw.Result() //nolint:bodyclose elapsedMs := float64(time.Since(startRequest) / time.Millisecond) var contentLength int64 if resp != nil { if resp.Header != nil { contentLength, _ = strconv.ParseInt(resp.Header.Get("content-length"), 10, 64) } } if err != nil { diag.DefaultHTTPMonitoring.ClientRequestCompleted(ctx, channelReq.Method, req.Message().GetMethod(), strconv.Itoa(http.StatusInternalServerError), contentLength, elapsedMs) return nil, err } rsp, err := h.parseChannelResponse(req, resp) if err != nil { diag.DefaultHTTPMonitoring.ClientRequestCompleted(ctx, channelReq.Method, req.Message().GetMethod(), strconv.Itoa(http.StatusInternalServerError), contentLength, elapsedMs) return nil, err } diag.DefaultHTTPMonitoring.ClientRequestCompleted(ctx, channelReq.Method, req.Message().GetMethod(), strconv.Itoa(int(rsp.Status().GetCode())), contentLength, elapsedMs) return rsp, nil } func (h *Channel) constructRequest(ctx context.Context, req *invokev1.InvokeMethodRequest, appID string) (*http.Request, error) { // Construct app channel URI: VERB http://localhost:3000/method?query1=value1 msg := req.Message() verb := msg.GetHttpExtension().GetVerb().String() method := msg.GetMethod() var headers []commonapi.NameValuePair uri := strings.Builder{} if appID != "" { // If appID includes http(s)://, use that as base URL // Otherwise, use baseAddress if this is an internal endpoint, or the base URL from the external endpoint configuration if external if strings.HasPrefix(appID, "https://") || strings.HasPrefix(appID, "http://") { uri.WriteString(appID) } else if endpoint, ok := h.compStore.GetHTTPEndpoint(appID); ok { uri.WriteString(endpoint.Spec.BaseURL) headers = endpoint.Spec.Headers } else { uri.WriteString(h.baseAddress) } } else { uri.WriteString(h.baseAddress) } if len(method) > 0 && method[0] != '/' { uri.WriteRune('/') } uri.WriteString(method) qs := req.EncodeHTTPQueryString() if qs != "" { uri.WriteRune('?') uri.WriteString(qs) } channelReq, err := http.NewRequestWithContext(ctx, verb, uri.String(), req.RawData()) if err != nil { return nil, err } // Recover headers invokev1.InternalMetadataToHTTPHeader(ctx, req.Metadata(), channelReq.Header.Add) if ct := req.ContentType(); ct != "" { channelReq.Header.Set("content-type", ct) } else { channelReq.Header.Del("content-type") } // Configure headers from http endpoint CRD (if any) for _, hdr := range headers { channelReq.Header.Set(hdr.Name, hdr.Value.String()) } if cl := channelReq.Header.Get(invokev1.ContentLengthHeader); cl != "" { v, err := strconv.ParseInt(cl, 10, 64) if err != nil { return nil, err } channelReq.ContentLength = v } // HTTP client needs to inject traceparent header for proper tracing stack. span := diagUtils.SpanFromContext(ctx) if span.SpanContext().HasTraceID() { tp := diag.SpanContextToW3CString(span.SpanContext()) channelReq.Header.Set("traceparent", tp) } ts := diag.TraceStateToW3CString(span.SpanContext()) if ts != "" { channelReq.Header.Set("tracestate", ts) } if h.appHeaderToken != "" { channelReq.Header.Set(securityConsts.APITokenHeader, h.appHeaderToken) } return channelReq, nil } func (h *Channel) parseChannelResponse(req *invokev1.InvokeMethodRequest, channelResp *http.Response) (*invokev1.InvokeMethodResponse, error) { contentType := channelResp.Header.Get("content-type") // Limit response body if needed var body io.ReadCloser if h.maxResponseBodySize > 0 { body = streamutils.LimitReadCloser(channelResp.Body, int64(h.maxResponseBodySize)<<20) } else { body = channelResp.Body } // Convert status code rsp := invokev1. NewInvokeMethodResponse(int32(channelResp.StatusCode), "", nil). WithHTTPHeaders(channelResp.Header). WithRawData(body). WithContentType(contentType) return rsp, nil } func copyHeader(dst http.Header, src http.Header) { for k, vv := range src { for _, v := range vv { dst.Add(k, v) } } }
mikeee/dapr
pkg/channel/http/http_channel.go
GO
mit
11,919
/* Copyright 2021 The Dapr 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 http import ( "context" "encoding/json" "io" "net/http" "net/http/httptest" "strconv" "sync" "sync/atomic" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" compapi "github.com/dapr/dapr/pkg/apis/components/v1alpha1" "github.com/dapr/dapr/pkg/config" invokev1 "github.com/dapr/dapr/pkg/messaging/v1" httpMiddleware "github.com/dapr/dapr/pkg/middleware/http" "github.com/dapr/dapr/pkg/runtime/compstore" "github.com/dapr/dapr/utils" ) // testConcurrencyHandler is used for testing max concurrency. type testConcurrencyHandler struct { maxCalls int32 currentCalls *atomic.Int32 testFailed bool } func (t *testConcurrencyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { cur := t.currentCalls.Add(1) if cur > t.maxCalls { t.testFailed = true } t.currentCalls.Add(-1) io.WriteString(w, r.URL.RawQuery) } type testContentTypeHandler struct{} func (t *testContentTypeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { io.WriteString(w, r.Header.Get("Content-Type")) } type testHandlerHeaders struct{} func (t *testHandlerHeaders) ServeHTTP(w http.ResponseWriter, r *http.Request) { headers := map[string]string{} for k, v := range r.Header { headers[k] = v[0] } rsp, _ := json.Marshal(headers) io.WriteString(w, string(rsp)) } // testQueryStringHandler is used for querystring test. type testQueryStringHandler struct { serverURL string t *testing.T } func (th *testQueryStringHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { assert.Equal(th.t, th.serverURL, r.Host) io.WriteString(w, r.URL.RawQuery) } // testStatusCodeHandler is used to send responses with a given status code. type testStatusCodeHandler struct { Code int } func (t *testStatusCodeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { code, err := strconv.Atoi(r.Header.Get("x-response-status")) if err != nil || code == 0 { code = t.Code if code == 0 { code = 200 } } w.WriteHeader(code) w.Write([]byte(strconv.Itoa(code))) } // testBodyEchoHandler sends back the body it receives type testBodyEchoHandler struct{} func (t *testBodyEchoHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Header().Add("content-type", r.Header.Get("content-type")) w.WriteHeader(http.StatusOK) io.Copy(w, r.Body) } // testHeadersHandler sends back the headers it receives type testHeadersHandler struct{} func (t *testHeadersHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Header().Set("content-type", invokev1.JSONContentType) w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(r.Header) } // testUppercaseHandler responds with "true" if the body contains all-uppercase ASCII characters, or "false" otherwise type testUppercaseHandler struct{} func (t *testUppercaseHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Header().Add("content-type", "text/plain") b, err := io.ReadAll(r.Body) if err != nil { w.WriteHeader(http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) for i := 0; i < len(b); i++ { if b[i] < 'A' || b[i] > 'Z' { w.Write([]byte("false")) return } } w.Write([]byte("true")) } func TestInvokeMethodMiddlewaresPipeline(t *testing.T) { var th http.Handler = &testStatusCodeHandler{Code: http.StatusOK} server := httptest.NewServer(th) ctx := context.Background() t.Run("pipeline should be called when handlers are not empty", func(t *testing.T) { called := 0 middleware := func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { called++ next.ServeHTTP(w, r) }) } pipeline := httpMiddleware.New() pipeline.Add(httpMiddleware.Spec{ Component: compapi.Component{ ObjectMeta: metav1.ObjectMeta{Name: "test"}, Spec: compapi.ComponentSpec{Type: "middleware.http.test", Version: "v1"}, }, Implementation: middleware, }) c := Channel{ baseAddress: server.URL, client: http.DefaultClient, compStore: compstore.New(), middleware: pipeline.BuildPipelineFromSpec("test", &config.PipelineSpec{ Handlers: []config.HandlerSpec{ {Name: "test", Type: "middleware.http.test", Version: "v1"}, }, }), } fakeReq := invokev1.NewInvokeMethodRequest("method"). WithHTTPExtension(http.MethodPost, "param1=val1&param2=val2") defer fakeReq.Close() // act resp, err := c.InvokeMethod(ctx, fakeReq, "") // assert require.NoError(t, err) defer resp.Close() assert.Equal(t, 1, called) assert.Equal(t, int32(http.StatusOK), resp.Status().GetCode()) }) t.Run("request can be short-circuited by middleware pipeline", func(t *testing.T) { called := 0 middleware := func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { called++ w.WriteHeader(http.StatusBadGateway) }) } pipeline := httpMiddleware.New() pipeline.Add(httpMiddleware.Spec{ Component: compapi.Component{ ObjectMeta: metav1.ObjectMeta{Name: "test"}, Spec: compapi.ComponentSpec{Type: "middleware.http.test", Version: "v1"}, }, Implementation: middleware, }) c := Channel{ baseAddress: server.URL, client: http.DefaultClient, compStore: compstore.New(), middleware: pipeline.BuildPipelineFromSpec("test", &config.PipelineSpec{ Handlers: []config.HandlerSpec{ {Name: "test", Type: "middleware.http.test", Version: "v1"}, }, }), } fakeReq := invokev1.NewInvokeMethodRequest("method"). WithHTTPExtension(http.MethodPost, "param1=val1&param2=val2") defer fakeReq.Close() // act resp, err := c.InvokeMethod(ctx, fakeReq, "") // assert require.NoError(t, err) defer resp.Close() assert.Equal(t, 1, called) assert.Equal(t, int32(http.StatusBadGateway), resp.Status().GetCode()) }) server.Close() t.Run("test uppercase middleware", func(t *testing.T) { server = httptest.NewServer(&testBodyEchoHandler{}) defer server.Close() pipeline := httpMiddleware.New() pipeline.Add(httpMiddleware.Spec{ Component: compapi.Component{ ObjectMeta: metav1.ObjectMeta{Name: "test"}, Spec: compapi.ComponentSpec{Type: "middleware.http.test", Version: "v1"}, }, Implementation: utils.UppercaseRequestMiddleware, }) c := Channel{ baseAddress: server.URL, client: http.DefaultClient, compStore: compstore.New(), middleware: pipeline.BuildPipelineFromSpec("test", &config.PipelineSpec{ Handlers: []config.HandlerSpec{ {Name: "test", Type: "middleware.http.test", Version: "v1"}, }, }), } fakeReq := invokev1.NewInvokeMethodRequest("method"). WithHTTPExtension(http.MethodPost, "param1=val1&param2=val2"). WithRawDataString("m'illumino d'immenso"). WithContentType("text/plain") defer fakeReq.Close() // act resp, err := c.InvokeMethod(ctx, fakeReq, "") // assert require.NoError(t, err) defer resp.Close() body, _ := resp.RawDataFull() require.Equal(t, int32(http.StatusOK), resp.Status().GetCode()) assert.Equal(t, "text/plain", resp.ContentType()) assert.Equal(t, "M'ILLUMINO D'IMMENSO", string(body)) }) t.Run("test uppercase middleware on request only", func(t *testing.T) { server = httptest.NewServer(&testUppercaseHandler{}) defer server.Close() pipeline := httpMiddleware.New() pipeline.Add(httpMiddleware.Spec{ Component: compapi.Component{ ObjectMeta: metav1.ObjectMeta{Name: "test"}, Spec: compapi.ComponentSpec{Type: "middleware.http.test", Version: "v1"}, }, Implementation: utils.UppercaseRequestMiddleware, }) c := Channel{ baseAddress: server.URL, client: http.DefaultClient, compStore: compstore.New(), middleware: pipeline.BuildPipelineFromSpec("test", &config.PipelineSpec{ Handlers: []config.HandlerSpec{ {Name: "test", Type: "middleware.http.test", Version: "v1"}, }, }), } fakeReq := invokev1.NewInvokeMethodRequest("method"). WithHTTPExtension(http.MethodPost, "param1=val1&param2=val2"). WithRawDataString("helloworld"). WithContentType("text/plain") defer fakeReq.Close() // act resp, err := c.InvokeMethod(ctx, fakeReq, "") // assert require.NoError(t, err) defer resp.Close() body, _ := resp.RawDataFull() require.Equal(t, int32(http.StatusOK), resp.Status().GetCode()) assert.Equal(t, "text/plain", resp.ContentType()) assert.Equal(t, "true", string(body)) }) t.Run("test uppercase middleware on response only", func(t *testing.T) { server = httptest.NewServer(&testUppercaseHandler{}) defer server.Close() pipeline := httpMiddleware.New() pipeline.Add(httpMiddleware.Spec{ Component: compapi.Component{ ObjectMeta: metav1.ObjectMeta{Name: "test"}, Spec: compapi.ComponentSpec{Type: "middleware.http.test", Version: "v1"}, }, Implementation: utils.UppercaseResponseMiddleware, }) c := Channel{ baseAddress: server.URL, client: http.DefaultClient, compStore: compstore.New(), middleware: pipeline.BuildPipelineFromSpec("test", &config.PipelineSpec{ Handlers: []config.HandlerSpec{ {Name: "test", Type: "middleware.http.test", Version: "v1"}, }, }), } fakeReq := invokev1.NewInvokeMethodRequest("method"). WithHTTPExtension(http.MethodPost, "param1=val1&param2=val2"). WithRawDataString("helloworld"). WithContentType("text/plain") defer fakeReq.Close() // act resp, err := c.InvokeMethod(ctx, fakeReq, "") // assert require.NoError(t, err) defer resp.Close() body, _ := resp.RawDataFull() require.Equal(t, int32(http.StatusOK), resp.Status().GetCode()) assert.Equal(t, "text/plain", resp.ContentType()) assert.Equal(t, "FALSE", string(body)) }) t.Run("test uppercase middleware on both request and response", func(t *testing.T) { server = httptest.NewServer(&testUppercaseHandler{}) defer server.Close() pipeline := httpMiddleware.New() pipeline.Add(httpMiddleware.Spec{ Component: compapi.Component{ ObjectMeta: metav1.ObjectMeta{Name: "test1"}, Spec: compapi.ComponentSpec{Type: "middleware.http.test1", Version: "v1"}, }, Implementation: utils.UppercaseRequestMiddleware, }) pipeline.Add(httpMiddleware.Spec{ Component: compapi.Component{ ObjectMeta: metav1.ObjectMeta{Name: "test2"}, Spec: compapi.ComponentSpec{Type: "middleware.http.test2", Version: "v1"}, }, Implementation: utils.UppercaseResponseMiddleware, }) c := Channel{ baseAddress: server.URL, client: http.DefaultClient, compStore: compstore.New(), middleware: pipeline.BuildPipelineFromSpec("test", &config.PipelineSpec{ Handlers: []config.HandlerSpec{ {Name: "test1", Type: "middleware.http.test1", Version: "v1"}, {Name: "test2", Type: "middleware.http.test2", Version: "v1"}, }, }), } fakeReq := invokev1.NewInvokeMethodRequest("method"). WithHTTPExtension(http.MethodPost, "param1=val1&param2=val2"). WithRawDataString("helloworld"). WithContentType("text/plain") defer fakeReq.Close() // act resp, err := c.InvokeMethod(ctx, fakeReq, "") // assert require.NoError(t, err) defer resp.Close() body, _ := resp.RawDataFull() require.Equal(t, int32(http.StatusOK), resp.Status().GetCode()) assert.Equal(t, "text/plain", resp.ContentType()) assert.Equal(t, "TRUE", string(body)) }) } func TestInvokeMethodHeaders(t *testing.T) { th := &testHeadersHandler{} ctx := context.Background() server := httptest.NewServer(th) defer server.Close() t.Run("content-type is included", func(t *testing.T) { c := Channel{ baseAddress: server.URL, client: http.DefaultClient, compStore: compstore.New(), tracingSpec: &config.TracingSpec{ SamplingRate: "0", }, middleware: httpMiddleware.New().BuildPipelineFromSpec("test", nil), } fakeReq := invokev1.NewInvokeMethodRequest("method"). WithHTTPExtension(http.MethodPost, ""). WithContentType("test/dapr") defer fakeReq.Close() // act resp, err := c.InvokeMethod(ctx, fakeReq, "") // assert require.NoError(t, err) defer resp.Close() headers := map[string][]string{} err = json.NewDecoder(resp.RawData()).Decode(&headers) require.NoError(t, err) require.Len(t, headers["Content-Type"], 1) assert.Equal(t, "test/dapr", headers["Content-Type"][0]) }) t.Run("content-type is omitted when empty", func(t *testing.T) { c := Channel{ baseAddress: server.URL, client: http.DefaultClient, compStore: compstore.New(), tracingSpec: &config.TracingSpec{ SamplingRate: "0", }, middleware: httpMiddleware.New().BuildPipelineFromSpec("test", nil), } fakeReq := invokev1.NewInvokeMethodRequest("method"). WithHTTPExtension(http.MethodPost, ""). WithContentType("") defer fakeReq.Close() // act resp, err := c.InvokeMethod(ctx, fakeReq, "") // assert require.NoError(t, err) defer resp.Close() headers := map[string][]string{} err = json.NewDecoder(resp.RawData()).Decode(&headers) require.NoError(t, err) require.Empty(t, headers["Content-Type"]) }) } func TestInvokeMethod(t *testing.T) { th := &testQueryStringHandler{t: t, serverURL: ""} ctx := context.Background() server := httptest.NewServer(th) defer server.Close() t.Run("query string", func(t *testing.T) { c := Channel{ baseAddress: server.URL, client: http.DefaultClient, compStore: compstore.New(), tracingSpec: &config.TracingSpec{ SamplingRate: "0", }, middleware: httpMiddleware.New().BuildPipelineFromSpec("test", nil), } th.serverURL = server.URL[len("http://"):] fakeReq := invokev1.NewInvokeMethodRequest("method"). WithHTTPExtension(http.MethodPost, "param1=val1&param2=val2") defer fakeReq.Close() // act resp, err := c.InvokeMethod(ctx, fakeReq, "") // assert require.NoError(t, err) defer resp.Close() body, _ := resp.RawDataFull() assert.Equal(t, "param1=val1&param2=val2", string(body)) }) t.Run("tracing is enabled", func(t *testing.T) { c := Channel{ baseAddress: server.URL, client: http.DefaultClient, compStore: compstore.New(), tracingSpec: &config.TracingSpec{ SamplingRate: "1", }, middleware: httpMiddleware.New().BuildPipelineFromSpec("test", nil), } th.serverURL = server.URL[len("http://"):] fakeReq := invokev1.NewInvokeMethodRequest("method"). WithHTTPExtension(http.MethodPost, "") defer fakeReq.Close() // act resp, err := c.InvokeMethod(ctx, fakeReq, "") // assert require.NoError(t, err) defer resp.Close() body, _ := resp.RawDataFull() assert.Equal(t, "", string(body)) }) } func TestInvokeMethodMaxConcurrency(t *testing.T) { ctx := context.Background() t.Run("single concurrency", func(t *testing.T) { handler := testConcurrencyHandler{ maxCalls: 1, currentCalls: &atomic.Int32{}, } server := httptest.NewServer(&handler) c := Channel{ baseAddress: server.URL, client: http.DefaultClient, compStore: compstore.New(), ch: make(chan struct{}, 1), middleware: httpMiddleware.New().BuildPipelineFromSpec("test", nil), } // act var wg sync.WaitGroup wg.Add(5) for i := 0; i < 5; i++ { go func() { req := invokev1. NewInvokeMethodRequest("method"). WithHTTPExtension("GET", "") defer req.Close() resp, err := c.InvokeMethod(ctx, req, "") require.NoError(t, err) defer resp.Close() wg.Done() }() } wg.Wait() // assert assert.False(t, handler.testFailed) server.Close() }) t.Run("10 concurrent calls", func(t *testing.T) { handler := testConcurrencyHandler{ maxCalls: 10, currentCalls: &atomic.Int32{}, } server := httptest.NewServer(&handler) c := Channel{ baseAddress: server.URL, client: http.DefaultClient, compStore: compstore.New(), ch: make(chan struct{}, 1), middleware: httpMiddleware.New().BuildPipelineFromSpec("test", nil), } // act var wg sync.WaitGroup wg.Add(20) for i := 0; i < 20; i++ { go func() { req := invokev1. NewInvokeMethodRequest("method"). WithHTTPExtension("GET", "") defer req.Close() resp, err := c.InvokeMethod(ctx, req, "") require.NoError(t, err) defer resp.Close() wg.Done() }() } wg.Wait() // assert assert.False(t, handler.testFailed) server.Close() }) t.Run("introduce failures", func(t *testing.T) { handler := testConcurrencyHandler{ maxCalls: 5, currentCalls: &atomic.Int32{}, } server := httptest.NewServer(&handler) c := Channel{ // False address to make first calls fail baseAddress: "http://0.0.0.0:0", client: http.DefaultClient, compStore: compstore.New(), ch: make(chan struct{}, 1), middleware: httpMiddleware.New().BuildPipelineFromSpec("test", nil), } // act for i := 0; i < 20; i++ { if i == 10 { c.baseAddress = server.URL } req := invokev1. NewInvokeMethodRequest("method"). WithHTTPExtension("GET", "") defer req.Close() resp, err := c.InvokeMethod(ctx, req, "") if resp != nil { defer resp.Close() } if i < 10 { require.Error(t, err) } else { require.NoError(t, err) } } // assert assert.False(t, handler.testFailed) server.Close() }) } func TestInvokeWithHeaders(t *testing.T) { ctx := context.Background() testServer := httptest.NewServer(&testHandlerHeaders{}) c := Channel{ baseAddress: testServer.URL, client: http.DefaultClient, compStore: compstore.New(), middleware: httpMiddleware.New().BuildPipelineFromSpec("test", nil), } req := invokev1.NewInvokeMethodRequest("method"). WithMetadata(map[string][]string{ "H1": {"v1"}, "H2": {"v2"}, }). WithHTTPExtension(http.MethodPost, "") defer req.Close() // act resp, err := c.InvokeMethod(ctx, req, "") // assert require.NoError(t, err) defer resp.Close() body, _ := resp.RawDataFull() actual := map[string]string{} json.Unmarshal(body, &actual) require.NoError(t, err) assert.Contains(t, "v1", actual["H1"]) assert.Contains(t, "v2", actual["H2"]) testServer.Close() } func TestContentType(t *testing.T) { ctx := context.Background() t.Run("no default content type", func(t *testing.T) { handler := &testContentTypeHandler{} testServer := httptest.NewServer(handler) c := Channel{ baseAddress: testServer.URL, client: http.DefaultClient, compStore: compstore.New(), middleware: httpMiddleware.New().BuildPipelineFromSpec("test", nil), } req := invokev1.NewInvokeMethodRequest("method"). WithHTTPExtension(http.MethodGet, "") defer req.Close() // act resp, err := c.InvokeMethod(ctx, req, "") // assert require.NoError(t, err) defer resp.Close() body, _ := resp.RawDataFull() assert.Equal(t, "", resp.ContentType()) assert.Equal(t, []byte{}, body) testServer.Close() }) t.Run("application/json", func(t *testing.T) { handler := &testContentTypeHandler{} testServer := httptest.NewServer(handler) c := Channel{ baseAddress: testServer.URL, client: http.DefaultClient, compStore: compstore.New(), middleware: httpMiddleware.New().BuildPipelineFromSpec("test", nil), } req := invokev1.NewInvokeMethodRequest("method"). WithContentType("application/json"). WithHTTPExtension(http.MethodPost, "") defer req.Close() // act resp, err := c.InvokeMethod(ctx, req, "") // assert require.NoError(t, err) defer resp.Close() body, _ := resp.RawDataFull() assert.Equal(t, "text/plain; charset=utf-8", resp.ContentType()) assert.Equal(t, []byte("application/json"), body) testServer.Close() }) t.Run("text/plain", func(t *testing.T) { handler := &testContentTypeHandler{} testServer := httptest.NewServer(handler) c := Channel{ baseAddress: testServer.URL, client: http.DefaultClient, compStore: compstore.New(), middleware: httpMiddleware.New().BuildPipelineFromSpec("test", nil), } req := invokev1.NewInvokeMethodRequest("method"). WithContentType("text/plain"). WithHTTPExtension(http.MethodPost, "") defer req.Close() // act resp, err := c.InvokeMethod(ctx, req, "") // assert require.NoError(t, err) defer resp.Close() body, _ := resp.RawDataFull() assert.Equal(t, "text/plain; charset=utf-8", resp.ContentType()) assert.Equal(t, []byte("text/plain"), body) testServer.Close() }) } func TestContentLength(t *testing.T) { ctx := context.Background() handler := &testHandlerHeaders{} testServer := httptest.NewServer(handler) c := Channel{ baseAddress: testServer.URL, client: http.DefaultClient, compStore: compstore.New(), middleware: httpMiddleware.New().BuildPipelineFromSpec("test", nil), } req := invokev1.NewInvokeMethodRequest("method"). WithContentType("text/plain"). WithMetadata(map[string][]string{invokev1.ContentLengthHeader: {"1"}}). WithHTTPExtension(http.MethodPost, ""). WithRawDataString("1") defer req.Close() // act resp, err := c.InvokeMethod(ctx, req, "") // assert require.NoError(t, err) defer resp.Close() body, _ := resp.RawDataFull() actual := map[string]string{} json.Unmarshal(body, &actual) _, hasContentLength := actual["Content-Length"] require.NoError(t, err) assert.True(t, hasContentLength) testServer.Close() } func TestAppToken(t *testing.T) { t.Run("token present", func(t *testing.T) { ctx := context.Background() testServer := httptest.NewServer(&testHandlerHeaders{}) c := Channel{ baseAddress: testServer.URL, client: http.DefaultClient, appHeaderToken: "token1", compStore: compstore.New(), middleware: httpMiddleware.New().BuildPipelineFromSpec("test", nil), } req := invokev1.NewInvokeMethodRequest("method"). WithHTTPExtension(http.MethodPost, "") defer req.Close() // act resp, err := c.InvokeMethod(ctx, req, "") // assert require.NoError(t, err) defer resp.Close() body, _ := resp.RawDataFull() actual := map[string]string{} json.Unmarshal(body, &actual) _, hasToken := actual["Dapr-Api-Token"] require.NoError(t, err) assert.True(t, hasToken) testServer.Close() }) t.Run("token not present", func(t *testing.T) { ctx := context.Background() testServer := httptest.NewServer(&testHandlerHeaders{}) c := Channel{ baseAddress: testServer.URL, client: http.DefaultClient, compStore: compstore.New(), middleware: httpMiddleware.New().BuildPipelineFromSpec("test", nil), } req := invokev1.NewInvokeMethodRequest("method"). WithHTTPExtension(http.MethodPost, "") defer req.Close() // act resp, err := c.InvokeMethod(ctx, req, "") // assert require.NoError(t, err) defer resp.Close() body, _ := resp.RawDataFull() actual := map[string]string{} json.Unmarshal(body, &actual) _, hasToken := actual["Dapr-Api-Token"] require.NoError(t, err) assert.False(t, hasToken) testServer.Close() }) } func TestHealthProbe(t *testing.T) { ctx := context.Background() h := &testStatusCodeHandler{} testServer := httptest.NewServer(h) c := Channel{ baseAddress: testServer.URL, client: http.DefaultClient, compStore: compstore.New(), middleware: httpMiddleware.New().BuildPipelineFromSpec("test", nil), } var ( success bool err error ) // OK response success, err = c.HealthProbe(ctx) require.NoError(t, err) assert.True(t, success) // Non-2xx status code h.Code = 500 success, err = c.HealthProbe(ctx) require.NoError(t, err) assert.False(t, success) // Stopped server // Should still return no error, but a failed probe testServer.Close() success, err = c.HealthProbe(ctx) require.NoError(t, err) assert.False(t, success) } func TestNoInvalidTraceContext(t *testing.T) { ctx := context.Background() handler := &testHandlerHeaders{} testServer := httptest.NewServer(handler) c := Channel{ baseAddress: testServer.URL, client: http.DefaultClient, compStore: compstore.New(), middleware: httpMiddleware.New().BuildPipelineFromSpec("test", nil), } req := invokev1.NewInvokeMethodRequest("method"). WithContentType("text/plain"). WithMetadata(map[string][]string{invokev1.ContentLengthHeader: {"1"}}). WithHTTPExtension(http.MethodPost, ""). WithRawDataString("1") defer req.Close() // act resp, err := c.InvokeMethod(ctx, req, "") // assert require.NoError(t, err) defer resp.Close() body, _ := resp.RawDataFull() actual := map[string]string{} json.Unmarshal(body, &actual) traceparent, hasTraceparent := actual["Traceparent"] require.NoError(t, err) if hasTraceparent { assert.NotEqual(t, "00-00000000000000000000000000000000-0000000000000000-00", traceparent) } testServer.Close() }
mikeee/dapr
pkg/channel/http/http_channel_test.go
GO
mit
25,401
package http /*! Adapted from the Go 1.19.2 source code Copyright 2009 The Go Authors. All rights reserved. License: BSD (https://github.com/golang/go/blob/go1.19.2/LICENSE) */ import ( "fmt" "io" "net/http" "net/textproto" "strconv" "strings" "golang.org/x/net/http/httpguts" ) type RWRecorder struct { statusCode int h http.Header W io.ReadWriter } func (w *RWRecorder) StatusCode() int { if w.statusCode == 0 { return http.StatusOK } return w.statusCode } func (w *RWRecorder) Header() http.Header { if w.h == nil { w.h = make(http.Header) } return w.h } func (w *RWRecorder) WriteHeader(code int) { if code < 100 || code > 999 { panic(fmt.Sprintf("invalid WriteHeader code %v", code)) } w.statusCode = code } func (w *RWRecorder) Write(p []byte) (int, error) { return w.W.Write(p) } func (w *RWRecorder) Result() *http.Response { res := &http.Response{ Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, Body: io.NopCloser(w.W), StatusCode: w.StatusCode(), Header: w.h, } res.Status = fmt.Sprintf("%03d %s", res.StatusCode, http.StatusText(res.StatusCode)) res.ContentLength = parseContentLength(res.Header.Get("Content-Length")) if trailers, ok := w.h["Trailer"]; ok { res.Trailer = make(http.Header, len(trailers)) for _, k := range trailers { for _, k := range strings.Split(k, ",") { k = http.CanonicalHeaderKey(textproto.TrimString(k)) if !httpguts.ValidTrailerHeader(k) { // Ignore since forbidden by RFC 7230, section 4.1.2. continue } vv, ok := w.h[k] if !ok { continue } vv2 := make([]string, len(vv)) copy(vv2, vv) res.Trailer[k] = vv2 } } } for k, vv := range w.h { if !strings.HasPrefix(k, http.TrailerPrefix) { continue } if res.Trailer == nil { res.Trailer = make(http.Header) } for _, v := range vv { res.Trailer.Add(strings.TrimPrefix(k, http.TrailerPrefix), v) } } return res } // parseContentLength trims whitespace from s and returns -1 if no value // is set, or the value if it's >= 0. func parseContentLength(cl string) int64 { cl = textproto.TrimString(cl) if cl == "" { return -1 } n, err := strconv.ParseUint(cl, 10, 63) if err != nil { return -1 } return int64(n) }
mikeee/dapr
pkg/channel/http/rwrecorder.go
GO
mit
2,282
// Code generated by mockery v2.14.0. package testing import ( "context" "sync" mock "github.com/stretchr/testify/mock" "github.com/dapr/dapr/pkg/apphealth" "github.com/dapr/dapr/pkg/config" invokev1 "github.com/dapr/dapr/pkg/messaging/v1" ) // MockAppChannel is an autogenerated mock type for the AppChannel type type MockAppChannel struct { mock.Mock requestsReceived map[string][]byte mutex sync.Mutex } // GetAppConfig provides a mock function with given fields: func (_m *MockAppChannel) GetAppConfig(_ context.Context, _ string) (*config.ApplicationConfig, error) { ret := _m.Called() var r0 *config.ApplicationConfig if rf, ok := ret.Get(0).(func() *config.ApplicationConfig); ok { r0 = rf() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*config.ApplicationConfig) } } var r1 error if rf, ok := ret.Get(1).(func() error); ok { r1 = rf() } else { r1 = ret.Error(1) } return r0, r1 } // HealthProbe provides a mock function with given fields: ctx func (_m *MockAppChannel) HealthProbe(ctx context.Context) (bool, error) { ret := _m.Called(ctx) var r0 bool if rf, ok := ret.Get(0).(func(context.Context) bool); ok { r0 = rf(ctx) } else { r0 = ret.Get(0).(bool) } var r1 error if rf, ok := ret.Get(1).(func(context.Context) error); ok { r1 = rf(ctx) } else { r1 = ret.Error(1) } return r0, r1 } func (_m *MockAppChannel) Init() { _m.mutex.Lock() _m.requestsReceived = make(map[string][]byte) _m.mutex.Unlock() } // InvokeMethod provides a mock function with given fields: ctx, req, appID func (_m *MockAppChannel) InvokeMethod(ctx context.Context, req *invokev1.InvokeMethodRequest, appID string) (*invokev1.InvokeMethodResponse, error) { _m.mutex.Lock() if _m.requestsReceived != nil { req.WithReplay(true) pd, err := req.ProtoWithData() if err != nil { return nil, err } var data []byte if pd != nil && pd.Message != nil && pd.Message.Data != nil { data = pd.Message.Data.Value } _m.requestsReceived[req.Message().Method] = data } _m.mutex.Unlock() ret := _m.Called(ctx, req) var r0 *invokev1.InvokeMethodResponse if rf, ok := ret.Get(0).(func(context.Context, *invokev1.InvokeMethodRequest, string) *invokev1.InvokeMethodResponse); ok { r0 = rf(ctx, req, appID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*invokev1.InvokeMethodResponse) } } var r1 error if rf, ok := ret.Get(1).(func(context.Context, *invokev1.InvokeMethodRequest) error); ok { r1 = rf(ctx, req) } else { r1 = ret.Error(1) } return r0, r1 } func (_m *MockAppChannel) GetInvokedRequest() map[string][]byte { _m.mutex.Lock() defer _m.mutex.Unlock() return _m.requestsReceived } // SetAppHealth provides a mock function with given fields: ah func (_m *MockAppChannel) SetAppHealth(ah *apphealth.AppHealth) { _m.Called(ah) } type mockConstructorTestingTNewMockAppChannel interface { mock.TestingT Cleanup(func()) } // NewMockAppChannel creates a new instance of MockAppChannel. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. func NewMockAppChannel(t mockConstructorTestingTNewMockAppChannel) *MockAppChannel { mock := &MockAppChannel{} mock.Mock.Test(t) t.Cleanup(func() { mock.AssertExpectations(t) }) return mock }
mikeee/dapr
pkg/channel/testing/channel_mock.go
GO
mit
3,302
/* Copyright 2021 The Dapr 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 testing import ( context "context" "encoding/json" "fmt" "reflect" "sync" "google.golang.org/protobuf/types/known/anypb" "google.golang.org/protobuf/types/known/emptypb" "github.com/dapr/dapr/pkg/api/grpc/metadata" commonv1pb "github.com/dapr/dapr/pkg/proto/common/v1" runtimev1pb "github.com/dapr/dapr/pkg/proto/runtime/v1" ) // MockServer implementation of fake user app server. // It implements both AppCallback and AppCallbackHealthCheck. // //nolint:nosnakecase type MockServer struct { Error error Subscriptions []*runtimev1pb.TopicSubscription Bindings []string BindingEventResponse runtimev1pb.BindingEventResponse TopicEventResponseStatus runtimev1pb.TopicEventResponse_TopicEventResponseStatus ListTopicSubscriptionsResponse *runtimev1pb.ListTopicSubscriptionsResponse RequestsReceived map[string]*runtimev1pb.TopicEventBulkRequest BulkResponsePerPath map[string]*runtimev1pb.TopicEventBulkResponse initialized bool mutex sync.Mutex ValidateCloudEventExtension *map[string]interface{} } func (m *MockServer) Init() { m.initialized = true m.RequestsReceived = make(map[string]*runtimev1pb.TopicEventBulkRequest) } func (m *MockServer) OnInvoke(ctx context.Context, in *commonv1pb.InvokeRequest) (*commonv1pb.InvokeResponse, error) { md, _ := metadata.FromIncomingContext(ctx) dt := map[string]string{ "method": in.GetMethod(), } for k, v := range md { dt[k] = v[0] } dt["httpverb"] = in.GetHttpExtension().GetVerb().String() dt["querystring"] = in.GetHttpExtension().GetQuerystring() ds, _ := json.Marshal(dt) return &commonv1pb.InvokeResponse{Data: &anypb.Any{Value: ds}, ContentType: "application/json"}, m.Error } func (m *MockServer) ListTopicSubscriptions(ctx context.Context, in *emptypb.Empty) (*runtimev1pb.ListTopicSubscriptionsResponse, error) { if m.ListTopicSubscriptionsResponse.GetSubscriptions() != nil { return m.ListTopicSubscriptionsResponse, m.Error } return &runtimev1pb.ListTopicSubscriptionsResponse{ Subscriptions: m.Subscriptions, }, m.Error } func (m *MockServer) ListInputBindings(ctx context.Context, in *emptypb.Empty) (*runtimev1pb.ListInputBindingsResponse, error) { return &runtimev1pb.ListInputBindingsResponse{ Bindings: m.Bindings, }, m.Error } func (m *MockServer) OnBindingEvent(ctx context.Context, in *runtimev1pb.BindingEventRequest) (*runtimev1pb.BindingEventResponse, error) { return &m.BindingEventResponse, m.Error } func (m *MockServer) OnTopicEvent(ctx context.Context, in *runtimev1pb.TopicEventRequest) (*runtimev1pb.TopicEventResponse, error) { jsonBytes, marshalErr := in.GetExtensions().MarshalJSON() if marshalErr != nil { return nil, marshalErr } extensionsMap := map[string]interface{}{} unmarshalErr := json.Unmarshal(jsonBytes, &extensionsMap) if unmarshalErr != nil { return nil, unmarshalErr } if m.ValidateCloudEventExtension != nil { for k, v := range *m.ValidateCloudEventExtension { if val, ok := extensionsMap[k]; !ok || !reflect.DeepEqual(val, v) { return nil, fmt.Errorf("cloud event extension %s with value %s is not valid", k, val) } } } return &runtimev1pb.TopicEventResponse{ Status: m.TopicEventResponseStatus, }, m.Error } func (m *MockServer) OnBulkTopicEventAlpha1(ctx context.Context, in *runtimev1pb.TopicEventBulkRequest) (*runtimev1pb.TopicEventBulkResponse, error) { m.mutex.Lock() defer m.mutex.Unlock() if !m.initialized { m.Init() } m.RequestsReceived[in.GetPath()] = in if m.BulkResponsePerPath != nil { return m.BulkResponsePerPath[in.GetPath()], m.Error } return nil, m.Error } func (m *MockServer) HealthCheck(ctx context.Context, in *emptypb.Empty) (*runtimev1pb.HealthCheckResponse, error) { return &runtimev1pb.HealthCheckResponse{}, m.Error }
mikeee/dapr
pkg/channel/testing/grpc_channel_server_mock.go
GO
mit
4,471
package testing import ( context "context" "google.golang.org/grpc" ) // MockClientConn is a mock implementation of grpc.ClientConnInterface. type MockClientConn struct { grpc.ClientConnInterface InvokeFn func(ctx context.Context, method string, args interface{}, reply interface{}, opts ...grpc.CallOption) error } func (m *MockClientConn) Invoke(ctx context.Context, method string, args interface{}, reply interface{}, opts ...grpc.CallOption) error { return m.InvokeFn(ctx, method, args, reply, opts...) } // Close implements io.Closer. func (m *MockClientConn) Close() error { return nil }
mikeee/dapr
pkg/channel/testing/grpc_mock_client_conn.go
GO
mit
605
/* Copyright The Dapr 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. */ // Code generated by client-gen. DO NOT EDIT. package versioned import ( "fmt" discovery "k8s.io/client-go/discovery" rest "k8s.io/client-go/rest" flowcontrol "k8s.io/client-go/util/flowcontrol" componentsv1alpha1 "github.com/dapr/dapr/pkg/client/clientset/versioned/typed/components/v1alpha1" configurationv1alpha1 "github.com/dapr/dapr/pkg/client/clientset/versioned/typed/configuration/v1alpha1" ) type Interface interface { Discovery() discovery.DiscoveryInterface ComponentsV1alpha1() componentsv1alpha1.ComponentsV1alpha1Interface ConfigurationV1alpha1() configurationv1alpha1.ConfigurationV1alpha1Interface } // Clientset contains the clients for groups. Each group has exactly one // version included in a Clientset. type Clientset struct { *discovery.DiscoveryClient componentsV1alpha1 *componentsv1alpha1.ComponentsV1alpha1Client configurationV1alpha1 *configurationv1alpha1.ConfigurationV1alpha1Client } // ComponentsV1alpha1 retrieves the ComponentsV1alpha1Client func (c *Clientset) ComponentsV1alpha1() componentsv1alpha1.ComponentsV1alpha1Interface { return c.componentsV1alpha1 } // ConfigurationV1alpha1 retrieves the ConfigurationV1alpha1Client func (c *Clientset) ConfigurationV1alpha1() configurationv1alpha1.ConfigurationV1alpha1Interface { return c.configurationV1alpha1 } // Discovery retrieves the DiscoveryClient func (c *Clientset) Discovery() discovery.DiscoveryInterface { if c == nil { return nil } return c.DiscoveryClient } // NewForConfig creates a new Clientset for the given config. // If config's RateLimiter is not set and QPS and Burst are acceptable, // NewForConfig will generate a rate-limiter in configShallowCopy. func NewForConfig(c *rest.Config) (*Clientset, error) { configShallowCopy := *c if configShallowCopy.RateLimiter == nil && configShallowCopy.QPS > 0 { if configShallowCopy.Burst <= 0 { return nil, fmt.Errorf("Burst is required to be greater than 0 when RateLimiter is not set and QPS is set to greater than 0") } configShallowCopy.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(configShallowCopy.QPS, configShallowCopy.Burst) } var cs Clientset var err error cs.componentsV1alpha1, err = componentsv1alpha1.NewForConfig(&configShallowCopy) if err != nil { return nil, err } cs.configurationV1alpha1, err = configurationv1alpha1.NewForConfig(&configShallowCopy) if err != nil { return nil, err } cs.DiscoveryClient, err = discovery.NewDiscoveryClientForConfig(&configShallowCopy) if err != nil { return nil, err } return &cs, nil } // NewForConfigOrDie creates a new Clientset for the given config and // panics if there is an error in the config. func NewForConfigOrDie(c *rest.Config) *Clientset { var cs Clientset cs.componentsV1alpha1 = componentsv1alpha1.NewForConfigOrDie(c) cs.configurationV1alpha1 = configurationv1alpha1.NewForConfigOrDie(c) cs.DiscoveryClient = discovery.NewDiscoveryClientForConfigOrDie(c) return &cs } // New creates a new Clientset for the given RESTClient. func New(c rest.Interface) *Clientset { var cs Clientset cs.componentsV1alpha1 = componentsv1alpha1.New(c) cs.configurationV1alpha1 = configurationv1alpha1.New(c) cs.DiscoveryClient = discovery.NewDiscoveryClient(c) return &cs }
mikeee/dapr
pkg/client/clientset/versioned/clientset.go
GO
mit
3,814
/* Copyright The Dapr 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. */ // Code generated by client-gen. DO NOT EDIT. // This package has the automatically generated clientset. package versioned
mikeee/dapr
pkg/client/clientset/versioned/doc.go
GO
mit
684
/* Copyright The Dapr 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. */ // Code generated by client-gen. DO NOT EDIT. package fake import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/discovery" fakediscovery "k8s.io/client-go/discovery/fake" "k8s.io/client-go/testing" clientset "github.com/dapr/dapr/pkg/client/clientset/versioned" componentsv1alpha1 "github.com/dapr/dapr/pkg/client/clientset/versioned/typed/components/v1alpha1" fakecomponentsv1alpha1 "github.com/dapr/dapr/pkg/client/clientset/versioned/typed/components/v1alpha1/fake" configurationv1alpha1 "github.com/dapr/dapr/pkg/client/clientset/versioned/typed/configuration/v1alpha1" fakeconfigurationv1alpha1 "github.com/dapr/dapr/pkg/client/clientset/versioned/typed/configuration/v1alpha1/fake" ) // NewSimpleClientset returns a clientset that will respond with the provided objects. // It's backed by a very simple object tracker that processes creates, updates and deletions as-is, // without applying any validations and/or defaults. It shouldn't be considered a replacement // for a real clientset and is mostly useful in simple unit tests. func NewSimpleClientset(objects ...runtime.Object) *Clientset { o := testing.NewObjectTracker(scheme, codecs.UniversalDecoder()) for _, obj := range objects { if err := o.Add(obj); err != nil { panic(err) } } cs := &Clientset{tracker: o} cs.discovery = &fakediscovery.FakeDiscovery{Fake: &cs.Fake} cs.AddReactor("*", "*", testing.ObjectReaction(o)) cs.AddWatchReactor("*", func(action testing.Action) (handled bool, ret watch.Interface, err error) { gvr := action.GetResource() ns := action.GetNamespace() watch, err := o.Watch(gvr, ns) if err != nil { return false, nil, err } return true, watch, nil }) return cs } // Clientset implements clientset.Interface. Meant to be embedded into a // struct to get a default implementation. This makes faking out just the method // you want to test easier. type Clientset struct { testing.Fake discovery *fakediscovery.FakeDiscovery tracker testing.ObjectTracker } func (c *Clientset) Discovery() discovery.DiscoveryInterface { return c.discovery } func (c *Clientset) Tracker() testing.ObjectTracker { return c.tracker } var _ clientset.Interface = &Clientset{} // ComponentsV1alpha1 retrieves the ComponentsV1alpha1Client func (c *Clientset) ComponentsV1alpha1() componentsv1alpha1.ComponentsV1alpha1Interface { return &fakecomponentsv1alpha1.FakeComponentsV1alpha1{Fake: &c.Fake} } // ConfigurationV1alpha1 retrieves the ConfigurationV1alpha1Client func (c *Clientset) ConfigurationV1alpha1() configurationv1alpha1.ConfigurationV1alpha1Interface { return &fakeconfigurationv1alpha1.FakeConfigurationV1alpha1{Fake: &c.Fake} }
mikeee/dapr
pkg/client/clientset/versioned/fake/clientset_generated.go
GO
mit
3,270
/* Copyright The Dapr 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. */ // Code generated by client-gen. DO NOT EDIT. // This package has the automatically generated fake clientset. package fake
mikeee/dapr
pkg/client/clientset/versioned/fake/doc.go
GO
mit
684
/* Copyright The Dapr 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. */ // Code generated by client-gen. DO NOT EDIT. package fake import ( v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" schema "k8s.io/apimachinery/pkg/runtime/schema" serializer "k8s.io/apimachinery/pkg/runtime/serializer" utilruntime "k8s.io/apimachinery/pkg/util/runtime" componentsv1alpha1 "github.com/dapr/dapr/pkg/apis/components/v1alpha1" configurationv1alpha1 "github.com/dapr/dapr/pkg/apis/configuration/v1alpha1" ) var ( scheme = runtime.NewScheme() codecs = serializer.NewCodecFactory(scheme) parameterCodec = runtime.NewParameterCodec(scheme) localSchemeBuilder = runtime.SchemeBuilder{ componentsv1alpha1.AddToScheme, configurationv1alpha1.AddToScheme, } ) // AddToScheme adds all types of this clientset into the given scheme. This allows composition // of clientsets, like in: // // import ( // "k8s.io/client-go/kubernetes" // clientsetscheme "k8s.io/client-go/kubernetes/scheme" // aggregatorclientsetscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme" // ) // // kclientset, _ := kubernetes.NewForConfig(c) // _ = aggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme) // // After this, RawExtensions in Kubernetes types will serialize kube-aggregator types // correctly. var AddToScheme = localSchemeBuilder.AddToScheme func init() { v1.AddToGroupVersion(scheme, schema.GroupVersion{Version: "v1"}) utilruntime.Must(AddToScheme(scheme)) }
mikeee/dapr
pkg/client/clientset/versioned/fake/register.go
GO
mit
2,043
/* Copyright The Dapr 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. */ // Code generated by client-gen. DO NOT EDIT. // This package contains the scheme of the automatically generated clientset. package scheme
mikeee/dapr
pkg/client/clientset/versioned/scheme/doc.go
GO
mit
700
/* Copyright The Dapr 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. */ // Code generated by client-gen. DO NOT EDIT. package scheme import ( v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" schema "k8s.io/apimachinery/pkg/runtime/schema" serializer "k8s.io/apimachinery/pkg/runtime/serializer" utilruntime "k8s.io/apimachinery/pkg/util/runtime" componentsv1alpha1 "github.com/dapr/dapr/pkg/apis/components/v1alpha1" configurationv1alpha1 "github.com/dapr/dapr/pkg/apis/configuration/v1alpha1" ) var ( Scheme = runtime.NewScheme() Codecs = serializer.NewCodecFactory(Scheme) ParameterCodec = runtime.NewParameterCodec(Scheme) localSchemeBuilder = runtime.SchemeBuilder{ componentsv1alpha1.AddToScheme, configurationv1alpha1.AddToScheme, } ) // AddToScheme adds all types of this clientset into the given scheme. This allows composition // of clientsets, like in: // // import ( // "k8s.io/client-go/kubernetes" // clientsetscheme "k8s.io/client-go/kubernetes/scheme" // aggregatorclientsetscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme" // ) // // kclientset, _ := kubernetes.NewForConfig(c) // _ = aggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme) // // After this, RawExtensions in Kubernetes types will serialize kube-aggregator types // correctly. var AddToScheme = localSchemeBuilder.AddToScheme func init() { v1.AddToGroupVersion(Scheme, schema.GroupVersion{Version: "v1"}) utilruntime.Must(AddToScheme(Scheme)) }
mikeee/dapr
pkg/client/clientset/versioned/scheme/register.go
GO
mit
2,045
/* Copyright The Dapr 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. */ // Code generated by client-gen. DO NOT EDIT. package v1alpha1 import ( "context" "time" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" rest "k8s.io/client-go/rest" v1alpha1 "github.com/dapr/dapr/pkg/apis/components/v1alpha1" scheme "github.com/dapr/dapr/pkg/client/clientset/versioned/scheme" ) // ComponentsGetter has a method to return a ComponentInterface. // A group's client should implement this interface. type ComponentsGetter interface { Components(namespace string) ComponentInterface } // ComponentInterface has methods to work with Component resources. type ComponentInterface interface { Create(*v1alpha1.Component) (*v1alpha1.Component, error) Update(*v1alpha1.Component) (*v1alpha1.Component, error) Delete(name string, options *v1.DeleteOptions) error DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error Get(name string, options v1.GetOptions) (*v1alpha1.Component, error) List(opts v1.ListOptions) (*v1alpha1.ComponentList, error) Watch(opts v1.ListOptions) (watch.Interface, error) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.Component, err error) ComponentExpansion } // components implements ComponentInterface type components struct { client rest.Interface ns string } // newComponents returns a Components func newComponents(c *ComponentsV1alpha1Client, namespace string) *components { return &components{ client: c.RESTClient(), ns: namespace, } } // Get takes name of the component, and returns the corresponding component object, and an error if there is any. func (c *components) Get(name string, options v1.GetOptions) (result *v1alpha1.Component, err error) { result = &v1alpha1.Component{} err = c.client.Get(). Namespace(c.ns). Resource("components"). Name(name). VersionedParams(&options, scheme.ParameterCodec). Do(context.TODO()). Into(result) return } // List takes label and field selectors, and returns the list of Components that match those selectors. func (c *components) List(opts v1.ListOptions) (result *v1alpha1.ComponentList, err error) { var timeout time.Duration if opts.TimeoutSeconds != nil { timeout = time.Duration(*opts.TimeoutSeconds) * time.Second } result = &v1alpha1.ComponentList{} err = c.client.Get(). Namespace(c.ns). Resource("components"). VersionedParams(&opts, scheme.ParameterCodec). Timeout(timeout). Do(context.TODO()). Into(result) return } // Watch returns a watch.Interface that watches the requested components. func (c *components) Watch(opts v1.ListOptions) (watch.Interface, error) { var timeout time.Duration if opts.TimeoutSeconds != nil { timeout = time.Duration(*opts.TimeoutSeconds) * time.Second } opts.Watch = true return c.client.Get(). Namespace(c.ns). Resource("components"). VersionedParams(&opts, scheme.ParameterCodec). Timeout(timeout). Watch(context.TODO()) } // Create takes the representation of a component and creates it. Returns the server's representation of the component, and an error, if there is any. func (c *components) Create(component *v1alpha1.Component) (result *v1alpha1.Component, err error) { result = &v1alpha1.Component{} err = c.client.Post(). Namespace(c.ns). Resource("components"). Body(component). Do(context.TODO()). Into(result) return } // Update takes the representation of a component and updates it. Returns the server's representation of the component, and an error, if there is any. func (c *components) Update(component *v1alpha1.Component) (result *v1alpha1.Component, err error) { result = &v1alpha1.Component{} err = c.client.Put(). Namespace(c.ns). Resource("components"). Name(component.Name). Body(component). Do(context.TODO()). Into(result) return } // Delete takes name of the component and deletes it. Returns an error if one occurs. func (c *components) Delete(name string, options *v1.DeleteOptions) error { return c.client.Delete(). Namespace(c.ns). Resource("components"). Name(name). Body(options). Do(context.TODO()). Error() } // DeleteCollection deletes a collection of objects. func (c *components) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { var timeout time.Duration if listOptions.TimeoutSeconds != nil { timeout = time.Duration(*listOptions.TimeoutSeconds) * time.Second } return c.client.Delete(). Namespace(c.ns). Resource("components"). VersionedParams(&listOptions, scheme.ParameterCodec). Timeout(timeout). Body(options). Do(context.TODO()). Error() } // Patch applies the patch and returns the patched component. func (c *components) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.Component, err error) { result = &v1alpha1.Component{} err = c.client.Patch(pt). Namespace(c.ns). Resource("components"). SubResource(subresources...). Name(name). Body(data). Do(context.TODO()). Into(result) return }
mikeee/dapr
pkg/client/clientset/versioned/typed/components/v1alpha1/component.go
GO
mit
5,623
/* Copyright The Dapr 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. */ // Code generated by client-gen. DO NOT EDIT. package v1alpha1 import ( rest "k8s.io/client-go/rest" v1alpha1 "github.com/dapr/dapr/pkg/apis/components/v1alpha1" "github.com/dapr/dapr/pkg/client/clientset/versioned/scheme" ) type ComponentsV1alpha1Interface interface { RESTClient() rest.Interface ComponentsGetter } // ComponentsV1alpha1Client is used to interact with features provided by the components.dapr.io group. type ComponentsV1alpha1Client struct { restClient rest.Interface } func (c *ComponentsV1alpha1Client) Components(namespace string) ComponentInterface { return newComponents(c, namespace) } // NewForConfig creates a new ComponentsV1alpha1Client for the given config. func NewForConfig(c *rest.Config) (*ComponentsV1alpha1Client, error) { config := *c if err := setConfigDefaults(&config); err != nil { return nil, err } client, err := rest.RESTClientFor(&config) if err != nil { return nil, err } return &ComponentsV1alpha1Client{client}, nil } // NewForConfigOrDie creates a new ComponentsV1alpha1Client for the given config and // panics if there is an error in the config. func NewForConfigOrDie(c *rest.Config) *ComponentsV1alpha1Client { client, err := NewForConfig(c) if err != nil { panic(err) } return client } // New creates a new ComponentsV1alpha1Client for the given RESTClient. func New(c rest.Interface) *ComponentsV1alpha1Client { return &ComponentsV1alpha1Client{c} } func setConfigDefaults(config *rest.Config) error { gv := v1alpha1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" config.NegotiatedSerializer = scheme.Codecs.WithoutConversion() if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } return nil } // RESTClient returns a RESTClient that is used to communicate // with API server by this client implementation. func (c *ComponentsV1alpha1Client) RESTClient() rest.Interface { if c == nil { return nil } return c.restClient }
mikeee/dapr
pkg/client/clientset/versioned/typed/components/v1alpha1/components_client.go
GO
mit
2,540
/* Copyright The Dapr 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. */ // Code generated by client-gen. DO NOT EDIT. // This package has the automatically generated typed clients. package v1alpha1
mikeee/dapr
pkg/client/clientset/versioned/typed/components/v1alpha1/doc.go
GO
mit
687
/* Copyright The Dapr 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. */ // Code generated by client-gen. DO NOT EDIT. // Package fake has the automatically generated clients. package fake
mikeee/dapr
pkg/client/clientset/versioned/typed/components/v1alpha1/fake/doc.go
GO
mit
677
/* Copyright The Dapr 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. */ // Code generated by client-gen. DO NOT EDIT. package fake import ( v1 "k8s.io/apimachinery/pkg/apis/meta/v1" labels "k8s.io/apimachinery/pkg/labels" schema "k8s.io/apimachinery/pkg/runtime/schema" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" testing "k8s.io/client-go/testing" v1alpha1 "github.com/dapr/dapr/pkg/apis/components/v1alpha1" ) // FakeComponents implements ComponentInterface type FakeComponents struct { Fake *FakeComponentsV1alpha1 ns string } var componentsResource = schema.GroupVersionResource{Group: "components.dapr.io", Version: "v1alpha1", Resource: "components"} var componentsKind = schema.GroupVersionKind{Group: "components.dapr.io", Version: "v1alpha1", Kind: "Component"} // Get takes name of the component, and returns the corresponding component object, and an error if there is any. func (c *FakeComponents) Get(name string, options v1.GetOptions) (result *v1alpha1.Component, err error) { obj, err := c.Fake. Invokes(testing.NewGetAction(componentsResource, c.ns, name), &v1alpha1.Component{}) if obj == nil { return nil, err } return obj.(*v1alpha1.Component), err } // List takes label and field selectors, and returns the list of Components that match those selectors. func (c *FakeComponents) List(opts v1.ListOptions) (result *v1alpha1.ComponentList, err error) { obj, err := c.Fake. Invokes(testing.NewListAction(componentsResource, componentsKind, c.ns, opts), &v1alpha1.ComponentList{}) if obj == nil { return nil, err } label, _, _ := testing.ExtractFromListOptions(opts) if label == nil { label = labels.Everything() } list := &v1alpha1.ComponentList{ListMeta: obj.(*v1alpha1.ComponentList).ListMeta} for _, item := range obj.(*v1alpha1.ComponentList).Items { if label.Matches(labels.Set(item.Labels)) { list.Items = append(list.Items, item) } } return list, err } // Watch returns a watch.Interface that watches the requested components. func (c *FakeComponents) Watch(opts v1.ListOptions) (watch.Interface, error) { return c.Fake. InvokesWatch(testing.NewWatchAction(componentsResource, c.ns, opts)) } // Create takes the representation of a component and creates it. Returns the server's representation of the component, and an error, if there is any. func (c *FakeComponents) Create(component *v1alpha1.Component) (result *v1alpha1.Component, err error) { obj, err := c.Fake. Invokes(testing.NewCreateAction(componentsResource, c.ns, component), &v1alpha1.Component{}) if obj == nil { return nil, err } return obj.(*v1alpha1.Component), err } // Update takes the representation of a component and updates it. Returns the server's representation of the component, and an error, if there is any. func (c *FakeComponents) Update(component *v1alpha1.Component) (result *v1alpha1.Component, err error) { obj, err := c.Fake. Invokes(testing.NewUpdateAction(componentsResource, c.ns, component), &v1alpha1.Component{}) if obj == nil { return nil, err } return obj.(*v1alpha1.Component), err } // Delete takes name of the component and deletes it. Returns an error if one occurs. func (c *FakeComponents) Delete(name string, options *v1.DeleteOptions) error { _, err := c.Fake. Invokes(testing.NewDeleteAction(componentsResource, c.ns, name), &v1alpha1.Component{}) return err } // DeleteCollection deletes a collection of objects. func (c *FakeComponents) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { action := testing.NewDeleteCollectionAction(componentsResource, c.ns, listOptions) _, err := c.Fake.Invokes(action, &v1alpha1.ComponentList{}) return err } // Patch applies the patch and returns the patched component. func (c *FakeComponents) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.Component, err error) { obj, err := c.Fake. Invokes(testing.NewPatchSubresourceAction(componentsResource, c.ns, name, pt, data, subresources...), &v1alpha1.Component{}) if obj == nil { return nil, err } return obj.(*v1alpha1.Component), err }
mikeee/dapr
pkg/client/clientset/versioned/typed/components/v1alpha1/fake/fake_component.go
GO
mit
4,645
/* Copyright The Dapr 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. */ // Code generated by client-gen. DO NOT EDIT. package fake import ( rest "k8s.io/client-go/rest" testing "k8s.io/client-go/testing" v1alpha1 "github.com/dapr/dapr/pkg/client/clientset/versioned/typed/components/v1alpha1" ) type FakeComponentsV1alpha1 struct { *testing.Fake } func (c *FakeComponentsV1alpha1) Components(namespace string) v1alpha1.ComponentInterface { return &FakeComponents{c, namespace} } // RESTClient returns a RESTClient that is used to communicate // with API server by this client implementation. func (c *FakeComponentsV1alpha1) RESTClient() rest.Interface { var ret *rest.RESTClient return ret }
mikeee/dapr
pkg/client/clientset/versioned/typed/components/v1alpha1/fake/fake_components_client.go
GO
mit
1,194
/* Copyright The Dapr 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. */ // Code generated by client-gen. DO NOT EDIT. package v1alpha1 type ComponentExpansion interface{}
mikeee/dapr
pkg/client/clientset/versioned/typed/components/v1alpha1/generated_expansion.go
GO
mit
661
/* Copyright The Dapr 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. */ // Code generated by client-gen. DO NOT EDIT. package v1alpha1 import ( "context" "time" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" rest "k8s.io/client-go/rest" v1alpha1 "github.com/dapr/dapr/pkg/apis/configuration/v1alpha1" scheme "github.com/dapr/dapr/pkg/client/clientset/versioned/scheme" ) // ConfigurationsGetter has a method to return a ConfigurationInterface. // A group's client should implement this interface. type ConfigurationsGetter interface { Configurations(namespace string) ConfigurationInterface } // ConfigurationInterface has methods to work with Configuration resources. type ConfigurationInterface interface { Create(*v1alpha1.Configuration) (*v1alpha1.Configuration, error) Update(*v1alpha1.Configuration) (*v1alpha1.Configuration, error) Delete(name string, options *v1.DeleteOptions) error DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error Get(name string, options v1.GetOptions) (*v1alpha1.Configuration, error) List(opts v1.ListOptions) (*v1alpha1.ConfigurationList, error) Watch(opts v1.ListOptions) (watch.Interface, error) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.Configuration, err error) ConfigurationExpansion } // configurations implements ConfigurationInterface type configurations struct { client rest.Interface ns string } // newConfigurations returns a Configurations func newConfigurations(c *ConfigurationV1alpha1Client, namespace string) *configurations { return &configurations{ client: c.RESTClient(), ns: namespace, } } // Get takes name of the configuration, and returns the corresponding configuration object, and an error if there is any. func (c *configurations) Get(name string, options v1.GetOptions) (result *v1alpha1.Configuration, err error) { result = &v1alpha1.Configuration{} err = c.client.Get(). Namespace(c.ns). Resource("configurations"). Name(name). VersionedParams(&options, scheme.ParameterCodec). Do(context.TODO()). Into(result) return } // List takes label and field selectors, and returns the list of Configurations that match those selectors. func (c *configurations) List(opts v1.ListOptions) (result *v1alpha1.ConfigurationList, err error) { var timeout time.Duration if opts.TimeoutSeconds != nil { timeout = time.Duration(*opts.TimeoutSeconds) * time.Second } result = &v1alpha1.ConfigurationList{} err = c.client.Get(). Namespace(c.ns). Resource("configurations"). VersionedParams(&opts, scheme.ParameterCodec). Timeout(timeout). Do(context.TODO()). Into(result) return } // Watch returns a watch.Interface that watches the requested configurations. func (c *configurations) Watch(opts v1.ListOptions) (watch.Interface, error) { var timeout time.Duration if opts.TimeoutSeconds != nil { timeout = time.Duration(*opts.TimeoutSeconds) * time.Second } opts.Watch = true return c.client.Get(). Namespace(c.ns). Resource("configurations"). VersionedParams(&opts, scheme.ParameterCodec). Timeout(timeout). Watch(context.TODO()) } // Create takes the representation of a configuration and creates it. Returns the server's representation of the configuration, and an error, if there is any. func (c *configurations) Create(configuration *v1alpha1.Configuration) (result *v1alpha1.Configuration, err error) { result = &v1alpha1.Configuration{} err = c.client.Post(). Namespace(c.ns). Resource("configurations"). Body(configuration). Do(context.TODO()). Into(result) return } // Update takes the representation of a configuration and updates it. Returns the server's representation of the configuration, and an error, if there is any. func (c *configurations) Update(configuration *v1alpha1.Configuration) (result *v1alpha1.Configuration, err error) { result = &v1alpha1.Configuration{} err = c.client.Put(). Namespace(c.ns). Resource("configurations"). Name(configuration.Name). Body(configuration). Do(context.TODO()). Into(result) return } // Delete takes name of the configuration and deletes it. Returns an error if one occurs. func (c *configurations) Delete(name string, options *v1.DeleteOptions) error { return c.client.Delete(). Namespace(c.ns). Resource("configurations"). Name(name). Body(options). Do(context.TODO()). Error() } // DeleteCollection deletes a collection of objects. func (c *configurations) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { var timeout time.Duration if listOptions.TimeoutSeconds != nil { timeout = time.Duration(*listOptions.TimeoutSeconds) * time.Second } return c.client.Delete(). Namespace(c.ns). Resource("configurations"). VersionedParams(&listOptions, scheme.ParameterCodec). Timeout(timeout). Body(options). Do(context.TODO()). Error() } // Patch applies the patch and returns the patched configuration. func (c *configurations) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.Configuration, err error) { result = &v1alpha1.Configuration{} err = c.client.Patch(pt). Namespace(c.ns). Resource("configurations"). SubResource(subresources...). Name(name). Body(data). Do(context.TODO()). Into(result) return }
mikeee/dapr
pkg/client/clientset/versioned/typed/configuration/v1alpha1/configuration.go
GO
mit
5,897
/* Copyright The Dapr 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. */ // Code generated by client-gen. DO NOT EDIT. package v1alpha1 import ( rest "k8s.io/client-go/rest" v1alpha1 "github.com/dapr/dapr/pkg/apis/configuration/v1alpha1" "github.com/dapr/dapr/pkg/client/clientset/versioned/scheme" ) type ConfigurationV1alpha1Interface interface { RESTClient() rest.Interface ConfigurationsGetter } // ConfigurationV1alpha1Client is used to interact with features provided by the configuration.dapr.io group. type ConfigurationV1alpha1Client struct { restClient rest.Interface } func (c *ConfigurationV1alpha1Client) Configurations(namespace string) ConfigurationInterface { return newConfigurations(c, namespace) } // NewForConfig creates a new ConfigurationV1alpha1Client for the given config. func NewForConfig(c *rest.Config) (*ConfigurationV1alpha1Client, error) { config := *c if err := setConfigDefaults(&config); err != nil { return nil, err } client, err := rest.RESTClientFor(&config) if err != nil { return nil, err } return &ConfigurationV1alpha1Client{client}, nil } // NewForConfigOrDie creates a new ConfigurationV1alpha1Client for the given config and // panics if there is an error in the config. func NewForConfigOrDie(c *rest.Config) *ConfigurationV1alpha1Client { client, err := NewForConfig(c) if err != nil { panic(err) } return client } // New creates a new ConfigurationV1alpha1Client for the given RESTClient. func New(c rest.Interface) *ConfigurationV1alpha1Client { return &ConfigurationV1alpha1Client{c} } func setConfigDefaults(config *rest.Config) error { gv := v1alpha1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" config.NegotiatedSerializer = scheme.Codecs.WithoutConversion() if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } return nil } // RESTClient returns a RESTClient that is used to communicate // with API server by this client implementation. func (c *ConfigurationV1alpha1Client) RESTClient() rest.Interface { if c == nil { return nil } return c.restClient }
mikeee/dapr
pkg/client/clientset/versioned/typed/configuration/v1alpha1/configuration_client.go
GO
mit
2,601
/* Copyright The Dapr 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. */ // Code generated by client-gen. DO NOT EDIT. // This package has the automatically generated typed clients. package v1alpha1
mikeee/dapr
pkg/client/clientset/versioned/typed/configuration/v1alpha1/doc.go
GO
mit
687
/* Copyright The Dapr 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. */ // Code generated by client-gen. DO NOT EDIT. // Package fake has the automatically generated clients. package fake
mikeee/dapr
pkg/client/clientset/versioned/typed/configuration/v1alpha1/fake/doc.go
GO
mit
677
/* Copyright The Dapr 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. */ // Code generated by client-gen. DO NOT EDIT. package fake import ( v1 "k8s.io/apimachinery/pkg/apis/meta/v1" labels "k8s.io/apimachinery/pkg/labels" schema "k8s.io/apimachinery/pkg/runtime/schema" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" testing "k8s.io/client-go/testing" v1alpha1 "github.com/dapr/dapr/pkg/apis/configuration/v1alpha1" ) // FakeConfigurations implements ConfigurationInterface type FakeConfigurations struct { Fake *FakeConfigurationV1alpha1 ns string } var configurationsResource = schema.GroupVersionResource{Group: "configuration.dapr.io", Version: "v1alpha1", Resource: "configurations"} var configurationsKind = schema.GroupVersionKind{Group: "configuration.dapr.io", Version: "v1alpha1", Kind: "Configuration"} // Get takes name of the configuration, and returns the corresponding configuration object, and an error if there is any. func (c *FakeConfigurations) Get(name string, options v1.GetOptions) (result *v1alpha1.Configuration, err error) { obj, err := c.Fake. Invokes(testing.NewGetAction(configurationsResource, c.ns, name), &v1alpha1.Configuration{}) if obj == nil { return nil, err } return obj.(*v1alpha1.Configuration), err } // List takes label and field selectors, and returns the list of Configurations that match those selectors. func (c *FakeConfigurations) List(opts v1.ListOptions) (result *v1alpha1.ConfigurationList, err error) { obj, err := c.Fake. Invokes(testing.NewListAction(configurationsResource, configurationsKind, c.ns, opts), &v1alpha1.ConfigurationList{}) if obj == nil { return nil, err } label, _, _ := testing.ExtractFromListOptions(opts) if label == nil { label = labels.Everything() } list := &v1alpha1.ConfigurationList{ListMeta: obj.(*v1alpha1.ConfigurationList).ListMeta} for _, item := range obj.(*v1alpha1.ConfigurationList).Items { if label.Matches(labels.Set(item.Labels)) { list.Items = append(list.Items, item) } } return list, err } // Watch returns a watch.Interface that watches the requested configurations. func (c *FakeConfigurations) Watch(opts v1.ListOptions) (watch.Interface, error) { return c.Fake. InvokesWatch(testing.NewWatchAction(configurationsResource, c.ns, opts)) } // Create takes the representation of a configuration and creates it. Returns the server's representation of the configuration, and an error, if there is any. func (c *FakeConfigurations) Create(configuration *v1alpha1.Configuration) (result *v1alpha1.Configuration, err error) { obj, err := c.Fake. Invokes(testing.NewCreateAction(configurationsResource, c.ns, configuration), &v1alpha1.Configuration{}) if obj == nil { return nil, err } return obj.(*v1alpha1.Configuration), err } // Update takes the representation of a configuration and updates it. Returns the server's representation of the configuration, and an error, if there is any. func (c *FakeConfigurations) Update(configuration *v1alpha1.Configuration) (result *v1alpha1.Configuration, err error) { obj, err := c.Fake. Invokes(testing.NewUpdateAction(configurationsResource, c.ns, configuration), &v1alpha1.Configuration{}) if obj == nil { return nil, err } return obj.(*v1alpha1.Configuration), err } // Delete takes name of the configuration and deletes it. Returns an error if one occurs. func (c *FakeConfigurations) Delete(name string, options *v1.DeleteOptions) error { _, err := c.Fake. Invokes(testing.NewDeleteAction(configurationsResource, c.ns, name), &v1alpha1.Configuration{}) return err } // DeleteCollection deletes a collection of objects. func (c *FakeConfigurations) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { action := testing.NewDeleteCollectionAction(configurationsResource, c.ns, listOptions) _, err := c.Fake.Invokes(action, &v1alpha1.ConfigurationList{}) return err } // Patch applies the patch and returns the patched configuration. func (c *FakeConfigurations) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.Configuration, err error) { obj, err := c.Fake. Invokes(testing.NewPatchSubresourceAction(configurationsResource, c.ns, name, pt, data, subresources...), &v1alpha1.Configuration{}) if obj == nil { return nil, err } return obj.(*v1alpha1.Configuration), err }
mikeee/dapr
pkg/client/clientset/versioned/typed/configuration/v1alpha1/fake/fake_configuration.go
GO
mit
4,893
/* Copyright The Dapr 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. */ // Code generated by client-gen. DO NOT EDIT. package fake import ( rest "k8s.io/client-go/rest" testing "k8s.io/client-go/testing" v1alpha1 "github.com/dapr/dapr/pkg/client/clientset/versioned/typed/configuration/v1alpha1" ) type FakeConfigurationV1alpha1 struct { *testing.Fake } func (c *FakeConfigurationV1alpha1) Configurations(namespace string) v1alpha1.ConfigurationInterface { return &FakeConfigurations{c, namespace} } // RESTClient returns a RESTClient that is used to communicate // with API server by this client implementation. func (c *FakeConfigurationV1alpha1) RESTClient() rest.Interface { var ret *rest.RESTClient return ret }
mikeee/dapr
pkg/client/clientset/versioned/typed/configuration/v1alpha1/fake/fake_configuration_client.go
GO
mit
1,218
/* Copyright The Dapr 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. */ // Code generated by client-gen. DO NOT EDIT. package v1alpha1 type ConfigurationExpansion interface{}
mikeee/dapr
pkg/client/clientset/versioned/typed/configuration/v1alpha1/generated_expansion.go
GO
mit
665
/* Copyright The Dapr 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. */ // Code generated by informer-gen. DO NOT EDIT. package components import ( v1alpha1 "github.com/dapr/dapr/pkg/client/informers/externalversions/components/v1alpha1" internalinterfaces "github.com/dapr/dapr/pkg/client/informers/externalversions/internalinterfaces" ) // Interface provides access to each of this group's versions. type Interface interface { // V1alpha1 provides access to shared informers for resources in V1alpha1. V1alpha1() v1alpha1.Interface } type group struct { factory internalinterfaces.SharedInformerFactory namespace string tweakListOptions internalinterfaces.TweakListOptionsFunc } // New returns a new Interface. func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { return &group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } // V1alpha1 returns a new v1alpha1.Interface. func (g *group) V1alpha1() v1alpha1.Interface { return v1alpha1.New(g.factory, g.namespace, g.tweakListOptions) }
mikeee/dapr
pkg/client/informers/externalversions/components/interface.go
GO
mit
1,619
/* Copyright The Dapr 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. */ // Code generated by informer-gen. DO NOT EDIT. package v1alpha1 import ( time "time" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" watch "k8s.io/apimachinery/pkg/watch" cache "k8s.io/client-go/tools/cache" componentsv1alpha1 "github.com/dapr/dapr/pkg/apis/components/v1alpha1" versioned "github.com/dapr/dapr/pkg/client/clientset/versioned" internalinterfaces "github.com/dapr/dapr/pkg/client/informers/externalversions/internalinterfaces" v1alpha1 "github.com/dapr/dapr/pkg/client/listers/components/v1alpha1" ) // ComponentInformer provides access to a shared informer and lister for // Components. type ComponentInformer interface { Informer() cache.SharedIndexInformer Lister() v1alpha1.ComponentLister } type componentInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc namespace string } // NewComponentInformer constructs a new informer for Component type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. func NewComponentInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewFilteredComponentInformer(client, namespace, resyncPeriod, indexers, nil) } // NewFilteredComponentInformer constructs a new informer for Component type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. func NewFilteredComponentInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { return cache.NewSharedIndexInformer( &cache.ListWatch{ ListFunc: func(options v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { tweakListOptions(&options) } return client.ComponentsV1alpha1().Components(namespace).List(options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } return client.ComponentsV1alpha1().Components(namespace).Watch(options) }, }, &componentsv1alpha1.Component{}, resyncPeriod, indexers, ) } func (f *componentInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { return NewFilteredComponentInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) } func (f *componentInformer) Informer() cache.SharedIndexInformer { return f.factory.InformerFor(&componentsv1alpha1.Component{}, f.defaultInformer) } func (f *componentInformer) Lister() v1alpha1.ComponentLister { return v1alpha1.NewComponentLister(f.Informer().GetIndexer()) }
mikeee/dapr
pkg/client/informers/externalversions/components/v1alpha1/component.go
GO
mit
3,619
/* Copyright The Dapr 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. */ // Code generated by informer-gen. DO NOT EDIT. package v1alpha1 import ( internalinterfaces "github.com/dapr/dapr/pkg/client/informers/externalversions/internalinterfaces" ) // Interface provides access to all the informers in this group version. type Interface interface { // Components returns a ComponentInformer. Components() ComponentInformer } type version struct { factory internalinterfaces.SharedInformerFactory namespace string tweakListOptions internalinterfaces.TweakListOptionsFunc } // New returns a new Interface. func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } // Components returns a ComponentInformer. func (v *version) Components() ComponentInformer { return &componentInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} }
mikeee/dapr
pkg/client/informers/externalversions/components/v1alpha1/interface.go
GO
mit
1,553
/* Copyright The Dapr 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. */ // Code generated by informer-gen. DO NOT EDIT. package configuration import ( v1alpha1 "github.com/dapr/dapr/pkg/client/informers/externalversions/configuration/v1alpha1" internalinterfaces "github.com/dapr/dapr/pkg/client/informers/externalversions/internalinterfaces" ) // Interface provides access to each of this group's versions. type Interface interface { // V1alpha1 provides access to shared informers for resources in V1alpha1. V1alpha1() v1alpha1.Interface } type group struct { factory internalinterfaces.SharedInformerFactory namespace string tweakListOptions internalinterfaces.TweakListOptionsFunc } // New returns a new Interface. func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { return &group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } // V1alpha1 returns a new v1alpha1.Interface. func (g *group) V1alpha1() v1alpha1.Interface { return v1alpha1.New(g.factory, g.namespace, g.tweakListOptions) }
mikeee/dapr
pkg/client/informers/externalversions/configuration/interface.go
GO
mit
1,625
/* Copyright The Dapr 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. */ // Code generated by informer-gen. DO NOT EDIT. package v1alpha1 import ( time "time" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" watch "k8s.io/apimachinery/pkg/watch" cache "k8s.io/client-go/tools/cache" configurationv1alpha1 "github.com/dapr/dapr/pkg/apis/configuration/v1alpha1" versioned "github.com/dapr/dapr/pkg/client/clientset/versioned" internalinterfaces "github.com/dapr/dapr/pkg/client/informers/externalversions/internalinterfaces" v1alpha1 "github.com/dapr/dapr/pkg/client/listers/configuration/v1alpha1" ) // ConfigurationInformer provides access to a shared informer and lister for // Configurations. type ConfigurationInformer interface { Informer() cache.SharedIndexInformer Lister() v1alpha1.ConfigurationLister } type configurationInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc namespace string } // NewConfigurationInformer constructs a new informer for Configuration type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. func NewConfigurationInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewFilteredConfigurationInformer(client, namespace, resyncPeriod, indexers, nil) } // NewFilteredConfigurationInformer constructs a new informer for Configuration type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. func NewFilteredConfigurationInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { return cache.NewSharedIndexInformer( &cache.ListWatch{ ListFunc: func(options v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { tweakListOptions(&options) } return client.ConfigurationV1alpha1().Configurations(namespace).List(options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } return client.ConfigurationV1alpha1().Configurations(namespace).Watch(options) }, }, &configurationv1alpha1.Configuration{}, resyncPeriod, indexers, ) } func (f *configurationInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { return NewFilteredConfigurationInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) } func (f *configurationInformer) Informer() cache.SharedIndexInformer { return f.factory.InformerFor(&configurationv1alpha1.Configuration{}, f.defaultInformer) } func (f *configurationInformer) Lister() v1alpha1.ConfigurationLister { return v1alpha1.NewConfigurationLister(f.Informer().GetIndexer()) }
mikeee/dapr
pkg/client/informers/externalversions/configuration/v1alpha1/configuration.go
GO
mit
3,728
/* Copyright The Dapr 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. */ // Code generated by informer-gen. DO NOT EDIT. package v1alpha1 import ( internalinterfaces "github.com/dapr/dapr/pkg/client/informers/externalversions/internalinterfaces" ) // Interface provides access to all the informers in this group version. type Interface interface { // Configurations returns a ConfigurationInformer. Configurations() ConfigurationInformer } type version struct { factory internalinterfaces.SharedInformerFactory namespace string tweakListOptions internalinterfaces.TweakListOptionsFunc } // New returns a new Interface. func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } // Configurations returns a ConfigurationInformer. func (v *version) Configurations() ConfigurationInformer { return &configurationInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} }
mikeee/dapr
pkg/client/informers/externalversions/configuration/v1alpha1/interface.go
GO
mit
1,589
/* Copyright The Dapr 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. */ // Code generated by informer-gen. DO NOT EDIT. package externalversions import ( reflect "reflect" sync "sync" time "time" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" schema "k8s.io/apimachinery/pkg/runtime/schema" cache "k8s.io/client-go/tools/cache" versioned "github.com/dapr/dapr/pkg/client/clientset/versioned" components "github.com/dapr/dapr/pkg/client/informers/externalversions/components" configuration "github.com/dapr/dapr/pkg/client/informers/externalversions/configuration" internalinterfaces "github.com/dapr/dapr/pkg/client/informers/externalversions/internalinterfaces" ) // SharedInformerOption defines the functional option type for SharedInformerFactory. type SharedInformerOption func(*sharedInformerFactory) *sharedInformerFactory type sharedInformerFactory struct { client versioned.Interface namespace string tweakListOptions internalinterfaces.TweakListOptionsFunc lock sync.Mutex defaultResync time.Duration customResync map[reflect.Type]time.Duration informers map[reflect.Type]cache.SharedIndexInformer // startedInformers is used for tracking which informers have been started. // This allows Start() to be called multiple times safely. startedInformers map[reflect.Type]bool } // WithCustomResyncConfig sets a custom resync period for the specified informer types. func WithCustomResyncConfig(resyncConfig map[v1.Object]time.Duration) SharedInformerOption { return func(factory *sharedInformerFactory) *sharedInformerFactory { for k, v := range resyncConfig { factory.customResync[reflect.TypeOf(k)] = v } return factory } } // WithTweakListOptions sets a custom filter on all listers of the configured SharedInformerFactory. func WithTweakListOptions(tweakListOptions internalinterfaces.TweakListOptionsFunc) SharedInformerOption { return func(factory *sharedInformerFactory) *sharedInformerFactory { factory.tweakListOptions = tweakListOptions return factory } } // WithNamespace limits the SharedInformerFactory to the specified namespace. func WithNamespace(namespace string) SharedInformerOption { return func(factory *sharedInformerFactory) *sharedInformerFactory { factory.namespace = namespace return factory } } // NewSharedInformerFactory constructs a new instance of sharedInformerFactory for all namespaces. func NewSharedInformerFactory(client versioned.Interface, defaultResync time.Duration) SharedInformerFactory { return NewSharedInformerFactoryWithOptions(client, defaultResync) } // NewFilteredSharedInformerFactory constructs a new instance of sharedInformerFactory. // Listers obtained via this SharedInformerFactory will be subject to the same filters // as specified here. // Deprecated: Please use NewSharedInformerFactoryWithOptions instead func NewFilteredSharedInformerFactory(client versioned.Interface, defaultResync time.Duration, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) SharedInformerFactory { return NewSharedInformerFactoryWithOptions(client, defaultResync, WithNamespace(namespace), WithTweakListOptions(tweakListOptions)) } // NewSharedInformerFactoryWithOptions constructs a new instance of a SharedInformerFactory with additional options. func NewSharedInformerFactoryWithOptions(client versioned.Interface, defaultResync time.Duration, options ...SharedInformerOption) SharedInformerFactory { factory := &sharedInformerFactory{ client: client, namespace: v1.NamespaceAll, defaultResync: defaultResync, informers: make(map[reflect.Type]cache.SharedIndexInformer), startedInformers: make(map[reflect.Type]bool), customResync: make(map[reflect.Type]time.Duration), } // Apply all options for _, opt := range options { factory = opt(factory) } return factory } // Start initializes all requested informers. func (f *sharedInformerFactory) Start(stopCh <-chan struct{}) { f.lock.Lock() defer f.lock.Unlock() for informerType, informer := range f.informers { if !f.startedInformers[informerType] { go informer.Run(stopCh) f.startedInformers[informerType] = true } } } // WaitForCacheSync waits for all started informers' cache were synced. func (f *sharedInformerFactory) WaitForCacheSync(stopCh <-chan struct{}) map[reflect.Type]bool { informers := func() map[reflect.Type]cache.SharedIndexInformer { f.lock.Lock() defer f.lock.Unlock() informers := map[reflect.Type]cache.SharedIndexInformer{} for informerType, informer := range f.informers { if f.startedInformers[informerType] { informers[informerType] = informer } } return informers }() res := map[reflect.Type]bool{} for informType, informer := range informers { res[informType] = cache.WaitForCacheSync(stopCh, informer.HasSynced) } return res } // InternalInformerFor returns the SharedIndexInformer for obj using an internal // client. func (f *sharedInformerFactory) InformerFor(obj runtime.Object, newFunc internalinterfaces.NewInformerFunc) cache.SharedIndexInformer { f.lock.Lock() defer f.lock.Unlock() informerType := reflect.TypeOf(obj) informer, exists := f.informers[informerType] if exists { return informer } resyncPeriod, exists := f.customResync[informerType] if !exists { resyncPeriod = f.defaultResync } informer = newFunc(f.client, resyncPeriod) f.informers[informerType] = informer return informer } // SharedInformerFactory provides shared informers for resources in all known // API group versions. type SharedInformerFactory interface { internalinterfaces.SharedInformerFactory ForResource(resource schema.GroupVersionResource) (GenericInformer, error) WaitForCacheSync(stopCh <-chan struct{}) map[reflect.Type]bool Components() components.Interface Configuration() configuration.Interface } func (f *sharedInformerFactory) Components() components.Interface { return components.New(f, f.namespace, f.tweakListOptions) } func (f *sharedInformerFactory) Configuration() configuration.Interface { return configuration.New(f, f.namespace, f.tweakListOptions) }
mikeee/dapr
pkg/client/informers/externalversions/factory.go
GO
mit
6,666
/* Copyright The Dapr 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. */ // Code generated by informer-gen. DO NOT EDIT. package externalversions import ( "fmt" schema "k8s.io/apimachinery/pkg/runtime/schema" cache "k8s.io/client-go/tools/cache" v1alpha1 "github.com/dapr/dapr/pkg/apis/components/v1alpha1" configurationv1alpha1 "github.com/dapr/dapr/pkg/apis/configuration/v1alpha1" ) // GenericInformer is type of SharedIndexInformer which will locate and delegate to other // sharedInformers based on type type GenericInformer interface { Informer() cache.SharedIndexInformer Lister() cache.GenericLister } type genericInformer struct { informer cache.SharedIndexInformer resource schema.GroupResource } // Informer returns the SharedIndexInformer. func (f *genericInformer) Informer() cache.SharedIndexInformer { return f.informer } // Lister returns the GenericLister. func (f *genericInformer) Lister() cache.GenericLister { return cache.NewGenericLister(f.Informer().GetIndexer(), f.resource) } // ForResource gives generic access to a shared informer of the matching type // TODO extend this to unknown resources with a client pool func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) { switch resource { // Group=components.dapr.io, Version=v1alpha1 case v1alpha1.SchemeGroupVersion.WithResource("components"): return &genericInformer{resource: resource.GroupResource(), informer: f.Components().V1alpha1().Components().Informer()}, nil // Group=configuration.dapr.io, Version=v1alpha1 case configurationv1alpha1.SchemeGroupVersion.WithResource("configurations"): return &genericInformer{resource: resource.GroupResource(), informer: f.Configuration().V1alpha1().Configurations().Informer()}, nil } return nil, fmt.Errorf("no informer found for %v", resource) }
mikeee/dapr
pkg/client/informers/externalversions/generic.go
GO
mit
2,347
/* Copyright The Dapr 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. */ // Code generated by informer-gen. DO NOT EDIT. package internalinterfaces import ( time "time" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" cache "k8s.io/client-go/tools/cache" versioned "github.com/dapr/dapr/pkg/client/clientset/versioned" ) // NewInformerFunc takes versioned.Interface and time.Duration to return a SharedIndexInformer. type NewInformerFunc func(versioned.Interface, time.Duration) cache.SharedIndexInformer // SharedInformerFactory a small interface to allow for adding an informer without an import cycle type SharedInformerFactory interface { Start(stopCh <-chan struct{}) InformerFor(obj runtime.Object, newFunc NewInformerFunc) cache.SharedIndexInformer } // TweakListOptionsFunc is a function that transforms a v1.ListOptions. type TweakListOptionsFunc func(*v1.ListOptions)
mikeee/dapr
pkg/client/informers/externalversions/internalinterfaces/factory_interfaces.go
GO
mit
1,414
/* Copyright The Dapr 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. */ // Code generated by lister-gen. DO NOT EDIT. package v1alpha1 import ( "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/labels" "k8s.io/client-go/tools/cache" v1alpha1 "github.com/dapr/dapr/pkg/apis/components/v1alpha1" ) // ComponentLister helps list Components. type ComponentLister interface { // List lists all Components in the indexer. List(selector labels.Selector) (ret []*v1alpha1.Component, err error) // Components returns an object that can list and get Components. Components(namespace string) ComponentNamespaceLister ComponentListerExpansion } // componentLister implements the ComponentLister interface. type componentLister struct { indexer cache.Indexer } // NewComponentLister returns a new ComponentLister. func NewComponentLister(indexer cache.Indexer) ComponentLister { return &componentLister{indexer: indexer} } // List lists all Components in the indexer. func (s *componentLister) List(selector labels.Selector) (ret []*v1alpha1.Component, err error) { err = cache.ListAll(s.indexer, selector, func(m interface{}) { ret = append(ret, m.(*v1alpha1.Component)) }) return ret, err } // Components returns an object that can list and get Components. func (s *componentLister) Components(namespace string) ComponentNamespaceLister { return componentNamespaceLister{indexer: s.indexer, namespace: namespace} } // ComponentNamespaceLister helps list and get Components. type ComponentNamespaceLister interface { // List lists all Components in the indexer for a given namespace. List(selector labels.Selector) (ret []*v1alpha1.Component, err error) // Get retrieves the Component from the indexer for a given namespace and name. Get(name string) (*v1alpha1.Component, error) ComponentNamespaceListerExpansion } // componentNamespaceLister implements the ComponentNamespaceLister // interface. type componentNamespaceLister struct { indexer cache.Indexer namespace string } // List lists all Components in the indexer for a given namespace. func (s componentNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Component, err error) { err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { ret = append(ret, m.(*v1alpha1.Component)) }) return ret, err } // Get retrieves the Component from the indexer for a given namespace and name. func (s componentNamespaceLister) Get(name string) (*v1alpha1.Component, error) { obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) if err != nil { return nil, err } if !exists { return nil, errors.NewNotFound(v1alpha1.Resource("component"), name) } return obj.(*v1alpha1.Component), nil }
mikeee/dapr
pkg/client/listers/components/v1alpha1/component.go
GO
mit
3,228
/* Copyright The Dapr 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. */ // Code generated by lister-gen. DO NOT EDIT. package v1alpha1 // ComponentListerExpansion allows custom methods to be added to // ComponentLister. type ComponentListerExpansion interface{} // ComponentNamespaceListerExpansion allows custom methods to be added to // ComponentNamespaceLister. type ComponentNamespaceListerExpansion interface{}
mikeee/dapr
pkg/client/listers/components/v1alpha1/expansion_generated.go
GO
mit
907
/* Copyright The Dapr 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. */ // Code generated by lister-gen. DO NOT EDIT. package v1alpha1 import ( "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/labels" "k8s.io/client-go/tools/cache" v1alpha1 "github.com/dapr/dapr/pkg/apis/configuration/v1alpha1" ) // ConfigurationLister helps list Configurations. type ConfigurationLister interface { // List lists all Configurations in the indexer. List(selector labels.Selector) (ret []*v1alpha1.Configuration, err error) // Configurations returns an object that can list and get Configurations. Configurations(namespace string) ConfigurationNamespaceLister ConfigurationListerExpansion } // configurationLister implements the ConfigurationLister interface. type configurationLister struct { indexer cache.Indexer } // NewConfigurationLister returns a new ConfigurationLister. func NewConfigurationLister(indexer cache.Indexer) ConfigurationLister { return &configurationLister{indexer: indexer} } // List lists all Configurations in the indexer. func (s *configurationLister) List(selector labels.Selector) (ret []*v1alpha1.Configuration, err error) { err = cache.ListAll(s.indexer, selector, func(m interface{}) { ret = append(ret, m.(*v1alpha1.Configuration)) }) return ret, err } // Configurations returns an object that can list and get Configurations. func (s *configurationLister) Configurations(namespace string) ConfigurationNamespaceLister { return configurationNamespaceLister{indexer: s.indexer, namespace: namespace} } // ConfigurationNamespaceLister helps list and get Configurations. type ConfigurationNamespaceLister interface { // List lists all Configurations in the indexer for a given namespace. List(selector labels.Selector) (ret []*v1alpha1.Configuration, err error) // Get retrieves the Configuration from the indexer for a given namespace and name. Get(name string) (*v1alpha1.Configuration, error) ConfigurationNamespaceListerExpansion } // configurationNamespaceLister implements the ConfigurationNamespaceLister // interface. type configurationNamespaceLister struct { indexer cache.Indexer namespace string } // List lists all Configurations in the indexer for a given namespace. func (s configurationNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Configuration, err error) { err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { ret = append(ret, m.(*v1alpha1.Configuration)) }) return ret, err } // Get retrieves the Configuration from the indexer for a given namespace and name. func (s configurationNamespaceLister) Get(name string) (*v1alpha1.Configuration, error) { obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) if err != nil { return nil, err } if !exists { return nil, errors.NewNotFound(v1alpha1.Resource("configuration"), name) } return obj.(*v1alpha1.Configuration), nil }
mikeee/dapr
pkg/client/listers/configuration/v1alpha1/configuration.go
GO
mit
3,423
/* Copyright The Dapr 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. */ // Code generated by lister-gen. DO NOT EDIT. package v1alpha1 // ConfigurationListerExpansion allows custom methods to be added to // ConfigurationLister. type ConfigurationListerExpansion interface{} // ConfigurationNamespaceListerExpansion allows custom methods to be added to // ConfigurationNamespaceLister. type ConfigurationNamespaceListerExpansion interface{}
mikeee/dapr
pkg/client/listers/configuration/v1alpha1/expansion_generated.go
GO
mit
931
/* Copyright 2022 The Dapr 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 bindings import ( "context" "fmt" "io" "sync" "sync/atomic" "github.com/dapr/components-contrib/bindings" "github.com/dapr/dapr/pkg/components/pluggable" proto "github.com/dapr/dapr/pkg/proto/components/v1" "github.com/dapr/kit/logger" ) // grpcInputBinding is a implementation of a inputbinding over a gRPC Protocol. type grpcInputBinding struct { *pluggable.GRPCConnector[proto.InputBindingClient] bindings.InputBinding logger logger.Logger closed atomic.Bool wg sync.WaitGroup closeCh chan struct{} } // Init initializes the grpc inputbinding passing out the metadata to the grpc component. func (b *grpcInputBinding) Init(ctx context.Context, metadata bindings.Metadata) error { if err := b.Dial(metadata.Name); err != nil { return err } protoMetadata := &proto.MetadataRequest{ Properties: metadata.Properties, } _, err := b.Client.Init(b.Context, &proto.InputBindingInitRequest{ Metadata: protoMetadata, }) return err } type readHandler = func(*proto.ReadResponse) // adaptHandler returns a non-error function that handle the message with the given handler and ack when returns. // //nolint:nosnakecase func (b *grpcInputBinding) adaptHandler(ctx context.Context, streamingPull proto.InputBinding_ReadClient, handler bindings.Handler) readHandler { safeSend := &sync.Mutex{} return func(msg *proto.ReadResponse) { var contentType *string if len(msg.GetContentType()) != 0 { contentType = &msg.ContentType } m := bindings.ReadResponse{ Data: msg.GetData(), Metadata: msg.GetMetadata(), ContentType: contentType, } var respErr *proto.AckResponseError bts, err := handler(ctx, &m) if err != nil { b.logger.Errorf("error when handling message for message: %s", msg.GetMessageId()) respErr = &proto.AckResponseError{ Message: err.Error(), } } // As per documentation: // When using streams, // one must take care to avoid calling either SendMsg or RecvMsg multiple times against the same Stream from different goroutines. // In other words, it's safe to have a goroutine calling SendMsg and another goroutine calling RecvMsg on the same stream at the same time. // But it is not safe to call SendMsg on the same stream in different goroutines, or to call RecvMsg on the same stream in different goroutines. // https://github.com/grpc/grpc-go/blob/master/Documentation/concurrency.md#streams safeSend.Lock() defer safeSend.Unlock() if err := streamingPull.Send(&proto.ReadRequest{ ResponseData: bts, ResponseError: respErr, MessageId: msg.GetMessageId(), }); err != nil { b.logger.Errorf("error when ack'ing message %s", msg.GetMessageId()) } } } // Read starts a bi-di stream reading messages from component and handling it used the given handler. func (b *grpcInputBinding) Read(ctx context.Context, handler bindings.Handler) error { readStream, err := b.Client.Read(ctx) if err != nil { return fmt.Errorf("unable to read from binding: %w", err) } streamCtx, cancel := context.WithCancel(readStream.Context()) handle := b.adaptHandler(streamCtx, readStream, handler) b.wg.Add(2) // Cancel on input binding close. go func() { defer b.wg.Done() defer cancel() select { case <-b.closeCh: case <-streamCtx.Done(): } }() go func() { defer b.wg.Done() defer cancel() for { msg, err := readStream.Recv() if err == io.EOF { // no more reads return } // TODO reconnect on error if err != nil { b.logger.Errorf("failed to receive message: %v", err) return } b.wg.Add(1) go func() { defer b.wg.Done() handle(msg) }() } }() return nil } func (b *grpcInputBinding) Close() error { defer b.wg.Wait() if b.closed.CompareAndSwap(false, true) { close(b.closeCh) } return b.InputBinding.Close() } // inputFromConnector creates a new GRPC inputbinding using the given underlying connector. func inputFromConnector(l logger.Logger, connector *pluggable.GRPCConnector[proto.InputBindingClient]) *grpcInputBinding { return &grpcInputBinding{ GRPCConnector: connector, logger: l, closeCh: make(chan struct{}), } } // NewGRPCInputBinding creates a new grpc inputbindingusing the given socket factory. func NewGRPCInputBinding(l logger.Logger, socket string) *grpcInputBinding { return inputFromConnector(l, pluggable.NewGRPCConnector(socket, proto.NewInputBindingClient)) } // newGRPCInputBinding creates a new input binding for the given pluggable component. func newGRPCInputBinding(dialer pluggable.GRPCConnectionDialer) func(l logger.Logger) bindings.InputBinding { return func(l logger.Logger) bindings.InputBinding { return inputFromConnector(l, pluggable.NewGRPCConnectorWithDialer(dialer, proto.NewInputBindingClient)) } } func init() { //nolint:nosnakecase pluggable.AddServiceDiscoveryCallback(proto.InputBinding_ServiceDesc.ServiceName, func(name string, dialer pluggable.GRPCConnectionDialer) { DefaultRegistry.RegisterInputBinding(newGRPCInputBinding(dialer), name) }) }
mikeee/dapr
pkg/components/bindings/input_pluggable.go
GO
mit
5,600
/* Copyright 2022 The Dapr 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 bindings import ( "context" "errors" "fmt" "net" "os" "runtime" "sync" "sync/atomic" "testing" guuid "github.com/google/uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/grpc" "github.com/dapr/components-contrib/bindings" contribMetadata "github.com/dapr/components-contrib/metadata" "github.com/dapr/dapr/pkg/components/pluggable" proto "github.com/dapr/dapr/pkg/proto/components/v1" testingGrpc "github.com/dapr/dapr/pkg/testing/grpc" "github.com/dapr/kit/logger" ) type inputBindingServer struct { proto.UnimplementedInputBindingServer initCalled atomic.Int64 initErr error onInitCalled func(*proto.InputBindingInitRequest) readCalled atomic.Int64 readResponseChan chan *proto.ReadResponse readErr error onReadRequestReceived func(*proto.ReadRequest) } func (b *inputBindingServer) Init(_ context.Context, req *proto.InputBindingInitRequest) (*proto.InputBindingInitResponse, error) { b.initCalled.Add(1) if b.onInitCalled != nil { b.onInitCalled(req) } return &proto.InputBindingInitResponse{}, b.initErr } //nolint:nosnakecase func (b *inputBindingServer) Read(stream proto.InputBinding_ReadServer) error { b.readCalled.Add(1) if b.onReadRequestReceived != nil { go func() { for { msg, err := stream.Recv() if err != nil { return } b.onReadRequestReceived(msg) } }() } if b.readResponseChan != nil { for resp := range b.readResponseChan { if err := stream.Send(resp); err != nil { return err } } } return b.readErr } func (b *inputBindingServer) Ping(context.Context, *proto.PingRequest) (*proto.PingResponse, error) { return &proto.PingResponse{}, nil } var testLogger = logger.NewLogger("bindings-test-pluggable-logger") func TestInputBindingCalls(t *testing.T) { getInputBinding := testingGrpc.TestServerFor(testLogger, func(s *grpc.Server, svc *inputBindingServer) { proto.RegisterInputBindingServer(s, svc) }, func(cci grpc.ClientConnInterface) *grpcInputBinding { client := proto.NewInputBindingClient(cci) inbinding := inputFromConnector(testLogger, pluggable.NewGRPCConnector("/tmp/socket.sock", proto.NewInputBindingClient)) inbinding.Client = client return inbinding }) if runtime.GOOS != "windows" { t.Run("test init should populate features and call grpc init", func(t *testing.T) { const ( fakeName = "name" fakeType = "type" fakeVersion = "v1" fakeComponentName = "component" fakeSocketFolder = "/tmp" ) uniqueID := guuid.New().String() socket := fmt.Sprintf("%s/%s.sock", fakeSocketFolder, uniqueID) defer os.Remove(socket) connector := pluggable.NewGRPCConnector(socket, proto.NewInputBindingClient) defer connector.Close() listener, err := net.Listen("unix", socket) require.NoError(t, err) defer listener.Close() s := grpc.NewServer() srv := &inputBindingServer{} proto.RegisterInputBindingServer(s, srv) go func() { if serveErr := s.Serve(listener); serveErr != nil { testLogger.Debugf("Server exited with error: %v", serveErr) } }() conn := inputFromConnector(testLogger, connector) err = conn.Init(context.Background(), bindings.Metadata{ Base: contribMetadata.Base{}, }) require.NoError(t, err) assert.Equal(t, int64(1), srv.initCalled.Load()) }) } t.Run("read should callback handler when new messages are available", func(t *testing.T) { const fakeData1, fakeData2 = "fakeData1", "fakeData2" messagesData := [][]byte{[]byte(fakeData1), []byte(fakeData2)} var ( messagesAcked sync.WaitGroup messagesProcessed sync.WaitGroup totalResponseErrors atomic.Int64 handleCalled atomic.Int64 ) messages := make([]*proto.ReadResponse, len(messagesData)) for idx, data := range messagesData { messages[idx] = &proto.ReadResponse{ Data: data, } } messagesAcked.Add(len(messages)) messagesProcessed.Add(len(messages)) messageChan := make(chan *proto.ReadResponse, len(messages)) defer close(messageChan) for _, message := range messages { messageChan <- message } srv := &inputBindingServer{ readResponseChan: messageChan, onReadRequestReceived: func(ma *proto.ReadRequest) { messagesAcked.Done() if ma.GetResponseError() != nil { totalResponseErrors.Add(1) } }, } handleErrors := make(chan error, 1) // simulating an ack error handleErrors <- errors.New("fake-error") close(handleErrors) binding, cleanup, err := getInputBinding(srv) require.NoError(t, err) defer cleanup() err = binding.Read(context.Background(), func(_ context.Context, resp *bindings.ReadResponse) ([]byte, error) { handleCalled.Add(1) messagesProcessed.Done() assert.Contains(t, messagesData, resp.Data) return []byte{}, <-handleErrors }) require.NoError(t, err) messagesProcessed.Wait() messagesAcked.Wait() assert.Equal(t, int64(len(messages)), handleCalled.Load()) assert.Equal(t, int64(1), totalResponseErrors.Load()) // at least one message should be an error }) }
mikeee/dapr
pkg/components/bindings/input_pluggable_test.go
GO
mit
5,728
/* Copyright 2022 The Dapr 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 bindings import ( "context" "github.com/dapr/components-contrib/bindings" "github.com/dapr/dapr/pkg/components/pluggable" proto "github.com/dapr/dapr/pkg/proto/components/v1" "github.com/dapr/kit/logger" ) // grpcOutputBinding is a implementation of a outputbinding over a gRPC Protocol. type grpcOutputBinding struct { *pluggable.GRPCConnector[proto.OutputBindingClient] bindings.OutputBinding operations []bindings.OperationKind } // Init initializes the grpc outputbinding passing out the metadata to the grpc component. func (b *grpcOutputBinding) Init(ctx context.Context, metadata bindings.Metadata) error { if err := b.Dial(metadata.Name); err != nil { return err } protoMetadata := &proto.MetadataRequest{ Properties: metadata.Properties, } _, err := b.Client.Init(b.Context, &proto.OutputBindingInitRequest{ Metadata: protoMetadata, }) if err != nil { return err } operations, err := b.Client.ListOperations(b.Context, &proto.ListOperationsRequest{}) if err != nil { return err } operationsList := operations.GetOperations() ops := make([]bindings.OperationKind, len(operationsList)) for idx, op := range operationsList { ops[idx] = bindings.OperationKind(op) } b.operations = ops return nil } // Operations list bindings operations. func (b *grpcOutputBinding) Operations() []bindings.OperationKind { return b.operations } // Invoke the component with the given payload, metadata and operation. func (b *grpcOutputBinding) Invoke(ctx context.Context, req *bindings.InvokeRequest) (*bindings.InvokeResponse, error) { resp, err := b.Client.Invoke(ctx, &proto.InvokeRequest{ Data: req.Data, Metadata: req.Metadata, Operation: string(req.Operation), }) if err != nil { return nil, err } var contentType *string if len(resp.GetContentType()) != 0 { contentType = &resp.ContentType } return &bindings.InvokeResponse{ Data: resp.GetData(), Metadata: resp.GetMetadata(), ContentType: contentType, }, nil } // outputFromConnector creates a new GRPC outputbinding using the given underlying connector. func outputFromConnector(_ logger.Logger, connector *pluggable.GRPCConnector[proto.OutputBindingClient]) *grpcOutputBinding { return &grpcOutputBinding{ GRPCConnector: connector, } } // NewGRPCOutputBinding creates a new grpc outputbinding using the given socket factory. func NewGRPCOutputBinding(l logger.Logger, socket string) *grpcOutputBinding { return outputFromConnector(l, pluggable.NewGRPCConnector(socket, proto.NewOutputBindingClient)) } // newGRPCOutputBinding creates a new output binding for the given pluggable component. func newGRPCOutputBinding(dialer pluggable.GRPCConnectionDialer) func(l logger.Logger) bindings.OutputBinding { return func(l logger.Logger) bindings.OutputBinding { return outputFromConnector(l, pluggable.NewGRPCConnectorWithDialer(dialer, proto.NewOutputBindingClient)) } } func init() { //nolint:nosnakecase pluggable.AddServiceDiscoveryCallback(proto.OutputBinding_ServiceDesc.ServiceName, func(name string, dialer pluggable.GRPCConnectionDialer) { DefaultRegistry.RegisterOutputBinding(newGRPCOutputBinding(dialer), name) }) }
mikeee/dapr
pkg/components/bindings/output_pluggable.go
GO
mit
3,751
/* Copyright 2022 The Dapr 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 bindings import ( "context" "errors" "fmt" "net" "os" "runtime" "sync/atomic" "testing" guuid "github.com/google/uuid" "github.com/dapr/components-contrib/bindings" "github.com/dapr/dapr/pkg/components/pluggable" proto "github.com/dapr/dapr/pkg/proto/components/v1" testingGrpc "github.com/dapr/dapr/pkg/testing/grpc" contribMetadata "github.com/dapr/components-contrib/metadata" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/grpc" ) type outputBindingServer struct { proto.UnimplementedOutputBindingServer initCalled atomic.Int64 initErr error onInitCalled func(*proto.OutputBindingInitRequest) invokeCalled atomic.Int64 invokeErr error onInvokeCalled func(*proto.InvokeRequest) invokeResp *proto.InvokeResponse listOperationsCalled atomic.Int64 listOperationsErr error listOperationsResp *proto.ListOperationsResponse } func (b *outputBindingServer) Init(_ context.Context, req *proto.OutputBindingInitRequest) (*proto.OutputBindingInitResponse, error) { b.initCalled.Add(1) if b.onInitCalled != nil { b.onInitCalled(req) } return &proto.OutputBindingInitResponse{}, b.initErr } func (b *outputBindingServer) Invoke(_ context.Context, req *proto.InvokeRequest) (*proto.InvokeResponse, error) { b.invokeCalled.Add(1) if b.onInvokeCalled != nil { b.onInvokeCalled(req) } return b.invokeResp, b.invokeErr } func (b *outputBindingServer) ListOperations(context.Context, *proto.ListOperationsRequest) (*proto.ListOperationsResponse, error) { b.listOperationsCalled.Add(1) resp := b.listOperationsResp if resp == nil { resp = &proto.ListOperationsResponse{} } return resp, b.listOperationsErr } func (b *outputBindingServer) Ping(context.Context, *proto.PingRequest) (*proto.PingResponse, error) { return &proto.PingResponse{}, nil } func TestOutputBindingCalls(t *testing.T) { getOutputBinding := testingGrpc.TestServerFor(testLogger, func(s *grpc.Server, svc *outputBindingServer) { proto.RegisterOutputBindingServer(s, svc) }, func(cci grpc.ClientConnInterface) *grpcOutputBinding { client := proto.NewOutputBindingClient(cci) outbinding := outputFromConnector(testLogger, pluggable.NewGRPCConnector("/tmp/socket.sock", proto.NewOutputBindingClient)) outbinding.Client = client return outbinding }) if runtime.GOOS != "windows" { t.Run("test init should populate features and call grpc init", func(t *testing.T) { const ( fakeName = "name" fakeType = "type" fakeVersion = "v1" fakeComponentName = "component" fakeSocketFolder = "/tmp" fakeOperation = "fake" ) fakeOperations := []string{fakeOperation} uniqueID := guuid.New().String() socket := fmt.Sprintf("%s/%s.sock", fakeSocketFolder, uniqueID) defer os.Remove(socket) connector := pluggable.NewGRPCConnector(socket, proto.NewOutputBindingClient) defer connector.Close() listener, err := net.Listen("unix", socket) require.NoError(t, err) defer listener.Close() s := grpc.NewServer() srv := &outputBindingServer{ listOperationsResp: &proto.ListOperationsResponse{ Operations: fakeOperations, }, } proto.RegisterOutputBindingServer(s, srv) go func() { if serveErr := s.Serve(listener); serveErr != nil { testLogger.Debugf("Server exited with error: %v", serveErr) } }() conn := outputFromConnector(testLogger, connector) err = conn.Init(context.Background(), bindings.Metadata{ Base: contribMetadata.Base{}, }) require.NoError(t, err) assert.Equal(t, int64(1), srv.listOperationsCalled.Load()) assert.Equal(t, int64(1), srv.initCalled.Load()) assert.ElementsMatch(t, conn.operations, []bindings.OperationKind{fakeOperation}) }) } t.Run("list operations should return operations when set", func(t *testing.T) { const fakeOperation = "fake" ops := []bindings.OperationKind{fakeOperation} outputGrpc := &grpcOutputBinding{ operations: ops, } assert.Equal(t, ops, outputGrpc.Operations()) }) t.Run("invoke should call grpc invoke when called", func(t *testing.T) { const fakeOp, fakeMetadataKey, fakeMetadataValue = "fake-op", "fake-key", "fake-value" fakeDataResp := []byte("fake-resp") fakeDataReq := []byte("fake-req") fakeMetadata := map[string]string{ fakeMetadataKey: fakeMetadataValue, } srv := &outputBindingServer{ invokeResp: &proto.InvokeResponse{ Data: fakeDataResp, Metadata: fakeMetadata, }, onInvokeCalled: func(ir *proto.InvokeRequest) { assert.Equal(t, fakeOp, ir.GetOperation()) }, } outputSvc, cleanup, err := getOutputBinding(srv) defer cleanup() require.NoError(t, err) resp, err := outputSvc.Invoke(context.Background(), &bindings.InvokeRequest{ Data: fakeDataReq, Metadata: fakeMetadata, Operation: fakeOp, }) require.NoError(t, err) assert.Equal(t, int64(1), srv.invokeCalled.Load()) assert.Equal(t, resp.Data, fakeDataResp) }) t.Run("invoke should return an error if grpc method returns an error", func(t *testing.T) { const errStr = "fake-invoke-err" srv := &outputBindingServer{ invokeErr: errors.New(errStr), } outputSvc, cleanup, err := getOutputBinding(srv) defer cleanup() require.NoError(t, err) _, err = outputSvc.Invoke(context.Background(), &bindings.InvokeRequest{}) require.Error(t, err) assert.Equal(t, int64(1), srv.invokeCalled.Load()) }) }
mikeee/dapr
pkg/components/bindings/output_pluggable_test.go
GO
mit
6,087
/* Copyright 2021 The Dapr 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 bindings import ( "fmt" "strings" "github.com/dapr/components-contrib/bindings" "github.com/dapr/dapr/pkg/components" "github.com/dapr/kit/logger" ) // Registry is the interface of a components that allows callers to get registered instances of input and output bindings. type Registry struct { Logger logger.Logger inputBindings map[string]func(logger.Logger) bindings.InputBinding outputBindings map[string]func(logger.Logger) bindings.OutputBinding } // DefaultRegistry is the singleton with the registry. var DefaultRegistry *Registry = NewRegistry() // NewRegistry is used to create new bindings. func NewRegistry() *Registry { return &Registry{ inputBindings: map[string]func(logger.Logger) bindings.InputBinding{}, outputBindings: map[string]func(logger.Logger) bindings.OutputBinding{}, } } // RegisterInputBinding adds a name input binding to the registry. func (b *Registry) RegisterInputBinding(componentFactory func(logger.Logger) bindings.InputBinding, names ...string) { for _, name := range names { b.inputBindings[createFullName(name)] = componentFactory } } // RegisterOutputBinding adds a name output binding to the registry. func (b *Registry) RegisterOutputBinding(componentFactory func(logger.Logger) bindings.OutputBinding, names ...string) { for _, name := range names { b.outputBindings[createFullName(name)] = componentFactory } } // CreateInputBinding Create instantiates an input binding based on `name`. func (b *Registry) CreateInputBinding(name, version, logName string) (bindings.InputBinding, error) { if method, ok := b.getInputBinding(name, version, logName); ok { return method(), nil } return nil, fmt.Errorf("couldn't find input binding %s/%s", name, version) } // CreateOutputBinding Create instantiates an output binding based on `name`. func (b *Registry) CreateOutputBinding(name, version, logName string) (bindings.OutputBinding, error) { if method, ok := b.getOutputBinding(name, version, logName); ok { return method(), nil } return nil, fmt.Errorf("couldn't find output binding %s/%s", name, version) } // HasInputBinding checks if an input binding based on `name` exists in the registry. func (b *Registry) HasInputBinding(name, version string) bool { _, ok := b.getInputBinding(name, version, "") return ok } // HasOutputBinding checks if an output binding based on `name` exists in the registry. func (b *Registry) HasOutputBinding(name, version string) bool { _, ok := b.getOutputBinding(name, version, "") return ok } func (b *Registry) getInputBinding(name, version, logName string) (func() bindings.InputBinding, bool) { nameLower := strings.ToLower(name) versionLower := strings.ToLower(version) bindingFn, ok := b.inputBindings[nameLower+"/"+versionLower] if ok { return b.wrapInputBindingFn(bindingFn, logName), true } if components.IsInitialVersion(versionLower) { bindingFn, ok = b.inputBindings[nameLower] if ok { return b.wrapInputBindingFn(bindingFn, logName), true } } return nil, false } func (b *Registry) getOutputBinding(name, version, logName string) (func() bindings.OutputBinding, bool) { nameLower := strings.ToLower(name) versionLower := strings.ToLower(version) bindingFn, ok := b.outputBindings[nameLower+"/"+versionLower] if ok { return b.wrapOutputBindingFn(bindingFn, logName), true } if components.IsInitialVersion(versionLower) { bindingFn, ok = b.outputBindings[nameLower] if ok { return b.wrapOutputBindingFn(bindingFn, logName), true } } return nil, false } func (b *Registry) wrapInputBindingFn(componentFactory func(logger.Logger) bindings.InputBinding, logName string) func() bindings.InputBinding { return func() bindings.InputBinding { l := b.Logger if logName != "" && l != nil { l = l.WithFields(map[string]any{ "component": logName, }) } return componentFactory(l) } } func (b *Registry) wrapOutputBindingFn(componentFactory func(logger.Logger) bindings.OutputBinding, logName string) func() bindings.OutputBinding { return func() bindings.OutputBinding { l := b.Logger if logName != "" && l != nil { l = l.WithFields(map[string]any{ "component": logName, }) } return componentFactory(l) } } func createFullName(name string) string { return strings.ToLower("bindings." + name) }
mikeee/dapr
pkg/components/bindings/registry.go
GO
mit
4,879
/* Copyright 2021 The Dapr 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 bindings_test import ( "fmt" "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" b "github.com/dapr/components-contrib/bindings" "github.com/dapr/dapr/pkg/components/bindings" "github.com/dapr/kit/logger" ) type ( mockInputBinding struct { b.InputBinding } mockOutputBinding struct { b.OutputBinding } ) func TestRegistry(t *testing.T) { testRegistry := bindings.NewRegistry() t.Run("input binding is registered", func(t *testing.T) { const ( inputBindingName = "mockInputBinding" inputBindingNameV2 = "mockInputBinding/v2" componentName = "bindings." + inputBindingName ) // Initiate mock object mockInput := &mockInputBinding{} mockInputV2 := &mockInputBinding{} // act testRegistry.RegisterInputBinding(func(_ logger.Logger) b.InputBinding { return mockInput }, inputBindingName) testRegistry.RegisterInputBinding(func(_ logger.Logger) b.InputBinding { return mockInputV2 }, inputBindingNameV2) // assert v0 and v1 assert.True(t, testRegistry.HasInputBinding(componentName, "v0")) p, e := testRegistry.CreateInputBinding(componentName, "v0", "") require.NoError(t, e) assert.Same(t, mockInput, p) p, e = testRegistry.CreateInputBinding(componentName, "v1", "") require.NoError(t, e) assert.Same(t, mockInput, p) // assert v2 assert.True(t, testRegistry.HasInputBinding(componentName, "v2")) pV2, e := testRegistry.CreateInputBinding(componentName, "v2", "") require.NoError(t, e) assert.Same(t, mockInputV2, pV2) // check case-insensitivity pV2, e = testRegistry.CreateInputBinding(strings.ToUpper(componentName), "V2", "") require.NoError(t, e) assert.Same(t, mockInputV2, pV2) }) t.Run("input binding is not registered", func(t *testing.T) { const ( inputBindingName = "fakeInputBinding" componentName = "bindings." + inputBindingName ) // act assert.False(t, testRegistry.HasInputBinding(componentName, "v0")) assert.False(t, testRegistry.HasInputBinding(componentName, "v1")) assert.False(t, testRegistry.HasInputBinding(componentName, "v2")) p, actualError := testRegistry.CreateInputBinding(componentName, "v1", "") expectedError := fmt.Errorf("couldn't find input binding %s/v1", componentName) // assert assert.Nil(t, p) assert.Equal(t, expectedError.Error(), actualError.Error()) }) t.Run("output binding is registered", func(t *testing.T) { const ( outputBindingName = "mockInputBinding" outputBindingNameV2 = "mockInputBinding/v2" componentName = "bindings." + outputBindingName ) // Initiate mock object mockOutput := &mockOutputBinding{} mockOutputV2 := &mockOutputBinding{} // act testRegistry.RegisterOutputBinding(func(_ logger.Logger) b.OutputBinding { return mockOutput }, outputBindingName) testRegistry.RegisterOutputBinding(func(_ logger.Logger) b.OutputBinding { return mockOutputV2 }, outputBindingNameV2) // assert v0 and v1 assert.True(t, testRegistry.HasOutputBinding(componentName, "v0")) p, e := testRegistry.CreateOutputBinding(componentName, "v0", "") require.NoError(t, e) assert.Same(t, mockOutput, p) assert.True(t, testRegistry.HasOutputBinding(componentName, "v1")) p, e = testRegistry.CreateOutputBinding(componentName, "v1", "") require.NoError(t, e) assert.Same(t, mockOutput, p) // assert v2 assert.True(t, testRegistry.HasOutputBinding(componentName, "v2")) pV2, e := testRegistry.CreateOutputBinding(componentName, "v2", "") require.NoError(t, e) assert.Same(t, mockOutputV2, pV2) }) t.Run("output binding is not registered", func(t *testing.T) { const ( outputBindingName = "fakeOutputBinding" componentName = "bindings." + outputBindingName ) // act assert.False(t, testRegistry.HasOutputBinding(componentName, "v0")) assert.False(t, testRegistry.HasOutputBinding(componentName, "v1")) assert.False(t, testRegistry.HasOutputBinding(componentName, "v2")) p, actualError := testRegistry.CreateOutputBinding(componentName, "v1", "") expectedError := fmt.Errorf("couldn't find output binding %s/v1", componentName) // assert assert.Nil(t, p) assert.Equal(t, expectedError.Error(), actualError.Error()) }) }
mikeee/dapr
pkg/components/bindings/registry_test.go
GO
mit
4,819
/* Copyright 2022 The Dapr 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 components type Category string // supported components category const ( CategoryBindings Category = "bindings" CategoryPubSub Category = "pubsub" CategorySecretStore Category = "secretstores" CategoryStateStore Category = "state" CategoryWorkflow Category = "workflow" CategoryWorkflowBackend Category = "workflowbackend" CategoryMiddleware Category = "middleware" CategoryConfiguration Category = "configuration" CategoryCryptoProvider Category = "crypto" CategoryLock Category = "lock" CategoryNameResolution Category = "nameresolution" )
mikeee/dapr
pkg/components/category.go
GO
mit
1,176
/* Copyright 2021 The Dapr 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 configuration import ( "fmt" "strings" "github.com/dapr/components-contrib/configuration" "github.com/dapr/dapr/pkg/components" "github.com/dapr/kit/logger" ) // Registry is an interface for a component that returns registered configuration store implementations. type Registry struct { Logger logger.Logger configurationStores map[string]func(logger.Logger) configuration.Store } // DefaultRegistry is the singleton with the registry. var DefaultRegistry *Registry func init() { DefaultRegistry = NewRegistry() } // NewRegistry is used to create configuration store registry. func NewRegistry() *Registry { return &Registry{ configurationStores: map[string]func(logger.Logger) configuration.Store{}, } } func (s *Registry) RegisterComponent(componentFactory func(logger.Logger) configuration.Store, names ...string) { for _, name := range names { s.configurationStores[createFullName(name)] = componentFactory } } func (s *Registry) Create(name, version, logName string) (configuration.Store, error) { if method, ok := s.getConfigurationStore(name, version, logName); ok { return method(), nil } return nil, fmt.Errorf("couldn't find configuration store %s/%s", name, version) } func (s *Registry) getConfigurationStore(name, version, logName string) (func() configuration.Store, bool) { nameLower := strings.ToLower(name) versionLower := strings.ToLower(version) configurationStoreFn, ok := s.configurationStores[nameLower+"/"+versionLower] if ok { return s.wrapFn(configurationStoreFn, logName), true } if components.IsInitialVersion(versionLower) { configurationStoreFn, ok = s.configurationStores[nameLower] if ok { return s.wrapFn(configurationStoreFn, logName), true } } return nil, false } func (s *Registry) wrapFn(componentFactory func(logger.Logger) configuration.Store, logName string) func() configuration.Store { return func() configuration.Store { l := s.Logger if logName != "" && l != nil { l = l.WithFields(map[string]any{ "component": logName, }) } return componentFactory(l) } } func createFullName(name string) string { return strings.ToLower("configuration." + name) }
mikeee/dapr
pkg/components/configuration/registry.go
GO
mit
2,745
/* Copyright 2021 The Dapr 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 configuration_test import ( "fmt" "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" c "github.com/dapr/components-contrib/configuration" "github.com/dapr/dapr/pkg/components/configuration" "github.com/dapr/kit/logger" ) type mockState struct { c.Store } func TestRegistry(t *testing.T) { testRegistry := configuration.NewRegistry() t.Run("configuration is registered", func(t *testing.T) { const ( stateName = "mockState" stateNameV2 = "mockState/v2" componentName = "configuration." + stateName ) // Initiate mock object mock := &mockState{} mockV2 := &mockState{} // act testRegistry.RegisterComponent(func(_ logger.Logger) c.Store { return mock }, stateName) testRegistry.RegisterComponent(func(_ logger.Logger) c.Store { return mockV2 }, stateNameV2) // assert v0 and v1 p, e := testRegistry.Create(componentName, "v0", "") require.NoError(t, e) assert.Same(t, mock, p) p, e = testRegistry.Create(componentName, "v1", "") require.NoError(t, e) assert.Same(t, mock, p) // assert v2 pV2, e := testRegistry.Create(componentName, "v2", "") require.NoError(t, e) assert.Same(t, mockV2, pV2) // check case-insensitivity pV2, e = testRegistry.Create(strings.ToUpper(componentName), "V2", "") require.NoError(t, e) assert.Same(t, mockV2, pV2) }) t.Run("configuration is not registered", func(t *testing.T) { const ( configurationName = "fakeConfiguration" componentName = "configuration." + configurationName ) // act p, actualError := testRegistry.Create(componentName, "v1", "") expectedError := fmt.Errorf("couldn't find configuration store %s/v1", componentName) // assert assert.Nil(t, p) assert.Equal(t, expectedError.Error(), actualError.Error()) }) }
mikeee/dapr
pkg/components/configuration/registry_test.go
GO
mit
2,394
/* Copyright 2023 The Dapr 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 crypto import ( "fmt" "strings" "github.com/dapr/components-contrib/crypto" "github.com/dapr/dapr/pkg/components" "github.com/dapr/kit/logger" ) // Registry is used to get registered crypto provider implementations. type Registry struct { Logger logger.Logger providers map[string]func(logger.Logger) crypto.SubtleCrypto } // DefaultRegistry is the singleton with the registry. var DefaultRegistry *Registry func init() { DefaultRegistry = NewRegistry() } // NewRegistry returns a new crypto provider registry. func NewRegistry() *Registry { return &Registry{ providers: map[string]func(logger.Logger) crypto.SubtleCrypto{}, } } // RegisterComponent adds a new crypto provider to the registry. func (s *Registry) RegisterComponent(componentFactory func(logger.Logger) crypto.SubtleCrypto, names ...string) { for _, name := range names { s.providers[createFullName(name)] = componentFactory } } // Create instantiates a crypto provider based on `name`. func (s *Registry) Create(name, version, logName string) (crypto.SubtleCrypto, error) { if method, ok := s.getCryptoProvider(name, version, logName); ok { return method(), nil } return nil, fmt.Errorf("couldn't find crypto provider %s/%s", name, version) } func (s *Registry) getCryptoProvider(name, version, logName string) (func() crypto.SubtleCrypto, bool) { nameLower := strings.ToLower(name) versionLower := strings.ToLower(version) cryptoProviderFn, ok := s.providers[nameLower+"/"+versionLower] if ok { return s.wrapFn(cryptoProviderFn, logName), true } if components.IsInitialVersion(versionLower) { cryptoProviderFn, ok = s.providers[nameLower] if ok { return s.wrapFn(cryptoProviderFn, logName), true } } return nil, false } func (s *Registry) wrapFn(componentFactory func(logger.Logger) crypto.SubtleCrypto, logName string) func() crypto.SubtleCrypto { return func() crypto.SubtleCrypto { l := s.Logger if logName != "" && l != nil { l = l.WithFields(map[string]any{ "component": logName, }) } return componentFactory(l) } } func createFullName(name string) string { return strings.ToLower("crypto." + name) }
mikeee/dapr
pkg/components/crypto/registry.go
GO
mit
2,718
/* Copyright 2023 The Dapr 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 crypto_test import ( "fmt" "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" cp "github.com/dapr/components-contrib/crypto" "github.com/dapr/dapr/pkg/components/crypto" "github.com/dapr/kit/logger" ) type mockCryptoProvider struct { cp.SubtleCrypto } func TestRegistry(t *testing.T) { testRegistry := crypto.NewRegistry() t.Run("cryto provider is registered", func(t *testing.T) { const ( cryptoProviderName = "mockCrypto" cryptoProviderNameV2 = "mockCrypto/v2" componentName = "crypto." + cryptoProviderName ) // Initiate mock object mock := &mockCryptoProvider{} mockV2 := &mockCryptoProvider{} // act testRegistry.RegisterComponent(func(_ logger.Logger) cp.SubtleCrypto { return mock }, cryptoProviderName) testRegistry.RegisterComponent(func(_ logger.Logger) cp.SubtleCrypto { return mockV2 }, cryptoProviderNameV2) // assert v0 and v1 p, e := testRegistry.Create(componentName, "v0", "") require.NoError(t, e) assert.Same(t, mock, p) p, e = testRegistry.Create(componentName, "v1", "") require.NoError(t, e) assert.Same(t, mock, p) // assert v2 pV2, e := testRegistry.Create(componentName, "v2", "") require.NoError(t, e) assert.Same(t, mockV2, pV2) // check case-insensitivity pV2, e = testRegistry.Create(strings.ToUpper(componentName), "V2", "") require.NoError(t, e) assert.Same(t, mockV2, pV2) }) t.Run("crypto provider is not registered", func(t *testing.T) { const ( resolverName = "fakeCrypto" componentName = "crypto." + resolverName ) // act p, actualError := testRegistry.Create(componentName, "v1", "") expectedError := fmt.Errorf("couldn't find crypto provider %s/v1", componentName) // assert assert.Nil(t, p) assert.Equal(t, expectedError.Error(), actualError.Error()) }) }
mikeee/dapr
pkg/components/crypto/registry_test.go
GO
mit
2,433
package lock import ( "fmt" "strings" "sync" ) const ( strategyKey = "keyprefix" strategyAppid = "appid" strategyStoreName = "name" strategyNone = "none" strategyDefault = strategyAppid apiPrefix = "lock" separator = "||" ) var ( locksConfigurationMu sync.RWMutex lockConfiguration = map[string]*StoreConfiguration{} ) type StoreConfiguration struct { keyPrefixStrategy string } func SaveLockConfiguration(storeName string, metadata map[string]string) error { strategy := strategyDefault for k, v := range metadata { if strings.ToLower(k) == strategyKey { //nolint:gocritic strategy = strings.ToLower(v) break } } err := checkKeyIllegal(strategy) if err != nil { return err } locksConfigurationMu.Lock() lockConfiguration[storeName] = &StoreConfiguration{keyPrefixStrategy: strategy} locksConfigurationMu.Unlock() return nil } func GetModifiedLockKey(key, storeName, appID string) (string, error) { if err := checkKeyIllegal(key); err != nil { return "", err } config := getConfiguration(storeName) switch config.keyPrefixStrategy { case strategyNone: // `lock||key` return apiPrefix + separator + key, nil case strategyStoreName: // `lock||store_name||key` return apiPrefix + separator + storeName + separator + key, nil case strategyAppid: // `lock||key` or `lock||app_id||key` if appID == "" { return apiPrefix + separator + key, nil } return apiPrefix + separator + appID + separator + key, nil default: // `lock||keyPrefixStrategy||key` return apiPrefix + separator + config.keyPrefixStrategy + separator + key, nil } } func getConfiguration(storeName string) *StoreConfiguration { locksConfigurationMu.RLock() c := lockConfiguration[storeName] if c != nil { locksConfigurationMu.RUnlock() return c } locksConfigurationMu.RUnlock() // Acquire a write lock now to update the value in cache locksConfigurationMu.Lock() defer locksConfigurationMu.Unlock() // Try checking the cache again after acquiring a write lock, in case another goroutine has created the object c = lockConfiguration[storeName] if c != nil { return c } c = &StoreConfiguration{keyPrefixStrategy: strategyDefault} lockConfiguration[storeName] = c return c } func checkKeyIllegal(key string) error { if strings.Contains(key, separator) { return fmt.Errorf("input key/keyPrefix '%s' can't contain '%s'", key, separator) } return nil }
mikeee/dapr
pkg/components/lock/lock_config.go
GO
mit
2,431